�����    �   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:>   �� ����,�,�@<�=@�=@�=���=hB���%-5=DKSZahpx������������������ $+19@GNU[bhpx�����������������&-5<CJRY`gnu|����������������� '.6=DKRZagow����������������� !(/6>ELSZbiqx�����������������&,4:BJQX`hpw~������������������$,4:AIPX`hov~����������������� !(08?GNV^emu}����������������� !(/7>EMU]emu|�����������������   " ) 0 8 @ H O W ^ e m t | � � � � � � � � � � � � � � � � �    ' / 7 = E L T [ b j q y � � � � � � � � � � � � � � � � � �    ( / 6 > D K S Z a i p w } � � � � � � � � � � � � � � � � � �     $ + 3 ; B J Q X ` h o v } � � � � � � � � � � � � � � � � �     % - 5 < C K R Y a i p v ~ � � � � � � � � � � � � � � � � �  %-4<DLS[ckqx����������������� $,39AIPW^fnu|����������������� ")08@GNV]dksz�����������������  (/6=DKS[biqx������������������&-5=DLS[cjrz�����������������&-5=EMU]dkrz����������������� '/7>ELTZaipx�����������������%,3:BJRYaiqx������������������  (07>ELT\ckrz����������������� "*29@FNV^eltz������������������%,4<CJQX`hpx�����������������  '.5<CJRZbiqx������������������$+3:BHPX`how����������������%-5<DLSZbipw~�����������������&.5;CKSZaipw~���������������3960565778927716171455719651619149658130216191030008413836574821663441684931161106785289953254194501282717514288129253321753440196043091767175106041345957326129781071468433136017486373101113220216001766375895148800231593212816406652112546913127341624415112721671748734015534009301957711367746462913960156110877732148318440805566162585278313964634545777264289981178407511360097721600359068751297632672333966460106627861307548592942261647516611455031824277571491213818071604044964403304227171941577619143581287600612873820298132113272488110731061772347211453814200651873266763699838414090166502542800324415415970754854814417375901534531678423021896793103923801822324842462091327291736937812274021480347911776034100558411765539411338609540140476317734388344104020021876063123009146773315188202765370923168370389592177166390064688617111041311726349304111129746459075396736202154057091097363211689518613002728420721488271153957345233635237780104209181709750513871185363984772237891799771267163315103591850001226286214277638182970131925887559392971565375610842359120429642032112816000149458219418275720105168960949423507176785032479421187056349113081127939071786108518968842117073351110191316883823784099361355827827471104458071775624310564640114050291533502667129280618011750225143480754229146120029931589921834518117542744468189187479015322971157831714057924426203728755401226460419952084135294926040565388446913904674159023941921844898763952570623804750533305735660310416632029593085773631438948927666582527536190948999369134555968329419135469361555371655048161886716242734181507311012850818335140381106217187206794424011548727184094011928886990768157428123187321747497751199492182981037110361797337964942813670850991927941517571808102607101323355737871787712322189281657302671590708039406401706771017160940146312137271077305048730891317292972168250549531848111494943958941180268731385554442736301246822012304425123494761034589518938114161548891350761620366153679521105495103949018890254140081622267688789535070973077776985186728237385591196759251917646914175581543681914704564286157316182644130488109696501639707660867314855612187394871215012312596182103034391040824995009531891553111783149607215918604275971829214673097866919216598286182487301387344412712538871570319672287187704333449504101040386811731276144111123641964143173887928031026860321177007311308195913872160119206221890328116761963203639899054910785415312945412643553492319247618351520712278363901666567011729215165299121455345315036335218912417574310658750148936561996099168661701779931046205619699769131227245201171122071535533963481805129768081250742849267214027510457377910776213820216764628231012899148793071680880117122592436329149134753282718420713697549718904679351600961404748253008547025148820876773734393492121833628760152146580811627166514930364191214681290764078308789532841103553767202901561949619888648127538917124018946409647466685622051200807988559871473725875884960964855751117761635132569564753367980040606971844128820006044151921637577921628476429659217652372147377367986838165029211059067918437456173040641710768471631582546633957585158796481133514187940011937483480295566786279123331111935815734111841314905864859211902051114871157830718156476217294353876258670961381712945118924403304639659711867970926367326647709141246162812295914762829181032738704800793954730207221983474445257213822111195993036712316446707212343990224662782433841809629914328101618511463038719361653334564914395321548598462196021987806118616476686414259676773555101072198717144808755803917056325182500243631866158827912382170161887593960781275183564696725846550705641391737745957531949029614813562194088528723896108493641028474120041861266699488742976238031146815111415463156700531106735144997279465736921581237205881558161511441013145176874438509194953848486118543028934203167098301434021916938710740542410205616107441561891448242824954935051561167710378045649618873965366725046194428551287336343970057240992670466214273955978852313567135370003112797879128172603024627284842716868398175342719446900421028717911256164799605483144165278546405021185573761458961528353431007561340003842742774129036361571369472135411234320180566187696502260266078011331221358457125851665197314187560162983956043882151032195039503144816324992027176473981611788446353366152458163592951166111614552774743762810863653103326844571768756352132098808152607125289881634839927909462058107827519799406118111412149396374441030249142017746348328377511199160192794768502756318863337760719771362150625495119651247073619529630117791948127121236690946323961399666013276785196633622794802146754561258010816498983157844811786352948278071348552918611324553647418503990602336613944322188178355043502162129661922587529661071429274891226751754575810066603994312118288151179680631082053099166554855646122059909600533114306247186083150307908745519280303157004001702065358261506492399153551776198409117190861381605114485622113806341687525213146332613481753643795435569151461176092799132290047795228570924514458761544855415401901202053513841024362041114063085159008551275673211460314174015601166932220449842843518579164419083275151705491682881605414113628862111161762374185256573926325791782037931027767567561759144551994061710991418770628973755657776278515913370375639675211129161176173411156552643556998593723002784163752827232728218931381057381466348716666556518286183466713730512201745753773912864943797786824474643398197180599721441056515659975272333911228963114144431425746569806921577316816576658102202713046434717347233511721835374175252812073666169428687633097514409160322192115991746671236441147043811854755167490187862726130074971043532852587601158383216557391538997176034485830936527637713714558199826567963308154983554077265122448171366356459462121790976312709917587035014121482999378523059711580009992796196647362212662183617617675971814865418781671107301461421587681843132086510288620123491333194901145737810416693843204090712914473691247019215289319117607456051010197810913945054329831142829791102881385659615417984891645575929074141961938475318930142141489821832185314350539123886997001654479241165801689484348496118111613172717403914569687612555510046980168425014914611130337145049215498655351152872040281168780801682478914234672159915148472469128708131010404768725961138393991411154164995251163381060939230138633894386402086567169814921975865413397339320463215113041588072812538949171661476992066183219166914818380847426839887343236207594735251441567244811591784137309783686946115015328524239196727287943507211415662084265935032218094841788077676096316893214514664182155511699297119931759158669061968024412509333231419419658473151278002432240107942282082816605966259672671068754773282441402911141253313714350193926871629477416250868986903315242582158722701332473113455228102337595955452161715773973118179092612052034674766814626212141175012316406725649615770498192203431759576163589187008632529559215346223197606907036248158087141231365723770561384669814456559857222873328771489912279274335284890493466429295264866196243221943320416962624817245063589329543662994280806481196475913357097195070181797257270010351540736447648951886272310161413646862516615960190271218729237131103681223644886785258102371556093619723092161450606673295103958114451085981502629490534050834111724986999364126334892500955884503542532175218593299954195364103861133273444125747496019887633866718339346��b�%:&�' 5�L�PW�Z�\�^�c�e�m��I���P�� �� ,�.�0�:�;�>�?�T�Y�hdmA|B����j��� �X�@�w������������3 � c&�E�k�{΃X�l�g�������M�����;�PS�^/d�����]���r�qm�z�|Y����g�����������1��jӌ��N�����0�]��*�3�7@<eDf���6�f�|�������������vX�:),0�>jR�_�fts�stzh�F���[�o�|�������� �  L? D G �M �� D� �� X� i� � S� �� �� �� 9� �� <& �2 �@ ZB �P �Y :c �o �q z t� H� � M� � �� +� �� �� yB �e �q �t �u V� $� � r � � > �) D? jE �J uS �S \W Ș 3� v� �� Ħ b� �� �� � �� � t� A� � w�  3� N� n� � � �� � Z� �� � �� T� �� G� �� ��!)�7^>``a�d�f j�o8v'|6���'�+���$���������zK���0 �&�+i1�8\H�Q����4z� �,%2�:�B�k������:��)�=���!���������k�Q���k���������r*�,�/ 7pLqU�rdv�{yN�y��ɓZ�1�kg�q�}��� -�/9�=>�M&T�\�`6m�}w�a�����B���9�� �2�?�N�O�\P�J�ɡ$���5��}������9��:�B�F�Vx_�v�y`|���֕.�C���J���������������`��;qE�K/R�e�fOl�m3q�q ����������������`�2�;mL$R�W*i�2�D�E M�U�xx�N��_�o���������/�V6�s$*�,/3v��ȪƬ���"���Y�����R��������t� aRn��)�,�-�9�E F�JWRZ`h�rH~!���Ν��������W���> 0 ���"-1�2?D$SUXW�oHstwy���M�*������4�5.8mB/IKS?i=qs(}#�3��٢p���C������������W��/Q7VS]�������x� 3 � I$ I9 F: �] �j z �} dž �� 1�!��!*�!��!�"�3"�=""?"�H"�M"�O"ZP"�W"a�"�"*�#��#o�#:�#��#��#Y�#�#��#�#P�#��#�$$~$�#$1$65$5=$�>$�C$N$Q$dZ$�e$��$„$��${�%��%��%,�%z�%*�%ó%m�%'�%�%��%��%Y�%�%��%��%q�%7&�O&Q&�S&aZ&�l&�n&�{&�|&e}&P&9�&��&7�&��&"�&p�&��&��&�&�&�'�('6)'y:'YQ'�W'|^'�o'�s'�'n�'ǃ'%�'�'��'�'�'�'��'��'��'c�'��'��'��'� (�(@&(P1(j4(�G(�M(;g(vr(x(yz(.�(k�(��(V�(c�(�(>�(�9)uY)�Y)�[)wc)~d)�s)�)8�)�)��)�*�%* &*'*S)*Q7*�A*�I*�S*�Y*�]*�_*�l*�*/�* �*��*4�*��*�*��*h�*F�*��*�*�*��*�++H+�+~ +a+|&+ *+yA+FH+�i+ �+Z�+��+Y�+D�+��+s�+;,VW,xY,�|,N�,��,��, �,7�,5�,�,��,W�,q-�-�$-�8-r>-�N-k-&o-�w-�y-�|-Ǒ-��-`�-5�-�-��-Ѻ-Q�-��-<�-��-L�-1. .� .�I.eN.��.p�.ţ.H//%/E*/cB/�S/�[/T_/>f/�p/`�/6�/��/K�/��/B�/L�/B�/��/��/#00G&0�*0�E0�U0}W0�0��00�0��0��0J�0� 1� 11�51p:1�D1�W1C]1�q1Fx1ډ122�282�2W2%2�'2�D2�O2!U2 Y2]2�g2Mi2̇2�2��20�2��2y�2��2�2|�2- 3i3�3�/3A33�33dA3�B34S3�T3�U31f3Gk3>s3f�3~�3�3��3ت3�3N�3��36�3��3�3&4�4�4^*4�44�^4 w4u|4�4F�4L�4֋4�4�4t�4K�4X�4��4��4��4ٻ4ʾ4��4��4�4 �4��4X�4��4�5�"5�J5�M5�Y5�j5�m5�o5hy5;}5>5��5a�5��5l�5e�5�5P�5��5'6�"6�*6V~7"�7��7�7��7Y8X8� 8� 8�8�"8�&8�)8,-8�18�I8�M8�i8��82�8��8}09[L9jM9�N9�Q9�c9Um9�9C�9n�9��91�9b�9k�96�9&�9��9D: :_:�:.:�2:�5:Y7:�`:d:ik:(<�d<pf<F�<�=0=�#=�U=\=�^=�j="n=�q=Y�=��=�=/** * Copyright (c) 2015 Translation Exchange, Inc. All rights reserved. * * _______ _ _ _ ______ _ * |__ __| | | | | (_) | ____| | | * | |_ __ __ _ _ __ ___| | __ _| |_ _ ___ _ __ | |__ __ _____| |__ __ _ _ __ __ _ ___ * | | '__/ _` | '_ \/ __| |/ _` | __| |/ _ \| '_ \| __| \ \/ / __| '_ \ / _` | '_ \ / _` |/ _ \ * | | | | (_| | | | \__ \ | (_| | |_| | (_) | | | | |____ > < (__| | | | (_| | | | | (_| | __/ * |_|_| \__,_|_| |_|___/_|\__,_|\__|_|\___/|_| |_|______/_/\_\___|_| |_|\__,_|_| |_|\__, |\___| * __/ | * |___/ * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.translationexchange.samples.wammer.adapters; import java.util.List; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.translationexchange.samples.wammer.R; import com.translationexchange.samples.wammer.models.NewsfeedStory; import com.translationexchange.samples.wammer.models.ResourceCache; public class NewsfeedListAdapter extends BaseAdapter { private Context context; private List stories; public NewsfeedListAdapter(Context context, List stories){ this.context = context; this.stories = stories; } public int getCount() { return stories.size(); } public Object getItem(int position) { return stories.get(position); } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE); convertView = mInflater.inflate(R.layout.newsfeed_list_item, null); } convertView.setMinimumHeight(150); NewsfeedStory story = stories.get(position); TextView txtTitle = (TextView) convertView.findViewById(R.id.textview_story_title); txtTitle.setText(story.getStory()); ImageView imageView = (ImageView) convertView.findViewById(R.id.imageview_story_photo); imageView.setImageBitmap(ResourceCache.getImage(context, story.getActorImageName() + ".png")); return convertView; } } 1-10 package net.safedata.spring.boot.training.solace.message; public abstract class AbstractCommand extends AbstractMessage { public AbstractCommand(long messageId) { super(messageId); } } Edouard87o1vuv/AlreadyAsleepjhippo4j-discovery/src/main/java/cn/hippo4j/discovery/core/Lease.java0 /* * 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 cn.hippo4j.discovery.core; /** * Lease. * * @author chen.ma * @date 2021/8/8 22:49 */ public class Lease { enum Action { /** * REGISTER */ REGISTER, /** * CANCEL */ CANCEL, /** * RENEW */ RENEW } private T holder; private long evictionTimestamp; private long registrationTimestamp; private long serviceUpTimestamp; /** * Make it volatile so that the expiration task would see this quicker */ private volatile long lastUpdateTimestamp; private long duration; public static final int DEFAULT_DURATION_IN_SECS = 90; public Lease(T r) { holder = r; registrationTimestamp = System.currentTimeMillis(); lastUpdateTimestamp = registrationTimestamp; duration = DEFAULT_DURATION_IN_SECS * 1000; } public void renew() { lastUpdateTimestamp = System.currentTimeMillis() + duration; } public void cancel() { if (evictionTimestamp <= 0) { evictionTimestamp = System.currentTimeMillis(); } } public void serviceUp() { if (serviceUpTimestamp == 0) { serviceUpTimestamp = System.currentTimeMillis(); } } public void setServiceUpTimestamp(long serviceUpTimestamp) { this.serviceUpTimestamp = serviceUpTimestamp; } public boolean isExpired() { return isExpired(0L); } public boolean isExpired(long additionalLeaseMs) { return (evictionTimestamp > 0 || System.currentTimeMillis() > (lastUpdateTimestamp + duration + additionalLeaseMs)); } public long getRegistrationTimestamp() { return registrationTimestamp; } public long getLastRenewalTimestamp() { return lastUpdateTimestamp; } public long getEvictionTimestamp() { return evictionTimestamp; } public long getServiceUpTimestamp() { return serviceUpTimestamp; } public T getHolder() { return holder; } } /******************************************************************************* * Copyright 2010-2011 , Topic Maps Lab * * 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.topicmapslab.aranuka.connectors; import java.util.Map; import java.util.Properties; import de.topicmapslab.aranuka.Configuration; public abstract class AbstractEngineConnector implements IEngineConnector { /** * Properties object. */ private Properties properties; /** * Configuration object. */ private Configuration configuration; /** * {@inheritDoc} */ public void setProperty(String propertyKey, String propertyValue) { if(this.properties == null) this.properties = new Properties(); this.properties.put(propertyKey, propertyValue); } public void setConfiguration(Configuration configuration) { this.configuration = configuration; } /** * {@inheritDoc} */ public String getProperty(String key){ if(this.properties == null) return configuration.getProperty(key); String result = (String) this.properties.get(key); if (result==null) return configuration.getProperty(key); return result; } /** * {@inheritDoc} */ public void setProperties(Properties properties) { this.properties = properties; } /** * Returns the properties. * @return Properties object. */ protected Properties getProperties() { if (properties==null) properties = new Properties(); return properties; } /** * Returns the prefix map. * @return Prefix map object. */ protected Map getPrefixMap() { return configuration.getPrefixMap(); } protected String getJDBCDriver(String dbms) { if ("h2".equals(dbms)) return "org.h2.Driver"; if ("postgresql".equals(dbms)) return "org.postgresql.Driver"; if ("mysql".equals(dbms)) return "com.mysql.jdbc.Driver"; throw new IllegalArgumentException("Unknown DB String"); } public void clearTopicMap(org.tmapi.core.TopicMap topicMap) { }; } kafka/src/main/java/fr/marissel/kafka/domain/Subject.java package fr.marissel.kafka.domain; public enum Subject { MATHEMATICS, HISTORY, ENGLISH, PHILOSOPHY; } src/main/java/dev/zihasz/clientbase/util/utils/ReflectionUtils.java package dev.zihasz.clientbase.util.utils; import dev.zihasz.clientbase.util.Util; import org.reflections.Reflections; import java.util.Set; public class ReflectionUtils extends Util { public static Set findClasses(String pack, Class subType) { Reflections reflections = new Reflections(pack); return reflections.getSubTypesOf(subType); } } 0 package primitivo.iterate; import java.util.Iterator; import java.util.NoSuchElementException; /** * Iterator of unboxed {@code char} values. * * @author * * @see primitivo.iterate */ public abstract class CharIterator implements Iterator { /** * Returns the unboxed {@code char} of the value that * {@link #next()} would have returned * if it had been called instead. * * @return The next {@code char} value in the iteration. */ public abstract char nextChar(); /** * @return The next {@link Character} value in the iteration. * This value is never null. */ //@Override public Character next() { return nextChar(); } //@Override public void remove() { throw new UnsupportedOperationException(); } public static final CharIterator EMPTY = new CharIterator() { //@Override public boolean hasNext() { return false; } @Override public char nextChar() { throw new NoSuchElementException(); } @Override public void remove() { throw new IllegalStateException(); } }; public static CharIterator of(Iterator iterator) { // Causes null value to result in a null pointer exception. return of(iterator, null); } public static CharIterator of(final Iterator iterator, final Character nullValue) { if (iterator == null) { throw new NullPointerException("iterator"); } if (!iterator.hasNext()) { return EMPTY; } if (iterator instanceof CharIterator) { return (CharIterator) iterator; } return new CharIterator() { //@Override public boolean hasNext() { return iterator.hasNext(); } @Override public char nextChar() { return next(); } @Override public Character next() { Character current = iterator.next(); if (current != null) { return current; } if (nullValue == null) { // Ensure that `next` and `nextChar` behave identically. throw new NullPointerException("current"); } return nullValue; } @Override public void remove() { iterator.remove(); } }; } public static CharIterator of(final char value) { return new CharIterator() { private boolean hasNext = true; //@Override public boolean hasNext() { return hasNext; } @Override public char nextChar() { if (!hasNext()) { throw new NoSuchElementException(); } hasNext = false; return value; } }; } public static CharIterator of(final char... values) { if (values == null) { throw new NullPointerException("values"); } if (values.length == 0) { return EMPTY; } return new CharIterator() { private int index = 0; //@Override public boolean hasNext() { return index < values.length; } @Override public char nextChar() { if (!hasNext()) { throw new NoSuchElementException(); } return values[index++]; } }; } public static CharIterator range(final char from, final char to) { if (from >= to) { return EMPTY; } return new CharIterator() { private char current = from; //@Override public boolean hasNext() { return current < to; } @Override public char nextChar() { if (!hasNext()) { throw new NoSuchElementException(); } return current++; } }; } } 1-10 /* First created by JCasGen Tue Sep 03 12:34:17 CEST 2019 */ package de.julielab.jcore.types.pubmed; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.jcas.cas.FSArray; import org.apache.uima.jcas.cas.TOP_Type; /** The special Header for PubMed (http://www.pubmed.org) documents * Updated by JCasGen Tue Sep 03 12:34:17 CEST 2019 * XML source: all-test-types.xml * @generated */ public class Header extends de.julielab.jcore.types.Header { /** @generated * @ordered */ @SuppressWarnings ("hiding") public final static int typeIndexID = JCasRegistry.register(Header.class); /** @generated * @ordered */ @SuppressWarnings ("hiding") public final static int type = typeIndexID; /** @generated * @return index of the type */ @Override public int getTypeIndexID() {return typeIndexID;} /** Never called. Disable default constructor * @generated */ protected Header() {/* intentionally empty block */} /** Internal - constructor used by generator * @generated * @param addr low level Feature Structure reference * @param type the type of this Feature Structure */ public Header(int addr, TOP_Type type) { super(addr, type); readObject(); } /** @generated * @param jcas JCas to which this Feature Structure belongs */ public Header(JCas jcas) { super(jcas); readObject(); } /** @generated * @param jcas JCas to which this Feature Structure belongs * @param begin offset to the begin spot in the SofA * @param end offset to the end spot in the SofA */ public Header(JCas jcas, int begin, int end) { super(jcas); setBegin(begin); setEnd(end); readObject(); } /** * * Write your own initialization here * * * @generated modifiable */ private void readObject() {/*default - does nothing empty block */} //*--------------* //* Feature: citationStatus /** getter for citationStatus - gets Indicates the status of citation of a PubMed document * @generated * @return value of the feature */ public String getCitationStatus() { if (Header_Type.featOkTst && ((Header_Type)jcasType).casFeat_citationStatus == null) jcasType.jcas.throwFeatMissing("citationStatus", "de.julielab.jcore.types.pubmed.Header"); return jcasType.ll_cas.ll_getStringValue(addr, ((Header_Type)jcasType).casFeatCode_citationStatus);} /** setter for citationStatus - sets Indicates the status of citation of a PubMed document * @generated * @param v value to set into the feature */ public void setCitationStatus(String v) { if (Header_Type.featOkTst && ((Header_Type)jcasType).casFeat_citationStatus == null) jcasType.jcas.throwFeatMissing("citationStatus", "de.julielab.jcore.types.pubmed.Header"); jcasType.ll_cas.ll_setStringValue(addr, ((Header_Type)jcasType).casFeatCode_citationStatus, v);} //*--------------* //* Feature: otherIDs /** getter for otherIDs - gets Other IDs (then the PubMed ID) may delivered by partners of the NLM to PubMed/Medline abstracts. If available, this feature discloses such other IDs and the respective sources. * @generated * @return value of the feature */ public FSArray getOtherIDs() { if (Header_Type.featOkTst && ((Header_Type)jcasType).casFeat_otherIDs == null) jcasType.jcas.throwFeatMissing("otherIDs", "de.julielab.jcore.types.pubmed.Header"); return (FSArray)(jcasType.ll_cas.ll_getFSForRef(jcasType.ll_cas.ll_getRefValue(addr, ((Header_Type)jcasType).casFeatCode_otherIDs)));} /** setter for otherIDs - sets Other IDs (then the PubMed ID) may delivered by partners of the NLM to PubMed/Medline abstracts. If available, this feature discloses such other IDs and the respective sources. * @generated * @param v value to set into the feature */ public void setOtherIDs(FSArray v) { if (Header_Type.featOkTst && ((Header_Type)jcasType).casFeat_otherIDs == null) jcasType.jcas.throwFeatMissing("otherIDs", "de.julielab.jcore.types.pubmed.Header"); jcasType.ll_cas.ll_setRefValue(addr, ((Header_Type)jcasType).casFeatCode_otherIDs, jcasType.ll_cas.ll_getFSRef(v));} /** indexed getter for otherIDs - gets an indexed value - Other IDs (then the PubMed ID) may delivered by partners of the NLM to PubMed/Medline abstracts. If available, this feature discloses such other IDs and the respective sources. * @generated * @param i index in the array to get * @return value of the element at index i */ public OtherID getOtherIDs(int i) { if (Header_Type.featOkTst && ((Header_Type)jcasType).casFeat_otherIDs == null) jcasType.jcas.throwFeatMissing("otherIDs", "de.julielab.jcore.types.pubmed.Header"); jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((Header_Type)jcasType).casFeatCode_otherIDs), i); return (OtherID)(jcasType.ll_cas.ll_getFSForRef(jcasType.ll_cas.ll_getRefArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((Header_Type)jcasType).casFeatCode_otherIDs), i)));} /** indexed setter for otherIDs - sets an indexed value - Other IDs (then the PubMed ID) may delivered by partners of the NLM to PubMed/Medline abstracts. If available, this feature discloses such other IDs and the respective sources. * @generated * @param i index in the array to set * @param v value to set into the array */ public void setOtherIDs(int i, OtherID v) { if (Header_Type.featOkTst && ((Header_Type)jcasType).casFeat_otherIDs == null) jcasType.jcas.throwFeatMissing("otherIDs", "de.julielab.jcore.types.pubmed.Header"); jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((Header_Type)jcasType).casFeatCode_otherIDs), i); jcasType.ll_cas.ll_setRefArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((Header_Type)jcasType).casFeatCode_otherIDs), i, jcasType.ll_cas.ll_getFSRef(v));} } package mar.paths.stemming; import javax.annotation.Nonnull; /** * Tokenizes based on camel case, it is copied from: * * https://stackoverflow.com/questions/2559759/how-do-i-convert-camelcase-into-human-readable-names-in-java * * See test case CamelCaseTokenizerTest. * * It also handles spaces, but it is probably not as good as {@link WhitespaceTokenizer} for that. * * @author jesus * */ public class CamelCaseTokenizer implements ITokenizer { public static final CamelCaseTokenizer INSTANCE = new CamelCaseTokenizer(); @Override public String[] tokenize(@Nonnull String word) { String[] result = (word.replaceAll("[^a-zA-Z0-9]", " ")).replaceAll( String.format("%s|%s|%s", "(?<=[A-Z])(?=[A-Z][a-z])", "(?<=[^A-Z])(?=[A-Z])", "(?<=[A-Za-z])(?=[^A-Za-z])" ), " " ).split("\\s+"); String[] newArray = new String[result.length]; int i = 0; for (String string : result) { newArray[i] = string.toLowerCase(); i++; } return newArray; } } shiv4nsh/dl4j-examples package org.deeplearning4j.utils; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IOUtils; import org.deeplearning4j.api.storage.StatsStorage; import org.deeplearning4j.ui.api.UIServer; import org.deeplearning4j.ui.storage.FileStatsStorage; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; /** * @Description: showing the training stats * @author wangfeng */ public class ShowData2UIServer { private static final boolean hdfsPath = false; public static void main(String[] args) throws Exception{ //load the data saved, and then it'll be showed ,in the browser:http://localhost:9000 File statsFile = null; if (hdfsPath) { statsFile = File.createTempFile("tmp", "dl4j"); OutputStream os = new FileOutputStream(statsFile); FileSystem fs = CommonUtils.openHdfsConnect(); InputStream in = fs.open(new Path("/user/hadoop/trainlog/AnimalModelByHdfsTrainingStatsSpark2.dl4j")); IOUtils.copyBytes(in, os, 4096, false); //复制到标准输出流 IOUtils.closeStream(in); CommonUtils.closeHdfsConnect(fs); os.close(); } else { statsFile = new File("/home/AnimalModelByHdfsTrainingStats1.dl4j"); } StatsStorage statsStorage = new FileStatsStorage(statsFile); UIServer uiServer = UIServer.getInstance(); uiServer.attach(statsStorage); } } caroldf07/grpc-kotlin // Generated by the protocol buffer compiler. DO NOT EDIT! // source: grpcKotlin.proto package br.com.zup; public interface FuncionarioResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:br.com.zup.FuncionarioResponse) com.google.protobuf.MessageOrBuilder { /** * string nome = 1; * @return The nome. */ java.lang.String getNome(); /** * string nome = 1; * @return The bytes for nome. */ com.google.protobuf.ByteString getNomeBytes(); /** * .google.protobuf.Timestamp criadoEm = 2; * @return Whether the criadoEm field is set. */ boolean hasCriadoEm(); /** * .google.protobuf.Timestamp criadoEm = 2; * @return The criadoEm. */ com.google.protobuf.Timestamp getCriadoEm(); /** * .google.protobuf.Timestamp criadoEm = 2; */ com.google.protobuf.TimestampOrBuilder getCriadoEmOrBuilder(); } F7ionsy/nybike package cn.tedu.nybike.pojo; import java.util.Arrays; public class demo4VO { private Integer[][] yData; public Integer[][] getyData() { return yData; } public void setyData(Integer[][] yData) { this.yData = yData; } @Override public String toString() { return "demo4VO [yData=" + Arrays.toString(yData) + "]"; } public demo4VO(Integer[][] yData) { super(); this.yData = yData; } public demo4VO() { super(); // TODO Auto-generated constructor stub } } package com.andremanuelbarbosa.euromillions.predictor.domain; import java.util.List; public class Number extends Item { private static final double AVERAGE_INTERVAL = 10.0; public static final int COUNT = 50; public Number(int id, int interval, double relativeFreq, List intervals) { super(id, ItemType.NUMBER, interval, relativeFreq, intervals); } @Override public double getAverageInterval() { return AVERAGE_INTERVAL; } } package com.burakgomec.shoppingapplication.Fragments; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.burakgomec.shoppingapplication.RecyclerAdapters.ProductRecyclerAdapter; import com.burakgomec.shoppingapplication.R; public class HomeFragment extends Fragment { //Vitrin Anasayfası RecyclerView recyclerView; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.home_fragment,container,false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); recyclerView = view.findViewById(R.id.recyclerViewProducts); ProductRecyclerAdapter productRecyclerAdapter = new ProductRecyclerAdapter(view.getContext()); recyclerView.setLayoutManager(new GridLayoutManager(view.getContext(),2)); recyclerView.setAdapter(productRecyclerAdapter); } } public class MultAndDivide { public static void main(String[] args) { double subtotal = 30; double tax = 0.0875; // Create variable that holds subtotal plus the product of subtotal and tax. double total = subtotal + (subtotal * tax); // print total System.out.println(total); // Create Variable that holds total divided by 4. double perPerson = total / 4; // print perPerson System.out.println(perPerson); } }package com.bt.pi.core.routing; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.*; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import com.bt.pi.core.routing.RoutingMessageRedirector; import rice.environment.Environment; import rice.environment.logging.LogManager; import rice.environment.logging.Logger; import rice.pastry.routing.RouteMessage; import rice.pastry.Id; import rice.pastry.NodeHandle; import rice.pastry.PastryNode; import rice.pastry.routing.Router; public class RoutingMessageRedirectorTest { private PastryNode pastryNode; private Router router; private Id id; private Logger logger; private LogManager logManager; private Environment environment; private RouteMessage routeMessage; private RoutingMessageRedirector routingMessageRedirector; private NodeHandle nodeHandle; @Before public void before() { id = Id.build("moo"); nodeHandle = mock(NodeHandle.class); List routingCandidateList = new ArrayList(); routingCandidateList.add(nodeHandle); router = mock(Router.class); when(router.getBestRoutingCandidates(id)).thenReturn(routingCandidateList.iterator()); logger = mock(Logger.class); logManager = mock(LogManager.class); when(logManager.getLogger(isA(Class.class), isA(String.class))).thenReturn(logger); environment = mock(Environment.class); when(environment.getLogManager()).thenReturn(logManager); pastryNode = mock(PastryNode.class); when(pastryNode.getEnvironment()).thenReturn(environment); when(pastryNode.getRouter()).thenReturn(router); routeMessage = mock(RouteMessage.class); this.routingMessageRedirector = new RoutingMessageRedirector(pastryNode); } @Test public void shouldUpdateRouteMessageOnRedirect() { // act routingMessageRedirector.reroute(routeMessage, id); // assert verify(routeMessage).setDestinationId(id); verify(routeMessage).setNextHopHandle(nodeHandle); } } killers/nokia/com.evenwell.powersaving.g3/sources/com/evenwell/powersaving/g3/dataconnection/DataConnectionUtils.java package com.evenwell.powersaving.g3.dataconnection; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences.Editor; import android.net.TrafficStats; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Handler; import android.os.Message; import android.os.PowerManager; import android.provider.Settings.System; import android.util.Log; import com.evenwell.powersaving.g3.C0321R; import com.evenwell.powersaving.g3.LpmDcUtils; import com.evenwell.powersaving.g3.PowerSavingUtils; import com.evenwell.powersaving.g3.p000e.doze.WifiTethering; import com.evenwell.powersaving.g3.powersaver.PowerSavingController.ScreeOnHandler; import com.evenwell.powersaving.g3.utils.PSConst.DC.DCPARM; import com.evenwell.powersaving.g3.utils.PSConst.DC.DCPARM.ALARMTYPE; import com.evenwell.powersaving.g3.utils.PSConst.DC.DCPREF; import com.evenwell.powersaving.g3.utils.PSConst.DC.INTENT.ACTION; import com.evenwell.powersaving.g3.utils.PSConst.DC.INTENT.EXTRA; import com.evenwell.powersaving.g3.utils.PSConst.DC.TIME.VALUE; import com.evenwell.powersaving.g3.utils.PSConst.FILENAME; import com.evenwell.powersaving.g3.utils.PSConst.SETTINGDB.DCDB; import com.evenwell.powersaving.g3.utils.PSConst.SS.SSPARM; import com.evenwell.powersaving.g3.utils.PSConst.SWITCHER; import com.evenwell.powersaving.g3.utils.PSConst.SYMBOLS; import com.evenwell.powersaving.g3.utils.PSConst.TAG; import java.util.Calendar; public class DataConnectionUtils { private static final boolean DBG = true; private static String TAG = TAG.PSLOG; private static boolean isPostDelayExist = false; public static final BroadcastReceiver mScreenOffReceiver = new C03442(); /* renamed from: com.evenwell.powersaving.g3.dataconnection.DataConnectionUtils$2 */ static class C03442 extends BroadcastReceiver { C03442() { } public void onReceive(Context context, Intent intent) { if (intent.getAction().equals("android.intent.action.BATTERY_CHANGED")) { int mPlugged = intent.getIntExtra("plugged", -1); int mStatus = intent.getIntExtra("status", -1); boolean mTetheringState = PowerSavingUtils.getTetherState(context); boolean mWifiState = DataConnectionUtils.isWifiAPEnabled(context); Log.i(DataConnectionUtils.TAG, "[DataConnectionUtils] Battery plugged is: " + mPlugged); Log.i(DataConnectionUtils.TAG, "[DataConnectionUtils] Battery status is: " + mStatus); Log.i(DataConnectionUtils.TAG, "[DataConnectionUtils] Tether state: " + PowerSavingUtils.getTetherState(context)); Log.i(DataConnectionUtils.TAG, "[DataConnectionUtils] WifiAP state: " + DataConnectionUtils.isWifiAPEnabled(context)); if (mPlugged != 1 && mPlugged != 2 && mPlugged != 4) { if (DataConnectionUtils.getPostDelayExist()) { DataConnectionUtils.unregisterScreenOffReceiver(context); } DataConnectionUtils.setPostDelayExist(false); } else if (mStatus == 2 || mStatus == 5 || mTetheringState || mWifiState) { DataConnectionUtils.stopPacketDetect(); DataConnectionUtils.stoplistenWakeup(); if (DataConnectionUtils.getPostDelayExist()) { DataConnectionUtils.unregisterScreenOffReceiver(context); } DataConnectionUtils.setPostDelayExist(false); } } } } public enum WIFI_AP_STATE { WIFI_AP_STATE_DISABLING, WIFI_AP_STATE_DISABLED, WIFI_AP_STATE_ENABLING, WIFI_AP_STATE_ENABLED, WIFI_AP_STATE_FAILED } public static class listenWakeupThread implements Runnable { Context context; long currentTime = 0; Handler handler; int period; long preCurrentTime = 0; public listenWakeupThread(Context context, Handler handler, int period) { this.period = period; this.handler = handler; this.context = context; this.preCurrentTime = System.currentTimeMillis(); } public void run() { if (DataConnectionUtils.isDataEnabled(this.context) || PowerSavingUtils.GetWiFiEnableByDB(this.context)) { this.currentTime = System.currentTimeMillis(); if (this.currentTime - this.preCurrentTime >= 30000) { Log.i(DataConnectionUtils.TAG, "[DataConnectionUtils] listenWakeupThread-system wakeup so disable ALLPDP"); Log.i(DataConnectionUtils.TAG, "[DataConnectionUtils] sleep time: " + Long.toString(this.currentTime - this.preCurrentTime)); DataConnectionUtils.DisableAllPDP(this.context); DataConnectionUtils.saveIntToPref(this.context, DCPREF.TXPACK, 0); DataConnectionUtils.saveIntToPref(this.context, DCPREF.RXPACK, 0); return; } this.preCurrentTime = this.currentTime; this.handler.postDelayed(this, (long) this.period); } } } public static class packetDetectThread implements Runnable { Context context; Handler handler; int period; public packetDetectThread(Context context, Handler handler, int period) { this.period = period; this.handler = handler; this.context = context; DataConnectionUtils.saveIntToPref(context, DCPREF.TXPACK, 0); DataConnectionUtils.saveIntToPref(context, DCPREF.RXPACK, 0); } public void run() { if (DataConnectionUtils.isDataEnabled(this.context) || PowerSavingUtils.GetWiFiEnableByDB(this.context)) { Log.i(DataConnectionUtils.TAG, "[DataConnectionUtils] packetDetectThread-mobile or wifi still enable !!"); if (!DataConnectionUtils.disableConnection(this.context)) { this.handler.postDelayed(this, (long) this.period); return; } return; } Log.i(DataConnectionUtils.TAG, "[DataConnectionUtils] packetDetectThread-mobile and wifi disable !!"); } } public static boolean isInTimeInterval(Context context, String nowTime) { String mStartTime = PowerSavingUtils.getStringItemFromDB(context, DCDB.PW_DATA_STARTTIME); String mEndTime = PowerSavingUtils.getStringItemFromDB(context, DCDB.PW_DATA_ENDTIME); int mStartTime_hour = Integer.valueOf(mStartTime.substring(0, 2)).intValue(); int mStartTime_min = Integer.valueOf(mStartTime.substring(3)).intValue(); int mEndTime_hour = Integer.valueOf(mEndTime.substring(0, 2)).intValue(); int mEndTime_min = Integer.valueOf(mEndTime.substring(3)).intValue(); int mNowTime_hour = Integer.valueOf(nowTime.substring(0, 2)).intValue(); int mNowTime_min = Integer.valueOf(nowTime.substring(3)).intValue(); Log.i(TAG, "mStartTime_hour: " + mStartTime_hour + " || mStartTime_min: " + mStartTime_min); Log.i(TAG, "mEndTime_hour: " + mEndTime_hour + " || mEndTime_min: " + mEndTime_min); Log.i(TAG, "mNowTime_hour: " + mNowTime_hour + " || mNowTime_min: " + mNowTime_min); if (mStartTime_hour > mEndTime_hour) { if (mStartTime_hour - mNowTime_hour > 0 && mEndTime_hour - mNowTime_hour > 0) { return true; } if (mStartTime_hour - mNowTime_hour > 0 && mEndTime_hour - mNowTime_hour < 0) { return false; } if (mStartTime_hour - mNowTime_hour < 0 && mEndTime_hour - mNowTime_hour < 0) { return true; } if (mStartTime_hour - mNowTime_hour != 0 || mEndTime_hour - mNowTime_hour >= 0) { if (mStartTime_hour - mNowTime_hour > 0 && mEndTime_hour - mNowTime_hour == 0) { if (mStartTime_min - mNowTime_min >= 0) { return true; } if (mStartTime_min - mNowTime_min < 0) { return true; } } } else if (mStartTime_min - mNowTime_min > 0) { return false; } else { if (mStartTime_min - mNowTime_min <= 0) { return true; } } } else if (mStartTime_hour == mEndTime_hour) { if (mStartTime_hour - mNowTime_hour != 0) { return false; } if (mStartTime_min > mEndTime_min) { if (mStartTime_min - mNowTime_min > 0 && mEndTime_min - mNowTime_min > 0) { return true; } if (mStartTime_min - mNowTime_min < 0 && mEndTime_min - mNowTime_min < 0) { return true; } if (mStartTime_min - mNowTime_min > 0 && mEndTime_min - mNowTime_min == 0) { return false; } if (mStartTime_min - mNowTime_min == 0 && mEndTime_min - mNowTime_min < 0) { return true; } if (mStartTime_min - mNowTime_min > 0 && mEndTime_min - mNowTime_min < 0) { return false; } } else if (mStartTime_min == mEndTime_min) { if (mStartTime_min - mNowTime_min == 0) { return true; } } else if (mStartTime_min - mNowTime_min > 0 && mEndTime_min - mNowTime_min > 0) { return false; } else { if (mStartTime_min - mNowTime_min < 0 && mEndTime_min - mNowTime_min < 0) { return false; } if (mStartTime_min - mNowTime_min < 0 && mEndTime_min - mNowTime_min > 0) { return true; } if (mStartTime_min - mNowTime_min == 0 && mEndTime_min - mNowTime_min > 0) { return true; } if (mStartTime_min - mNowTime_min < 0 && mEndTime_min - mNowTime_min == 0) { return false; } } } else if (mStartTime_hour - mNowTime_hour > 0 && mEndTime_hour - mNowTime_hour > 0) { return false; } else { if (mStartTime_hour - mNowTime_hour < 0 && mEndTime_hour - mNowTime_hour > 0) { return true; } if (mStartTime_hour - mNowTime_hour < 0 && mEndTime_hour - mNowTime_hour < 0) { return false; } if (mStartTime_hour - mNowTime_hour >= 0 || mEndTime_hour - mNowTime_hour != 0) { if (mStartTime_hour - mNowTime_hour == 0 && mEndTime_hour - mNowTime_hour > 0) { if (mStartTime_min - mNowTime_min > 0) { return false; } if (mStartTime_min - mNowTime_min <= 0) { return true; } } } else if (mEndTime_min - mNowTime_min > 0) { return true; } else { if (mEndTime_min - mNowTime_min <= 0) { return false; } } } return false; } public static String getNowTime() { Calendar calendar = Calendar.getInstance(); String mHour = String.valueOf(calendar.get(11)); String mMinuts = String.valueOf(calendar.get(12)); if (mHour.length() < 2) { mHour = SYMBOLS.ZERO + mHour; } if (mMinuts.length() < 2) { mMinuts = SYMBOLS.ZERO + mMinuts; } return mHour + ":" + mMinuts; } public static void SetSettingsToPhoneForRestore(Context mContext) { LpmDcUtils.WiFiAndMobileDataRestore(mContext, 2); LpmDcUtils.SetLpmOrDcApplyStatus(mContext, 2, false); if (LpmDcUtils.IsLPMApply(mContext)) { LpmDcUtils.NotifyLpmOrDc(mContext, 1); } } public static void screenOnAction(Context context, final ScreeOnHandler mHandler) { new Thread() { public void run() { Log.i(DataConnectionUtils.TAG, "[DataConnectionUtils] screenOnAction_()"); Message message = new Message(); message.what = DCPARM.SCREENON_MESSAGE; mHandler.sendMessage(message); } }.start(); } public static void screenOnActionHandler(Context context) { Log.i(TAG, "[DataConnectionUtils] screenOnActionHandler()"); stopPacketDetect(); stoplistenWakeup(); if (getPostDelayExist()) { unregisterScreenOffReceiver(context); } setPostDelayExist(false); Log.i(TAG, "Receive screen on intent, restore network state !!"); if (LpmDcUtils.IsDCApply(context)) { SetSettingsToPhoneForRestore(context); } saveIntToPref(context, DCPREF.TXPACK, 0); saveIntToPref(context, DCPREF.RXPACK, 0); } public static void screenOffAction(Context context) { Log.i(TAG, "[DataConnectionUtils] screenOffAction()"); if (isDataEnabled(context) || PowerSavingUtils.GetWiFiEnableByDB(context)) { Log.i(TAG, "[DataConnectionUtils] Have data connection: mobile status: " + isDataEnabled(context) + "|| wifi status is: " + PowerSavingUtils.GetWiFiEnableByDB(context)); String detectTime = PowerSavingUtils.getStringItemFromDB(context, DCDB.PW_DATA_DETECTTIME); if (detectTime == null) { detectTime = context.getResources().getString(C0321R.string.powersaving_db_dc_detect_time); } startPacketDetect(context, DataConnection.handler, Integer.valueOf(detectTime).intValue()); startlistenWakeup(context, DataConnection.handler, VALUE.DETECT_WAKE_UP_TIME); registerScreenOffReceiver(context); setPostDelayExist(true); return; } Log.i(TAG, "[DataConnectionUtils] No data connection"); if (LpmDcUtils.IsLPMApply(context)) { LpmDcUtils.SetLpmOrDcApplyStatus(context, 2, true); saveToPref(context, DCPREF.MOBILE, isDataEnabled(context)); saveToPref(context, DCPREF.WIFI, PowerSavingUtils.GetWiFiEnableByDB(context)); return; } Log.i(TAG, "[DataConnectionUtils] No data connection [user choose]"); } public static boolean isDataEnabled(Context context) { return PowerSavingUtils.GetMobileDataEnable(context); } public static boolean isWiFiEnable(Context context) { WifiManager mWifiManager = (WifiManager) context.getSystemService(SSPARM.WIFI); WifiInfo wifiInfo = mWifiManager.getConnectionInfo(); int ipAddress = wifiInfo == null ? 0 : wifiInfo.getIpAddress(); if (!mWifiManager.isWifiEnabled() || ipAddress == 0) { return false; } return true; } public static boolean disableConnection(Context context) { Log.i(TAG, "[DataConnectionUtils] disableConnection()"); long preTxPkts = (long) getIntFromPref(context, DCPREF.TXPACK); long preRxPkts = (long) getIntFromPref(context, DCPREF.RXPACK); long txPkts = TrafficStats.getTotalTxPackets(); long rxPkts = TrafficStats.getTotalRxPackets(); Log.i(TAG, "[DataConnectionUtils] disableConnection()tx_pkts: " + txPkts + "||rxPkts: " + rxPkts); Log.i(TAG, "[DataConnectionUtils] disableConnection()preTxPkts: " + preTxPkts + "||preRxPkts: " + preRxPkts); saveIntToPref(context, DCPREF.TXPACK, (int) txPkts); saveIntToPref(context, DCPREF.RXPACK, (int) rxPkts); if (txPkts - preTxPkts > 0 || rxPkts - preRxPkts > 0) { Log.i(TAG, "[DataConnectionUtils] disableConnection() - has packet transfer"); return false; } Log.i(TAG, "[DataConnectionUtils] disableConnection() - no packet transfer"); DisableAllPDP(context); saveIntToPref(context, DCPREF.TXPACK, 0); saveIntToPref(context, DCPREF.RXPACK, 0); return true; } public static void DisableAllPDP(Context context) { if (getPostDelayExist()) { unregisterScreenOffReceiver(context); } setPostDelayExist(false); Log.i(TAG, "[DataConnectionUtils] DisableAllPDP-in DCTime"); LpmDcUtils.SetLpmOrDcApplyStatus(context, 2, true); saveToPref(context, DCPREF.MOBILE, isDataEnabled(context)); saveToPref(context, DCPREF.WIFI, PowerSavingUtils.GetWiFiEnableByDB(context)); if (isDataEnabled(context) && PowerSavingUtils.GetWiFiEnableByDB(context)) { setMobileDataEnabled(context, false); setWifiEnable(context, false); } else if (isDataEnabled(context) && !PowerSavingUtils.GetWiFiEnableByDB(context)) { setMobileDataEnabled(context, false); } else if (!isDataEnabled(context) && PowerSavingUtils.GetWiFiEnableByDB(context)) { setWifiEnable(context, false); } } public static void setWifiEnable(Context context, boolean value) { boolean mWifi = false; if (value) { mWifi = true; } Log.i(TAG, "[DataConnectionUtils] Turn Wifi: " + mWifi); WifiManager mWifiManager = (WifiManager) context.getSystemService(SSPARM.WIFI); boolean desiredState = mWifi; if (desiredState && !isRadioAllowed(context, SSPARM.WIFI)) { Log.i(TAG, "Mobile in airplane mode!!"); } if (mWifiManager != null) { int wifiApState = mWifiManager.getWifiApState(); if (desiredState && (wifiApState == 12 || wifiApState == 13)) { try { new WifiTethering(context).setTethering(false); } catch (Exception e) { Log.i(TAG, "[DataConnectionUtils] setWifiApEnabled() failed."); e.printStackTrace(); } } mWifiManager.setWifiEnabled(desiredState); } } public static boolean isRadioAllowed(Context mContext, String type) { if (!isAirplaneModeOn(mContext)) { return true; } String toggleable = System.getString(mContext.getContentResolver(), "airplane_mode_toggleable_radios"); if (toggleable == null || !toggleable.contains(type)) { return false; } return true; } public static boolean isAirplaneModeOn(Context mContext) { return System.getInt(mContext.getContentResolver(), "airplane_mode_on", 0) != 0; } public static void setMobileDataEnabled(Context context, boolean enabled) { Log.i(TAG, "[DataConnectionUtils] Turn mobile data: " + enabled); PowerSavingUtils.SetMobileDataEnable(context, enabled); } public static void saveToPref(Context context, String type, boolean mState) { Editor editor = context.getSharedPreferences(FILENAME.PREF_POWER_SAVING_DATA_CONNECTION_FILE, 0).edit(); editor.putBoolean(type, mState); editor.commit(); } public static boolean getFromPref(Context context, String type) { return context.getSharedPreferences(FILENAME.PREF_POWER_SAVING_DATA_CONNECTION_FILE, 0).getBoolean(type, false); } public static void saveIntToPref(Context context, String key, int value) { Editor editor = context.getSharedPreferences(FILENAME.PREF_POWER_SAVING_DATA_CONNECTION_FILE, 0).edit(); editor.putInt(key, value); editor.commit(); } public static int getIntFromPref(Context context, String key) { return context.getSharedPreferences(FILENAME.PREF_POWER_SAVING_DATA_CONNECTION_FILE, 0).getInt(key, 0); } public static boolean isScreenOnorOff(Context context) { return ((PowerManager) context.getSystemService("power")).isScreenOn(); } public static boolean checkAlwaysOnOrNot(Context context) { if (PowerSavingUtils.getStringItemFromDB(context, DCDB.PW_DATA_ALWAYSON).equals(SWITCHER.ON)) { return true; } return false; } public static void setStartOrEndAlarm(Context context, String alarm_type) { int mHour; int mMin; Calendar calendar = Calendar.getInstance(); AlarmManager alarmmanager = (AlarmManager) context.getSystemService("alarm"); Intent intent = new Intent(ACTION.ACTION_DC_APPLY_TIME); intent.putExtra(EXTRA.TIME_KEY, alarm_type); if (alarm_type.equals(ALARMTYPE.START)) { String mStartTime = PowerSavingUtils.getStringItemFromDB(context, DCDB.PW_DATA_STARTTIME); mHour = Integer.valueOf(mStartTime.substring(0, 2)).intValue(); mMin = Integer.valueOf(mStartTime.substring(3)).intValue(); } else { String mEndTime = PowerSavingUtils.getStringItemFromDB(context, DCDB.PW_DATA_ENDTIME); mHour = Integer.valueOf(mEndTime.substring(0, 2)).intValue(); mMin = Integer.valueOf(mEndTime.substring(3)).intValue(); } int nowSec = ((calendar.get(11) * 60) + calendar.get(12)) * 60; calendar.set(11, mHour); calendar.set(12, mMin); calendar.set(13, 0); int alarmSec = ((calendar.get(11) * 60) + calendar.get(12)) * 60; if (alarmSec <= nowSec) { calendar.add(5, 1); } if (alarm_type.equals(ALARMTYPE.START)) { Log.i(TAG, "[DataConnectionUtils] setStartOrEndAlarm() Set start alarm"); alarmmanager.setRepeating(0, calendar.getTimeInMillis(), 86400000, PendingIntent.getBroadcast(context, 3002, intent, 134217728)); } else { Log.i(TAG, "[DataConnectionUtils] setStartOrEndAlarm() Set end alarm"); AlarmManager alarmManager = alarmmanager; alarmManager.setRepeating(0, calendar.getTimeInMillis(), 86400000, PendingIntent.getBroadcast(context, 3003, intent, 134217728)); } Log.i(TAG, "[DataConnectionUtils] setStartOrEndAlarm()Now sec: " + nowSec + " || Alarm sec: " + alarmSec + " || Alarm time: " + calendar.getTime()); } public static void cancelStartOrEndAlarm(Context context, String alarm_type) { AlarmManager alarmmanager = (AlarmManager) context.getSystemService("alarm"); Intent alarm_intent = new Intent(ACTION.ACTION_DC_APPLY_TIME); if (alarm_type.equals(ALARMTYPE.START)) { alarmmanager.cancel(PendingIntent.getBroadcast(context, 3002, alarm_intent, 134217728)); } else { alarmmanager.cancel(PendingIntent.getBroadcast(context, 3003, alarm_intent, 134217728)); } } public static void checkScreenStateAndAction(Context context) { if (isScreenOnorOff(context)) { Log.i(TAG, "[DataConnectionUtils] checkScreenStateAndAction() Screen on, do nothing !!"); return; } Log.i(TAG, "[DataConnectionUtils] checkScreenStateAndAction() Screen off, ready to disconnect network !!"); screenOffAction(context); } public static void startPacketDetect(Context context, Handler handler, int period) { if (DataConnection.mPacketDetectThread == null) { DataConnection.mPacketDetectThread = new packetDetectThread(context, handler, period); } DataConnection.handler.removeCallbacks(DataConnection.mPacketDetectThread); DataConnection.handler.postDelayed(DataConnection.mPacketDetectThread, (long) period); } public static void stopPacketDetect() { if (DataConnection.mPacketDetectThread != null) { Log.i(TAG, "[DataConnectionUtils] mPacketDetectThread is not null"); DataConnection.handler.removeCallbacks(DataConnection.mPacketDetectThread); } DataConnection.mPacketDetectThread = null; } public static void startlistenWakeup(Context context, Handler handler, int period) { if (DataConnection.mListenWakeupThread == null) { DataConnection.mListenWakeupThread = new listenWakeupThread(context, handler, period); } DataConnection.handler.removeCallbacks(DataConnection.mListenWakeupThread); DataConnection.handler.postDelayed(DataConnection.mListenWakeupThread, (long) period); } public static void stoplistenWakeup() { if (DataConnection.mListenWakeupThread != null) { Log.i(TAG, "[DataConnectionUtils] mListenWakeupThread is not null"); DataConnection.handler.removeCallbacks(DataConnection.mListenWakeupThread); } DataConnection.mListenWakeupThread = null; } public static void registerScreenOffReceiver(Context ctx) { Log.i(TAG, "[DataConnectionUtils] registerScreenOffReceiver"); IntentFilter filter = new IntentFilter(); filter.addAction("android.intent.action.BATTERY_CHANGED"); ctx.registerReceiver(mScreenOffReceiver, filter); } public static void unregisterScreenOffReceiver(Context ctx) { Log.i(TAG, "[DataConnectionUtils] unregisterScreenOffReceiver"); try { if (mScreenOffReceiver != null) { ctx.unregisterReceiver(mScreenOffReceiver); } } catch (Exception e) { e.printStackTrace(); } } public static WIFI_AP_STATE getWifiAPState(Context mContext) { WifiManager mWifiManager = (WifiManager) mContext.getSystemService(SSPARM.WIFI); try { int tmp = ((Integer) mWifiManager.getClass().getMethod("getWifiApState", new Class[0]).invoke(mWifiManager, new Object[0])).intValue(); if (tmp > 10) { tmp -= 10; } return ((WIFI_AP_STATE[]) WIFI_AP_STATE.class.getEnumConstants())[tmp]; } catch (Exception e) { return WIFI_AP_STATE.WIFI_AP_STATE_FAILED; } } public static boolean isWifiAPEnabled(Context mContext) { return getWifiAPState(mContext) == WIFI_AP_STATE.WIFI_AP_STATE_ENABLED; } public static void setPostDelayExist(boolean isUse) { isPostDelayExist = isUse; } public static boolean getPostDelayExist() { return isPostDelayExist; } } RomuloCANunes/dals0 /* * This file is part of DALS - Distributed Artificial Life Simulation. * DALS is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Foobar is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with DALS. If not, see . */ package genetic.net; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.Socket; import java.net.UnknownHostException; /** * * @author romulo */ public class EnvironmentClient extends Thread { private Socket socket = null; private BufferedReader in = null; private PrintStream out = null; private String host; /** * Constructor * @param host */ public EnvironmentClient(String host) { this.host = host; } /** * The proccess to be run when started as a Thread */ public void run() { try { socket = new Socket(host, 9666); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintStream(socket.getOutputStream(), true); String line; while( (line = in.readLine()) != null) { System.out.print("c received: " + line); } System.out.println("client stopped listening"); } catch (UnknownHostException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } /** * Prints some string in this client (sends it to the server) * @param s */ public void print(String s) { System.out.print("c enviando: " + s); if(socket != null) { if(socket.isConnected()) { out.print(s); } else { System.out.println("c not connected."); } } else { System.out.println("c Socket is null."); } } /** * Prints something to this client (sends it to the server), adding a \n char * to the end of message, indicating the end of line * @param s */ public void println(String s) { print(s + "\n"); } /** * Closes this connection */ public void close() { if(socket != null) { if(socket.isConnected()) { try { socket.close(); } catch (IOException ex) { ex.printStackTrace(); } } } if( in != null ) { try { in.close(); } catch (IOException ex) { ex.printStackTrace(); } } if( out != null ) { out.close(); } } } mkrmpotic/SignMeApp package eu.signme.app.model; import com.google.gson.annotations.SerializedName; public class Signature { @SerializedName("user_id") private int userId; @SerializedName("user_name") private String userName; @SerializedName("user_status") private int status; @SerializedName("id") private int signatureId; public Signature(int userId) { this.userId = userId; } public int getIUserd() { return this.userId; } public void setUserId(int userId) { this.userId = userId; } public String getUserName() { return this.userName; } public void setUserName(String userName) { this.userName = userName; } public int getStatus() { return this.status; } public void setStatus(int status) { this.status = status; } public int getId() { return this.signatureId; } public void setId(int signatureId) { this.signatureId = signatureId; } @Override public boolean equals(Object object) { boolean isEqual = false; if (object != null && object instanceof Signature) { isEqual = (this.userId == ((Signature) object).userId); } return isEqual; } @Override public int hashCode() { return this.userId; } } package com.github.liachmodded.datapacks; import net.minecraft.server.command.ServerCommandSource; import net.minecraft.server.function.CommandFunction; public interface ExecutingFunctionManager { boolean isExecuting(); void execute(FunctionExecutionCallback callback, ServerCommandSource serverCommandSource_1, CommandFunction... function); } martintaraz/DBDataPublisherBot /* * Stationsdatenbereitstellung * An API providing master data for german railway stations by DB Station&Service AG. * * OpenAPI spec version: 2.2.01 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package io.github.martintaraz.dbdatapublisherbot.models.stations; import java.util.Objects; import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.github.martintaraz.dbdatapublisherbot.models.stations.Address; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * 3-S-Zentralen are 7/24 hours operating centers for german railway stations */ @ApiModel(description = "3-S-Zentralen are 7/24 hours operating centers for german railway stations") @javax.annotation.processing.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2018-12-07T20:50:44.823+01:00") public class SZentrale { @SerializedName("number") private Integer number = null; @SerializedName("name") private String name = null; @SerializedName("publicPhoneNumber") private String publicPhoneNumber = null; @SerializedName("address") private Address address = null; @SerializedName("publicFaxNumber") private String publicFaxNumber = null; @SerializedName("internalPhoneNumber") private String internalPhoneNumber = null; @SerializedName("internalFaxNumber") private String internalFaxNumber = null; @SerializedName("mobilePhoneNumber") private String mobilePhoneNumber = null; @SerializedName("email") private String email = null; public SZentrale number(Integer number) { this.number = number; return this; } /** * unique identifier for SZentrale * @return number **/ @ApiModelProperty(value = "unique identifier for SZentrale") public Integer getNumber() { return number; } public void setNumber(Integer number) { this.number = number; } public SZentrale name(String name) { this.name = name; return this; } /** * unique identifier of 3SZentrale * @return name **/ @ApiModelProperty(value = "unique identifier of 3SZentrale") public String getName() { return name; } public void setName(String name) { this.name = name; } public SZentrale publicPhoneNumber(String publicPhoneNumber) { this.publicPhoneNumber = publicPhoneNumber; return this; } /** * Get publicPhoneNumber * @return publicPhoneNumber **/ @ApiModelProperty(value = "") public String getPublicPhoneNumber() { return publicPhoneNumber; } public void setPublicPhoneNumber(String publicPhoneNumber) { this.publicPhoneNumber = publicPhoneNumber; } public SZentrale address(Address address) { this.address = address; return this; } /** * Get address * @return address **/ @ApiModelProperty(value = "") public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public SZentrale publicFaxNumber(String publicFaxNumber) { this.publicFaxNumber = publicFaxNumber; return this; } /** * public fax number * @return publicFaxNumber **/ @ApiModelProperty(value = "public fax number") public String getPublicFaxNumber() { return publicFaxNumber; } public void setPublicFaxNumber(String publicFaxNumber) { this.publicFaxNumber = publicFaxNumber; } public SZentrale internalPhoneNumber(String internalPhoneNumber) { this.internalPhoneNumber = internalPhoneNumber; return this; } /** * internal phone number * @return internalPhoneNumber **/ @ApiModelProperty(value = "internal phone number") public String getInternalPhoneNumber() { return internalPhoneNumber; } public void setInternalPhoneNumber(String internalPhoneNumber) { this.internalPhoneNumber = internalPhoneNumber; } public SZentrale internalFaxNumber(String internalFaxNumber) { this.internalFaxNumber = internalFaxNumber; return this; } /** * internal fax number * @return internalFaxNumber **/ @ApiModelProperty(value = "internal fax number") public String getInternalFaxNumber() { return internalFaxNumber; } public void setInternalFaxNumber(String internalFaxNumber) { this.internalFaxNumber = internalFaxNumber; } public SZentrale mobilePhoneNumber(String mobilePhoneNumber) { this.mobilePhoneNumber = mobilePhoneNumber; return this; } /** * mobile phone number (no longer supported!) * @return mobilePhoneNumber **/ @ApiModelProperty(value = "mobile phone number (no longer supported!)") public String getMobilePhoneNumber() { return mobilePhoneNumber; } public void setMobilePhoneNumber(String mobilePhoneNumber) { this.mobilePhoneNumber = mobilePhoneNumber; } public SZentrale email(String email) { this.email = email; return this; } /** * email adress of the 3-S-Zentrale (no longer supported!) * @return email **/ @ApiModelProperty(value = "email adress of the 3-S-Zentrale (no longer supported!)") public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SZentrale szentrale = (SZentrale) o; return Objects.equals(this.number, szentrale.number) && Objects.equals(this.name, szentrale.name) && Objects.equals(this.publicPhoneNumber, szentrale.publicPhoneNumber) && Objects.equals(this.address, szentrale.address) && Objects.equals(this.publicFaxNumber, szentrale.publicFaxNumber) && Objects.equals(this.internalPhoneNumber, szentrale.internalPhoneNumber) && Objects.equals(this.internalFaxNumber, szentrale.internalFaxNumber) && Objects.equals(this.mobilePhoneNumber, szentrale.mobilePhoneNumber) && Objects.equals(this.email, szentrale.email); } @Override public int hashCode() { return Objects.hash(number, name, publicPhoneNumber, address, publicFaxNumber, internalPhoneNumber, internalFaxNumber, mobilePhoneNumber, email); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class SZentrale {\n"); sb.append(" number: ").append(toIndentedString(number)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" publicPhoneNumber: ").append(toIndentedString(publicPhoneNumber)).append("\n"); sb.append(" address: ").append(toIndentedString(address)).append("\n"); sb.append(" publicFaxNumber: ").append(toIndentedString(publicFaxNumber)).append("\n"); sb.append(" internalPhoneNumber: ").append(toIndentedString(internalPhoneNumber)).append("\n"); sb.append(" internalFaxNumber: ").append(toIndentedString(internalFaxNumber)).append("\n"); sb.append(" mobilePhoneNumber: ").append(toIndentedString(mobilePhoneNumber)).append("\n"); sb.append(" email: ").append(toIndentedString(email)).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 "); } } package com.mobgen.halo.android.sdk.core.management.segmentation; import android.content.Context; import com.mobgen.halo.android.sdk.BuildConfig; /** * Tag that provides the platform name. In this case the hardcoded name is Android since this * is the Android SDK for HALO. */ public class PlatformNameCollector implements TagCollector { @Override public HaloSegmentationTag collect(Context context) { return HaloSegmentationTag.createDeviceTag("Platform Name", BuildConfig.HALO_PLATFORM_NAME); } } /* * Copyright (c) CovertJaguar, 2014 http://railcraft.info * * This code is the property of CovertJaguar * and may only be used with explicit written * permission unless otherwise specified on the * license page at http://railcraft.info/wiki/info:license. */ package mods.railcraft.client.core; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.TickEvent; import net.minecraft.entity.player.EntityPlayer; import mods.railcraft.common.core.StartupChecks; import mods.railcraft.common.plugins.forge.ChatPlugin; import net.minecraft.client.Minecraft; /** * * @author CovertJaguar */ public class LatestVersionMessage { private boolean messageSent; @SubscribeEvent public void tick(TickEvent.ClientTickEvent event) { if (!messageSent && StartupChecks.isVersionCheckComplete() && Minecraft.getMinecraft().thePlayer != null) { messageSent = true; if (StartupChecks.shouldSendMessage()) { EntityPlayer player = Minecraft.getMinecraft().thePlayer; ChatPlugin.sendLocalizedChat(player, "railcraft.gui.update.message", StartupChecks.getLatestVersion()); // "Railcraft " + StartupChecks.getLatestVersion() + " is available from "); } FMLCommonHandler.instance().bus().unregister(this); } } } package maquina1995.spring.security.repository; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import maquina1995.spring.security.domain.Usuario; public interface UsuarioRepository extends JpaRepository { @Query("select user from Usuario user join fetch user.roles where user.userName = :nombreUsuario") Optional findUserName(String nombreUsuario); } barkhyehyeon/mainsrc/main/java/seedu/souschef/model/AppContent.java package seedu.souschef.model; import static java.util.Objects.requireNonNull; import java.util.List; import javafx.collections.ObservableList; import seedu.souschef.model.healthplan.HealthPlan; import seedu.souschef.model.ingredient.Ingredient; import seedu.souschef.model.planner.Day; import seedu.souschef.model.planner.DayComparator; import seedu.souschef.model.planner.Meal; import seedu.souschef.model.recipe.CrossRecipe; import seedu.souschef.model.recipe.Recipe; /** * Wraps all data at the application * content level * Duplicates are not allowed (by .isSame comparison) */ public class AppContent implements ReadOnlyAppContent { private final UniqueList recipes; private final UniqueList ingredients; private final UniqueList crossRecipes; private final UniqueList healthPlans; private final UniqueList mealPlanner; private final UniqueList favourites; /* * The 'unusual' code block below is an non-static initialization block, sometimes used to avoid duplication * between constructors. See https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html * * Note that non-static init blocks are not recommended to use. There are other ways to avoid duplication * among constructors. */ { recipes = new UniqueList<>(); ingredients = new UniqueList<>(); crossRecipes = new UniqueList<>(); healthPlans = new UniqueList<>(); mealPlanner = new UniqueList<>(); favourites = new UniqueList<>(); } public AppContent() {} /** * Creates an AppContent using the recipes in the {@code toBeCopied} */ public AppContent(ReadOnlyAppContent toBeCopied) { this(); resetData(toBeCopied); } //// list overwrite operations /** * Resets the existing data of this {@code AppContent} with {@code newData}. */ public void resetData(ReadOnlyAppContent newData) { requireNonNull(newData); this.recipes.set(newData.getObservableRecipeList()); this.ingredients.set(newData.getObservableIngredientList()); this.crossRecipes.set(newData.getObservableCrossRecipeList()); this.healthPlans.set(newData.getObservableHealthPlanList()); this.mealPlanner.set(newData.getObservableMealPlanner()); this.favourites.set(newData.getObservableFavouritesList()); } /** * * Function call to include new data into the app data instead of deleting old data */ public void includeData(ReadOnlyAppContent newData) { requireNonNull(newData); if (newData.getObservableRecipeList().size() > 0) { this.recipes.set(newData.getObservableRecipeList()); } if (newData.getObservableHealthPlanList().size() > 0) { this.healthPlans.set(newData.getObservableHealthPlanList()); } if (newData.getObservableIngredientList().size() > 0) { this.ingredients.set(newData.getObservableIngredientList()); } if (newData.getObservableCrossRecipeList().size() > 0) { this.crossRecipes.set(newData.getObservableCrossRecipeList()); } if (newData.getObservableMealPlanner().size() > 0) { List dayList = newData.getObservableMealPlanner(); List fullRecipeList = recipes.asUnmodifiableObservableList(); for (Day d : dayList) { for (Meal m : d.getMeals()) { for (Recipe r : fullRecipeList) { if (!m.isEmpty() && m.getRecipe().isSame(r)) { m.setRecipe(r); } } } } this.mealPlanner.set(newData.getObservableMealPlanner()); this.mealPlanner.sortList(new DayComparator()); } if (newData.getObservableFavouritesList().size() > 0) { this.favourites.set(newData.getObservableFavouritesList()); } } //// recipe-level operations public UniqueList getRecipes() { return recipes; } //// ingredient-level operations public UniqueList getIngredients() { return ingredients; } //// cross recipe-level operations public UniqueList getCrossRecipes() { if (crossRecipes.size() == 0) { for (Recipe recipe : recipes) { crossRecipes.add(new CrossRecipe(recipe, recipe.getIngredients())); } } return crossRecipes; } //healthplan level operations public UniqueList getHealthPlans() { return healthPlans; } // meal planner level operations public UniqueList getMealPlanner() { return mealPlanner; } // favourite-level operations public UniqueList getFavourites() { return favourites; } //// util methods @Override public String toString() { return recipes.asUnmodifiableObservableList().size() + " recipes"; // TODO: refine later } @Override public ObservableList getObservableRecipeList() { return recipes.asUnmodifiableObservableList(); } @Override public ObservableList getObservableIngredientList() { return ingredients.asUnmodifiableObservableList(); } @Override public ObservableList getObservableCrossRecipeList() { return crossRecipes.asUnmodifiableObservableList(); } @Override public ObservableList getObservableHealthPlanList() { return healthPlans.asUnmodifiableObservableList(); } @Override public ObservableList getObservableMealPlanner() { return mealPlanner.asUnmodifiableObservableList(); } @Override public ObservableList getObservableFavouritesList() { return favourites.asUnmodifiableObservableList(); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof AppContent // instanceof handles nulls && recipes.equals(((AppContent) other).recipes) && healthPlans.equals(((AppContent) other).healthPlans) && mealPlanner.equals(((AppContent) other).mealPlanner) && ingredients.equals(((AppContent) other).ingredients) && favourites.equals(((AppContent) other).favourites)); } @Override public int hashCode() { return recipes.hashCode(); } } designlibrary/src/main/java/com/werdpressed/partisan/reallyusefulnotes/designlibrary/AsciiEmojis.java package com.werdpressed.partisan.reallyusefulnotes.designlibrary; public final class AsciiEmojis { public static final String[] EMOJIS = new String[] { "_φ( °-°)/", "_φ(°-°=)", "φ(..;)", "φ(^∇^ )", "φ(◎◎ヘ)", "ψ(。。)" }; private AsciiEmojis() {throw new AssertionError(); } public static String getRandomEmoji() { int index = (int)(Math.random()*EMOJIS.length); if (index > (EMOJIS.length - 1)) index = EMOJIS.length - 1; return EMOJIS[index]; } } 0 package com.google.android.gms.internal; import com.google.android.gms.drive.metadata.MetadataField; import com.google.android.gms.drive.metadata.internal.C0873b; import com.google.android.gms.drive.metadata.internal.C0877f; /* renamed from: com.google.android.gms.internal.lr */ public class C1860lr { /* renamed from: RW */ public static final MetadataField f4046RW = new C0877f("contentAvailability", 4300000); /* renamed from: RX */ public static final MetadataField f4047RX = new C0873b("isPinnable", 4300000); } iavanish/PAProject package iavanish.test4_checked; public class Cook implements Runnable{ Kitchen kitchen; Dish dish; String name; static int count; long totalTimeToCook; long waitAtStore; long waitAtCounter; public Cook(Kitchen kit) { this.kitchen=kit; dish=new Dish(); synchronized(Cook.class) { name="Cook"+(++count); } } public void run() { try { totalTimeToCook=System.currentTimeMillis(); getIngredients(); prepareDish(); totalTimeToCook= System.currentTimeMillis()-totalTimeToCook; PrintStatus p=PrintStatus.getInstance(); p.ckPrint(this); } catch (InterruptedException e) { e.printStackTrace(); } } private void prepareDish() throws InterruptedException { synchronized (kitchen.table) { //System.out.println(name+":I am cooking now"); waitAtCounter=System.currentTimeMillis(); while(kitchen.table.isDirty()){ kitchen.table.wait(); } waitAtCounter=System.currentTimeMillis()-waitAtCounter; Thread.sleep(dish.recipe.getCookingTime()); kitchen.table.setDirty(true); //System.out.println(name+":I finished cooking"); } } private void getIngredients() throws InterruptedException { synchronized (kitchen.store) { //System.out.println(name+":I entered store to get ingredients"); waitAtStore=System.currentTimeMillis(); boolean ig1=kitchen.store.isIngredientAvailable(dish.recipe.getIngredient1()); boolean ig2=kitchen.store.isIngredientAvailable(dish.recipe.getIngredient2()); while(!ig1 && !ig2){ //System.out.println("Ingredient not available.. I am going to wait now.."); kitchen.store.isThreadWaiting=true; if(!ig1){ kitchen.stock.require(dish.recipe.ingredient1); } if(!ig2){ kitchen.stock.require(dish.recipe.ingredient2); } kitchen.store.wait(); ig1=kitchen.store.isIngredientAvailable(dish.recipe.getIngredient1()); ig2=kitchen.store.isIngredientAvailable(dish.recipe.getIngredient2()); } waitAtStore=System.currentTimeMillis()-waitAtStore; kitchen.store.consumeIngredients(dish.recipe.getIngredient1(), dish.recipe.getIngredient2()); Thread.sleep(100); //System.out.println(name+":I collected I am going out"); } } @Override public String toString() { return "Cook [name=" + name +", "+dish.recipe+", totalTimeToCook=" + totalTimeToCook + ", waitAtStore=" + waitAtStore + ", waitAtCounter=" + waitAtCounter + "]"; } } babytun/src/main/java/com/geekouc/babytun/dao/GoodsCoverDAO.java package com.geekouc.babytun.dao; import com.geekouc.babytun.entity.GoodsCover; import java.util.List; public interface GoodsCoverDAO { public List findByGoodsId(Long goodsId); } package com.github.fppt.jedismock.operations.connection; import com.github.fppt.jedismock.operations.RedisCommand; import com.github.fppt.jedismock.operations.RedisOperation; import com.github.fppt.jedismock.server.Response; import com.github.fppt.jedismock.datastructures.Slice; import com.github.fppt.jedismock.storage.OperationExecutorState; @RedisCommand(value = "quit", transactional = false) public class Quit implements RedisOperation { private OperationExecutorState state; public Quit(OperationExecutorState state) { this.state = state; } @Override public Slice execute() { state.owner().sendResponse(Response.clientResponse("quit", Response.OK), "quit"); state.owner().close(); return Response.SKIP; } } package example2; public class PrinterImpl implements Printer { private String prefix; public PrinterImpl(String prefix) { this.prefix = prefix; } @Override public void print(String sentence) { System.out.println(this.prefix + sentence.trim()); } } /* Risky Rescue: A Roguelike RPG Copyright (C) 2013-2014 Any questions should be directed to the author via email at: */ package com.puttysoftware.riskyrescue; import javax.swing.JFrame; import com.puttysoftware.commondialogs.CommonDialogs; import com.puttysoftware.integration.NativeIntegration; import com.puttysoftware.riskyrescue.assets.SoundConstants; import com.puttysoftware.riskyrescue.assets.SoundManager; import com.puttysoftware.riskyrescue.battle.BattleLogic; import com.puttysoftware.riskyrescue.game.GameLogic; import com.puttysoftware.riskyrescue.items.Shop; import com.puttysoftware.riskyrescue.items.ShopTypes; import com.puttysoftware.riskyrescue.map.objects.MapObjectList; import com.puttysoftware.riskyrescue.prefs.PreferencesManager; import com.puttysoftware.riskyrescue.scenario.ScenarioManager; public class Application { // Fields private AboutDialog about; private GameLogic gameMgr; private ScenarioManager scenarioMgr; private MenuManager menuMgr; private GUIManager guiMgr; private final MapObjectList objects; private Shop weapons, armor, healer, regenerator; private BattleLogic battle; private int currentMode; private int formerMode; private NativeIntegration integration; public static final int STATUS_GUI = 0; public static final int STATUS_GAME = 1; private static final int STATUS_PREFS = 2; public static final int STATUS_BATTLE = 3; private static final int STATUS_NULL = 4; // Constructors public Application() { this.objects = new MapObjectList(); this.currentMode = Application.STATUS_NULL; this.formerMode = Application.STATUS_NULL; } // Methods void postConstruct(final NativeIntegration ni) { // Create Managers this.about = new AboutDialog(Support.getVersionString()); this.guiMgr = new GUIManager(); this.menuMgr = new MenuManager(); this.battle = new BattleLogic(); this.weapons = new Shop(ShopTypes.SHOP_TYPE_WEAPONS); this.armor = new Shop(ShopTypes.SHOP_TYPE_ARMOR); this.healer = new Shop(ShopTypes.SHOP_TYPE_HEALER); this.regenerator = new Shop(ShopTypes.SHOP_TYPE_REGENERATOR); // Cache Logo this.guiMgr.updateLogo(); // Late native hooks this.integration = ni; ni.setDefaultMenuBar(this.menuMgr.getMainMenuBar()); // Set Up Support.createScenario(); } void setInGUI() { this.currentMode = Application.STATUS_GUI; } public void setInPrefs() { this.formerMode = this.currentMode; this.currentMode = Application.STATUS_PREFS; } public void setInGame() { this.currentMode = Application.STATUS_GAME; } public void setInBattle() { this.currentMode = Application.STATUS_BATTLE; } public int getMode() { return this.currentMode; } public void restoreFormerMode() { this.currentMode = this.formerMode; } public int getFormerMode() { return this.formerMode; } public void showMessage(final String msg) { if (this.currentMode == Application.STATUS_GAME) { this.getGameManager().setStatusMessage(msg); } else if (this.currentMode == Application.STATUS_BATTLE) { this.getBattle().setStatusMessage(msg); } else { CommonDialogs.showDialog(msg); } } public MenuManager getMenuManager() { return this.menuMgr; } public GUIManager getGUIManager() { return this.guiMgr; } public GameLogic getGameManager() { if (this.gameMgr == null) { this.gameMgr = new GameLogic(); } return this.gameMgr; } public ScenarioManager getScenarioManager() { if (this.scenarioMgr == null) { this.scenarioMgr = new ScenarioManager(); } return this.scenarioMgr; } AboutDialog getAboutDialog() { return this.about; } static void playLogoSound() { SoundManager.playSound(SoundConstants.LOGO); } public void attachMenus(final JFrame frame) { if (!this.integration.isMacOS()) { frame.setJMenuBar(this.menuMgr.getMainMenuBar()); } } public JFrame getOutputFrame() { if (this.getMode() == Application.STATUS_PREFS) { return PreferencesManager.getPrefFrame(); } else if (this.getMode() == Application.STATUS_BATTLE) { return this.getBattle().getOutputFrame(); } else if (this.getMode() == Application.STATUS_GAME) { return this.getGameManager().getOutputFrame(); } else { return this.getGUIManager().getGUIFrame(); } } public MapObjectList getObjects() { return this.objects; } public Shop getGenericShop(final int shopType) { switch (shopType) { case ShopTypes.SHOP_TYPE_ARMOR: return this.armor; case ShopTypes.SHOP_TYPE_HEALER: return this.healer; case ShopTypes.SHOP_TYPE_REGENERATOR: return this.regenerator; case ShopTypes.SHOP_TYPE_WEAPONS: return this.weapons; default: // Invalid shop type return null; } } public BattleLogic getBattle() { return this.battle; } } /** * Simple Driver for a map reduce job counting tweets or tweet content */ package org.university.tutorial.mapreduce.driver; import java.io.IOException; import java.util.*; import org.apache.hadoop.fs.Path; import org.apache.hadoop.conf.*; import org.apache.hadoop.io.*; import org.apache.hadoop.mapred.*; import org.apache.hadoop.util.*; import org.university.tutorial.mapreduce.tasks.TweetMap; import org.university.tutorial.mapreduce.tasks.TweetReduce; /** * Author: <> * */ public class TweetDriver { public static void main(String[] args) throws Exception { JobConf conf = new JobConf(TweetDriver.class); conf.setJobName("example-hadoop-job"); conf.setOutputKeyClass(Text.class); conf.setOutputValueClass(IntWritable.class); conf.setMapperClass(TweetMap.class); conf.setReducerClass(TweetReduce.class); conf.setInputFormat(TextInputFormat.class); conf.setOutputFormat(TextOutputFormat.class); FileInputFormat.addInputPath(conf, new Path(args[0])); FileOutputFormat.setOutputPath(conf, new Path(args[1])); JobClient.runJob(conf); } } 1000+ /* * Copyright 2017-present Open Networking 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.onosproject.provider.lldp.cli; import java.util.Optional; import org.apache.karaf.shell.api.action.Argument; import org.apache.karaf.shell.api.action.Command; import org.apache.karaf.shell.api.action.Completion; import org.apache.karaf.shell.api.action.Option; import org.apache.karaf.shell.api.action.lifecycle.Service; import org.onosproject.cli.AbstractShellCommand; import org.onosproject.cli.net.DeviceIdCompleter; import org.onosproject.cli.net.PortNumberCompleter; import org.onosproject.net.ConnectPoint; import org.onosproject.net.DeviceId; import org.onosproject.net.PortNumber; import org.onosproject.net.config.NetworkConfigService; import org.onosproject.net.device.DeviceService; import org.onosproject.provider.lldp.impl.LinkDiscoveryFromDevice; import org.onosproject.provider.lldp.impl.LinkDiscoveryFromPort; /** * */ @Service @Command(scope = "onos", name = "config-link-discovery", description = "Adds configuration to disable LLDP link discovery") public class ConfigLinkDiscoveryCommand extends AbstractShellCommand { @Argument(index = 0, name = "device", description = "DeviceID", required = true) @Completion(DeviceIdCompleter.class) String device = null; @Argument(index = 1, name = "port", description = "Port number", required = false) @Completion(PortNumberCompleter.class) String port = null; @Option(name = "--remove", aliases = "-r", description = "remove configuration", required = false) boolean remove = false; @Option(name = "--enable", description = "add configuration to enable LinkDiscovery", required = false) boolean enable = false; @Override protected void doExecute() { DeviceService deviceService = get(DeviceService.class); NetworkConfigService netcfgService = get(NetworkConfigService.class); DeviceId did = DeviceId.deviceId(device); ConnectPoint cp = Optional.ofNullable(port) .map(PortNumber::fromString) .map(pn -> new ConnectPoint(did, pn)) .orElse(null); if (cp == null) { // device config if (!remove) { if (deviceService.getDevice(did) == null) { print("[WARN] configuring about unknown device %s", did); } LinkDiscoveryFromDevice cfg; cfg = netcfgService.addConfig(did, LinkDiscoveryFromDevice.class); cfg.enabled(enable); cfg.apply(); } else { netcfgService.removeConfig(did, LinkDiscoveryFromDevice.class); } } else { // port config if (!remove) { if (deviceService.getPort(cp) == null) { print("[WARN] configuring about unknown port %s", cp); } LinkDiscoveryFromPort cfg; cfg = netcfgService.addConfig(cp, LinkDiscoveryFromPort.class); cfg.enabled(enable); cfg.apply(); } else { netcfgService.removeConfig(cp, LinkDiscoveryFromPort.class); } } } } package com.uicode.smallchat.smallchatserver.model.global; import java.util.Date; public class GlobalStatus { private String status; private Integer confId; private String messaging; private Date upDate; private Date currentDate; private String version; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Integer getConfId() { return confId; } public void setConfId(Integer confId) { this.confId = confId; } public String getMessaging() { return messaging; } public void setMessaging(String messaging) { this.messaging = messaging; } public Date getUpDate() { return upDate; } public void setUpDate(Date upDate) { this.upDate = upDate; } public Date getCurrentDate() { return currentDate; } public void setCurrentDate(Date currentDate) { this.currentDate = currentDate; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } } package tech.acodesigner.servlet; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import tech.acodesigner.util.PictureUtil; import tech.acodesigner.util.PropertiesUtil; 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.File; import java.io.IOException; import java.util.Iterator; import java.util.List; /** * Created by 张秦遥 on 2017/2/22/0022. */ @WebServlet(name = "PictureManageServlet", urlPatterns = "/pictureManage") public class PictureManageServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String imageBasePath = getServletContext().getRealPath("images"); // System.out.println(imageBasePath); processUpload(request, response, imageBasePath); String[] userImages = PictureUtil.getPictures(imageBasePath, PropertiesUtil.getValue("userPicturePath")); String[] articleImages = PictureUtil.getPictures(imageBasePath, PropertiesUtil.getValue("articlePicturePath")); request.setAttribute("userImages", userImages); request.setAttribute("articleImages", articleImages); request.setAttribute("mainPage", "pictureManage.jsp"); request.getRequestDispatcher("manage.jsp").forward(request, response); } private void processUpload(HttpServletRequest request, HttpServletResponse response, String imageBasePath) { System.out.println("process upload"); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = null; try { items = upload.parseRequest(request); } catch (FileUploadException e) { return; // e.printStackTrace(); } if (items == null) { return; } Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); if (item.isFormField()) { System.out.println("error"); } else if ("userImage".equals(item.getFieldName())) { try { String imageName = item.getName(); String filePath = imageBasePath + File.separator + PropertiesUtil.getValue("userPicturePath") + File.separator + imageName; System.out.println(filePath); item.write(new File(filePath)); } catch (Exception e) { e.printStackTrace(); } } else if ("articleImage".equals(item.getFieldName())) { try { String imageName = item.getName(); String filePath = imageBasePath + File.separator + PropertiesUtil.getValue("articlePicturePath") + File.separator + imageName; System.out.println(filePath); item.write(new File(filePath)); } catch (Exception e) { e.printStackTrace(); } } } } } components/storage/src/main/java/net/gethos/cohesion/storage/buffer/HeapBufferBacking.java /** * Cohesion Framework - Storage Library * Copyright (c) 2017 - , Gethos. Licensed under the MIT licence. * vim: set ts=4 sw=0: */ package net.gethos.cohesion.storage.buffer; import java.io.PrintStream; import net.gethos.cohesion.storage.backing.BTreeBacking; import net.gethos.cohesion.storage.backing.BTreeBackingTransaction; import net.gethos.cohesion.storage.backing.ReadOnlyBTreeBackingTransaction; /** * @author {@literal <>} * */ public class HeapBufferBacking implements BTreeBacking { private final HeapBufferStorage storage; private final NodeCapacities nodeCapacities; public HeapBufferBacking(int capacity) { this.nodeCapacities = new ByteBufferNodeCapacities(capacity); this.storage = new HeapBufferStorage(nodeCapacities); } @Override public void close() { } @Override public BTreeBackingTransaction open() { return new HeapBufferBackingTransaction(storage, nodeCapacities); } @Override public ReadOnlyBTreeBackingTransaction openReadOnly() { return new HeapBufferBackingTransaction(storage, nodeCapacities); } /** * @param out */ public void dump(PrintStream out) { storage.dump(out); } } @SuppressWarnings("unchecked") public static T[] remove(final T[] array, final int from, final int to) { assert (to >= from) : to + " - " + from; int length = getLength(array); if (from < 0 || to >= length) { throw new IndexOutOfBoundsException("from: " + from + ", to: " + to + ", Length: " + length); } int remsize = to - from + 1; Object result = Array.newInstance(array.getClass().getComponentType(), length - remsize); System.arraycopy(array, 0, result, 0, from); if (to < length - 1) { System.arraycopy(array, to + 1, result, from, length - to - 1); } return (T[]) result; } package com.xsmp.espm.util; import javax.persistence.EntityManagerFactory; /** * * Utility class for initializing entity manager factory. * */ public class Utility { private static EntityManagerFactory emf; public static EntityManagerFactory getEntityManagerFactory() { if (emf == null) { throw new IllegalArgumentException( "EntityManagerfactory is not initialized!!!"); } return emf; } public static void setEntityManagerFactory(EntityManagerFactory emf) { Utility.emf = emf; } } package com.mryan.sqlSession; import com.mryan.config.BoundSql; import com.mryan.pojo.Configuration; import com.mryan.pojo.MappedStatement; import com.mryan.utils.GenericTokenParser; import com.mryan.utils.ParameterMapping; import com.mryan.utils.ParameterMappingTokenHandler; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List; /** * @description: BaseExecutor * @Author MRyan * @Date 2021/8/3 18:53 * @Version 1.0 */ public abstract class BaseExecutor implements Executor { protected PreparedStatement getPreparedStatement(Configuration configuration, MappedStatement mappedStatement, Object... param) throws SQLException, NoSuchFieldException, IllegalAccessException { Connection connection = configuration.getDataSource().getConnection(); String sql = mappedStatement.getSql(); BoundSql boundSql = getBoundSql(sql); // 1.获取预处理对象:preparedStatement PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText()); // 2. 设置参数 //获取到了参数的全路径 Class parameterType = mappedStatement.getParameterType(); List parameterMappingList = boundSql.getParameterMappingList(); for (int i = 0; i < parameterMappingList.size(); i++) { ParameterMapping parameterMapping = parameterMappingList.get(i); String content = parameterMapping.getContent(); //反射 Field declaredField = parameterType.getDeclaredField(content); //暴力访问 declaredField.setAccessible(true); Object o = declaredField.get(param[0]); preparedStatement.setObject(i + 1, o); } return preparedStatement; } /** * 对#{}的解析工作 * 将#{}使用?替换 * 解析#{}的值进行存储 * * @param sql * @return */ private BoundSql getBoundSql(String sql) { //标记处理类,完成占位符解析工作 ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler(); GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler); //解析出来的sql语句 String sqlText = genericTokenParser.parse(sql); //#{}解析出来的参数名称 List parameterMappingList = parameterMappingTokenHandler.getParameterMappings(); return new BoundSql(sqlText, parameterMappingList); } } src/main/java/no/ion/mvndeps/misc/FileWriter.java package no.ion.mvndeps.misc; import java.io.BufferedWriter; import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import static no.ion.mvndeps.misc.Exceptions.uncheckIO; public class FileWriter implements AutoCloseable { private final BufferedWriter writer; public static FileWriter truncateForWriting(Path path) { var writer = uncheckIO(() -> Files.newBufferedWriter(path, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)); return new FileWriter(writer); } private FileWriter(BufferedWriter writer) { this.writer = writer; } public FileWriter writeln(String string) { return write(string + "\n"); } public FileWriter write(String string) { uncheckIO(() -> writer.write(string)); uncheckIO(writer::flush); return this; } @Override public void close() throws UncheckedIOException { uncheckIO(writer::close);; } } flink-java-project/src/main/java/org/apache/flink/quickstart/POJOExample.java package org.apache.flink.quickstart; import java.util.ArrayList; import java.util.List; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; public class POJOExample { public static class Person { public int id; public String name; public Person() {}; public Person(int id, String name){ this.id = id; this.name = name; }; } public static void main(String[] args) throws Exception { final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); List> data = new ArrayList>(); data.add(new Tuple2<>("odd", 1)); data.add(new Tuple2<>("even", 2)); data.add(new Tuple2<>("odd", 3)); data.add(new Tuple2<>("even", 4)); DataStream personStream = env.fromElements(new Person(1, "Bob")); personStream.map(s -> "Flink says:".concat(s.name)).print(); env.execute(); } } package intro.JavaHW4.integer; import intro.JavaHW4.exceptions.DivideByZeroException; import intro.JavaHW4.exceptions.OverFlowException; import intro.JavaHW4.expr.Divide; import intro.JavaHW4.expr.TripleOperation; public class IntegerDivide extends Divide { public IntegerDivide(TripleOperation a, TripleOperation b) { super(a, b); } protected Integer calc(Integer x, Integer y) throws DivideByZeroException, OverFlowException { if (y == 0) { throw new DivideByZeroException(); } return x / y; } } src/main/java/com/elastic/search/elasticsearch/infrastructure/common/SearchAdapter.java package com.elastic.search.elasticsearch.infrastructure.common; import com.elastic.search.elasticsearch.infrastructure.annotation.Cascade; import com.elastic.search.elasticsearch.infrastructure.annotation.Cascades; import com.elastic.search.elasticsearch.infrastructure.annotation.EsObject; import com.elastic.search.elasticsearch.infrastructure.conf.BaseTypeIndexConfiguration; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.elastic.search.elasticsearch.dataobject.BaseESObject; import com.elastic.search.elasticsearch.searchservice.ESSearchService; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.reflect.FieldUtils; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author niuzhiwei */ public class SearchAdapter { /** * 缓存 */ private static final Map> NEED_FIELDS_CACHE = Maps.newHashMap(); /** * 搜索服务接口,封装类无状态 */ protected ESSearchService esSearchService; /** * 主键hash,搜索接口需要 */ protected Map primary = new HashMap(); /** * 默认主键名称,作为搜索主键 */ protected final String primaryKeyName = "id"; @SuppressWarnings("unchecked") protected K setConfig(BaseTypeIndexConfiguration conf, K k) { BaseESObject obj = (BaseESObject) k; obj.setSystemName(conf.getSystemName()); obj.setIndexName(conf.getIndexName()); obj.setTypeName(conf.getTypeName()); return (K) obj; } @SuppressWarnings("unchecked") protected Class getGenericActualType(Class clazz) { ParameterizedType parameterizedType = (ParameterizedType) this.getClass().getGenericSuperclass(); Class c = (Class) (parameterizedType.getActualTypeArguments()[0]); return c; } protected List getNeedFields(Class clazz) { List fieldNames = NEED_FIELDS_CACHE.get(clazz); if (null == fieldNames) { fieldNames = Lists.newArrayList(); Field[] fs = FieldUtils.getAllFields(clazz); for (Field f : fs) { if ("serialVersionUID".equals(f.getName())) { continue; } if (null == f.getAnnotation(EsObject.class)) { fieldNames.add(f.getName()); } else if (f.getType().isAssignableFrom(List.class)) { String prefix = f.getName() + "."; ParameterizedType pt = (ParameterizedType) f.getGenericType(); if (ArrayUtils.isEmpty(pt.getActualTypeArguments())) { continue; } for (String fieldName : getNeedFields((Class) pt.getActualTypeArguments()[0])) { fieldNames.add(prefix + fieldName); } } else if (f.getType().isArray()) { String prefix = f.getName() + "."; for (String fieldName : getNeedFields(f.getType().getComponentType())) { fieldNames.add(prefix + fieldName); } } else { String prefix = f.getName() + "."; for (String fieldName : getNeedFields(f.getType())) { fieldNames.add(prefix + fieldName); } } } NEED_FIELDS_CACHE.put(clazz, fieldNames); } return fieldNames; } protected List getCascade(T t) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { Cascade cascade = t.getClass().getDeclaredAnnotation(Cascade.class); Cascades cascades = t.getClass().getDeclaredAnnotation(Cascades.class); List fields = new ArrayList<>(); //单个关联 Node f = null; if (null != cascade && null != (f = this.getNode(t, cascade))) { fields.add(f); } //多个关联 Cascade[] cs = null; if (null != cascades && (cs = cascades.value()).length != 0) { for (Cascade c : cs) { Node f2 = null; if (null != cascade && null != (f2 = this.getNode(t, c))) { fields.add(f2); } } } return fields; } private Node getNode(T t, Cascade cascade) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { String[] fieldNames = cascade.fields(); if (StringUtils.isBlank(cascade.value()) || fieldNames.length == 0) { return null; } StringBuilder sb = new StringBuilder(""); Field field = null; Object val = null; for (String fieldName : fieldNames) { field = t.getClass().getDeclaredField(fieldName); field.setAccessible(true); val = field.get(t); if (null != val) { sb.append(val).append("\t"); } } return new Node(cascade.value(), sb.toString()); } protected class Node { private String nodeName; private String nodeValue; public String getNodeName() { return nodeName; } public void setNodeName(String nodeName) { this.nodeName = nodeName; } public String getNodeValue() { return nodeValue; } public void setNodeValue(String nodeValue) { this.nodeValue = nodeValue; } public Node(String nodeName, String nodeValue) { this.nodeName = nodeName; this.nodeValue = nodeValue; } } } package com.secureai.utils; public class MapUtils { } package com.github.gauthierj.dsm.webapi.client; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class DsmWebapiResponse { private boolean success; private T data; private DsmWebApiResponseError error; @JsonCreator public DsmWebapiResponse(@JsonProperty("success") boolean success, @JsonProperty("data") T data, @JsonProperty("error") DsmWebApiResponseError error) { this.success = success; this.data = data; this.error = error; } public boolean isSuccess() { return success; } public T getData() { return data; } public DsmWebApiResponseError getError() { return error; } } devonfw-sample/devonfw-swagger-gen-demo package com.cg.devonwithswagger.general.service.impl.rest; import javax.annotation.security.PermitAll; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.transaction.Transactional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.web.csrf.CsrfToken; import org.springframework.security.web.csrf.CsrfTokenRepository; import com.cg.devonwithswagger.general.common.api.exception.NoActiveUserException; import com.cg.devonwithswagger.general.common.api.to.UserProfileTo; import com.cg.devonwithswagger.general.service.api.rest.SecurityRestService; /** * Implementation of {@link SecurityRestService}. */ @Named @Transactional public class SecurityRestServiceImpl implements SecurityRestService { /** Logger instance. */ private static final Logger LOG = LoggerFactory.getLogger(SecurityRestServiceImpl.class); /** * Use {@link CsrfTokenRepository} for CSRF protection. */ private CsrfTokenRepository csrfTokenRepository; @Override @PermitAll public CsrfToken getCsrfToken(HttpServletRequest request, HttpServletResponse response) { CsrfToken token = this.csrfTokenRepository.loadToken(request); if (token == null) { LOG.error("No CsrfToken could be found - instantiating a new Token"); token = this.csrfTokenRepository.generateToken(request); this.csrfTokenRepository.saveToken(token, request, response); } return token; } @Override @PermitAll public UserProfileTo getCurrentUser() { SecurityContext context = SecurityContextHolder.getContext(); Authentication authentication = null; if (context != null) { authentication = context.getAuthentication(); } if (authentication == null) { throw new NoActiveUserException(); } UserDetails user = (UserDetails) authentication.getPrincipal(); UserProfileTo profile = new UserProfileTo(); profile.setLogin(user.getUsername()); return profile; } /** * @param csrfTokenRepository the csrfTokenRepository to set */ @Inject public void setCsrfTokenRepository(CsrfTokenRepository csrfTokenRepository) { this.csrfTokenRepository = csrfTokenRepository; } } Reapie/Tradeara package at.ahif18.tradeara.data; import java.time.MonthDay; public class HelpText { private String title; private String descriptions; private String link; public HelpText(String title, String description,String link) { this.title = title; this.descriptions = description; this.link = link; } public String getTitle() { return title; } public String getDescription() {return descriptions;} public String getLink() {return link;} } src_geotools/org/geotools/referencing/wkt/AbstractParser.java /* * GeoTools - The Open Source Java GIS Toolkit * http://geotools.org * * (C) 2002-2008, Open Source Geospatial Foundation (OSGeo) * * 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; * version 2.1 of the License. * * This library 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. */ package org.geotools.referencing.wkt; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import java.text.DecimalFormat; import java.text.FieldPosition; import java.text.Format; import java.text.NumberFormat; import java.text.ParseException; import java.text.ParsePosition; import org.opengis.metadata.citation.Citation; import org.opengis.parameter.GeneralParameterValue; import org.opengis.parameter.InvalidParameterValueException; import org.opengis.referencing.IdentifiedObject; import org.opengis.referencing.operation.MathTransform; import org.geotools.util.Utilities; import org.geotools.resources.i18n.Errors; import org.geotools.resources.i18n.ErrorKeys; /** * Base class for Well Know Text (WKT) parser. * * @since 2.0 * * * @source $URL: http://svn.osgeo.org/geotools/trunk/modules/library/referencing/src/main/java/org/geotools/referencing/wkt/AbstractParser.java $ * @version $Id: AbstractParser.java 38089 2011-09-27 02:21:51Z mbedward $ * @author * @author (IRD) * * @see Well Know Text specification * @see OGC WKT Coordinate System Issues */ public abstract class AbstractParser extends Format { /** * Set to {@code true} if parsing of number in scientific notation is allowed. * The way to achieve that is currently a hack, because {@link NumberFormat} has no * API for managing that as of J2SE 1.5. * * @todo See if a future version of J2SE allows us to get ride of this ugly hack. */ private static final boolean SCIENTIFIC_NOTATION = true; /** * A formatter using the same symbols than this parser. * Will be created by the {@link #format} method only when first needed. */ private transient Formatter formatter; /** * The symbols to use for parsing WKT. */ final Symbols symbols; /** * The object to use for parsing numbers. */ private final NumberFormat numberFormat; /** * Constructs a parser using the specified set of symbols. * * @param symbols The set of symbols to use. */ public AbstractParser(final Symbols symbols) { this.symbols = symbols; this.numberFormat = (NumberFormat) symbols.numberFormat.clone(); if (SCIENTIFIC_NOTATION && numberFormat instanceof DecimalFormat) { final DecimalFormat numberFormat = (DecimalFormat) this.numberFormat; String pattern = numberFormat.toPattern(); if (pattern.indexOf("E0") < 0) { final int split = pattern.indexOf(';'); if (split >= 0) { pattern = pattern.substring(0, split) + "E0" + pattern.substring(split); } pattern += "E0"; numberFormat.applyPattern(pattern); } } } /** * Returns the preferred authority for formatting WKT entities. * The {@link #format format} methods will uses the name specified * by this authority, if available. * * @return The expected authority. */ public Citation getAuthority() { return getFormatter().getAuthority(); } /** * Set the preferred authority for formatting WKT entities. * The {@link #format format} methods will uses the name specified * by this authority, if available. * * @param authority The new authority. */ public void setAuthority(final Citation authority) { if (authority == null) { throw new IllegalArgumentException(Errors.format( ErrorKeys.NULL_ARGUMENT_$1, "authority")); } getFormatter().setAuthority(authority); } /** * Returns {@code true} if syntax coloring is enabled. * By default, syntax coloring is disabled. * * @return {@code true} if syntax coloring are enabled. * * @since 2.4 */ public boolean isColorEnabled() { return getFormatter().colorEnabled; } /** * Enables or disables syntax coloring on ANSI X3.64 (aka ECMA-48 and ISO/IEC 6429) compatible * terminal. This apply only when formatting text. By default, syntax coloring is disabled. * When enabled, {@link #format(Object)} tries to highlight most of the elements compared by * {@link org.geotools.referencing.CRS#equalsIgnoreMetadata}. * * @param enabled {@code true} for enabling syntax coloring. * * @since 2.4 */ public void setColorEnabled(final boolean enabled) { getFormatter().colorEnabled = enabled; } /** * Parses a Well Know Text (WKT). * * @param text The text to be parsed. * @return The object. * @throws ParseException if the string can't be parsed. */ @Override public final Object parseObject(final String text) throws ParseException { final Element element = getTree(text, new ParsePosition(0)); final Object object = parse(element); element.close(); return object; } /** * Parses a Well Know Text (WKT). * * @param text The text to be parsed. * @param position The position to start parsing from. * @return The object. */ public final Object parseObject(final String text, final ParsePosition position) { final int origin = position.getIndex(); try { return parse(getTree(text, position)); } catch (ParseException exception) { position.setIndex(origin); if (position.getErrorIndex() < origin) { position.setErrorIndex(exception.getErrorOffset()); } return null; } } /** * Parse the number at the given position. */ final Number parseNumber(String text, final ParsePosition position) { if (SCIENTIFIC_NOTATION) { /* * HACK: DecimalFormat.parse(...) do not understand lower case 'e' for scientific * notation. It understand upper case 'E' only. Performs the replacement... */ final int base = position.getIndex(); Number number = numberFormat.parse(text, position); if (number != null) { int i = position.getIndex(); if (iWell Know Text (WKT) tree. * * @param element The element to be parsed. * @return The object. * @throws ParseException if the element can't be parsed. */ protected abstract Object parse(final Element element) throws ParseException; /** * Returns a tree of {@link Element} for the specified text. * * @param text The text to parse. * @param position In input, the position where to start parsing from. * In output, the first character after the separator. * @return The tree of elements to parse. * @throws ParseException If an parsing error occured while creating the tree. */ protected final Element getTree(final String text, final ParsePosition position) throws ParseException { return new Element(new Element(this, text, position)); } /** * Returns the formatter. Creates it if needed. */ private Formatter getFormatter() { if (formatter == null) { if (SCIENTIFIC_NOTATION) { // We do not want to expose the "scientific notation hack" to the formatter. // TODO: Remove this block if some future version of J2SE 1.5 provides something // like 'allowScientificNotationParsing(true)' in DecimalFormat. formatter = new Formatter(symbols, (NumberFormat) symbols.numberFormat.clone()); } else { formatter = new Formatter(symbols, numberFormat); } } return formatter; } /** * Format the specified object as a Well Know Text. * Formatting will uses the same set of symbols than the one used for parsing. * * @param object The object to format. * @param toAppendTo Where the text is to be appended. * @param pos An identification of a field in the formatted text. * * @see #getWarning */ public StringBuffer format(final Object object, final StringBuffer toAppendTo, final FieldPosition pos) { final Formatter formatter = getFormatter(); try { formatter.clear(); formatter.buffer = toAppendTo; formatter.bufferBase = toAppendTo.length(); if (object instanceof MathTransform) { formatter.append((MathTransform) object); } else if (object instanceof GeneralParameterValue) { // Special processing for parameter values, which is formatted // directly in 'Formatter'. Note that in GeoAPI, this interface // doesn't share the same parent interface than other interfaces. formatter.append((GeneralParameterValue) object); } else { formatter.append((IdentifiedObject) object); } return toAppendTo; } finally { formatter.buffer = null; } } /** * Read WKT strings from an input stream and reformat them to the specified * output stream. WKT strings are read until the the end-of-stream, or until * an unparsable WKT has been hit. In this later case, an error message is * formatted to the specified error stream. * * @param in The input stream. * @param out The output stream. * @param err The error stream. * @throws IOException if an error occured while reading from the input stream * or writting to the output stream. */ public void reformat(final BufferedReader in, final Writer out, final PrintWriter err) throws IOException { final String lineSeparator = System.getProperty("line.separator", "\n"); String line = null; try { while ((line=in.readLine()) != null) { if ((line=line.trim()).length() != 0) { out.write(lineSeparator); out.write(format(parseObject(line))); out.write(lineSeparator); out.write(lineSeparator); out.flush(); } } } catch (ParseException exception) { err.println(exception.getLocalizedMessage()); if (line != null) { reportError(err, line, exception.getErrorOffset()); } } catch (InvalidParameterValueException exception) { err.print(Errors.format(ErrorKeys.IN_$1, exception.getParameterName())); err.print(' '); err.println(exception.getLocalizedMessage()); } } /** * If a warning occured during the last WKT {@linkplain #format formatting}, * returns the warning. Otherwise returns {@code null}. The warning is cleared * every time a new object is formatted. * * @return The last warning, or {@code null} if none. * * @since 2.4 */ public String getWarning() { if (formatter != null && formatter.isInvalidWKT()) { if (formatter.warning != null) { return formatter.warning; } return Errors.format(ErrorKeys.INVALID_WKT_FORMAT_$1, formatter.getUnformattableClass()); } return null; } /** * Report a failure while parsing the specified line. * * @param err The stream where to report the failure. * @param line The line that failed. * @param errorOffset The error offset in the specified line. This is usually the * value provided by {@link ParseException#getErrorOffset}. */ static void reportError(final PrintWriter err, String line, int errorOffset) { line = line.replace('\r', ' ').replace('\n', ' '); final int WINDOW_WIDTH = 80; // Arbitrary value. int stop = line.length(); int base = errorOffset - WINDOW_WIDTH/2; final int baseMax = stop - WINDOW_WIDTH; final boolean hasTrailing = (Math.max(base,0) < baseMax); if (!hasTrailing) { base = baseMax; } if (base < 0) { base = 0; } stop = Math.min(stop, base + WINDOW_WIDTH); if (hasTrailing) { stop -= 3; } if (base != 0) { err.print("..."); errorOffset += 3; base += 3; } err.print(line.substring(base, stop)); if (hasTrailing) { err.println("..."); } else { err.println(); } err.print(Utilities.spaces(errorOffset - base)); err.println('^'); } } 0 package org.watermelon.framework.global.model.viewmodel; import androidx.lifecycle.MutableLiveData; import org.watermelon.framework.global.model.view.states.LoginState; public interface ViewModelLoginState { MutableLiveData> getLoginState(); } neradb-engine/src/main/java/com/neradb/command/dml/BackupCommand.java0 /* * Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0, * and the EPL 1.0 (http://h2database.com/html/license.html). * Initial Developer: H2 Group */ package com.neradb.command.dml; import com.neradb.command.CommandInterface; import com.neradb.command.Prepared; import com.neradb.command.expression.Expression; import com.neradb.engine.Session; import com.neradb.result.ResultInterface; /** * This class represents the statement * BACKUP */ public class BackupCommand extends Prepared { private Expression fileNameExpr; public BackupCommand(Session session) { super(session); } public void setFileName(Expression fileName) { this.fileNameExpr = fileName; } @Override public int update() { String name = fileNameExpr.getValue(session).getString(); session.getUser().checkAdmin(); backupTo(name); return 0; } private void backupTo(String fileName) { } @Override public boolean isTransactional() { return true; } /** * Fix the file name, replacing backslash with slash. * * @param f the file name * @return the corrected file name */ public static String correctFileName(String f) { f = f.replace('\\', '/'); if (f.startsWith("/")) { f = f.substring(1); } return f; } @Override public boolean needRecompile() { return false; } @Override public ResultInterface queryMeta() { return null; } @Override public int getType() { return CommandInterface.BACKUP; } } package com.fishercoder; import com.fishercoder.common.classes.ListNode; import com.fishercoder.common.utils.LinkedListUtils; import com.fishercoder.solutions._1; import com.fishercoder.solutions._1669; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; public class _1669Test { private static _1669.Solution1 solution1; private static ListNode list1; private static ListNode list2; private static ListNode expected; private static ListNode actual; @BeforeClass public static void setup() { solution1 = new _1669.Solution1(); } @Test public void test1() { list1 = LinkedListUtils.contructLinkedList(new int[]{0, 1, 2, 3, 4, 5}); list2 = LinkedListUtils.contructLinkedList(new int[]{1000000, 1000001, 1000002}); expected = LinkedListUtils.contructLinkedList(new int[]{0, 1, 2, 1000000, 1000001, 1000002, 5}); actual = solution1.mergeInBetween(list1, 3, 4, list2); LinkedListUtils.printList(actual); assertEquals(expected, actual); } }package com.layoutxml.applistmanagerlibrary.interfaces; import com.layoutxml.applistmanagerlibrary.objects.AppData; import java.util.List; /** * Created by LayoutXML on 22/08/2018 */ public interface AppListener { void appListener(List appDataList, Integer applicationFlags, Boolean applicationFlagsMatch, String[] permissions, Boolean matchPermissions, Integer uniqueIdentifier); } /** * Copyright (c) 2020 Source Auditor Inc. * * SPDX-License-Identifier: Apache-2.0 * * 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.spdx.utility.compare; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.Optional; import org.spdx.library.InvalidSPDXAnalysisException; import org.spdx.library.model.Annotation; import org.spdx.library.model.Checksum; import org.spdx.library.model.Relationship; import org.spdx.library.model.SpdxFile; import org.spdx.library.model.enumerations.FileType; import org.spdx.library.model.license.AnyLicenseInfo; /** * Contains the results of a comparison between two SPDX files with the same name * @author * */ public class SpdxFileDifference extends SpdxItemDifference { private List fileTypeA; private List fileTypeB; private List contributorsA; private String noticeA; private List contributorsB; private String noticeB; private List dependantFileNamesA; private List dependantFileNamesB; private boolean checksumsEquals; private List uniqueChecksumsA; private List uniqueChecksumsB; private String spdxIdA; private String spdxIdB; @SuppressWarnings("deprecation") public SpdxFileDifference(SpdxFile fileA, SpdxFile fileB, boolean concludedLicensesEqual, boolean seenLicensesEqual, List uniqueSeenLicensesA, List uniqueSeenLicensesB, boolean checksumsEquals, List uniqueChecksumsA, List uniqueChecksumsB, boolean relationshipsEquals, List uniqueRelationshipA, List uniqueRelationshipB, boolean annotationsEquals, List uniqueAnnotationsA, List uniqueAnnotationsB ) throws InvalidSPDXAnalysisException, SpdxCompareException { super(fileA, fileB, concludedLicensesEqual, seenLicensesEqual, uniqueSeenLicensesA, uniqueSeenLicensesB, relationshipsEquals, uniqueRelationshipA, uniqueRelationshipB, annotationsEquals, uniqueAnnotationsA,uniqueAnnotationsB); this.fileTypeA = Arrays.asList(fileA.getFileTypes().toArray(new FileType[fileA.getFileTypes().size()])); this.fileTypeB = Arrays.asList(fileB.getFileTypes().toArray(new FileType[fileB.getFileTypes().size()])); this.contributorsA = Arrays.asList(fileA.getFileContributors().toArray(new String[fileA.getFileContributors().size()])); this.contributorsB = Arrays.asList(fileB.getFileContributors().toArray(new String[fileB.getFileContributors().size()])); this.dependantFileNamesA = new ArrayList<>(); for (SpdxFile dependantFile:fileA.getFileDependency()) { Optional dependantFileName = dependantFile.getName(); if (dependantFileName.isPresent()) { dependantFileNamesA.add(dependantFileName.get()); } } this.dependantFileNamesB = new ArrayList<>(); for (SpdxFile dependantFile:fileB.getFileDependency()) { Optional dependantFileName = dependantFile.getName(); if (dependantFileName.isPresent()) { dependantFileNamesB.add(dependantFileName.get()); } } Optional noticeTextA =fileA.getNoticeText(); if (noticeTextA.isPresent()) { this.noticeA = noticeTextA.get(); } else { this.noticeA = ""; } Optional noticeTextB =fileB.getNoticeText(); if (noticeTextB.isPresent()) { this.noticeB = noticeTextB.get(); } else { this.noticeB = ""; } this.checksumsEquals = checksumsEquals; this.uniqueChecksumsA = uniqueChecksumsA; this.uniqueChecksumsB = uniqueChecksumsB; this.spdxIdA = fileA.getId(); this.spdxIdB = fileB.getId(); } /** * @return the fileName */ public String getFileName() { return this.getName(); } /** * @return the fileTypeA */ public List getFileTypeA() { return fileTypeA; } /** * @return the fileTypeB */ public List getFileTypeB() { return fileTypeB; } public boolean isContributorsEqual() { return SpdxComparer.stringListsEqual(this.contributorsA, this.contributorsB); } public boolean isNoticeTextsEqual() { return SpdxComparer.stringsEqual(this.noticeA, this.noticeB); } public boolean isFileDependenciesEqual() { return SpdxComparer.stringListsEqual(this.dependantFileNamesA, this.dependantFileNamesB); } /** * @return */ public boolean isTypeEqual() { return SpdxComparer.listsEquals(fileTypeA, fileTypeB); } /** * @return */ public boolean isChecksumsEquals() { return this.checksumsEquals; } /** * @return */ public String getContributorsAAsString() { return stringListToString(this.contributorsA); } /** * @return */ public String getContributorsBAsString() { return stringListToString(this.contributorsB); } static String stringListToString(List s) { StringBuilder sb = new StringBuilder(); if (s != null && s.size() > 0) { sb.append(s.get(0)); for (int i = 1; i < s.size(); i++) { if (Objects.nonNull(s.get(i)) && !s.get(i).isEmpty()) { sb.append(", "); sb.append(s.get(i)); } } } return sb.toString(); } /** * @return */ public String getFileDependenciesAAsString() { return stringListToString(this.dependantFileNamesA); } /** * @return */ public String getFileDependenciesBAsString() { return stringListToString(this.dependantFileNamesB); } /** * @return the contributorsA */ public List getContributorsA() { return contributorsA; } /** * @return the noticeA */ public String getNoticeA() { return noticeA; } /** * @return the contributorsB */ public List getContributorsB() { return contributorsB; } /** * @return the noticeB */ public String getNoticeB() { return noticeB; } /** * @return the dependantFileNamesA */ public List getDependantFileNamesA() { return dependantFileNamesA; } /** * @return the dependantFileNamesB */ public List getDependantFileNamesB() { return dependantFileNamesB; } /** * @return the uniqueChecksumsA */ public List getUniqueChecksumsA() { return uniqueChecksumsA; } /** * @return the uniqueChecksumsB */ public List getUniqueChecksumsB() { return uniqueChecksumsB; } /** * @return */ public String getSpdxIdA() { return this.spdxIdA; } /** * @return */ public String getSpdxIdB() { return this.spdxIdB; } } mithunvelocis/eGov-dcr-service /* * eGov SmartCity eGovernance suite aims to improve the internal efficiency,transparency, * accountability and the service delivery of the government organizations. * * Copyright (C) 2017 eGovernments Foundation * * The updated version of eGov suite of products as by eGovernments Foundation * is available at http://www.egovernments.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses/ or * http://www.gnu.org/licenses/gpl.html . * * In addition to the terms of the GPL license to be adhered to in using this * program, the following additional terms are to be complied with: * * 1) All versions of this program, verbatim or modified must carry this * Legal Notice. * Further, all user interfaces, including but not limited to citizen facing interfaces, * Urban Local Bodies interfaces, dashboards, mobile applications, of the program and any * derived works should carry eGovernments Foundation logo on the top right corner. * * For the logo, please refer http://egovernments.org/html/logo/egov_logo.png. * For any further queries on attribution, including queries on brand guidelines, * please contact * * 2) Any misrepresentation of the origin of the material is prohibited. It * is required that all modified versions of this material be marked in * reasonable ways as different from the original version. * * 3) This license does not grant any rights to any user of the program * with regards to rights under trademark law for use of the trade names * or trademarks of eGovernments Foundation. * * In case of any queries, you can reach eGovernments Foundation at . * */ package org.egov.commons; import com.fasterxml.jackson.annotation.JsonIgnore; import org.egov.infra.persistence.entity.AbstractAuditable; import org.hibernate.envers.AuditJoinTable; import org.hibernate.envers.AuditOverride; import org.hibernate.envers.AuditOverrides; import org.hibernate.envers.Audited; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.persistence.Transient; import java.util.HashSet; import java.util.Set; import static org.egov.commons.CChartOfAccounts.SEQ_CHARTOFACCOUNTS; @Entity @Table(name = "CHARTOFACCOUNTS") @SequenceGenerator(name = SEQ_CHARTOFACCOUNTS, sequenceName = SEQ_CHARTOFACCOUNTS, allocationSize = 1) @AuditOverrides({ @AuditOverride(forClass = AbstractAuditable.class, name = "lastModifiedBy"), @AuditOverride(forClass = AbstractAuditable.class, name = "lastModifiedDate") }) @Audited public class CChartOfAccounts extends AbstractAuditable { public static final String SEQ_CHARTOFACCOUNTS = "SEQ_CHARTOFACCOUNTS"; private static final long serialVersionUID = 61219209022946300L; @Id @GeneratedValue(generator = SEQ_CHARTOFACCOUNTS, strategy = GenerationType.SEQUENCE) private Long id; private String glcode; private String name; private Long purposeId; @Column(name = "DESCRIPTION") private String desc; private Boolean isActiveForPosting; private Long parentId; @Column(name = "SCHEDULEID") private Long schedule; private Character operation; private Character type; private Long classification; private Boolean functionReqd; private Boolean budgetCheckReq; private String majorCode; @Column(name = "CLASS") private Long myClass; @Transient private Boolean isSubLedger; @AuditJoinTable @JsonIgnore @OneToMany(orphanRemoval = true, cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "glCodeId", targetEntity = CChartOfAccountDetail.class) private Set chartOfAccountDetails = new HashSet<>(); public Set getChartOfAccountDetails() { return chartOfAccountDetails; } public void setChartOfAccountDetails(final Set chartOfAccountDetail) { chartOfAccountDetails = chartOfAccountDetail; } public String getMajorCode() { return majorCode; } public void setMajorCode(final String majorCode) { this.majorCode = majorCode; } public Long getMyClass() { return myClass; } public void setMyClass(final Long myClass) { this.myClass = myClass; } public String getGlcode() { return glcode; } public void setGlcode(final String glcode) { this.glcode = glcode; } public String getName() { return name; } public void setName(final String name) { this.name = name; } public Long getPurposeId() { return purposeId; } public void setPurposeId(final Long purposeId) { this.purposeId = purposeId; } public Long getClassification() { return classification; } public void setClassification(final Long classification) { this.classification = classification; } public String getDesc() { return desc; } public void setDesc(final String desc) { this.desc = desc; } public Boolean getFunctionReqd() { return functionReqd; } public void setFunctionReqd(final Boolean functionReqd) { this.functionReqd = functionReqd; } public Boolean getIsActiveForPosting() { return isActiveForPosting; } public void setIsActiveForPosting(final Boolean isActiveForPosting) { this.isActiveForPosting = isActiveForPosting; } public Character getOperation() { return operation; } public void setOperation(final Character operation) { this.operation = operation; } public Long getParentId() { return parentId; } public void setParentId(final Long parentId) { this.parentId = parentId; } public Long getSchedule() { return schedule; } public void setSchedule(final Long schedule) { this.schedule = schedule; } public Character getType() { return type; } public void setType(final Character type) { this.type = type; } @Override public boolean equals(final Object o) { return o instanceof CChartOfAccounts && ((CChartOfAccounts) o).getId().equals(getId()); } @Override public int hashCode() { return Integer.valueOf(glcode != null ? glcode : "0"); } public Boolean getBudgetCheckReq() { return budgetCheckReq; } public void setBudgetCheckReq(final Boolean budgetCheckReq) { this.budgetCheckReq = budgetCheckReq; } public Boolean getIsSubLedger() { return isSubLedger; } public void setIsSubLedger(final Boolean isSubLedger) { this.isSubLedger = isSubLedger; } @Override public Long getId() { return id; } @Override public void setId(final Long id) { this.id = id; } } /******************************************************************************* * Software Name : RCS IMS Stack * * Copyright (C) 2010-2016 Orange. * * 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.gsma.rcs.ri.messaging.chat.group; import com.gsma.rcs.ri.R; import com.gsma.rcs.ri.messaging.GroupTalkView; import com.gsma.rcs.ri.messaging.TalkList; import com.gsma.rcs.ri.messaging.chat.ChatMessageDAO; import com.gsma.rcs.ri.messaging.chat.ChatPendingIntentManager; import com.gsma.rcs.ri.utils.LogUtils; import com.gsma.rcs.ri.utils.RcsContactUtil; import com.gsma.services.rcs.chat.ChatLog; import com.gsma.services.rcs.chat.GroupChat; import com.gsma.services.rcs.chat.GroupChatIntent; import com.gsma.services.rcs.contact.ContactId; import android.app.IntentService; import android.app.Notification; import android.app.PendingIntent; import android.content.Intent; import android.media.RingtoneManager; import android.support.v4.app.NotificationCompat; import android.text.TextUtils; import android.util.Log; /** * File transfer intent service * * @author */ public class GroupChatIntentService extends IntentService { private ChatPendingIntentManager mChatPendingIntentManager; private static final String LOGTAG = LogUtils.getTag(GroupChatIntentService.class .getSimpleName()); /** * Creates an IntentService. */ public GroupChatIntentService() { super("GroupChatIntentService"); } @Override public void onCreate() { super.onCreate(); mChatPendingIntentManager = ChatPendingIntentManager.getChatPendingIntentManager(this); } @Override public int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); // We want this service to stop running if forced stop // so return not sticky. return START_NOT_STICKY; } @Override protected void onHandleIntent(Intent intent) { String action; if ((action = intent.getAction()) == null) { return; } if (GroupChatIntent.ACTION_NEW_GROUP_CHAT_MESSAGE.equals(action)) { // Gets message ID from the incoming Intent String messageId = intent.getStringExtra(GroupChatIntent.EXTRA_MESSAGE_ID); if (messageId == null) { if (LogUtils.isActive) { Log.e(LOGTAG, "Cannot read message ID"); } return; } String mimeType = intent.getStringExtra(GroupChatIntent.EXTRA_MIME_TYPE); if (mimeType == null) { if (LogUtils.isActive) { Log.e(LOGTAG, "Cannot read message mime-type"); } return; } handleNewGroupChatMessage(intent, messageId); } else if (GroupChatIntent.ACTION_NEW_INVITATION.equals(action)) { /* Gets chat ID from the incoming Intent */ String chatId = intent.getStringExtra(GroupChatIntent.EXTRA_CHAT_ID); if (chatId != null) { handleNewGroupChatInvitation(intent, chatId); } } else { if (LogUtils.isActive) { Log.e(LOGTAG, "Unknown action ".concat(action)); } } } private void handleNewGroupChatInvitation(Intent invitation, String chatId) { /* Get Chat from provider */ GroupChatDAO groupChatDAO = GroupChatDAO.getGroupChatDao(this, chatId); if (groupChatDAO == null) { Log.e(LOGTAG, "Cannot find group chat with ID=".concat(chatId)); return; } if (LogUtils.isActive) { Log.d(LOGTAG, "Group chat invitation =".concat(groupChatDAO.toString())); } /* Check if it's a spam */ if (groupChatDAO.getReasonCode() == GroupChat.ReasonCode.REJECTED_SPAM) { if (LogUtils.isActive) { Log.e(LOGTAG, "Do nothing on a spam"); } return; } forwardGCInvitation2UI(invitation, chatId, groupChatDAO); TalkList.notifyNewConversationEvent(this, GroupChatIntent.ACTION_NEW_INVITATION); } private void handleNewGroupChatMessage(Intent newGroupChatMessage, String messageId) { /* Get ChatMessage from provider */ ChatMessageDAO messageDAO = ChatMessageDAO.getChatMessageDAO(this, messageId); if (messageDAO == null) { Log.e(LOGTAG, "Cannot find group chat message with ID=".concat(messageId)); return; } if (LogUtils.isActive) { Log.d(LOGTAG, "Group chat message =".concat(messageDAO.toString())); } forwardGCMessage2UI(newGroupChatMessage, messageDAO); TalkList.notifyNewConversationEvent(this, GroupChatIntent.ACTION_NEW_GROUP_CHAT_MESSAGE); } private void forwardGCMessage2UI(Intent newGroupChatMessage, ChatMessageDAO message) { String chatId = message.getChatId(); Intent intent = GroupTalkView.forgeIntentNewMessage(this, newGroupChatMessage, chatId); String content = message.getContent(); Integer uniqueId = mChatPendingIntentManager.tryContinueChatConversation(intent, chatId); if (uniqueId != null) { PendingIntent contentIntent = PendingIntent.getActivity(this, uniqueId, intent, PendingIntent.FLAG_UPDATE_CURRENT); /* Create notification */ ContactId contact = message.getContact(); String mimeType = message.getMimeType(); String displayName = RcsContactUtil.getInstance(this).getDisplayName(contact); String title = getString(R.string.title_recv_chat, displayName); String msg; if (ChatLog.Message.MimeType.GEOLOC_MESSAGE.equals(mimeType)) { msg = getString(R.string.label_geoloc_msg); } else if (ChatLog.Message.MimeType.TEXT_MESSAGE.equals(mimeType)) { msg = content; } else { /* If the GC message does not convey user content then discards */ if (LogUtils.isActive) { Log.w(LOGTAG, "Discard message of type '" + mimeType + "' for chatId " + chatId); } return; } Notification notif = buildNotification(contentIntent, title, msg); /* Send notification */ mChatPendingIntentManager.postNotification(uniqueId, notif); } } private void forwardGCInvitation2UI(Intent invitation, String chatId, GroupChatDAO groupChat) { /* Create pending intent */ Intent intent = GroupTalkView.forgeIntentInvitation(this, invitation); /* * If the PendingIntent has the same operation, action, data, categories, components, and * flags it will be replaced. Invitation should be notified individually so we use a random * generator to provide a unique request code and reuse it for the notification. */ Integer uniqueId = mChatPendingIntentManager.tryContinueChatConversation(intent, chatId); if (uniqueId != null) { PendingIntent contentIntent = PendingIntent.getActivity(this, uniqueId, intent, PendingIntent.FLAG_UPDATE_CURRENT); /* Create notification */ String title = getString(R.string.title_group_chat); /* Try to retrieve display name of remote contact */ String displayName = RcsContactUtil.getInstance(this).getDisplayName( groupChat.getContact()); if (displayName != null) { title = getString(R.string.title_recv_group_chat, displayName); } String subject = groupChat.getSubject(); if (TextUtils.isEmpty(subject)) { subject = "<" + getString(R.string.label_no_subject) + ">"; } String msg = getString(R.string.label_subject_notif, subject); Notification notif = buildNotification(contentIntent, title, msg); /* Send notification */ mChatPendingIntentManager.postNotification(uniqueId, notif); } else { if (LogUtils.isActive) { Log.w(LOGTAG, "Received invitation for an existing group chat conversation chatId=" + chatId + "!"); } } } private Notification buildNotification(PendingIntent invitation, String title, String message) { // Create notification NotificationCompat.Builder notif = new NotificationCompat.Builder(this); notif.setContentIntent(invitation); notif.setSmallIcon(R.drawable.ri_notif_chat_icon); notif.setWhen(System.currentTimeMillis()); notif.setAutoCancel(true); notif.setOnlyAlertOnce(true); notif.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)); notif.setDefaults(Notification.DEFAULT_VIBRATE); notif.setContentTitle(title); notif.setContentText(message); return notif.build(); } } apollo/src/main/java/com/gengoai/apollo/ml/model/Model.java1-10 /* * 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.gengoai.apollo.ml.model; import com.gengoai.Copyable; import com.gengoai.apollo.ml.DataSet; import com.gengoai.apollo.ml.Datum; import com.gengoai.apollo.ml.observation.Observation; import com.gengoai.apollo.ml.transform.Transform; import com.gengoai.io.Compression; import com.gengoai.io.resource.Resource; import lombok.NonNull; import java.io.IOException; import java.io.Serializable; /** *

* A model represents a learned mapping, i.e. {@link Transform}, from one or more input {@link Observation}s to one or * more outputs. A Model learns its mapping by estimating, or fitting, its model parameters to a given {@link DataSet} * (i.e. through the {@link Transform#fitAndTransform(DataSet)} method. *

*

* In addition to the parameters defining the mapping, each model has a set of parameters that control the learning * process and are represented as {@link FitParameters}. Each model will have its own subclass of {@link FitParameters} * defining its specific parameters. Implementations should have the following set of constructors for consistency. *

*

    *
  • Model() - No Arg Constructor that initializes the estimator with default parameters.
  • *
  • Model(? extends FitParameters) - FitParameter constructor that takes in a non-null instance of this * Model's custom FitParameters.
  • *
  • Model(Consumer<? extends FitParameters>) - Updating constructing which creates a default set of * parameters which is then updated by the given consumer.
  • *

* * @author */ public interface Model extends Transform, Serializable { /** * Reads the model from the given resource * * @param resource the resource * @return the model * @throws IOException Something went wrong reading the model */ static Model load(@NonNull Resource resource) throws IOException { return resource.getChild("model.bin.gz").readObject(); } @Override default Model copy() { return Copyable.deepCopy(this); } /** * Estimates (fits) the model's parameters using the given {@link DataSet} * * @param dataset the dataset */ void estimate(@NonNull DataSet dataset); @Override default DataSet fitAndTransform(@NonNull DataSet dataset) { estimate(dataset); return dataset.map(this::transform); } /** * Gets the {@link FitParameters} defined for this estimator * * @return the FitParameters */ FitParameters getFitParameters(); /** * Returns the {@link LabelType} for the {@link Datum#DEFAULT_OUTPUT} source * * @return the LabelType */ default LabelType getLabelType() { return getLabelType(Datum.DEFAULT_OUTPUT); } /** * Returns the {@link LabelType} for the given source * * @return the LabelType */ LabelType getLabelType(@NonNull String name); /** * Writes the model the given ZipWriter. * * @param resource the resource to write the model to * @throws IOException Something went wrong writing the model */ default void save(@NonNull Resource resource) throws IOException { resource.getChild("model.bin.gz").setCompression(Compression.GZIP).writeObject(this); } }//END OF Model package com.thundersharp.cadmin.ui.fragment.organisationinfo; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.firebase.ui.auth.data.model.User; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.thundersharp.cadmin.R; import com.thundersharp.cadmin.core.globalAdapters.UsersAdapter; import com.thundersharp.cadmin.core.globalmodels.UserData; import java.util.ArrayList; import java.util.List; public class FindUsers extends Fragment { RecyclerView allUsers; MyAdapter adapter; List userList; String org_id; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View root = inflater.inflate(R.layout.add_users, container, false); allUsers = root.findViewById(R.id.org_add_user); allUsers.setHasFixedSize(true); allUsers.setLayoutManager(new LinearLayoutManager(getContext())); userList = new ArrayList<>(); //getAllUsers(); return root; } private void getAllUsers() { } } 1-10 package com.verygood.security.larky.modules.types; import net.starlark.java.eval.Dict; import net.starlark.java.eval.EvalException; import net.starlark.java.eval.Printer; import net.starlark.java.eval.Starlark; import net.starlark.java.eval.StarlarkCallable; import net.starlark.java.eval.StarlarkFunction; import net.starlark.java.eval.StarlarkThread; import net.starlark.java.eval.Tuple; import lombok.Builder; @Builder public class Partial implements StarlarkCallable { private final StarlarkFunction method; private final Tuple func_args; private final Dict func_kwargs; public static Partial create(StarlarkFunction func, Tuple args, Dict kwargs) { return Partial.builder().method(func).func_args(args).func_kwargs(kwargs).build(); } @Override @SuppressWarnings("unchecked") public Object call(StarlarkThread thread, Tuple args, Dict kwargs) throws EvalException, InterruptedException { kwargs.update(Dict.empty(), this.func_kwargs, thread); Tuple joinedArgs = Tuple.concat(this.func_args, args); return Starlark.call(thread, this.method, joinedArgs, kwargs); } /** * Returns the form this callable value should take in a stack trace. */ @Override public String getName() { return /*functools.partial(, 1)*/method.getName(); } @Override public void repr(Printer printer) { printer .append("partial( 0) { printer.append(", args=").append(String.valueOf(this.func_args)); } if(this.func_kwargs.size() > 0) { printer.append(", kwargs=").append(String.valueOf(this.func_kwargs)); } printer .append(">)"); } @Override public String toString() { return func_args.toString(); } } vShop_Java/shop/src/main/java/com/ruoyi/project/shop/service/IVBrandService.java package com.ruoyi.project.shop.service; import java.util.List; import com.ruoyi.project.shop.domain.VBrand; /** * 品牌 Service接口 * * @author wanghuan * @date 2020-04-02 */ public interface IVBrandService { /** * 查询品牌 * * @param brandId 品牌 ID * @return 品牌 */ public VBrand selectVBrandById(Long brandId); /** * 查询品牌 列表 * * @param vBrand 品牌 * @return 品牌 集合 */ public List selectVBrandList(VBrand vBrand); /** * 新增品牌 * * @param vBrand 品牌 * @return 结果 */ public int insertVBrand(VBrand vBrand); /** * 修改品牌 * * @param vBrand 品牌 * @return 结果 */ public int updateVBrand(VBrand vBrand); /** * 批量删除品牌 * * @param brandIds 需要删除的品牌 ID * @return 结果 */ public int deleteVBrandByIds(Long[] brandIds); /** * 删除品牌 信息 * * @param brandId 品牌 ID * @return 结果 */ public int deleteVBrandById(Long brandId); } cmhulbert/n5-ij /** * Copyright (c) 2018--2020, Saalfeld lab * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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 OWNER 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 org.janelia.saalfeldlab.n5.ij; import java.io.IOException; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import org.janelia.saalfeldlab.n5.Compression; import org.janelia.saalfeldlab.n5.DatasetAttributes; import org.janelia.saalfeldlab.n5.N5Reader; import org.janelia.saalfeldlab.n5.N5Writer; import org.janelia.saalfeldlab.n5.imglib2.N5Utils; import org.janelia.saalfeldlab.n5.metadata.ImageplusMetadata; import org.janelia.saalfeldlab.n5.metadata.N5ImagePlusMetadata; import org.janelia.saalfeldlab.n5.metadata.N5Metadata; import org.janelia.saalfeldlab.n5.metadata.N5MetadataParser; import org.janelia.saalfeldlab.n5.metadata.N5MetadataWriter; import ij.ImagePlus; import net.imglib2.RandomAccessibleInterval; import net.imglib2.converter.Converters; import net.imglib2.exception.ImgLibException; import net.imglib2.img.Img; import net.imglib2.img.cell.LazyCellImg; import net.imglib2.img.display.imagej.ImageJFunctions; import net.imglib2.img.imageplus.ImagePlusImg; import net.imglib2.img.imageplus.ImagePlusImgs; import net.imglib2.img.imageplus.IntImagePlus; import net.imglib2.type.NativeType; import net.imglib2.type.numeric.ARGBType; import net.imglib2.type.numeric.NumericType; import net.imglib2.type.numeric.RealType; import net.imglib2.type.numeric.integer.UnsignedByteType; import net.imglib2.type.numeric.integer.UnsignedIntType; import net.imglib2.util.Pair; import net.imglib2.view.Views; /** * * @author <> * @author <> * */ public class N5IJUtils { public static & NumericType> ImagePlus load( final N5Reader n5, final String dataset ) throws IOException, ImgLibException { return load( n5, dataset, null ); } /** * Loads and N5 dataset into an {@link ImagePlus}. Other than * {@link N5Utils#open(N5Reader, String)} which uses {@link LazyCellImg}, * the data is actually loaded completely into memory. * * @param the image data type. * @param the metadata type * @param the metadata parser type * @param n5 the reader * @param dataset the dataset * @param metaReader an optional metadata reader * @return the ImagePlus * @throws IOException io exception * @throws ImgLibException imglib2 exception */ @SuppressWarnings( { "unchecked", "rawtypes" } ) public static & NumericType, M extends N5Metadata, W extends N5MetadataParser< M > & ImageplusMetadata< M > > ImagePlus load( final N5Reader n5, final String dataset, final W metaReader ) throws IOException, ImgLibException { final RandomAccessibleInterval rai = N5Utils.open(n5, dataset); final DatasetAttributes attributes = n5.getDatasetAttributes(dataset); final long[] dimensions = attributes.getDimensions(); M metadata = null; if( metaReader != null && metaReader != null ) { try { metadata = metaReader.parseMetadata( n5, dataset ); } catch ( final Exception e ) { System.err.println( "Warning: could not read metadata." );} } final ImagePlusImg impImg; switch (attributes.getDataType()) { case UINT8: impImg = (ImagePlusImg)ImagePlusImgs.unsignedBytes(dimensions); break; case INT8: impImg = (ImagePlusImg)ImagePlusImgs.bytes(dimensions); break; case UINT16: impImg = (ImagePlusImg)ImagePlusImgs.unsignedShorts(dimensions); break; case INT16: impImg = (ImagePlusImg)ImagePlusImgs.shorts(dimensions); break; case UINT32: impImg = (ImagePlusImg)ImagePlusImgs.unsignedInts(dimensions); break; case INT32: impImg = (ImagePlusImg)ImagePlusImgs.ints(dimensions); break; case FLOAT32: impImg = (ImagePlusImg)ImagePlusImgs.floats(dimensions); break; default: System.err.println("Data type " + attributes.getDataType() + " not supported in ImageJ."); return null; } for (final Pair pair : Views.flatIterable(Views.interval(Views.pair(rai, impImg), rai))) pair.getB().set(pair.getA()); final ImagePlus imp = impImg.getImagePlus(); if( metadata != null ) metaReader.writeMetadata( metadata, imp ); return imp; } /** * Save an {@link ImagePlus} as an N5 dataset. * * @param imp the ImagePlus * @param n5 the writer * @param datasetName the dataset name * @param blockSize the block size * @param compression the compression type * @throws IOException io exception */ public static void save( final ImagePlus imp, final N5Writer n5, final String datasetName, final int[] blockSize, final Compression compression) throws IOException { final N5ImagePlusMetadata nullWriter = null; save( imp, n5, datasetName, blockSize, compression, nullWriter ); } /** * Save an {@link ImagePlus} as an N5 dataset. * * @param the image data type * @param the image data type * @param the metadata writer type * @param imp the ImagePlus * @param n5 the writer * @param datasetName the dataset name * @param blockSize the block size * @param compression the compression type * @param metaWriter (optional) metadata writer * @throws IOException io exception */ @SuppressWarnings( { "unchecked", "rawtypes" } ) public static & ImageplusMetadata< M >> void save( final ImagePlus imp, final N5Writer n5, final String datasetName, final int[] blockSize, final Compression compression, final W metaWriter ) throws IOException { final Img rai; if( imp.getType() == ImagePlus.COLOR_RGB ) rai = ( Img< T > ) wrapRgbAsInt( imp ); else rai = ImageJFunctions.wrap(imp); N5Utils.save( rai, n5, datasetName, blockSize, compression); if( metaWriter != null && metaWriter !=null ) { try { final M metadata = metaWriter.readMetadata( imp ); metaWriter.writeMetadata( metadata, n5, datasetName ); } catch ( final Exception e ) { e.printStackTrace(); } } } /** * Save and {@link ImagePlus} as an N5 dataset. Parallelizes export using * an {@link ExecutorService}. * * @param imp the ImagePlus * @param n5 the writer * @param datasetName the dataset name * @param blockSize the block size * @param compression the compression type * @param exec executor * @throws IOException io exception * @throws InterruptedException interrupted * @throws ExecutionException execution */ public static void save( final ImagePlus imp, final N5Writer n5, final String datasetName, final int[] blockSize, final Compression compression, final ExecutorService exec ) throws IOException, InterruptedException, ExecutionException { save( imp, n5, datasetName, blockSize, compression, exec, null ); } /** * Save and {@link ImagePlus} as an N5 dataset. Parallelizes export using * an {@link ExecutorService}. * * @param the image data type. * @param the metadata type. * @param the metadata writer type. * @param imp the ImagePlus * @param n5 the writer * @param datasetName the dataset name * @param blockSize the block size * @param compression the compression type * @param exec the executor * @param metaWriter (optional) metadata writer * @throws IOException io * @throws InterruptedException interrupted * @throws ExecutionException execution */ @SuppressWarnings( { "unchecked", "rawtypes" } ) public static & ImageplusMetadata< M >> void save( final ImagePlus imp, final N5Writer n5, final String datasetName, final int[] blockSize, final Compression compression, final ExecutorService exec, final W metaWriter ) throws IOException, InterruptedException, ExecutionException { final Img rai; if( imp.getType() == ImagePlus.COLOR_RGB ) rai = ( Img< T > ) wrapRgbAsInt( imp ); else rai = ImageJFunctions.wrap(imp); N5Utils.save( rai, n5, datasetName, blockSize, compression, exec); if( metaWriter != null && metaWriter !=null ) { try { final M metadata = metaWriter.readMetadata( imp ); metaWriter.writeMetadata( metadata, n5, datasetName ); } catch ( final Exception e ) { e.printStackTrace(); } } } /** * Save an ARGB image that contains gray scale data and uses inequality of * the three colors as a mask channel into an N5 group with two uint8 datasets * ('gray' and 'mask). Mask is 1 where all color channels are equal and 0 * everywhere else. * * @param imp argb image * @param n5 the writer * @param groupName the base path of the datasets * @param blockSize the block size * @param compression the compression type * @throws IOException io */ public static void saveMaskedUnsignedByte( final ImagePlus imp, final N5Writer n5, final String groupName, final int[] blockSize, final Compression compression) throws IOException { final ImagePlusImg rai = ImagePlusImgs.from(imp); final RandomAccessibleInterval mask = Converters.convert( (RandomAccessibleInterval)rai, (argb, uint8) -> { final int argbValue = argb.get(); final int r = ARGBType.red(argbValue); final int g = ARGBType.green(argbValue); final int b = ARGBType.blue(argbValue); if (r == g && g == b) uint8.set(1); else uint8.set(0); }, new UnsignedByteType()); final RandomAccessibleInterval gray = Converters.convert( (RandomAccessibleInterval)rai, (argb, uint8) -> { uint8.set(ARGBType.red(argb.get())); }, new UnsignedByteType()); n5.createGroup(groupName); N5Utils.save( mask, n5, groupName + "/mask", blockSize, compression); N5Utils.save( gray, n5, groupName + "/gray", blockSize, compression); } /** * Save an ARGB image that contains gray scale data and uses inequality of * the three colors as a mask channel into an N5 group with two uint8 datasets * ('gray' and 'mask). Mask is 1 where all color channels are equal and 0 * everywhere else. Parallelizes export using an {@link ExecutorService}. * * @param imp ARGB image * @param n5 the writer * @param groupName the base path of the datasets * @param blockSize the block size * @param compression the compression type * @param exec the executor service * @throws IOException io * @throws InterruptedException interrupted * @throws ExecutionException execution */ public static void saveMaskedUnsignedByte( final ImagePlus imp, final N5Writer n5, final String groupName, final int[] blockSize, final Compression compression, final ExecutorService exec) throws IOException, InterruptedException, ExecutionException { final ImagePlusImg rai = ImagePlusImgs.from(imp); final RandomAccessibleInterval mask = Converters.convert( (RandomAccessibleInterval)rai, (argb, uint8) -> { final int argbValue = argb.get(); final int r = ARGBType.red(argbValue); final int g = ARGBType.green(argbValue); final int b = ARGBType.blue(argbValue); if (r == g && g == b) uint8.set(1); else uint8.set(0); }, new UnsignedByteType()); final RandomAccessibleInterval gray = Converters.convert( (RandomAccessibleInterval)rai, (argb, uint8) -> { uint8.set(ARGBType.red(argb.get())); }, new UnsignedByteType()); n5.createGroup(groupName); N5Utils.save( mask, n5, groupName + "/mask", blockSize, compression, exec); N5Utils.save( gray, n5, groupName + "/gray", blockSize, compression, exec); } /** * Wraps an RGB image as a {@link Img} of type {@link UnsignedIntType}. * * @param imp the ImagePlus * @return the wrapped image */ public static Img< UnsignedIntType > wrapRgbAsInt( final ImagePlus imp ) { if ( imp.getType() != ImagePlus.COLOR_RGB ) return null; final IntImagePlus< UnsignedIntType > container = new IntImagePlus<>( imp ); // create a Type that is linked to the container final UnsignedIntType linkedType = new UnsignedIntType( container ); // pass it to the DirectAccessContainer container.setLinkedType( linkedType ); return container; } } package com.example.mystudyapp; import android.content.Intent; import android.support.design.widget.Snackbar; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.view.KeyEvent; import com.example.R; import com.example.activity.ChatActivity; import com.example.controller.MainController; import com.example.view.MainView; import cn.jpush.im.android.api.JMessageClient; import cn.jpush.im.android.api.content.PromptContent; import cn.jpush.im.android.api.event.NotificationClickEvent; public class MainActivity extends FragmentActivity { private MainView mMainView;//最外层布局 private MainController mMainController;//主界面viewpager适配器 private long mExitTime;//监听back键事件 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mMainView = (MainView) findViewById(R.id.main_view); mMainView.initModule(); mMainController = new MainController(mMainView, this); mMainView.setOnClickListener(mMainController); mMainView.setOnPageChangeListener(mMainController); } public FragmentManager getSupportFragmentManger() { return getSupportFragmentManager(); } @Override protected void onPause() { super.onPause(); } @Override protected void onResume() { super.onResume(); } @Override protected void onDestroy() { super.onDestroy(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { exit(); return true; } return super.onKeyDown(keyCode, event); } private void exit() { if ((System.currentTimeMillis() - mExitTime) > 2000) { Snackbar.make(mMainView, "再按一次退出!", Snackbar.LENGTH_SHORT).show(); mExitTime = System.currentTimeMillis(); } else { finish(); } } } package cn.jpush.api.push.model; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import java.util.Map; public class Message implements PushModel { private static final String TITLE = "title"; private static final String MSG_CONTENT = "msg_content"; private static final String CONTENT_TYPE = "content_type"; private static final String EXTRAS = "extras"; private final String title; private final String msgContent; private final String contentType; private final ImmutableMap extras; private final ImmutableMap numberExtras; private final ImmutableMap booleanExtras; private Message(String title, String msgContent, String contentType, ImmutableMap extras, ImmutableMap numberExtras, ImmutableMap booleanExtras) { this.title = title; this.msgContent = msgContent; this.contentType = contentType; this.extras = extras; this.numberExtras = numberExtras; this.booleanExtras = booleanExtras; } public static Builder newBuilder() { return new Builder(); } public static Message content(String msgContent) { return new Builder().setMsgContent(msgContent).build(); } @Override public JsonElement toJSON() { JsonObject json = new JsonObject(); if (null != title) { json.add(TITLE, new JsonPrimitive(title)); } if (null != msgContent) { json.add(MSG_CONTENT, new JsonPrimitive(msgContent)); } if (null != contentType) { json.add(CONTENT_TYPE, new JsonPrimitive(contentType)); } JsonObject extrasObject = null; if (null != extras || null != numberExtras || null != booleanExtras) { extrasObject = new JsonObject(); } if (null != extras) { for (String key : extras.keySet()) { extrasObject.add(key, new JsonPrimitive(extras.get(key))); } } if (null != numberExtras) { for (String key : numberExtras.keySet()) { extrasObject.add(key, new JsonPrimitive(numberExtras.get(key))); } } if (null != booleanExtras) { for (String key : booleanExtras.keySet()) { extrasObject.add(key, new JsonPrimitive(booleanExtras.get(key))); } } if (null != extras || null != numberExtras || null != booleanExtras) { json.add(EXTRAS, extrasObject); } return json; } public static class Builder { private String title; private String msgContent; private String contentType; private ImmutableMap.Builder extrasBuilder; private ImmutableMap.Builder numberExtrasBuilder; private ImmutableMap.Builder booleanExtrasBuilder; public Builder setTitle(String title) { this.title = title; return this; } public Builder setMsgContent(String msgContent) { this.msgContent = msgContent; return this; } public Builder setContentType(String contentType) { this.contentType = contentType; return this; } public Builder addExtra(String key, String value) { Preconditions.checkArgument(!(null == key || null == value), "Key/Value should not be null."); if (null == extrasBuilder) { extrasBuilder = ImmutableMap.builder(); } extrasBuilder.put(key, value); return this; } public Builder addExtras(Map extras) { Preconditions.checkArgument(!(null == extras), "extras should not be null."); if (null == extrasBuilder) { extrasBuilder = ImmutableMap.builder(); } for (String key : extras.keySet()) { extrasBuilder.put(key, extras.get(key)); } return this; } public Builder addExtra(String key, Number value) { Preconditions.checkArgument(!(null == key || null == value), "Key/Value should not be null."); if (null == numberExtrasBuilder) { numberExtrasBuilder = ImmutableMap.builder(); } numberExtrasBuilder.put(key, value); return this; } public Builder addExtra(String key, Boolean value) { Preconditions.checkArgument(!(null == key || null == value), "Key/Value should not be null."); if (null == booleanExtrasBuilder) { booleanExtrasBuilder = ImmutableMap.builder(); } booleanExtrasBuilder.put(key, value); return this; } public Message build() { Preconditions.checkArgument(!(null == msgContent), "msgContent should be set"); return new Message(title, msgContent, contentType, (null == extrasBuilder) ? null : extrasBuilder.build(), (null == numberExtrasBuilder) ? null : numberExtrasBuilder.build(), (null == booleanExtrasBuilder) ? null : booleanExtrasBuilder.build()); } } } /* * Copyright (c) 2021, HuXiaozhong. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. */ public class No704 { public int search(int[] nums, int target) { int left = 0, right = nums.length - 1; while (left < right) { int mid = left + (right - left) / 2; if (nums[mid] == target) return mid; else if (nums[mid] < target) left = mid + 1; else right = mid; } return nums[left] == target ? left : -1; } } //package net.romvoid95.galactic.feature.common.serverhub.assets; // //import java.awt.image.*; //import java.io.*; //import java.util.*; // //import org.apache.commons.io.filefilter.*; // //import net.minecraft.client.*; //import net.minecraft.client.resources.*; //import net.minecraft.client.resources.data.*; //import net.minecraft.util.*; //import net.romvoid95.galactic.*; //import net.romvoid95.galactic.core.config.*; // //public class HubAssets implements IResourcePack { // // private boolean debug = CoreBooleanValues.OUTPUT_DEBUG.currentValue; // // private static String loc = "config/GalacticTweaks/assets"; // // @Override // public InputStream getInputStream(ResourceLocation rl) throws IOException { // if (!resourceExists(rl)) { // return null; // } else { // // File file = new File(new File(Minecraft.getMinecraft().mcDataDir, loc + "/" + rl.getResourceDomain()), // rl.getResourcePath()); // String realFileName = file.getCanonicalFile().getName(); // if (!realFileName.equals(file.getName())) { // GalacticTweaks.LOG.debug("Resource Location " + rl.toString() + " only matches the file " + realFileName // + " : We are running a Non-Case Sensitive OS Environment(regarding file name cases"); // } // return new FileInputStream(file); // } // } // // @Override // public boolean resourceExists(ResourceLocation rl) { // File fileRequested = new File(new File(Minecraft.getMinecraft().mcDataDir, loc + "/" + rl.getResourceDomain()), // rl.getResourcePath()); // if (debug && !fileRequested.isFile()) { // GalacticTweaks.LOG // .debug("Looking For: " + rl.toString() + " But Cannot Find At: " + fileRequested.getAbsolutePath()); // } // // return fileRequested.isFile(); // } // // @Override // public Set getResourceDomains() { // File folder = new File(Minecraft.getMinecraft().mcDataDir, loc); // if (!folder.exists()) { // folder.mkdir(); // } // HashSet folders = new HashSet(); // GalacticTweaks.LOG.debug("[GalacticTweaks] Domains: "); // File[] resourceDomains = folder.listFiles((FileFilter) DirectoryFileFilter.DIRECTORY); // for (File resourceFolder : resourceDomains) { // if (resourceFolder.getName().equals("debug")) { // debug = true; // } // } // for (File resourceFolder : resourceDomains) { // GalacticTweaks.LOG // .debug("GalacticTweaks - " + resourceFolder.getName() + " | " + resourceFolder.getAbsolutePath()); // folders.add(resourceFolder.getName()); // } // // return folders; // } // // @SuppressWarnings("unchecked") // @Override // public IMetadataSection getPackMetadata(MetadataSerializer p_135058_1_, String p_135058_2_) throws IOException { // return null; // } // // @Override // public BufferedImage getPackImage() throws IOException { // return null; // } // // @Override // public String getPackName() { // return "GalacticTweaksAssets"; // } //} tc214/mobile package org.tc.appsvr.controller; import cn.hutool.http.HttpStatus; import lombok.extern.slf4j.Slf4j; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.User; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.tc.appsvr.entity.Rest; import org.tc.appsvr.entity.RestBody; import org.tc.appsvr.entity.SysUser; import org.tc.appsvr.service.SysUserService; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Map; @Slf4j @RestController @RequestMapping("/login") public class LoginController { @Resource private SysUserService sysUserService; @PostMapping(value="/success") public Rest myLoginSuccess(HttpServletRequest req, HttpServletResponse res) { // 登录成功后用户的认证信息 UserDetails会存在 SecurityContextHolder 中 User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); String loginName = principal.getUsername(); SysUser sysUser = sysUserService.queryByUsername(loginName); String loginPwd = principal.getPassword(); // 脱敏 sysUser.setEncodePassword("[PROTECT]"); // 不返回真实的密码 Map resMap = sysUserService.getAuthToken(req, res, loginName, loginPwd, "user"); return RestBody.okData(resMap,"登录成功"); } /** * 登录失败返回401 * @return */ @PostMapping(value="/failure") public Rest myLoginFailure() { return RestBody.failure(HttpStatus.HTTP_UNAUTHORIZED, "登录失败"); } } package de.is24.util.monitoring.jmx; import org.springframework.web.context.ServletContextAware; import javax.servlet.ServletContext; /** * This classes provides the contextPath of the servletContext as jmx prefix for the {@link InApplicationMonitorJMXConnector}. * This should be used for webApps, cause multiple webApps create multiple instances of the {@link InApplicationMonitorJMXConnector} and override eachother. * * @see InApplicationMonitorJMXConnector */ public class WebContextJmxAppMon4JNamingStrategy implements JmxAppMon4JNamingStrategy, ServletContextAware { private String prefix = "is24"; /** * @see JmxAppMon4JNamingStrategy#getJmxPrefix() * @return the String provided by the {@link ServletContext#getContext(String)} method */ public String getJmxPrefix() { return prefix; } /** * @see ServletContextAware#setServletContext(ServletContext) * @param servletContext the servlet context */ public void setServletContext(ServletContext servletContext) { if (servletContext == null) { throw new IllegalArgumentException("servletContext is null"); } String contextPath = servletContext.getContextPath(); if ((contextPath != null) && (contextPath.length() > 1)) { // use context path as jmx prefix prefix = contextPath.replaceFirst("/", ""); } else { // use default jmx prefix } } } spicall_artemide_spartacus_exodus/android/support/v4/view/PagerTitleStrip.java package android.support.v4.view; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.Configuration; import android.content.res.Resources; import android.content.res.TypedArray; import android.database.DataSetObserver; import android.graphics.drawable.Drawable; import android.support.v4.widget.TextViewCompat; import android.text.TextUtils.TruncateAt; import android.text.method.SingleLineTransformationMethod; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.view.View; import android.view.View.MeasureSpec; import android.view.ViewGroup; import android.widget.TextView; import java.lang.ref.WeakReference; import java.util.Locale; @ViewPager.DecorView public class PagerTitleStrip extends ViewGroup { private static final int[] ATTRS = { 16842804, 16842901, 16842904, 16842927 }; private static final float SIDE_ALPHA = 0.6F; private static final int[] TEXT_ATTRS = { 16843660 }; private static final int TEXT_SPACING = 16; TextView mCurrText; private int mGravity; private int mLastKnownCurrentPage = -1; float mLastKnownPositionOffset = -1.0F; TextView mNextText; private int mNonPrimaryAlpha; private final PageListener mPageListener = new PageListener(); ViewPager mPager; TextView mPrevText; private int mScaledTextSpacing; int mTextColor; private boolean mUpdatingPositions; private boolean mUpdatingText; private WeakReference mWatchingAdapter; public PagerTitleStrip(Context paramContext) { this(paramContext, null); } public PagerTitleStrip(Context paramContext, AttributeSet paramAttributeSet) { super(paramContext, paramAttributeSet); TextView localTextView = new TextView(paramContext); this.mPrevText = localTextView; addView(localTextView); localTextView = new TextView(paramContext); this.mCurrText = localTextView; addView(localTextView); localTextView = new TextView(paramContext); this.mNextText = localTextView; addView(localTextView); paramAttributeSet = paramContext.obtainStyledAttributes(paramAttributeSet, ATTRS); boolean bool = false; int i = paramAttributeSet.getResourceId(0, 0); if (i != 0) { TextViewCompat.setTextAppearance(this.mPrevText, i); TextViewCompat.setTextAppearance(this.mCurrText, i); TextViewCompat.setTextAppearance(this.mNextText, i); } int j = paramAttributeSet.getDimensionPixelSize(1, 0); if (j != 0) { setTextSize(0, j); } if (paramAttributeSet.hasValue(2)) { j = paramAttributeSet.getColor(2, 0); this.mPrevText.setTextColor(j); this.mCurrText.setTextColor(j); this.mNextText.setTextColor(j); } this.mGravity = paramAttributeSet.getInteger(3, 80); paramAttributeSet.recycle(); this.mTextColor = this.mCurrText.getTextColors().getDefaultColor(); setNonPrimaryAlpha(0.6F); this.mPrevText.setEllipsize(TextUtils.TruncateAt.END); this.mCurrText.setEllipsize(TextUtils.TruncateAt.END); this.mNextText.setEllipsize(TextUtils.TruncateAt.END); if (i != 0) { paramAttributeSet = paramContext.obtainStyledAttributes(i, TEXT_ATTRS); bool = paramAttributeSet.getBoolean(0, false); paramAttributeSet.recycle(); } if (bool) { setSingleLineAllCaps(this.mPrevText); setSingleLineAllCaps(this.mCurrText); setSingleLineAllCaps(this.mNextText); } else { this.mPrevText.setSingleLine(); this.mCurrText.setSingleLine(); this.mNextText.setSingleLine(); } this.mScaledTextSpacing = ((int)(paramContext.getResources().getDisplayMetrics().density * 16.0F)); } private static void setSingleLineAllCaps(TextView paramTextView) { paramTextView.setTransformationMethod(new SingleLineAllCapsTransform(paramTextView.getContext())); } int getMinHeight() { Drawable localDrawable = getBackground(); int i; if (localDrawable != null) { i = localDrawable.getIntrinsicHeight(); } else { i = 0; } return i; } public int getTextSpacing() { return this.mScaledTextSpacing; } protected void onAttachedToWindow() { super.onAttachedToWindow(); Object localObject = getParent(); if ((localObject instanceof ViewPager)) { localObject = (ViewPager)localObject; PagerAdapter localPagerAdapter = ((ViewPager)localObject).getAdapter(); ((ViewPager)localObject).setInternalPageChangeListener(this.mPageListener); ((ViewPager)localObject).addOnAdapterChangeListener(this.mPageListener); this.mPager = ((ViewPager)localObject); localObject = this.mWatchingAdapter; if (localObject != null) { localObject = (PagerAdapter)((WeakReference)localObject).get(); } else { localObject = null; } updateAdapter((PagerAdapter)localObject, localPagerAdapter); return; } throw new IllegalStateException("PagerTitleStrip must be a direct child of a ViewPager."); } protected void onDetachedFromWindow() { super.onDetachedFromWindow(); ViewPager localViewPager = this.mPager; if (localViewPager != null) { updateAdapter(localViewPager.getAdapter(), null); this.mPager.setInternalPageChangeListener(null); this.mPager.removeOnAdapterChangeListener(this.mPageListener); this.mPager = null; } } protected void onLayout(boolean paramBoolean, int paramInt1, int paramInt2, int paramInt3, int paramInt4) { if (this.mPager != null) { float f = this.mLastKnownPositionOffset; if (f < 0.0F) { f = 0.0F; } updateTextPositions(this.mLastKnownCurrentPage, f, true); } } protected void onMeasure(int paramInt1, int paramInt2) { if (View.MeasureSpec.getMode(paramInt1) == 1073741824) { int i = getPaddingTop() + getPaddingBottom(); int j = getChildMeasureSpec(paramInt2, i, -2); int k = View.MeasureSpec.getSize(paramInt1); paramInt1 = getChildMeasureSpec(paramInt1, (int)(k * 0.2F), -2); this.mPrevText.measure(paramInt1, j); this.mCurrText.measure(paramInt1, j); this.mNextText.measure(paramInt1, j); if (View.MeasureSpec.getMode(paramInt2) == 1073741824) { paramInt1 = View.MeasureSpec.getSize(paramInt2); } else { paramInt1 = this.mCurrText.getMeasuredHeight(); paramInt1 = Math.max(getMinHeight(), paramInt1 + i); } setMeasuredDimension(k, View.resolveSizeAndState(paramInt1, paramInt2, this.mCurrText.getMeasuredState() << 16)); return; } throw new IllegalStateException("Must measure with an exact width"); } public void requestLayout() { if (!this.mUpdatingText) { super.requestLayout(); } } public void setGravity(int paramInt) { this.mGravity = paramInt; requestLayout(); } public void setNonPrimaryAlpha(float paramFloat) { this.mNonPrimaryAlpha = ((int)(paramFloat * 255.0F) & 0xFF); int i = this.mNonPrimaryAlpha << 24 | this.mTextColor & 0xFFFFFF; this.mPrevText.setTextColor(i); this.mNextText.setTextColor(i); } public void setTextColor(int paramInt) { this.mTextColor = paramInt; this.mCurrText.setTextColor(paramInt); paramInt = this.mNonPrimaryAlpha << 24 | this.mTextColor & 0xFFFFFF; this.mPrevText.setTextColor(paramInt); this.mNextText.setTextColor(paramInt); } public void setTextSize(int paramInt, float paramFloat) { this.mPrevText.setTextSize(paramInt, paramFloat); this.mCurrText.setTextSize(paramInt, paramFloat); this.mNextText.setTextSize(paramInt, paramFloat); } public void setTextSpacing(int paramInt) { this.mScaledTextSpacing = paramInt; requestLayout(); } void updateAdapter(PagerAdapter paramPagerAdapter1, PagerAdapter paramPagerAdapter2) { if (paramPagerAdapter1 != null) { paramPagerAdapter1.unregisterDataSetObserver(this.mPageListener); this.mWatchingAdapter = null; } if (paramPagerAdapter2 != null) { paramPagerAdapter2.registerDataSetObserver(this.mPageListener); this.mWatchingAdapter = new WeakReference(paramPagerAdapter2); } paramPagerAdapter1 = this.mPager; if (paramPagerAdapter1 != null) { this.mLastKnownCurrentPage = -1; this.mLastKnownPositionOffset = -1.0F; updateText(paramPagerAdapter1.getCurrentItem(), paramPagerAdapter2); requestLayout(); } } void updateText(int paramInt, PagerAdapter paramPagerAdapter) { if (paramPagerAdapter != null) { i = paramPagerAdapter.getCount(); } else { i = 0; } this.mUpdatingText = true; Object localObject1 = null; if ((paramInt >= 1) && (paramPagerAdapter != null)) { localObject2 = paramPagerAdapter.getPageTitle(paramInt - 1); } else { localObject2 = null; } this.mPrevText.setText((CharSequence)localObject2); TextView localTextView = this.mCurrText; if ((paramPagerAdapter != null) && (paramInt < i)) { localObject2 = paramPagerAdapter.getPageTitle(paramInt); } else { localObject2 = null; } localTextView.setText((CharSequence)localObject2); int j = paramInt + 1; Object localObject2 = localObject1; if (j < i) { localObject2 = localObject1; if (paramPagerAdapter != null) { localObject2 = paramPagerAdapter.getPageTitle(j); } } this.mNextText.setText((CharSequence)localObject2); j = View.MeasureSpec.makeMeasureSpec(Math.max(0, (int)((getWidth() - getPaddingLeft() - getPaddingRight()) * 0.8F)), Integer.MIN_VALUE); int i = View.MeasureSpec.makeMeasureSpec(Math.max(0, getHeight() - getPaddingTop() - getPaddingBottom()), Integer.MIN_VALUE); this.mPrevText.measure(j, i); this.mCurrText.measure(j, i); this.mNextText.measure(j, i); this.mLastKnownCurrentPage = paramInt; if (!this.mUpdatingPositions) { updateTextPositions(paramInt, this.mLastKnownPositionOffset, false); } this.mUpdatingText = false; } void updateTextPositions(int paramInt, float paramFloat, boolean paramBoolean) { if (paramInt != this.mLastKnownCurrentPage) { updateText(paramInt, this.mPager.getAdapter()); } else if ((!paramBoolean) && (paramFloat == this.mLastKnownPositionOffset)) { return; } this.mUpdatingPositions = true; int i = this.mPrevText.getMeasuredWidth(); int j = this.mCurrText.getMeasuredWidth(); int k = this.mNextText.getMeasuredWidth(); int m = j / 2; int n = getWidth(); int i1 = getHeight(); int i2 = getPaddingLeft(); int i3 = getPaddingRight(); paramInt = getPaddingTop(); int i4 = getPaddingBottom(); int i5 = i3 + m; float f1 = 0.5F + paramFloat; float f2 = f1; if (f1 > 1.0F) { f2 = f1 - 1.0F; } m = n - i5 - (int)((n - (i2 + m) - i5) * f2) - m; i5 = j + m; int i6 = this.mPrevText.getBaseline(); j = this.mCurrText.getBaseline(); int i7 = this.mNextText.getBaseline(); int i8 = Math.max(Math.max(i6, j), i7); i6 = i8 - i6; j = i8 - j; i7 = i8 - i7; i8 = this.mPrevText.getMeasuredHeight(); int i9 = this.mCurrText.getMeasuredHeight(); int i10 = this.mNextText.getMeasuredHeight(); i8 = Math.max(Math.max(i8 + i6, i9 + j), i10 + i7); i10 = this.mGravity & 0x70; if (i10 != 16) { if (i10 != 80) { i1 = i6 + paramInt; j += paramInt; paramInt += i7; } else { paramInt = i1 - i4 - i8; i1 = i6 + paramInt; j += paramInt; paramInt += i7; } } else { paramInt = (i1 - paramInt - i4 - i8) / 2; i1 = i6 + paramInt; j += paramInt; paramInt += i7; } TextView localTextView = this.mCurrText; localTextView.layout(m, j, i5, localTextView.getMeasuredHeight() + j); j = Math.min(i2, m - this.mScaledTextSpacing - i); localTextView = this.mPrevText; localTextView.layout(j, i1, i + j, localTextView.getMeasuredHeight() + i1); i1 = Math.max(n - i3 - k, i5 + this.mScaledTextSpacing); localTextView = this.mNextText; localTextView.layout(i1, paramInt, i1 + k, localTextView.getMeasuredHeight() + paramInt); this.mLastKnownPositionOffset = paramFloat; this.mUpdatingPositions = false; } private class PageListener extends DataSetObserver implements ViewPager.OnAdapterChangeListener, ViewPager.OnPageChangeListener { private int mScrollState; PageListener() {} public void onAdapterChanged(ViewPager paramViewPager, PagerAdapter paramPagerAdapter1, PagerAdapter paramPagerAdapter2) { PagerTitleStrip.this.updateAdapter(paramPagerAdapter1, paramPagerAdapter2); } public void onChanged() { PagerTitleStrip localPagerTitleStrip = PagerTitleStrip.this; localPagerTitleStrip.updateText(localPagerTitleStrip.mPager.getCurrentItem(), PagerTitleStrip.this.mPager.getAdapter()); float f1 = PagerTitleStrip.this.mLastKnownPositionOffset; float f2 = 0.0F; if (f1 >= 0.0F) { f2 = PagerTitleStrip.this.mLastKnownPositionOffset; } localPagerTitleStrip = PagerTitleStrip.this; localPagerTitleStrip.updateTextPositions(localPagerTitleStrip.mPager.getCurrentItem(), f2, true); } public void onPageScrollStateChanged(int paramInt) { this.mScrollState = paramInt; } public void onPageScrolled(int paramInt1, float paramFloat, int paramInt2) { paramInt2 = paramInt1; if (paramFloat > 0.5F) { paramInt2 = paramInt1 + 1; } PagerTitleStrip.this.updateTextPositions(paramInt2, paramFloat, false); } public void onPageSelected(int paramInt) { if (this.mScrollState == 0) { PagerTitleStrip localPagerTitleStrip = PagerTitleStrip.this; localPagerTitleStrip.updateText(localPagerTitleStrip.mPager.getCurrentItem(), PagerTitleStrip.this.mPager.getAdapter()); float f1 = PagerTitleStrip.this.mLastKnownPositionOffset; float f2 = 0.0F; if (f1 >= 0.0F) { f2 = PagerTitleStrip.this.mLastKnownPositionOffset; } localPagerTitleStrip = PagerTitleStrip.this; localPagerTitleStrip.updateTextPositions(localPagerTitleStrip.mPager.getCurrentItem(), f2, true); } } } private static class SingleLineAllCapsTransform extends SingleLineTransformationMethod { private Locale mLocale; SingleLineAllCapsTransform(Context paramContext) { this.mLocale = paramContext.getResources().getConfiguration().locale; } public CharSequence getTransformation(CharSequence paramCharSequence, View paramView) { paramCharSequence = super.getTransformation(paramCharSequence, paramView); if (paramCharSequence != null) { paramCharSequence = paramCharSequence.toString().toUpperCase(this.mLocale); } else { paramCharSequence = null; } return paramCharSequence; } } } /* Location: ~/android/support/v4/view/PagerTitleStrip.class * * Reversed by: J */package biz.aQute.mqtt.test; import static org.assertj.core.api.Assertions.assertThat; import java.io.Closeable; import java.io.IOException; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Random; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; import org.osgi.dto.DTO; import org.osgi.service.cm.Configuration; import org.osgi.service.cm.ConfigurationAdmin; import aQute.launchpad.Launchpad; import aQute.launchpad.LaunchpadBuilder; import aQute.launchpad.Service; import biz.aQute.broker.api.Broker; import biz.aQute.broker.api.Topic; public class BrokerTest { static LaunchpadBuilder builder = new LaunchpadBuilder().bndrun("basic.bndrun"); static ScheduledExecutorService ses = Executors.newScheduledThreadPool(10); static Random random = new Random(); @Service ConfigurationAdmin admin; final CountDownLatch latch = new CountDownLatch(50); static public class Event extends DTO { public long timestamp; public String from; public String name; public double value; } class Backend { final List events = new CopyOnWriteArrayList<>(); final Map localDevices = new HashMap<>(); final Broker broker; final Closeable subscription; final Map> ids = new ConcurrentHashMap<>(); final ScheduledFuture schedule; Backend(Broker broker) { this.broker = broker; subscription = broker.subscribe(this::receive, Event.class, 0, "backend"); schedule = ses.scheduleAtFixedRate(this::tick, 100, 100, TimeUnit.MILLISECONDS); } public void receive(Event event) { System.out.println("backend received " + event); events.add(event); ids.computeIfAbsent("device/" + event.from, topic -> broker.topic(topic, false, 0, Command.class)); } public void tick() { if (events.size() > 10) { Command command = new Command(); command.action = Action.STOP; ids.values().removeIf(topic -> { try { topic.publish(command); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return true; }); } latch.countDown(); } void close() throws IOException { subscription.close(); schedule.cancel(true); } } enum Action { START, STOP, HIGH, LOW; }; static public class Command extends DTO { public Action action; public double argument; } class LocalDevice { final String id; final Topic topic; final Broker broker; final Closeable subscribe; final AtomicInteger errors = new AtomicInteger(); final ScheduledFuture schedule; volatile boolean on = true; volatile double low = 0; volatile double high = 1; LocalDevice(String id, Broker broker, int period) { this.id = id; this.broker = broker; this.topic = broker.topic("backend", false, 0, Event.class); this.subscribe = broker.subscribe(this::receive, Command.class, 0, "device/" + id); schedule = ses.scheduleAtFixedRate(this::tick, 200, 200, TimeUnit.MILLISECONDS); } synchronized void tick() { try { if (on) { Event event = new Event(); event.from = id; event.timestamp = System.currentTimeMillis(); event.value = random.nextDouble() % (high - low) + low; topic.publish(event); } } catch (Exception e) { e.printStackTrace(); errors.incrementAndGet(); } } private void receive(Command command) { System.out.println("device " + id + " received " + command); switch (command.action) { case HIGH: this.high = command.argument; break; case LOW: this.low = command.argument; break; case START: on = true; break; case STOP: on = false; break; default: break; } } public void close() throws IOException { subscribe.close(); schedule.cancel(true); } } @Test public void simple() throws Exception { try (Launchpad lp = builder.create().inject(this).debug()) { update("biz.aQute.mqtt.moquette.server", // "host", "localhost", // "allow.anonymous", true, // "port", 2883); update("biz.aQute.mqtt.paho.client", // "uri", "tcp://clientid@localhost:2883", // "name", "broker"); Optional t = lp.waitForService(Broker.class, 60_000); lp.report(); assertThat(t).isPresent(); Broker broker = t.get(); Backend backend = new Backend(broker); LocalDevice a = new LocalDevice("D-000A", broker, 100); LocalDevice b = new LocalDevice("D-000B", broker, 200); latch.await(); assertThat(a.on).isFalse(); assertThat(b.on).isFalse(); assertThat(backend.events).hasSizeGreaterThan(10); a.close(); b.close(); backend.close(); } } private void update(String pid, Object... kvs) throws IOException { Configuration configuration = admin.getConfiguration(pid, "?"); Hashtable properties = new Hashtable<>(); for (int i = 0; i < kvs.length; i += 2) { String key = kvs[i].toString(); Object value = kvs[i + 1]; properties.put(key, value); } configuration.update(properties); } } sunabove/ProgBasic package lec.thread; class TwoThreadsTest { public static void main(String[] args) { // new SimpleThread("John").start(); // new SimpleThread("Brown").start(); // Thread 생성 var threads = new java.util.ArrayList(); for( int i = 0; i< 20 ; i ++ ) { //threads.add( new SimpleThread( "MyThread " + i) ); var thread = new SimpleThread( "MyThread " + i); threads.add( thread ); } // -- Thread 생성 // Thread 시작 threads.forEach( thread -> { thread.start(); }); // Thread 시작 /* for( var thread : threads ) { thread.start(); } */ } }/* * Copyright 2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.sergeivisotsky.metadata.selector.dao.impl; import java.util.ArrayList; import java.util.Collection; import java.util.List; import io.github.sergeivisotsky.metadata.selector.dao.AbstractMetadataDao; import io.github.sergeivisotsky.metadata.selector.dao.ViewQueryDao; import io.github.sergeivisotsky.metadata.selector.domain.Paging; import io.github.sergeivisotsky.metadata.selector.domain.ViewField; import io.github.sergeivisotsky.metadata.selector.domain.ViewMetadata; import io.github.sergeivisotsky.metadata.selector.domain.ViewQueryResult; import io.github.sergeivisotsky.metadata.selector.filtering.dto.ViewQuery; import io.github.sergeivisotsky.metadata.selector.jdbc.sqlgen.dialect.SQLDialect; /** * @author */ public class ViewQueryDaoImpl extends AbstractMetadataDao implements ViewQueryDao { private final SQLDialect sqlDialect; public ViewQueryDaoImpl(SQLDialect sqlDialect) { this.sqlDialect = sqlDialect; } /** * {@inheritDoc} */ @Override public ViewQueryResult query(ViewMetadata metadata, ViewQuery query) { String sqlTemplate = metadata.getDefinition(); ViewQuery plusOneRowQuery = query.plusOneRowQuery(); String sql = sqlDialect.createSelectQuery(sqlTemplate, plusOneRowQuery); List fieldList = metadata.getViewField(); List> rowList = jdbcTemplate.query(sql, (rs, rowNum) -> { List row = new ArrayList<>(fieldList.size()); for (ViewField field : fieldList) { Object value = sqlDialect.getValueFromResultSet(rs, field); row.add(value); } return row; }); boolean hasMoreElements = false; if (plusOneRowQuery.getLimit() != null && rowList.size() == plusOneRowQuery.getLimit()) { rowList.remove(rowList.size() - 1); hasMoreElements = true; } return ViewQueryResult.builder() .fieldList(fieldList) .rowList(rowList) .orderList(plusOneRowQuery.getOrderList()) .paging(Paging.builder() .offset(query.getOffset()) .hasMoreElements(hasMoreElements) .totalElements(rowList.stream().mapToLong(Collection::size).sum()) .build()) .build(); } } package net.peepocloud.lib.player; /* * Created by Mc_Ruben on 03.01.2019 */ import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import net.peepocloud.lib.network.packet.serialization.PacketSerializable; import java.io.DataInput; import java.io.DataOutput; @NoArgsConstructor @AllArgsConstructor @Getter public class PeepoClientSettings implements PacketSerializable { private String locale; private byte viewDistance; private int chatFlags; private boolean chatColours; private PeepoPlayerSkinConfiguration skinParts; private int mainHand; @Override public void serialize(DataOutput dataOutput) throws Exception { dataOutput.writeUTF(locale); dataOutput.writeByte(viewDistance); dataOutput.writeInt(chatFlags); dataOutput.writeBoolean(chatColours); dataOutput.writeByte(skinParts.toByte()); dataOutput.writeInt(mainHand); } @Override public void deserialize(DataInput dataInput) throws Exception { locale = dataInput.readUTF(); viewDistance = dataInput.readByte(); chatFlags = dataInput.readInt(); chatColours = dataInput.readBoolean(); skinParts = PeepoPlayerSkinConfiguration.fromByte(dataInput.readByte()); mainHand = dataInput.readInt(); } } package com.lsh.wms.integration.wumart.obd; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.datatype.XMLGregorianCalendar; /** *

Java class for anonymous complex type. * *

The following schema fragment specifies the expected content contained within this class. * *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="CreatedItems" type="{urn:sap-com:document:sap:soap:functions:mc-style}TableOfBapidlvitemcreated" minOccurs="0"/>
 *         <element name="DebugFlg" type="{urn:sap-com:document:sap:rfc:functions}char1" minOccurs="0"/>
 *         <element name="Deliveries" type="{urn:sap-com:document:sap:soap:functions:mc-style}TableOfBapishpdelivnumb" minOccurs="0"/>
 *         <element name="DueDate" type="{urn:sap-com:document:sap:rfc:functions}date" minOccurs="0"/>
 *         <element name="ExtensionIn" type="{urn:sap-com:document:sap:soap:functions:mc-style}TableOfBapiparex" minOccurs="0"/>
 *         <element name="ExtensionOut" type="{urn:sap-com:document:sap:soap:functions:mc-style}TableOfBapiparex" minOccurs="0"/>
 *         <element name="NoDequeue" type="{urn:sap-com:document:sap:rfc:functions}char1" minOccurs="0"/>
 *         <element name="Return" type="{urn:sap-com:document:sap:soap:functions:mc-style}TableOfBapiret2" minOccurs="0"/>
 *         <element name="SerialNumbers" type="{urn:sap-com:document:sap:soap:functions:mc-style}TableOfBapidlvserialnumber" minOccurs="0"/>
 *         <element name="ShipPoint" type="{urn:sap-com:document:sap:rfc:functions}char4" minOccurs="0"/>
 *         <element name="StockTransItems" type="{urn:sap-com:document:sap:soap:functions:mc-style}TableOfBapidlvreftosto"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 * 
* * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "createdItems", "debugFlg", "deliveries", "dueDate", "extensionIn", "extensionOut", "noDequeue", "_return", "serialNumbers", "shipPoint", "stockTransItems" }) @XmlRootElement(name = "ZBapiOutbCreateObd") public class ZBapiOutbCreateObd { @XmlElement(name = "CreatedItems") protected TableOfBapidlvitemcreated createdItems; @XmlElement(name = "DebugFlg") protected String debugFlg; @XmlElement(name = "Deliveries") protected TableOfBapishpdelivnumb deliveries; @XmlElement(name = "DueDate") protected XMLGregorianCalendar dueDate; @XmlElement(name = "ExtensionIn") protected TableOfBapiparex extensionIn; @XmlElement(name = "ExtensionOut") protected TableOfBapiparex extensionOut; @XmlElement(name = "NoDequeue") protected String noDequeue; @XmlElement(name = "Return") protected TableOfBapiret2 _return; @XmlElement(name = "SerialNumbers") protected TableOfBapidlvserialnumber serialNumbers; @XmlElement(name = "ShipPoint") protected String shipPoint; @XmlElement(name = "StockTransItems", required = true) protected TableOfBapidlvreftosto stockTransItems; /** * Gets the value of the createdItems property. * * @return * possible object is * {@link TableOfBapidlvitemcreated } * */ public TableOfBapidlvitemcreated getCreatedItems() { return createdItems; } /** * Sets the value of the createdItems property. * * @param value * allowed object is * {@link TableOfBapidlvitemcreated } * */ public void setCreatedItems(TableOfBapidlvitemcreated value) { this.createdItems = value; } /** * Gets the value of the debugFlg property. * * @return * possible object is * {@link String } * */ public String getDebugFlg() { return debugFlg; } /** * Sets the value of the debugFlg property. * * @param value * allowed object is * {@link String } * */ public void setDebugFlg(String value) { this.debugFlg = value; } /** * Gets the value of the deliveries property. * * @return * possible object is * {@link TableOfBapishpdelivnumb } * */ public TableOfBapishpdelivnumb getDeliveries() { return deliveries; } /** * Sets the value of the deliveries property. * * @param value * allowed object is * {@link TableOfBapishpdelivnumb } * */ public void setDeliveries(TableOfBapishpdelivnumb value) { this.deliveries = value; } /** * Gets the value of the dueDate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getDueDate() { return dueDate; } /** * Sets the value of the dueDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setDueDate(XMLGregorianCalendar value) { this.dueDate = value; } /** * Gets the value of the extensionIn property. * * @return * possible object is * {@link TableOfBapiparex } * */ public TableOfBapiparex getExtensionIn() { return extensionIn; } /** * Sets the value of the extensionIn property. * * @param value * allowed object is * {@link TableOfBapiparex } * */ public void setExtensionIn(TableOfBapiparex value) { this.extensionIn = value; } /** * Gets the value of the extensionOut property. * * @return * possible object is * {@link TableOfBapiparex } * */ public TableOfBapiparex getExtensionOut() { return extensionOut; } /** * Sets the value of the extensionOut property. * * @param value * allowed object is * {@link TableOfBapiparex } * */ public void setExtensionOut(TableOfBapiparex value) { this.extensionOut = value; } /** * Gets the value of the noDequeue property. * * @return * possible object is * {@link String } * */ public String getNoDequeue() { return noDequeue; } /** * Sets the value of the noDequeue property. * * @param value * allowed object is * {@link String } * */ public void setNoDequeue(String value) { this.noDequeue = value; } /** * Gets the value of the return property. * * @return * possible object is * {@link TableOfBapiret2 } * */ public TableOfBapiret2 getReturn() { return _return; } /** * Sets the value of the return property. * * @param value * allowed object is * {@link TableOfBapiret2 } * */ public void setReturn(TableOfBapiret2 value) { this._return = value; } /** * Gets the value of the serialNumbers property. * * @return * possible object is * {@link TableOfBapidlvserialnumber } * */ public TableOfBapidlvserialnumber getSerialNumbers() { return serialNumbers; } /** * Sets the value of the serialNumbers property. * * @param value * allowed object is * {@link TableOfBapidlvserialnumber } * */ public void setSerialNumbers(TableOfBapidlvserialnumber value) { this.serialNumbers = value; } /** * Gets the value of the shipPoint property. * * @return * possible object is * {@link String } * */ public String getShipPoint() { return shipPoint; } /** * Sets the value of the shipPoint property. * * @param value * allowed object is * {@link String } * */ public void setShipPoint(String value) { this.shipPoint = value; } /** * Gets the value of the stockTransItems property. * * @return * possible object is * {@link TableOfBapidlvreftosto } * */ public TableOfBapidlvreftosto getStockTransItems() { return stockTransItems; } /** * Sets the value of the stockTransItems property. * * @param value * allowed object is * {@link TableOfBapidlvreftosto } * */ public void setStockTransItems(TableOfBapidlvreftosto value) { this.stockTransItems = value; } } 1-10 package mutable.recurrentjava.matrix; import java.io.Serializable; import java.util.Random; /** ARray MATrix. This is modified RecurrentJava Matrix. Matrix class is now superclass of this and CLMatrix (opencl). */ @Deprecated //merging ArMat and ClMat back into Matrix with Buffer and lazyCreate CLMem public class ArMat /*extends Matrix implements Serializable*/{ /* //benrayfield changed double to float and (TODO) many places that depend on it //and is planning to replace each with pair (probably in some wrapper together). public float[] w; public float[] dw; public float[] stepCache; /** see RjOptions.testDelayedUpdateOfWeights. FIXME remove this after get those test results, or at least leave the array null. Instead of adding the weight changes directly into w[], add them here, and later move from here to w[]. * public double[] testDelayedUpdateOfWeights; * @Override public String toString() { String result = ""; for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { result += String.format("%.4f",getW(r, c)) + "\t"; } result += "\n"; } return result; } public Matrix clone() { ArMat result = new ArMat(rows, cols); for (int i = 0; i < w.length; i++) { result.w[i] = w[i]; result.dw[i] = dw[i]; result.stepCache[i] = stepCache[i]; } return result; } public void resetDw() { for (int i = 0; i < dw.length; i++) { dw[i] = 0; } } public void resetStepCache() { for (int i = 0; i < stepCache.length; i++) { stepCache[i] = 0; } } public static ArMat transpose(ArMat m) { ArMat result = new ArMat(m.cols, m.rows); for (int r = 0; r < m.rows; r++) { for (int c = 0; c < m.cols; c++) { result.setW(c, r, m.getW(r, c)); } } return result; } public static ArMat rand(int rows, int cols, float initParamsStdDev, Random rng) { ArMat result = new ArMat(rows, cols); for (int i = 0; i < result.w.length; i++) { result.w[i] = (float)(rng.nextGaussian() * initParamsStdDev); } return result; } public static ArMat ident(int dim) { ArMat result = new ArMat(dim, dim); for (int i = 0; i < dim; i++) { result.setW(i, i, 1f); } return result; } public static ArMat uniform(int rows, int cols, float s) { ArMat result = new ArMat(rows, cols); for (int i = 0; i < result.w.length; i++) { result.w[i] = s; } return result; } public static ArMat ones(int rows, int cols) { return uniform(rows, cols, 1f); } public static Matrix negones(int rows, int cols) { return uniform(rows, cols, -1f); } public ArMat(int dim){ super(dim,1); this.w = new float[rows * cols]; this.dw = new float[rows * cols]; this.stepCache = new float[rows * cols]; //if(RjOptions.testDelayedUpdateOfWeights){ // this.testDelayedUpdateOfWeights = new double[rows*cols]; //} } public ArMat(int rows, int cols) { super(rows,cols); this.w = new float[rows * cols]; this.dw = new float[rows * cols]; this.stepCache = new float[rows * cols]; //if(RjOptions.testDelayedUpdateOfWeights){ // this.testDelayedUpdateOfWeights = new double[rows*cols]; //} } public ArMat(float[] vector) { super(vector.length,1); this.w = vector; this.dw = new float[vector.length]; this.stepCache = new float[vector.length]; //if(RjOptions.testDelayedUpdateOfWeights){ // this.testDelayedUpdateOfWeights = new double[vector.length]; //} } private float getW(int row, int col) { return w[index(row, col)]; } private void setW(int row, int col, float val) { w[index(row, col)] = val; } public void normByMaxRadius(float maxRadiusPerRow, float maxRadiusPerCol){ normByMaxRadius(new MatrixStat(w,rows,cols), maxRadiusPerRow, maxRadiusPerCol); } /** benrayfield is adding funcs to measure and norm, such as by maxradius andOr L1 andOr L2 norm, but since theres stepCache (is that a kind of rmsprop?) norming each weight change on bellcurve of recent changes to that weight, I'll start with just maxradius since its idempotent of that. * public void normByMaxRadius(MatrixStat stat, float maxRadiusPerRow, float maxRadiusPerCol){ if(maxRadiusPerRow <= 0 || maxRadiusPerCol <= 0) throw new Error("must be positive"); int offset = 0; for(int c=0; chpehl/hal.next /* * Copyright 2022 Red Hat * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.hal.config; import java.util.List; /** Instance holding information about the console and its environment. */ public interface Environment { /** @return the name. */ String getName(); void setName(String name); /** @return the organization. */ String getOrganization(); void setOrganization(String organization); /** @return the HAL version. */ Version getHalVersion(); Build getHalBuild(); List getLocales(); /** @return information about the server instance. */ InstanceInfo getInstanceInfo(); void setInstanceInfo(String productName, String productVersion, String releaseName, String releaseVersion); OperationMode getOperationMode(); /** @return true for standalone mode, false otherwise. */ boolean isStandalone(); void setOperationMode(OperationMode operationMode); /** @return the name of the domain controller (DC). */ String getDomainController(); void setDomainController(String domainController); /** @return the management model version. */ Version getManagementVersion(); void setManagementVersion(Version version); AccessControlProvider getAccessControlProvider(); void setAccessControlProvider(AccessControlProvider accessControlProvider); void setSingleSignOn(boolean sso); /** @return true if SSO is used, false otherwise. */ boolean isSingleSignOn(); /** @return the standard and scoped roles. */ Roles getRoles(); /** @return whether HAL is run in development mode */ boolean isDevMode(); /** @return whether HAL is run in production mode */ boolean isProductionMode(); void setPatchingEnabled(boolean enabled); boolean isPatchingEnabled(); } paullewallencom/rabbitmq-978-1-7839-8456-5_src/src/main/java/org/packt/rabbitmq/book/samples/chapter2/CompetingReceiver.java package org.packt.rabbitmq.book.samples.chapter2; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.ConsumerCancelledException; import com.rabbitmq.client.QueueingConsumer; import com.rabbitmq.client.ShutdownSignalException; public class CompetingReceiver { private final static String QUEUE_NAME = "event_queue"; private final static Logger LOGGER = LoggerFactory.getLogger(CompetingReceiver.class); private Connection connection = null; private Channel channel = null; public void initialize() { try { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); connection = factory.newConnection(); channel = connection.createChannel(); } catch (IOException e) { LOGGER.error(e.getMessage(), e); } } public String receive() { if (channel == null) { initialize(); } String message = null; try { channel.queueDeclare(QUEUE_NAME, false, false, false, null); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(QUEUE_NAME, true, consumer); QueueingConsumer.Delivery delivery = consumer.nextDelivery(); message = new String(delivery.getBody()); LOGGER.info("Message received: " + message); return message; } catch (IOException e) { LOGGER.error(e.getMessage(), e); } catch (ShutdownSignalException e) { LOGGER.error(e.getMessage(), e); } catch (ConsumerCancelledException e) { LOGGER.error(e.getMessage(), e); } catch (InterruptedException e) { LOGGER.error(e.getMessage(), e); } return message; } public void destroy() { if (connection != null) { try { connection.close(); } catch (IOException e) { LOGGER.warn(e.getMessage(), e); } } } } /* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2017, * * Project Info: http://plantuml.com * * This file is part of PlantUML. * * Licensed under The MIT License (Massachusetts Institute of Technology License) * * See http://opensource.org/licenses/MIT * * 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. * * * Original Author: */ package smetana.core; import smetana.core.amiga.StarArrayOfPtr; import smetana.core.amiga.StarStar; import smetana.core.amiga.StarStruct; public class Memory { public static __ptr__ malloc(Class cl) { JUtils.LOG("MEMORY::malloc " + cl); return StarStruct.malloc(cl); } public static __ptr__ malloc(size_t size) { return (__ptr__) size.malloc(); } public static __ptr__ realloc(__ptr__ old, size_t size) { if (old instanceof StarArrayOfPtr) { ((StarArrayOfPtr) old).realloc(((size_t_array_of_something) size).getNb()); return old; } if (old instanceof StarStar) { ((StarStar) old).realloc(((size_t_array_of_array_of_something_empty) size).getNb()); return old; } throw new UnsupportedOperationException(); } public static void free(Object arg) { } public static int identityHashCode(CString data) { if (data==null) { return 0; } //int result = 2 * System.identityHashCode(data); int result = data.getUid(); Z._().all.put(result, data); // System.err.println("Memory::identityHashCode data=" + data); // System.err.println("Memory::identityHashCode result=" + result + " " + Z._().all.size()); return result; } public static Object fromIdentityHashCode(int hash) { // System.err.println("Memory::fromIdentityHashCode hash=" + hash); if (hash % 2 != 0) { throw new IllegalArgumentException(); } Object result = Z._().all.get(hash); // System.err.println("Memory::fromIdentityHashCode result=" + result); if (result == null) { throw new UnsupportedOperationException(); } return result; } } package dk.mmj.eevhe.gui.configurer; import dk.mmj.eevhe.entities.Candidate; import dk.mmj.eevhe.gui.Manager; import dk.mmj.eevhe.gui.configurer.csv.CSVImportController; import dk.mmj.eevhe.gui.configurer.csv.CandidateCSVConfig; import dk.mmj.eevhe.gui.configurer.csv.InstanceCSVConfig; import dk.mmj.eevhe.gui.wrappers.BuildFailedException; import dk.mmj.eevhe.gui.wrappers.ConfigurationBuilder; import javafx.application.Platform; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.collections.transformation.SortedList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import javafx.stage.DirectoryChooser; import javafx.stage.Stage; import java.io.File; import java.io.IOException; import java.util.Objects; import java.util.stream.Collectors; import static dk.mmj.eevhe.gui.Utilities.*; public class ConfigurerManager implements Manager { private final ObservableList instanceInfos = FXCollections.observableArrayList(); private final ObservableList candidates = FXCollections.observableArrayList(); @FXML public Button doBuild; @FXML public Label certFileLabel; @FXML public Button chooseCertFile; @FXML public Label certKeyFileLabel; @FXML public Button chooseCertKeyFile; @FXML public Button addInstance; @FXML public TableView daTable; @FXML public TableColumn id; @FXML public TableColumn address; @FXML public TableColumn type; @FXML public TextField days; @FXML public TextField hours; @FXML public TextField minutes; @FXML public Label outputFolderLabel; @FXML public Button chooseOutputFolder; @FXML public TableView candidateTable; @FXML public TableColumn candidateIdx; @FXML public TableColumn candidateName; @FXML public TableColumn candidateDescription; @FXML public Button addCandidate; @FXML public Button importDA; @FXML public Button importCandidates; private Stage parentStage; private ConfigurationBuilder configurationBuilder; @FXML public void initialize() { configurationBuilder = new ConfigurationBuilder(); chooseCertFile.setOnAction(event -> { final File certFile = getFileChooser("Choose certificate file").showOpenDialog(parentStage); if (certFile != null) { configurationBuilder.setCertFilePath(certFile.getPath()); certFileLabel.setText(certFile.getName()); } }); chooseCertKeyFile.setOnAction(event -> { final File certKeyFile = getFileChooser("Choose certificate private-key file").showOpenDialog(parentStage); if (certKeyFile != null) { configurationBuilder.setCertKeyFilePath(certKeyFile.getPath()); certKeyFileLabel.setText(certKeyFile.getName()); } }); chooseOutputFolder.setOnAction(event -> { final DirectoryChooser outputChooser = new DirectoryChooser(); outputChooser.setTitle("Choose output destination"); final File folder = outputChooser.showDialog(parentStage); if (folder != null) { configurationBuilder.setOutputFolder(folder.getPath()); outputFolderLabel.setText(folder.getName()); } }); addInstance.setOnAction(event -> { FXMLLoader loader = new FXMLLoader(getClass().getResource("/layout/configurer/AddNewInstance.fxml")); try { final Parent addDAParent = loader.load(); final AddNewInstanceController controller = loader.getController(); final Stage dialogue = new Stage(); controller.onSave(inf -> { instanceInfos.add(inf); dialogue.close(); }); controller.onCancel(dialogue::close); showDialogueAndWait(parentStage, addDAParent, dialogue); daTable.refresh(); } catch (IOException e) { handleUnexpectedException(e, "Failed to open 'Add DA' dialogue"); } }); addCandidate.setOnAction(event -> { try { FXMLLoader loader = new FXMLLoader(getClass().getResource("/layout/configurer/AddNewCandidate.fxml")); final Parent addCandidateParent = loader.load(); final AddNewCandidateController controller = loader.getController(); final Stage dialogue = new Stage(); controller.onSave(candidate -> { candidates.add(candidate); dialogue.close(); }); controller.onCancel(dialogue::close); controller.setIdx(candidates.stream().mapToInt(Candidate::getIdx).max().orElse(-1) + 1); showDialogueAndWait(parentStage, addCandidateParent, dialogue); candidateTable.refresh(); } catch (IOException e) { handleUnexpectedException(e, "Failed to open 'Add Candidate' dialogue"); } }); importDA.setOnAction(event -> { FXMLLoader loader = new FXMLLoader(getClass().getResource("/layout/configurer/csv/CSVImport.fxml")); try { final Parent addDAParent = loader.load(); final CSVImportController controller = loader.getController(); final Stage dialogue = new Stage(); controller.configure( daInfos -> { instanceInfos.addAll(daInfos); dialogue.close(); }, new InstanceCSVConfig() ); controller.onCancel(dialogue::close); showDialogueAndWait(parentStage, addDAParent, dialogue); daTable.refresh(); } catch (IOException e) { handleUnexpectedException(e, "Failed to open 'Add DA' dialogue"); } }); importCandidates.setOnAction(event -> { FXMLLoader loader = new FXMLLoader(getClass().getResource("/layout/configurer/csv/CSVImport.fxml")); try { final Parent csvParent = loader.load(); final CSVImportController controller = loader.getController(); final Stage dialogue = new Stage(); controller.configure( candidateList -> { candidates.addAll(candidateList); dialogue.close(); }, new CandidateCSVConfig() ); controller.onCancel(dialogue::close); showDialogueAndWait(parentStage, csvParent, dialogue); daTable.refresh(); } catch (IOException e) { handleUnexpectedException(e, "Failed to open 'Add Instance' dialogue"); } }); SortedList sortedInfos = new SortedList<>(instanceInfos); sortedInfos.comparatorProperty().bind(daTable.comparatorProperty()); daTable.setItems(sortedInfos); id.setCellValueFactory(new PropertyValueFactory<>("id")); address.setCellValueFactory(new PropertyValueFactory<>("address")); type.setCellValueFactory(new PropertyValueFactory<>("type")); populateCandidateTable( candidateTable, candidates, candidateIdx, candidateName, candidateDescription ); doBuild.setOnAction(this::doBuild); } private void doBuild(ActionEvent event) { final Alert waitAlert = new Alert(Alert.AlertType.INFORMATION); waitAlert.setTitle("Operation in progress"); waitAlert.setContentText("Computing configuration files"); waitAlert.setHeaderText("Please wait... "); ProgressIndicator progress = new ProgressIndicator(); waitAlert.setGraphic(progress); waitAlert.getDialogPane().lookupButton(ButtonType.OK).setVisible(false); waitAlert.show(); new Thread(() -> { try { configurationBuilder.setDaAddresses( instanceInfos.stream() .filter(i -> InstanceType.DA.equals(i.getType())) .collect(Collectors.toMap(InstanceInfo::getId, InstanceInfo::getAddress)) ); configurationBuilder.setBbPeerAddresses( instanceInfos.stream() .filter(i -> InstanceType.BB.equals(i.getType())) .collect(Collectors.toMap(InstanceInfo::getId, InstanceInfo::getAddress)) ); configurationBuilder.setElectionDuration(new ConfigurationBuilder.Duration( Integer.parseInt(days.getText()), Integer.parseInt(hours.getText()), Integer.parseInt(minutes.getText()) )); configurationBuilder.setCandidates(candidates); configurationBuilder.build(); } catch (BuildFailedException | NumberFormatException e) { Platform.runLater(() -> { final Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Configuration Error"); alert.setHeaderText("Failed to produce configuration output"); alert.setContentText(e.getMessage()); alert.showAndWait(); }); } finally { Platform.runLater(waitAlert::close); } }).start(); } @Override public void manage(Stage parentStage) { this.parentStage = parentStage; try { Parent root = FXMLLoader.load(getClass().getResource("/layout/configurer/ConfigureMain.fxml")); parentStage.setScene(new Scene(root)); parentStage.centerOnScreen(); parentStage.show(); } catch (IOException e) { throw new RuntimeException("Failed to load resource", e); } } public static class InstanceInfo { public final int id; public final String address; public final InstanceType type; public InstanceInfo(int id, String address, InstanceType type) { this.id = id; this.address = address; this.type = type; } public int getId() { return id; } public String getAddress() { return address; } public InstanceType getType() { return type; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; InstanceInfo that = (InstanceInfo) o; return id == that.id && Objects.equals(address, that.address) && type == that.type; } @Override public int hashCode() { return Objects.hash(id, address, type); } } } misc/services/camel/de-metas-camel-edi/src/main/java/de/metas/edi/esb/desadvexport/stepcom/StepComXMLDesadvBean.java /* * #%L * de-metas-edi-esb-camel * %% * Copyright (C) 2020 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * . * #L% */ package de.metas.edi.esb.desadvexport.stepcom; import static de.metas.edi.esb.commons.Util.formatNumber; import static de.metas.edi.esb.commons.Util.toDate; import static de.metas.edi.esb.commons.Util.toFormattedStringDate; import static de.metas.edi.esb.commons.Util.trimAndTruncate; import static de.metas.edi.esb.commons.ValidationHelper.validateObject; import static de.metas.edi.esb.commons.ValidationHelper.validateString; import static java.math.BigDecimal.ZERO; import java.math.BigDecimal; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import javax.xml.datatype.XMLGregorianCalendar; import de.metas.edi.esb.commons.DesadvSettings; import de.metas.edi.esb.desadvexport.LineAndPack; import org.apache.camel.Exchange; import org.apache.camel.RuntimeCamelException; import org.apache.commons.lang.StringUtils; import org.springframework.lang.Nullable; import de.metas.edi.esb.commons.Constants; import de.metas.edi.esb.commons.SystemTime; import de.metas.edi.esb.commons.Util; import de.metas.edi.esb.commons.ValidationHelper; import de.metas.edi.esb.jaxb.metasfresh.EDIExpCBPartnerLocationType; import de.metas.edi.esb.jaxb.metasfresh.EDIExpCUOMType; import de.metas.edi.esb.jaxb.metasfresh.EDIExpDesadvLinePackType; import de.metas.edi.esb.jaxb.metasfresh.EDIExpDesadvLineType; import de.metas.edi.esb.jaxb.metasfresh.EDIExpDesadvType; import de.metas.edi.esb.jaxb.stepcom.desadv.DETAILXlief; import de.metas.edi.esb.jaxb.stepcom.desadv.DMARK1; import de.metas.edi.esb.jaxb.stepcom.desadv.DPRDE1; import de.metas.edi.esb.jaxb.stepcom.desadv.DPRIN1; import de.metas.edi.esb.jaxb.stepcom.desadv.DQUAN1; import de.metas.edi.esb.jaxb.stepcom.desadv.DQVAR1; import de.metas.edi.esb.jaxb.stepcom.desadv.DREFE1; import de.metas.edi.esb.jaxb.stepcom.desadv.Document; import de.metas.edi.esb.jaxb.stepcom.desadv.HADRE1; import de.metas.edi.esb.jaxb.stepcom.desadv.HDATE1; import de.metas.edi.esb.jaxb.stepcom.desadv.HEADERXlief; import de.metas.edi.esb.jaxb.stepcom.desadv.HREFE1; import de.metas.edi.esb.jaxb.stepcom.desadv.ObjectFactory; import de.metas.edi.esb.jaxb.stepcom.desadv.PACKINXlief; import de.metas.edi.esb.jaxb.stepcom.desadv.PPACK1; import de.metas.edi.esb.jaxb.stepcom.desadv.TRAILR; import de.metas.edi.esb.jaxb.stepcom.desadv.Xlief4H; import de.metas.edi.esb.commons.MeasurementUnit; import de.metas.edi.esb.desadvexport.stepcom.qualifier.AddressQual; import de.metas.edi.esb.desadvexport.stepcom.qualifier.ControlQual; import de.metas.edi.esb.desadvexport.stepcom.qualifier.DateQual; import de.metas.edi.esb.desadvexport.stepcom.qualifier.DiscrepencyCode; import de.metas.edi.esb.desadvexport.stepcom.qualifier.DocumentFunction; import de.metas.edi.esb.desadvexport.stepcom.qualifier.DocumentType; import de.metas.edi.esb.desadvexport.stepcom.qualifier.IdentificationQual; import de.metas.edi.esb.desadvexport.stepcom.qualifier.PackIdentificationQual; import de.metas.edi.esb.desadvexport.stepcom.qualifier.PackagingLevel; import de.metas.edi.esb.desadvexport.stepcom.qualifier.ProductDescQual; import de.metas.edi.esb.desadvexport.stepcom.qualifier.ProductDescType; import de.metas.edi.esb.desadvexport.stepcom.qualifier.ProductQual; import de.metas.edi.esb.desadvexport.stepcom.qualifier.QuantityQual; import de.metas.edi.esb.desadvexport.stepcom.qualifier.ReferenceQual; import de.metas.edi.esb.commons.route.AbstractEDIRoute; import lombok.NonNull; import lombok.Value; public class StepComXMLDesadvBean { public static final String METHOD_createXMLEDIData = "createXMLEDIData"; private static final String DEFAULT_PACK_DETAIL = "1"; private static final ObjectFactory DESADV_objectFactory = new ObjectFactory(); public final void createXMLEDIData(@NonNull final Exchange exchange) { final StepComDesadvValidation validation = new StepComDesadvValidation(); // validate mandatory exchange properties final EDIExpDesadvType xmlDesadv = validation.validateExchange(exchange); // throw exceptions if mandatory fields are missing final DesadvSettings settings = DesadvSettings.forReceiverGLN(exchange.getContext(), xmlDesadv.getCBPartnerID().getEdiRecipientGLN()); final Xlief4H xlief4H = createDesadvDocumentFromXMLBean(xmlDesadv, exchange, settings); final Document document = DESADV_objectFactory.createDocument(); document.getXlief4H().add(xlief4H); exchange.getIn().setBody(DESADV_objectFactory.createDocument(document)); final String fileName = settings.getFileNamePrefix() + "_" + xlief4H.getHEADER().getDOCUMENTID() + "_" + SystemTime.millis() + ".xml"; exchange.getIn().setHeader(Exchange.FILE_NAME, fileName); } private Xlief4H createDesadvDocumentFromXMLBean( @NonNull final EDIExpDesadvType xmlDesadv, @NonNull final Exchange exchange, @NonNull final DesadvSettings settings) { // TODO instead of adding all the properties above to the exchange, add them to this settings instance final DecimalFormat decimalFormat = exchange.getProperty(Constants.DECIMAL_FORMAT, DecimalFormat.class); final String dateFormat = (String)exchange.getProperty(AbstractEDIRoute.EDI_ORDER_EDIMessageDatePattern); final String ownerId = exchange.getProperty(StepComXMLDesadvRoute.EDI_XML_OWNER_ID, String.class); final String supplierGln = exchange.getProperty(StepComXMLDesadvRoute.EDI_XML_SUPPLIER_GLN, String.class); xmlDesadv.getEDIExpDesadvLine().sort(Comparator.comparing(EDIExpDesadvLineType::getLine)); final Xlief4H xlief4H = DESADV_objectFactory.createXlief4H(); final HEADERXlief header = DESADV_objectFactory.createHEADERXlief(); final String documentId = xmlDesadv.getDocumentNo(); header.setDOCUMENTID(documentId); header.setPARTNERID(settings.getPartnerId()); header.setOWNERID(ownerId); header.setTESTINDICATOR(settings.getTestIndicator()); header.setMESSAGEREF(formatNumber(xmlDesadv.getSequenceNoAttr(), decimalFormat)); if (!Util.isEmpty(settings.getApplicationRef())) { header.setAPPLICATIONREF(settings.getApplicationRef()); } header.setDOCUMENTTYP(DocumentType.DADV.toString()); header.setDOCUMENTFUNCTION(DocumentFunction.ORIG.toString()); mapDates(xmlDesadv, header, dateFormat); mapHeaderReferences(xmlDesadv, header, settings, dateFormat); mapAddresses(xmlDesadv, header, supplierGln); mapPackaging(xmlDesadv, header, settings, decimalFormat, dateFormat); final TRAILR trailr = DESADV_objectFactory.createTRAILR(); trailr.setDOCUMENTID(documentId); trailr.setCONTROLQUAL(ControlQual.LINE.toString()); trailr.setCONTROLVALUE(formatNumber(xmlDesadv.getEDIExpDesadvLine().size(), decimalFormat)); xlief4H.setHEADER(header); xlief4H.setTRAILR(trailr); return xlief4H; } private void mapDates( @NonNull final EDIExpDesadvType xmlDesadv, @NonNull final HEADERXlief header, @NonNull final String dateFormat) { final HDATE1 messageDate = DESADV_objectFactory.createHDATE1(); messageDate.setDOCUMENTID(header.getDOCUMENTID()); messageDate.setDATEQUAL(DateQual.CREA.toString()); messageDate.setDATEFROM(toFormattedStringDate(SystemTime.asDate(), dateFormat)); final HDATE1 deliveryDate = DESADV_objectFactory.createHDATE1(); deliveryDate.setDOCUMENTID(header.getDOCUMENTID()); deliveryDate.setDATEQUAL(DateQual.DELV.toString()); deliveryDate.setDATEFROM(toFormattedStringDate(toDate(xmlDesadv.getMovementDate()), dateFormat)); header.getHDATE1().add(messageDate); header.getHDATE1().add(deliveryDate); } private void mapHeaderReferences( @NonNull final EDIExpDesadvType xmlDesadv, @NonNull final HEADERXlief header, @NonNull final DesadvSettings settings, @NonNull final String dateFormat) { final String buyerReference = xmlDesadv.getPOReference(); final HREFE1 orderReference = DESADV_objectFactory.createHREFE1(); orderReference.setDOCUMENTID(header.getDOCUMENTID()); orderReference.setREFERENCEQUAL(ReferenceQual.ORBU.toString()); orderReference.setREFERENCE(buyerReference); orderReference.setREFERENCEDATE1(toFormattedStringDate(toDate(xmlDesadv.getDateOrdered()), dateFormat)); header.getHREFE1().add(orderReference); if (!Util.isEmpty(settings.getDesadvHeaderORIGReference())) { final HREFE1 origReference = DESADV_objectFactory.createHREFE1(); origReference.setDOCUMENTID(header.getDOCUMENTID()); origReference.setREFERENCEQUAL(ReferenceQual.ORIG.toString()); origReference.setREFERENCE(settings.getDesadvHeaderORIGReference().trim()); origReference.setREFERENCEDATE1(toFormattedStringDate(toDate(xmlDesadv.getDateOrdered()), dateFormat)); header.getHREFE1().add(origReference); } } private void mapAddresses( @NonNull final EDIExpDesadvType xmlDesadv, @NonNull final HEADERXlief header, @NonNull final String supplierGln) { final EDIExpCBPartnerLocationType buyrLocation = validateObject(xmlDesadv.getCBPartnerLocationID(), "@FillMandatory@ @EDI_Desadv_ID@=" + xmlDesadv.getDocumentNo() + " @C_BPartner_Location_ID@"); final HADRE1 buyerAddress = DESADV_objectFactory.createHADRE1(); buyerAddress.setDOCUMENTID(header.getDOCUMENTID()); buyerAddress.setADDRESSQUAL(AddressQual.BUYR.toString()); buyerAddress.setPARTYIDGLN(buyrLocation.getGLN()); header.getHADRE1().add(buyerAddress); final EDIExpCBPartnerLocationType delvLocation = xmlDesadv.getHandOverLocationID() != null ? xmlDesadv.getHandOverLocationID() : buyrLocation; final HADRE1 deliveryAddress = DESADV_objectFactory.createHADRE1(); deliveryAddress.setDOCUMENTID(header.getDOCUMENTID()); deliveryAddress.setADDRESSQUAL(AddressQual.DELV.toString()); deliveryAddress.setPARTYIDGLN(delvLocation.getGLN()); header.getHADRE1().add(deliveryAddress); final HADRE1 supplierAddress = DESADV_objectFactory.createHADRE1(); supplierAddress.setDOCUMENTID(header.getDOCUMENTID()); supplierAddress.setADDRESSQUAL(AddressQual.SUPL.toString()); supplierAddress.setPARTYIDGLN(supplierGln); header.getHADRE1().add(supplierAddress); // TODO: add shipToLocation to the desadv final HADRE1 ucAddress = DESADV_objectFactory.createHADRE1(); ucAddress.setDOCUMENTID(header.getDOCUMENTID()); ucAddress.setADDRESSQUAL(AddressQual.ULCO.toString()); ucAddress.setPARTYIDGLN(buyrLocation.getGLN()); header.getHADRE1().add(ucAddress); // address HCTAD1 contact not mapped for now // transport details HTRSD1 not mapped for now } private void mapPackaging( @NonNull final EDIExpDesadvType xmlDesadv, @NonNull final HEADERXlief header, @NonNull final DesadvSettings settings, @NonNull final DecimalFormat decimalFormat, @NonNull final String dateFormat) { final PACKINXlief packIn = DESADV_objectFactory.createPACKINXlief(); header.setPACKIN(packIn); packIn.setDOCUMENTID(header.getDOCUMENTID()); final boolean ssccRequired = settings.isDesadvLineSSCCRequired(); final boolean packagingCodeTURequired = settings.isDesadvLinePackagingCodeTURequired(); final boolean ppack1NeededInGeneral = ssccRequired || packagingCodeTURequired; if (ppack1NeededInGeneral) { int packagingTotalNumber = 0; for (final EDIExpDesadvLineType line : xmlDesadv.getEDIExpDesadvLine()) { BigDecimal qtyDelivered = ZERO; final String documentId = xmlDesadv.getDocumentNo(); final String lineNumber = extractLineNumber(line, decimalFormat); final List packs = line.getEDIExpDesadvLinePack(); if (packs.isEmpty()) { final LineAndPack lineAndPack = new LineAndPack(line, null/* pack */); final DETAILXlief detail = createDETAILXliefForLineAndPack(xmlDesadv, lineAndPack, settings, decimalFormat, dateFormat); packIn.getDETAIL().add(detail); // check if we need a discrepancy information final BigDecimal quantityDiff = ZERO.subtract(line.getQtyEntered()); if (settings.isDesadvLineDQVAR1() && quantityDiff.signum() != 0) { detail.setDOCUMENTID(documentId); detail.setLINENUMBER(lineNumber); final DQVAR1 dqvar1 = createDQVAR1(documentId, line, quantityDiff, decimalFormat); detail.setDQVAR1(dqvar1); } continue; } for (final EDIExpDesadvLinePackType pack : packs) { final LineAndPack lineAndPack = new LineAndPack(line, pack); boolean detailAdded = false; if (ssccRequired) { final PPACK1 ppack1 = createPPACK1(header); packIn.getPPACK1().add(ppack1); final String sscc18 = validateString( lineAndPack.getPack().getIPASSCC18(), "@FillMandatory@ SSCC in @EDI_DesadvLine_ID@ " + lineAndPack.getLine().getLine()); ppack1.setIDENTIFICATIONCODE(Util.lpadZero(sscc18, 18)/* if ssccRequired and we got here, then this is not null */); ppack1.setIDENTIFICATIONQUAL(PackIdentificationQual.SSCC.toString()); if (settings.isDesadvLinePackagingCodeLURequired()) { final String packagingCodeLU = validateString( lineAndPack.getPack().getMHUPackagingCodeLUText(), "@FillMandatory@ @EDI_DesadvLine_ID@=" + lineAndPack.getLine().getLine() + " @M_HU_PackagingCode_LU_ID@"); ppack1.setPACKAGINGCODE(packagingCodeLU); ppack1.setPACKAGINGLEVEL(PackagingLevel.OUTE.toString()); } final DETAILXlief detailXlief = createDETAILXliefForLineAndPack(xmlDesadv, lineAndPack, settings, decimalFormat, dateFormat); ppack1.getDETAIL().add(detailXlief); detailAdded = true; } if (packagingCodeTURequired) { final PPACK1 ppack1 = createPPACK1(header); packIn.getPPACK1().add(ppack1); final String packagingCodeTU = validateString( lineAndPack.getPack().getMHUPackagingCodeTUText(), "@FillMandatory@ @EDI_DesadvLine_ID@=" + lineAndPack.getLine().getLine() + " @M_HU_PackagingCode_TU_ID@"); ppack1.setPACKAGINGCODE(packagingCodeTU); ppack1.setPACKAGINGLEVEL(PackagingLevel.INNE.toString()); if (!detailAdded) { final DETAILXlief detailXlief = createDETAILXliefForLineAndPack(xmlDesadv, lineAndPack, settings, decimalFormat, dateFormat); ppack1.getDETAIL().add(detailXlief); } } packagingTotalNumber++; // if there are no PPacks,packagingTotalNumber shall remain zero qtyDelivered = qtyDelivered.add(extractQtyDelivered(lineAndPack.getPack())); } // we iterated all packs if the current line; now check if we a discrepancy information final BigDecimal quantityDiff = qtyDelivered.subtract(line.getQtyEntered()); if (settings.isDesadvLineDQVAR1() && quantityDiff.signum() != 0) { final DETAILXlief detail = DESADV_objectFactory.createDETAILXlief(); detail.setDOCUMENTID(documentId); detail.setLINENUMBER(lineNumber); final DQVAR1 dqvar1 = createDQVAR1(documentId, line, quantityDiff, decimalFormat); detail.setDQVAR1(dqvar1); } } packIn.setPACKAGINGTOTAL(formatNumber(packagingTotalNumber, decimalFormat)); } else { final PackagingLUGroupings packagingCodeLUs = extractPackagingCodeLU(xmlDesadv.getEDIExpDesadvLine(), settings); // has at least one key, even if there is no packagingCodeLU if (packagingCodeLUs.hasSinglePackagingCode()) { // only one global packagingCodeLU, so no need for PPACK1s. We can add the one packagingCodeLU to the PACKIN if (settings.isDesadvLinePackagingCodeLURequired()) { final String packagingCodeLUText = packagingCodeLUs.getSinglePackagingCode(); final String packagingCodeLU = validateString( "NONE".equals(packagingCodeLUText) ? null : packagingCodeLUText, "@FillMandatory@ @EDI_Desadv_ID@=" + xmlDesadv.getDocumentNo() + " @M_HU_PackagingCode_LU_ID@"); packIn.setPACKAGINGCODE(packagingCodeLU); packIn.setPACKAGINGLEVEL(PackagingLevel.OUTE.toString()); } for (final EDIExpDesadvLineType line : xmlDesadv.getEDIExpDesadvLine()) { // don't create PPACK1s, but create one aggregated detail per line final DETAILXlief detailXlief = createDETAILXliefForLine(xmlDesadv, line, settings, decimalFormat, dateFormat); packIn.getDETAIL().add(detailXlief); } } else { for (final String packagingCodeLUText : packagingCodeLUs.getPackagingCodes()) { final PPACK1 ppack1 = createPPACK1(header); packIn.getPPACK1().add(ppack1); // no need to have PPACK1s. We can add the one packagingCodeLU to the PACKIN if (settings.isDesadvLinePackagingCodeLURequired()) { final String packagingCodeLU = validateString( "NONE".equals(packagingCodeLUText) ? null : packagingCodeLUText, // fail if "NONE" "@FillMandatory@ @EDI_Desadv_ID@=" + xmlDesadv.getDocumentNo() + " @M_HU_PackagingCode_LU_ID@"); ppack1.setPACKAGINGCODE(packagingCodeLU); ppack1.setPACKAGINGLEVEL(PackagingLevel.OUTE.toString()); } for (final EDIExpDesadvLineType line : packagingCodeLUs.getLines(packagingCodeLUText)) { for (final EDIExpDesadvLinePackType pack : packagingCodeLUs.getPacks(packagingCodeLUText, line)) { final LineAndPack lineAndPack = new LineAndPack(line, pack); final DETAILXlief detailXlief = createDETAILXliefForLineAndPack(xmlDesadv, lineAndPack, settings, decimalFormat, dateFormat); ppack1.getDETAIL().add(detailXlief); } } } } packIn.setPACKAGINGTOTAL(formatNumber(0, decimalFormat)); } } private PackagingLUGroupings extractPackagingCodeLU( @NonNull final List lines, @NonNull final DesadvSettings settings) { final PackagingLUGroupings packingLUGroupings = new PackagingLUGroupings(); for (final EDIExpDesadvLineType line : lines) { for (final EDIExpDesadvLinePackType pack : line.getEDIExpDesadvLinePack()) { final String packagingCodeLU; if (!settings.isDesadvLinePackagingCodeLURequired()) { // Even if packagincCodes are not of interest, then still add "something", to avoid having different keys that we don't actually care for packagingCodeLU = "NONE"; } else { packagingCodeLU = StringUtils.isEmpty(pack.getMHUPackagingCodeLUText()) ? "NONE" : pack.getMHUPackagingCodeLUText(); } packingLUGroupings.add(packagingCodeLU, line, pack); } } return packingLUGroupings; } /** Needed if we have to partition our lines and packs by different LU-packagingCodes. One line can have more than one different LU-packagingCode. */ @Value // note that this class is NOT immutable private static class PackagingLUGroupings { LinkedHashMap> packagingCodeTolines = new LinkedHashMap<>(); Map> packs = new HashMap<>(); public void add( @NonNull final String packagingCodeLU, @NonNull final EDIExpDesadvLineType line, @NonNull final EDIExpDesadvLinePackType pack) { final LinkedHashSet codeLines = packagingCodeTolines.computeIfAbsent(packagingCodeLU, key -> new LinkedHashSet<>()); codeLines.add(line); final PackagingCodeLUAndLine packagingCodeLUAndLine = new PackagingCodeLUAndLine(packagingCodeLU, line); final List codeAndLinePacks = packs.computeIfAbsent(packagingCodeLUAndLine, key -> new ArrayList<>()); codeAndLinePacks.add(pack); } public boolean hasSinglePackagingCode() { return packagingCodeTolines.size() == 1; } public String getSinglePackagingCode() { return packagingCodeTolines.keySet().iterator().next(); } public Collection getPackagingCodes() { return packagingCodeTolines.keySet(); } public Collection getLines(@NonNull final String packagingCodeLUText) { return packagingCodeTolines.get(packagingCodeLUText); } public Collection getPacks(@NonNull final String packagingCodeLU, @NonNull final EDIExpDesadvLineType line) { final PackagingCodeLUAndLine packagingCodeLUAndLine = new PackagingCodeLUAndLine(packagingCodeLU, line); return packs.get(packagingCodeLUAndLine); } } @Value private static class PackagingCodeLUAndLine { String packagingCodeLU; EDIExpDesadvLineType line; } private PPACK1 createPPACK1(@NonNull final HEADERXlief header) { final PPACK1 ppack1 = DESADV_objectFactory.createPPACK1(); ppack1.setDOCUMENTID(header.getDOCUMENTID()); ppack1.setPACKAGINGDETAIL(DEFAULT_PACK_DETAIL); // one, as per spec return ppack1; } private DETAILXlief createDETAILXliefForLineAndPack( @NonNull final EDIExpDesadvType xmlDesadv, @NonNull final LineAndPack lineAndPack, @NonNull final DesadvSettings settings, @NonNull final DecimalFormat decimalFormat, @NonNull final String dateFormat) { final EDIExpDesadvLineType line = lineAndPack.getLine(); final DETAILXlief detail = createDetailAndAddLineData(xmlDesadv, line, settings, decimalFormat); final String documentId = xmlDesadv.getDocumentNo(); final String lineNumber = extractLineNumber(line, decimalFormat); final BigDecimal qtyDelivered = extractQtyDelivered(lineAndPack.getPack()); final DQUAN1 cuQuantity = createQuantityDetail(documentId, lineNumber, QuantityQual.DELV); cuQuantity.setQUANTITY(formatNumber(qtyDelivered, decimalFormat)); detail.getDQUAN1().add(cuQuantity); // we set some of cuQuantity's properties in the following if-else-blocks if (lineAndPack.hasPack()) { final EDIExpDesadvLinePackType pack = lineAndPack.getPack(); final String measurementUnitName = extractMeasurementUnitOrNull(pack.getCUOMID(), line, settings); cuQuantity.setMEASUREMENTUNIT(measurementUnitName); if (settings.isDesadvLineCUTURequired()) { final BigDecimal qtyItemCapacity = validateObject(pack.getQtyCU(), "@FillMandatory@ @EDI_DesadvLine_ID@=" + line.getLine() + " @QtyCU@"); final DQUAN1 cuTuQuantity = createQuantityDetail(documentId, lineNumber, QuantityQual.CUTU); cuTuQuantity.setQUANTITY(formatNumber(qtyItemCapacity, decimalFormat)); cuTuQuantity.setMEASUREMENTUNIT(measurementUnitName); detail.getDQUAN1().add(cuTuQuantity); } final boolean dmark1Required = settings.isDesadvLineDMARK1BestBeforeDateRequired() // || settings.isDesadvLineDMARK1BatchNoRequired(); if (dmark1Required) { final String lotNumber = validateString(pack.getLotNumber(), "@FillMandatory@ @EDI_DesadvLine_ID@=" + line.getLine() + " @LotNumber@"); final DMARK1 dmark1 = DESADV_objectFactory.createDMARK1(); dmark1.setDOCUMENTID(documentId); dmark1.setLINENUMBER(lineNumber); dmark1.setIDENTIFICATIONQUAL(IdentificationQual.BATC.name()); dmark1.setIDENTIFICATIONCODE(lotNumber); if (settings.isDesadvLineDMARK1BestBeforeDateRequired()) { final XMLGregorianCalendar bestBefore = validateObject(pack.getBestBeforeDate(), "@FillMandatory@ @EDI_DesadvLine_ID@=" + line.getLine() + " @BestBeforeDate@"); dmark1.setIDENTIFICATIONDATE1(toFormattedStringDate(toDate(bestBefore), dateFormat)); } detail.getDMARK1().add(dmark1); } } return detail; } private DETAILXlief createDETAILXliefForLine( @NonNull final EDIExpDesadvType xmlDesadv, @NonNull final EDIExpDesadvLineType line, @NonNull final DesadvSettings settings, @NonNull final DecimalFormat decimalFormat, @NonNull final String dateFormat) { BigDecimal qtyCU = null; BigDecimal qtyDelivered = ZERO; String measurementUnitName = null; for (final EDIExpDesadvLinePackType pack : line.getEDIExpDesadvLinePack()) { qtyDelivered = qtyDelivered.add(extractQtyDelivered(pack)); measurementUnitName = extractMeasurementUnitOrNull(pack.getCUOMID(), line, settings); qtyCU = pack.getQtyCU(); } if (measurementUnitName == null) // case: there were no packs { measurementUnitName = extractMeasurementUnitOrNull(line.getCUOMID(), line, settings); } final String documentId = xmlDesadv.getDocumentNo(); final String lineNumber = extractLineNumber(line, decimalFormat); // now create the detail and add our stuff final DETAILXlief detail = createDetailAndAddLineData(xmlDesadv, line, settings, decimalFormat); final DQUAN1 cuQuantity = createQuantityDetail(documentId, lineNumber, QuantityQual.DELV); detail.getDQUAN1().add(cuQuantity); cuQuantity.setQUANTITY(formatNumber(qtyDelivered, decimalFormat)); cuQuantity.setMEASUREMENTUNIT(measurementUnitName); if (qtyDelivered.signum() > 0 && settings.isDesadvLineCUTURequired()) { final BigDecimal qtyItemCapacity = validateObject(qtyCU, "@FillMandatory@ @EDI_DesadvLine_ID@=" + line.getLine() + " @QtyCU@"); final DQUAN1 cuTuQuantity = createQuantityDetail(documentId, lineNumber, QuantityQual.CUTU); cuTuQuantity.setQUANTITY(formatNumber(qtyItemCapacity, decimalFormat)); cuTuQuantity.setMEASUREMENTUNIT(measurementUnitName); detail.getDQUAN1().add(cuTuQuantity); } // check if we need a discrepancy information final BigDecimal quantityDiff = qtyDelivered.subtract(line.getQtyEntered()); if (settings.isDesadvLineDQVAR1() && quantityDiff.signum() != 0) { detail.setDOCUMENTID(documentId); detail.setLINENUMBER(lineNumber); final DQVAR1 dqvar1 = createDQVAR1(documentId, line, quantityDiff, decimalFormat); detail.setDQVAR1(dqvar1); } return detail; } private String extractMeasurementUnitOrNull( @Nullable final EDIExpCUOMType uom, @NonNull final EDIExpDesadvLineType line, @NonNull final DesadvSettings settings) { if (!settings.isDesadvLineMEASUREMENTUNITRequired()) { return null; } final String x12DE355 = ValidationHelper.validateString( uom == null ? null : uom.getX12DE355(), "@FillMandatory@ @EDI_DesadvLine_ID@=" + line.getLine() + " @C_UOM_ID@"); final MeasurementUnit measurementUnit = MeasurementUnit.fromMetasfreshUOM(x12DE355); if (!settings.isMeasurementUnitAllowed(measurementUnit)) { throw new RuntimeCamelException("@C_InvoiceLine_ID@=" + line.getLine() + " @C_UOM_ID@=" + settings.getDesadvLineRequiredMEASUREMENTUNIT() + " @REQUIRED@"); } return measurementUnit == null ? null : measurementUnit.name(); } private String extractLineNumber(@NonNull final EDIExpDesadvLineType line, @NonNull final DecimalFormat decimalFormat) { return formatNumber(line.getLine(), decimalFormat); } private DETAILXlief createDetailAndAddLineData( @NonNull final EDIExpDesadvType xmlDesadv, @NonNull final EDIExpDesadvLineType line, @NonNull final DesadvSettings settings, final DecimalFormat decimalFormat) { final DETAILXlief detail = DESADV_objectFactory.createDETAILXlief(); final String documentId = xmlDesadv.getDocumentNo(); detail.setDOCUMENTID(documentId); final String lineNumber = extractLineNumber(line, decimalFormat); detail.setLINENUMBER(lineNumber); if (settings.isDesadvLineEANCRequired()) { final String eanc = ValidationHelper.validateString(line.getEANCU(), "@FillMandatory@ @EDI_DesadvLine_ID@=" + line.getLine() + " @EANCU@"); final DPRIN1 eancProdInfo = DESADV_objectFactory.createDPRIN1(); eancProdInfo.setDOCUMENTID(documentId); eancProdInfo.setPRODUCTQUAL(ProductQual.EANC.toString()); eancProdInfo.setLINENUMBER(lineNumber); eancProdInfo.setPRODUCTID(eanc); detail.getDPRIN1().add(eancProdInfo); } if (settings.isDesadvLineEANTRequired()) { final String eant = ValidationHelper.validateString(line.getEANTU(), "@FillMandatory@ @EDI_DesadvLine_ID@=" + line.getLine() + " @EANTU@"); final DPRIN1 eancProdInfo = DESADV_objectFactory.createDPRIN1(); eancProdInfo.setDOCUMENTID(documentId); eancProdInfo.setPRODUCTQUAL(ProductQual.EANT.toString()); eancProdInfo.setLINENUMBER(lineNumber); eancProdInfo.setPRODUCTID(eant); detail.getDPRIN1().add(eancProdInfo); } if (settings.isDesadvLineGTINRequired()) { final String gtin = ValidationHelper.validateString(line.getGTIN(), "@FillMandatory@ @EDI_DesadvLine_ID@=" + line.getLine() + " @GTIN@"); final DPRIN1 gtinProdInfo = DESADV_objectFactory.createDPRIN1(); gtinProdInfo.setDOCUMENTID(documentId); gtinProdInfo.setPRODUCTQUAL(ProductQual.GTIN.toString()); gtinProdInfo.setLINENUMBER(lineNumber); gtinProdInfo.setPRODUCTID(gtin); detail.getDPRIN1().add(gtinProdInfo); } if (settings.isDesadvLineUPCCRequired()) { final String upcc = ValidationHelper.validateString(line.getUPC(), "@FillMandatory@ @EDI_DesadvLine_ID@=" + line.getLine() + " @UPC@"); final DPRIN1 eancProdInfo = DESADV_objectFactory.createDPRIN1(); eancProdInfo.setDOCUMENTID(documentId); eancProdInfo.setPRODUCTQUAL(ProductQual.UPCC.toString()); eancProdInfo.setLINENUMBER(lineNumber); eancProdInfo.setPRODUCTID(upcc); detail.getDPRIN1().add(eancProdInfo); } if (settings.isDesadvLineUPCCRequired()) { final String upct = ValidationHelper.validateString(line.getUPCTU(), "@FillMandatory@ @EDI_DesadvLine_ID@=" + line.getLine() + " @UPCTU@"); final DPRIN1 eancProdInfo = DESADV_objectFactory.createDPRIN1(); eancProdInfo.setDOCUMENTID(documentId); eancProdInfo.setPRODUCTQUAL(ProductQual.UPCT.toString()); eancProdInfo.setLINENUMBER(lineNumber); eancProdInfo.setPRODUCTID(upct); detail.getDPRIN1().add(eancProdInfo); } if (settings.isDesadvLineBUYRRequired()) { final String buyr = ValidationHelper.validateString(line.getProductNo(), "@FillMandatory@ @EDI_DesadvLine_ID@=" + line.getLine() + " @ProductNo@"); final DPRIN1 prodInfo = DESADV_objectFactory.createDPRIN1(); prodInfo.setDOCUMENTID(documentId); prodInfo.setPRODUCTQUAL(ProductQual.BUYR.toString()); prodInfo.setLINENUMBER(lineNumber); prodInfo.setPRODUCTID(buyr); detail.getDPRIN1().add(prodInfo); } if (StringUtils.isNotEmpty(line.getProductDescription())) { final DPRDE1 prodDescr = DESADV_objectFactory.createDPRDE1(); prodDescr.setDOCUMENTID(documentId); prodDescr.setLINENUMBER(lineNumber); prodDescr.setPRODUCTDESCQUAL(ProductDescQual.PROD.toString()); prodDescr.setPRODUCTDESCTYPE(ProductDescType.CU.toString()); prodDescr.setPRODUCTDESCTEXT(trimAndTruncate(line.getProductDescription(), 512)); detail.getDPRDE1().add(prodDescr); } if (settings.isDesadvLinePRICRequired()) { final BigDecimal priceActual = validateObject(line.getPriceActual(), "@FillMandatory@ @EDI_DesadvLine_ID@=" + line.getLine() + " @PriceActual@"); final DPRDE1 prodDescr = DESADV_objectFactory.createDPRDE1(); prodDescr.setDOCUMENTID(documentId); prodDescr.setLINENUMBER(lineNumber); prodDescr.setPRODUCTDESCQUAL(ProductDescQual.PRIC.toString()); prodDescr.setPRODUCTDESCTYPE(ProductDescType.CU.toString()); prodDescr.setPRODUCTDESCTEXT(formatNumber(priceActual, decimalFormat)); detail.getDPRDE1().add(prodDescr); } final boolean orbuOrderReference = settings.isDesadvLineORBUOrderReference(); final boolean orbuLineReference = settings.isDesadvLineORBUOrderLineReference(); if (orbuOrderReference || orbuLineReference) { final DREFE1 orderHeaderRef = DESADV_objectFactory.createDREFE1(); orderHeaderRef.setDOCUMENTID(documentId); orderHeaderRef.setLINENUMBER(lineNumber); orderHeaderRef.setREFERENCEQUAL(ReferenceQual.ORBU.toString()); if (orbuOrderReference) { orderHeaderRef.setREFERENCE(xmlDesadv.getPOReference()); } if (orbuLineReference) { orderHeaderRef.setREFERENCELINE(lineNumber); } detail.getDREFE1().add(orderHeaderRef); } if (settings.isDesadvLineLIRN()) { final DREFE1 orderLineRef = DESADV_objectFactory.createDREFE1(); orderLineRef.setDOCUMENTID(documentId); orderLineRef.setLINENUMBER(lineNumber); orderLineRef.setREFERENCEQUAL(ReferenceQual.LIRN.toString()); orderLineRef.setREFERENCELINE(lineNumber); detail.getDREFE1().add(orderLineRef); } return detail; } private DQUAN1 createQuantityDetail( @NonNull final String documentId, @NonNull final String lineNumber, @NonNull final QuantityQual qualifier) { final DQUAN1 cuQuantity = DESADV_objectFactory.createDQUAN1(); cuQuantity.setDOCUMENTID(documentId); cuQuantity.setLINENUMBER(lineNumber); cuQuantity.setQUANTITYQUAL(qualifier.toString()); return cuQuantity; } private DQVAR1 createDQVAR1( @NonNull final String documentId, @NonNull final EDIExpDesadvLineType line, @NonNull final BigDecimal quantityDiff, @NonNull final DecimalFormat decimalFormat) { final DQVAR1 dqvar1 = DESADV_objectFactory.createDQVAR1(); dqvar1.setDOCUMENTID(documentId); dqvar1.setLINENUMBER(extractLineNumber(line, decimalFormat)); dqvar1.setQUANTITY(formatNumber(quantityDiff, decimalFormat)); dqvar1.setDISCREPANCYCODE(extractDiscrepancyCode(line.getIsSubsequentDeliveryPlanned(), quantityDiff).toString()); return dqvar1; } private BigDecimal extractQtyDelivered(@Nullable final EDIExpDesadvLinePackType pack) { if (pack == null) { return ZERO; } final BigDecimal qtyDelivered = pack.getQtyCUsPerLU(); if (qtyDelivered == null) { return ZERO; } return qtyDelivered; } private DiscrepencyCode extractDiscrepancyCode( @Nullable final String isSubsequentDeliveryPlanned, @NonNull final BigDecimal diff) { DiscrepencyCode discrepancyCode; if (diff.signum() > 0) { discrepancyCode = DiscrepencyCode.OVSH; // = Over-shipped return discrepancyCode; } if (Boolean.parseBoolean(isSubsequentDeliveryPlanned)) { discrepancyCode = DiscrepencyCode.BFOL; // = Shipment partial - back order to follow } else { discrepancyCode = DiscrepencyCode.BCOM; // = shipment partial - considered complete, no backorder; } return discrepancyCode; } } package example; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.imagesearch.model.v20180319.SearchItemResponse; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import java.io.IOException; import java.io.InputStream; import java.util.Collections; import static example.HelloServlet.MAX_FILE_SIZE; import static example.HelloServlet.MAX_REQUEST_SIZE; import static example.ImageSearchDemo.createErrorResponse; @WebServlet("/search_picture") @MultipartConfig(maxFileSize = MAX_FILE_SIZE, maxRequestSize = MAX_REQUEST_SIZE) public class HelloServlet extends HttpServlet { private ImageSearchDemo demo; private static Properties props; private static final Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); // max size 2MB https://www.alibabacloud.com/help/doc-detail/66610.htm static final int MAX_FILE_SIZE = 1024 * 1024 * 2; // 2MB static final int MAX_REQUEST_SIZE = 1024 * 1024 * 8; // 8MB public HelloServlet() throws IOException, ClientException { demo = new ImageSearchDemo(); props = new Properties("image-search.properties"); } public HelloServlet(ImageSearchDemo demo) throws IOException { this.demo = demo; props = new Properties("image-search.properties"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF8"); Part part = req.getPart("file_name"); InputStream inputStream = part.getInputStream(); if (inputStream.available() == 0) { String message = "ERR: input file is empty."; System.out.println(message); SearchItemResponse response = createErrorResponse(message); respondJson(resp, response); } else { String catId = req.getParameter("cat_id"); // can be null System.out.println("INPUT POST catId: " + catId); searchPicture(resp, inputStream, catId); } } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { String fileName = "image_search_pictures/bag02.jpg"; InputStream inputStream = Resources.getInputStream(fileName); String catId = req.getParameter("cat_id"); // can be null System.out.println("INPUT GET catId: " + catId); searchPicture(resp, inputStream, catId); } private void searchPicture(HttpServletResponse resp, InputStream inputStream, String catId) throws IOException { SearchItemResponse response = demo.searchPictureWithResize(inputStream, catId); respondJson(resp, response); } private void respondJson(HttpServletResponse resp, SearchItemResponse response) throws IOException { resp.setContentType("application/json"); resp.setCharacterEncoding("utf-8"); resp.setHeader("Access-Control-Allow-Origin", props.get("CORS_URL")); resp.getWriter().write(prettyGson.toJson( Collections.singletonMap("SearchItemResponse", response) )); } } 1-10 package com.jeiker.demo; import org.springframework.amqp.rabbit.annotation.RabbitHandler; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; /** * 消息: 消费者 * @Author : xiao * @Date : 17/6/27 下午3:59 */ @Component @RabbitListener(queues = "hello") public class Consumer { @RabbitHandler public void process(String hello) { System.out.println("Consumer : " + hello); } } src/main/java/rbasamoyai/industrialwarfare/common/capabilities/itemstacks/partitem/PartItemDataCapability.java package rbasamoyai.industrialwarfare.common.capabilities.itemstacks.partitem; import net.minecraft.nbt.CompoundNBT; import net.minecraft.nbt.INBT; import net.minecraft.util.Direction; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.CapabilityInject; import net.minecraftforge.common.capabilities.CapabilityManager; import rbasamoyai.industrialwarfare.common.capabilities.itemstacks.qualityitem.QualityItemDataCapability; public class PartItemDataCapability { public static final String TAG_PART_COUNT = "partCount"; // Just a general part count, not as important as the part weight public static final String TAG_WEIGHT = "weight"; // Refers to how much the quality of an item will impact part quality aspect the of the crafted product quality @CapabilityInject(IPartItemDataHandler.class) public static Capability PART_ITEM_DATA_CAPABILITY = null; public static void register() { CapabilityManager.INSTANCE.register(IPartItemDataHandler.class, new Storage<>(), PartItemDataHandler::new); } public static class Storage extends QualityItemDataCapability.Storage { @Override public INBT writeNBT(Capability capability, T instance, Direction side) { CompoundNBT tag = (CompoundNBT) super.writeNBT(capability, instance, side); tag.putInt(TAG_PART_COUNT, instance.getPartCount()); tag.putFloat(TAG_WEIGHT, instance.getWeight()); return tag; } @Override public void readNBT(Capability capability, T instance, Direction side, INBT nbt) { super.readNBT(capability, instance, side, nbt); CompoundNBT tag = (CompoundNBT) nbt; instance.setPartCount(tag.getInt(TAG_PART_COUNT)); instance.setWeight(tag.getFloat(TAG_WEIGHT)); } } } heheiscool/23designpattern669-EmoticonWar/src/main/java/content/substance/Ground.java package main.java.content.substance; import main.java.auxiliary.Constant; import main.java.base.BaseElement; import main.java.base.IElement; import main.java.content.player.Player; import java.awt.*; /** * @author 左边牙齿疼 * @Description: 地面 从下往上绘制多张礼物盒图片拼凑而成 * @date 2019/3/23 */ @IElement("groud.gif") public class Ground extends BaseElement{ private int thickness = 15; public Ground(int x, int y) { super(x, y); } @Override public void drawImage(Graphics g) { int i = Constant.FRAME_HEIGHT;//从屏幕最下面开始画 while (i >= this.y) { g.drawImage(this.leftImage, this.x, i, this.width, this.height, null); i -= 10;//让盒子叠在一起 } } @Override public boolean aboveIntersects(E element) { Rectangle myself = new Rectangle(this.x + 3, y, this.height - 8, Constant.FRAME_HEIGHT - thickness); Rectangle be = element.getRectangle(); return be.getY() < myself.getY() && myself.intersects(be); } @Override public Rectangle getRectangle() { //地面矩形范围 减去地面厚度 ,延申至地下 return new Rectangle(this.x + 3, y + thickness, this.height - 8, Constant.FRAME_HEIGHT); } /** * 跟随玩家移动 * * @param player */ public void movedByPlayer(Player player) { this.x -= player.getxSpeed(); } } 0 package io.github.vampirestudios.raa_dimension.generation.feature.todo; import com.mojang.datafixers.Dynamic; import io.github.vampirestudios.raa.utils.Rands; import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; import net.minecraft.block.PillarBlock; import net.minecraft.util.math.BlockBox; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Direction; import net.minecraft.world.ModifiableTestableWorld; import net.minecraft.world.TestableWorld; import net.minecraft.world.gen.feature.AbstractTreeFeature; import net.minecraft.world.gen.feature.TreeFeatureConfig; import java.util.Random; import java.util.Set; import java.util.function.Function; /** * @author */ //Code kindly taken from The Hallow, thanks to everyone who is working on it! public class LargeSkeletalTreeFeature extends AbstractTreeFeature { private static final BlockState LOG = Blocks.BONE_BLOCK.getDefaultState(); public LargeSkeletalTreeFeature(Function, ? extends TreeFeatureConfig> configDeserializer, Function function) { super(configDeserializer, function); } private static boolean isSurroundedByAir(TestableWorld testableWorld, BlockPos blockPos, Direction ignore) { for (Direction direction : Direction.Type.HORIZONTAL) { if (direction == ignore) continue; if (!isAir(testableWorld, blockPos.offset(direction))) return false; } return true; } private void addLog(ModifiableTestableWorld modifiableTestableWorld, BlockPos blockPos, Direction.Axis axis, BlockBox mutableIntBoundingBox) { if (canTreeReplace(modifiableTestableWorld, blockPos)) { this.setBlockState(modifiableTestableWorld, blockPos, LOG.with(PillarBlock.AXIS, axis), mutableIntBoundingBox); } } @Override protected boolean generate(ModifiableTestableWorld modifiableTestableWorld, Random random, BlockPos blockPos, Set set, Set set1, BlockBox blockBox, TreeFeatureConfig treeFeatureConfig) { if (!isNaturalDirtOrGrass(modifiableTestableWorld, blockPos.down(1))) return false; generateBranch(modifiableTestableWorld, random, blockPos.add(0, -1, 0), blockBox, Rands.randInt(4), null); return true; } private void generateBranch(ModifiableTestableWorld world, Random random, BlockPos pos, BlockBox blockBox, int maxBranchouts, Direction lastDir) { int baseHeight = Rands.randInt(4) + 2; for (int int_4 = 0; int_4 < baseHeight; ++int_4) { BlockPos blockPos = pos.up(int_4 + 1); if (!isSurroundedByAir(world, blockPos, null)) { return; } addLog(world, blockPos, Direction.Axis.Y, blockBox); } int int_5 = Rands.randInt(4) + 1; int int_1 = 8; if (maxBranchouts > 0) { for (int int_6 = 0; int_6 < int_5; ++int_6) { Direction direction_1 = Direction.Type.HORIZONTAL.random(random); if (direction_1 == lastDir) continue; BlockPos blockPos_4 = pos.up(baseHeight).offset(direction_1); if (Math.abs(blockPos_4.getX() - pos.getX()) < int_1 && Math.abs(blockPos_4.getZ() - pos.getZ()) < int_1 && isAir(world, blockPos_4) && isAir(world, blockPos_4.down(1)) && isSurroundedByAir(world, blockPos_4, direction_1.getOpposite())) { addLog(world, blockPos_4, direction_1.getAxis(), blockBox); generateBranch(world, random, blockPos_4, blockBox, maxBranchouts - 1, direction_1.getOpposite()); } } } } }redrabit/openfmb-adapters // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11 // See http://java.sun.com/xml/jaxb // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2016.10.27 at 02:07:42 PM EDT // package com.greenenergycorp.openfmb.xml; import java.io.Serializable; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * Set of values obtained from the meter. * *

Java class for InterchangeScheduleProfile complex type. * *

The following schema fragment specifies the expected content contained within this class. * *

 * <complexType name="InterchangeScheduleProfile">
 *   <complexContent>
 *     <extension base="{http://openfmb.org/xsd/2015/12/openfmb/commonmodule}Container">
 *       <sequence>
 *         <element name="InterchangeSchedule" type="{http://openfmb.org/xsd/2015/12/openfmb/interchangemodule}InterchangeSchedule"/>
 *         <element name="PowerSystemResource" type="{http://openfmb.org/xsd/2015/12/openfmb/commonmodule}PowerSystemResource"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 * 
* * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "InterchangeScheduleProfile", namespace = "http://openfmb.org/xsd/2015/12/openfmb/interchangemodule", propOrder = { "interchangeSchedule", "powerSystemResource" }) @XmlRootElement(name = "InterchangeScheduleProfile", namespace = "http://openfmb.org/xsd/2015/12/openfmb/interchangemodule") public class InterchangeScheduleProfile extends Container implements Serializable { private final static long serialVersionUID = 1L; @XmlElement(name = "InterchangeSchedule", required = true) protected InterchangeSchedule interchangeSchedule; @XmlElement(name = "PowerSystemResource", required = true) protected PowerSystemResource powerSystemResource; /** * Gets the value of the interchangeSchedule property. * * @return * possible object is * {@link InterchangeSchedule } * */ public InterchangeSchedule getInterchangeSchedule() { return interchangeSchedule; } /** * Sets the value of the interchangeSchedule property. * * @param value * allowed object is * {@link InterchangeSchedule } * */ public void setInterchangeSchedule(InterchangeSchedule value) { this.interchangeSchedule = value; } /** * Gets the value of the powerSystemResource property. * * @return * possible object is * {@link PowerSystemResource } * */ public PowerSystemResource getPowerSystemResource() { return powerSystemResource; } /** * Sets the value of the powerSystemResource property. * * @param value * allowed object is * {@link PowerSystemResource } * */ public void setPowerSystemResource(PowerSystemResource value) { this.powerSystemResource = value; } } src/test/java/com/jfcorugedo/udemy/dynamicprogramming2/SumSequences.java0 package com.jfcorugedo.udemy.dynamicprogramming2; import org.junit.Test; import java.util.stream.IntStream; import static org.assertj.core.api.Assertions.assertThat; /** * Given a set of contiguous numbers starting at 1 and ending at n, write an algorithm that calculates the sum of that sequence * * For example: * Given [1, 2, 3, 4, 5, 6] * Then the sum is 21 (1 + 2 + 3 + 4 + 5 + 6 = 21) * */ public class SumSequences { @Test public void sumSequences() { assertThat(solution(IntStream.range(1, 3).toArray())).isEqualTo(3); assertThat(solution(IntStream.range(1, 7).toArray())).isEqualTo(21); assertThat(solution(IntStream.range(1, 101).toArray())).isEqualTo(5050); } private long solution(int[] numbers) { int sum = 0; for(int i = 0 ; i < numbers.length ; i++) { sum += numbers[i]; } return sum; } @Test public void sumSequences2() { assertThat(solution2(IntStream.range(1, 3).toArray())).isEqualTo(3); assertThat(solution2(IntStream.range(1, 7).toArray())).isEqualTo(21); assertThat(solution2(IntStream.range(1, 101).toArray())).isEqualTo(5050); } /** * Using Zomg Wut approach: * * Given X as the sum of numbers from 1 to n we can define X as: * * X = 1 + 2 + 3 + 4 + ... + n-2 + n-1 + n * * So X + X will be: * * 1 + 2 + 3 + 4 + ... + n-2 + n-1 + n * + * 1 + 2 + 3 + 4 + ... + n-2 + n-1 + n * * Given that 1 + 2 + 3 + 4 + ... + n-2 + n-1 + n is equal to n + n-1 + n-2 ... + 4 + 3 + 2 + 1 * Then we can say that: * X + X: * 1 + 2 + 3 + 4 + ... + n-2 + n-1 + n * + * n + n-1 + n-2 ... + 4 + 3 + 2 + 1 * ---------------------------------- * n+1 + n+1 + n+1 + n+1 + ... + n+1 * * So: * * X + X = n * (n+1) * 2X = n * (n+1) * X = n * (n+1) / 2 * * @param numbers * @return */ private long solution2(int[] numbers) { int n = numbers[numbers.length-1]; return n * (n+1) / 2; } } saibz5base/src/main/java/net/ibizsys/paas/web/VCPage.java package net.ibizsys.paas.web; import javax.servlet.jsp.PageContext; import net.ibizsys.paas.appmodel.IApplicationModel; import net.ibizsys.paas.controller.IViewController; import net.ibizsys.paas.controller.ViewControllerGlobal; import net.ibizsys.paas.ctrlmodel.IAppMenuModel; import net.ibizsys.paas.ctrlmodel.ICtrlModel; import net.ibizsys.paas.util.StringHelper; import net.sf.json.JSONObject; /** * 视图控制器页面对象 * @author Administrator * */ public class VCPage extends Page { /** * */ private final static JSONObject EMPTYJSON = new JSONObject(); /** * 视图控制类 */ private IViewController iViewController = null; /** * 初始化页面对象 * @param context */ final public boolean init(PageContext context,String strViewControllerId) throws Exception { if(iViewController==null) { iViewController = ViewControllerGlobal.getViewController(strViewControllerId); iViewController.prepareViewController(); this.setAccessUserMode(iViewController.getAccessUserMode()); this.setAccessKey(iViewController.getAccessKey()); } return init(context); } /* (non-Javadoc) * @see net.ibizsys.paas.web.Page#onInit() */ @Override protected void onInit() throws Exception { super.onInit(); } /** * 获取视图控制类 * @return */ public IViewController getViewController() { return this.iViewController; } /** * 获取当前应用菜单模型 * @return * @throws Exception */ public IAppMenuModel getAppMenuModel()throws Exception{ return this.getApplicationModel().getAppMenuModel(this.getWebContext().getCurUserMode()); } /** * 获取控件模型 * @param strName * @return * @throws Exception */ public ICtrlModel getCtrlModel(String strName)throws Exception { return getViewController().getCtrlModel(strName); } /** * 获取传入的父数据对象 * @return */ public JSONObject getParentData() { String strParentData = this.getWebContext().getParamValue(WebContext.PARAM_PARENTDATA); if(!StringHelper.isNullOrEmpty(strParentData)) { return JSONObject.fromString(strParentData); } return EMPTYJSON; } /** * 获取传入的父数据模式 * @return */ public JSONObject getParentMode() { String strParentMode = this.getWebContext().getParamValue(WebContext.PARAM_PARENTMODE); if(!StringHelper.isNullOrEmpty(strParentMode)) { return JSONObject.fromString(strParentMode); } return EMPTYJSON; } /* (non-Javadoc) * @see net.ibizsys.paas.web.Page#getApplicationModel() */ @Override protected IApplicationModel getApplicationModel() throws Exception { return getViewController().getAppModel(); } /* (non-Javadoc) * @see net.ibizsys.paas.web.Page#mapRealPageUrl(java.lang.String) */ @Override protected String mapRealPageUrl(String strPageUrl )throws Exception { if(strPageUrl.charAt(0)=='/') { return "../.."+strPageUrl; } return strPageUrl; } } 1-10 /* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * 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. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package org.deeplearning4j.spark.text.functions; import org.apache.spark.Accumulator; import org.apache.spark.api.java.function.Function2; import org.nd4j.common.primitives.Counter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.concurrent.atomic.AtomicLong; /** * @author jeffreytang */ public class FoldWithinPartitionFunction implements Function2, Iterator> { public FoldWithinPartitionFunction(Accumulator> maxPartitionAcc) { this.maxPerPartitionAcc = maxPartitionAcc; } private Accumulator> maxPerPartitionAcc; @Override public Iterator call(Integer ind, Iterator partition) throws Exception { List foldedItemList = new ArrayList() { { add(new AtomicLong(0L)); } }; // Recurrent state implementation of cum sum int foldedItemListSize = 1; while (partition.hasNext()) { long curPartitionItem = partition.next().get(); int lastFoldedIndex = foldedItemListSize - 1; long lastFoldedItem = foldedItemList.get(lastFoldedIndex).get(); AtomicLong sumLastCurrent = new AtomicLong(curPartitionItem + lastFoldedItem); foldedItemList.set(lastFoldedIndex, sumLastCurrent); foldedItemList.add(sumLastCurrent); foldedItemListSize += 1; } // Update Accumulator long maxFoldedItem = foldedItemList.remove(foldedItemListSize - 1).get(); Counter partitionIndex2maxItemCounter = new Counter<>(); partitionIndex2maxItemCounter.incrementCount(ind, maxFoldedItem); maxPerPartitionAcc.add(partitionIndex2maxItemCounter); return foldedItemList.iterator(); } } /* * Copyright (c) 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bicarb.core; import static org.assertj.core.api.Assertions.assertThat; import java.time.Instant; /** * Time Assert Utils. * * @author olOwOlo */ public class TimeAssert { public static void assertNow(Instant instant) { assertThat(instant).isBetween(Instant.now().minusSeconds(30), Instant.now().plusSeconds(30)); } } /* * Copyright (c) 2020, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * The Universal Permissive License (UPL), Version 1.0 * * Subject to the condition set forth below, permission is hereby granted to any * person obtaining a copy of this software, associated documentation and/or * data (collectively the "Software"), free of charge and under any and all * copyright rights in the Software, and any and all patent rights owned or * freely licensable by each licensor hereunder covering either (i) the * unmodified Software as contributed to or provided by such licensor, or (ii) * the Larger Works (as defined below), to deal in both * * (a) the Software, and * * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if * one is included with the Software each a "Larger Work" to which the Software * is contributed by such licensors), * * without restriction, including without limitation the rights to copy, create * derivative works of, display, perform, and distribute the Software and make, * use, sell, offer for sale, import, export, have made, and have sold the * Software and the Larger Work(s), and to sublicense the foregoing rights on * either these or other terms. * * This license is subject to the following condition: * * The above copyright notice and either this complete permission notice or at a * minimum a reference to the UPL must 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.oracle.truffle.js.nodes.access; import com.oracle.truffle.api.dsl.GenerateUncached; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.library.CachedLibrary; import com.oracle.truffle.api.object.DynamicObject; import com.oracle.truffle.api.object.DynamicObjectLibrary; import com.oracle.truffle.js.nodes.JavaScriptBaseNode; import com.oracle.truffle.js.runtime.JSContext; import com.oracle.truffle.js.runtime.builtins.JSOrdinary; import com.oracle.truffle.js.runtime.objects.JSAttributes; import com.oracle.truffle.js.runtime.objects.PropertyDescriptor; import com.oracle.truffle.js.runtime.objects.Undefined; /** * Creates a JS object from a {@link PropertyDescriptor}. */ @GenerateUncached public abstract class FromPropertyDescriptorNode extends JavaScriptBaseNode { protected static final int SHAPE_LIMIT = 6; protected FromPropertyDescriptorNode() { } public static FromPropertyDescriptorNode create() { return FromPropertyDescriptorNodeGen.create(); } public static FromPropertyDescriptorNode getUncached() { return FromPropertyDescriptorNodeGen.getUncached(); } public abstract DynamicObject execute(PropertyDescriptor desc, JSContext context); @Specialization final DynamicObject toJSObject(PropertyDescriptor desc, JSContext context, @CachedLibrary(limit = "SHAPE_LIMIT") DynamicObjectLibrary putValueNode, @CachedLibrary(limit = "SHAPE_LIMIT") DynamicObjectLibrary putWritableNode, @CachedLibrary(limit = "SHAPE_LIMIT") DynamicObjectLibrary putGetNode, @CachedLibrary(limit = "SHAPE_LIMIT") DynamicObjectLibrary putSetNode, @CachedLibrary(limit = "SHAPE_LIMIT") DynamicObjectLibrary putEnumerableNode, @CachedLibrary(limit = "SHAPE_LIMIT") DynamicObjectLibrary putConfigurableNode) { if (desc == null) { return Undefined.instance; } DynamicObject obj = JSOrdinary.create(context, getRealm()); if (desc.hasValue()) { putValueNode.put(obj, JSAttributes.VALUE, desc.getValue()); } if (desc.hasWritable()) { putWritableNode.put(obj, JSAttributes.WRITABLE, desc.getWritable()); } if (desc.hasGet()) { putGetNode.put(obj, JSAttributes.GET, desc.getGet()); } if (desc.hasSet()) { putSetNode.put(obj, JSAttributes.SET, desc.getSet()); } if (desc.hasEnumerable()) { putEnumerableNode.put(obj, JSAttributes.ENUMERABLE, desc.getEnumerable()); } if (desc.hasConfigurable()) { putConfigurableNode.put(obj, JSAttributes.CONFIGURABLE, desc.getConfigurable()); } return obj; } } 0 // Use varargs with standard arguments. class VarArgs2 { // Here, msg is a normal parameter and v is a // varargs parameter. static void vaTest(String msg, int ... v) { System.out.print(msg + v.length + " Contents: "); for(int x : v) System.out.print(x + " "); System.out.println(); } public static void main(String args[]) { vaTest("One vararg: ", 10); vaTest("Three varargs: ", 1, 2, 3); vaTest("No varargs: "); } }package com.liuchongming.utils; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSession; /** * Created by liuchongming on 2017/6/5. * Project Name: MyApplication * Package Mame: com.liuchongming.utils */ public class UnSafeHostnameVerifier implements HostnameVerifier { @Override public boolean verify(String hostname, SSLSession session) { return true; } }1-10 package org.thothtrust.sc.thothpgp; import KM101.T101OpenAPI; import javacard.framework.ISOException; import javacard.framework.JCSystem; import javacard.framework.Util; import javacard.security.MessageDigest; public class APIShim { private byte[] aocPin; private byte[] pukUserPin; private byte[] nonceBuffer = JCSystem.makeTransientByteArray((short) 8, JCSystem.MEMORY_TYPE_TRANSIENT_RESET); private byte[] appName = { (byte) 0x4f, (byte) 0x70, (byte) 0x65, (byte) 0x6e, (byte) 0x50, (byte) 0x47, (byte) 0x50 }; public static final byte[] adminName = { (byte) 0x61, (byte) 0x64, (byte) 0x6d }; public static final byte[] pukName = { (byte) 0x70, (byte) 0x75, (byte) 0x6b }; public static final byte[] userName = { (byte) 0x75, (byte) 0x73, (byte) 0x72 }; public static final byte[] keyHandleSign = { (byte) 0x73, (byte) 0x69, (byte) 0x67, (byte) 0x4b }; public static final byte[] keyHandleCipher = { (byte) 0x63, (byte) 0x69, (byte) 0x70, (byte) 0x4b }; public static final byte[] keyHandleAuth = { (byte) 0x61, (byte) 0x75, (byte) 0x74, (byte) 0x4b }; public static final byte[] keyHandleSM = { (byte) 0x73, (byte) 0x6d, (byte) 0x65, (byte) 0x4b }; public static final byte[] defaultExpiryTime = new byte[4]; private short aocPinMaxRetry = 5; private byte[] tempBuf = null; public static final byte[] TXT_CHANGE_PIN_TITLE = { (byte) 0x55, (byte) 0x70, (byte) 0x64, (byte) 0x74, (byte) 0x65, (byte) 0x20, (byte) 0x50, (byte) 0x49, (byte) 0x4e }; public static final byte[] TXT_RESET_PIN_TITLE = { (byte) 0x52, (byte) 0x65, (byte) 0x73, (byte) 0x65, (byte) 0x74, (byte) 0x20, (byte) 0x50, (byte) 0x49, (byte) 0x4e }; public static final byte[] TXT_NEW_PIN = { (byte) 0x4e, (byte) 0x65, (byte) 0x77, (byte) 0x20, (byte) 0x50, (byte) 0x49, (byte) 0x4e }; public static final byte[] TXT_NEW_PUK_TITLE = { (byte) 0x4e, (byte) 0x65, (byte) 0x77, (byte) 0x20, (byte) 0x50, (byte) 0x55, (byte) 0x4b }; public static final byte[] TXT_RESET_CARD_TITLE = { (byte) 0x57, (byte) 0x49, (byte) 0x50, (byte) 0x45, (byte) 0x20, (byte) 0x43, (byte) 0x41, (byte) 0x52, (byte) 0x44 }; public static final byte[] TXT_RESET_CARD = { (byte) 0x50, (byte) 0x72, (byte) 0x65, (byte) 0x73, (byte) 0x73, (byte) 0x20, (byte) 0x4f, (byte) 0x4b, (byte) 0x20, (byte) 0x74, (byte) 0x6f, (byte) 0x20, (byte) 0x77, (byte) 0x69, (byte) 0x70, (byte) 0x65, (byte) 0x20, (byte) 0x63, (byte) 0x61, (byte) 0x72, (byte) 0x64, (byte) 0x20, (byte) 0x6f, (byte) 0x72, (byte) 0x20, (byte) 0x43, (byte) 0x20, (byte) 0x74, (byte) 0x6f, (byte) 0x20, (byte) 0x61, (byte) 0x62, (byte) 0x6f, (byte) 0x72, (byte) 0x74, (byte) 0x2e }; public static final byte[] TXT_SUCCESS = new byte[] { (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x4f, (byte) 0x70, (byte) 0x65, (byte) 0x72, (byte) 0x61, (byte) 0x74, (byte) 0x69, (byte) 0x6f, (byte) 0x6e, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x53, (byte) 0x75, (byte) 0x63, (byte) 0x63, (byte) 0x65, (byte) 0x73, (byte) 0x73, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20 }; public static final byte[] TXT_FAILED = new byte[] { (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x4f, (byte) 0x70, (byte) 0x65, (byte) 0x72, (byte) 0x61, (byte) 0x74, (byte) 0x69, (byte) 0x6f, (byte) 0x6e, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x46, (byte) 0x61, (byte) 0x69, (byte) 0x6c, (byte) 0x65, (byte) 0x64, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20, (byte) 0x20 }; public static final byte[] TXT_CRYPT_OPS_TITLE = new byte[] { (byte) 0x43, (byte) 0x72, (byte) 0x79, (byte) 0x70, (byte) 0x74, (byte) 0x20, (byte) 0x4f, (byte) 0x70, (byte) 0x73 }; public static final byte[] TXT_SIG_OPS_TITLE = new byte[] { (byte) 0x53, (byte) 0x69, (byte) 0x67, (byte) 0x6e, (byte) 0x20, (byte) 0x4f, (byte) 0x70, (byte) 0x73 }; public static final byte[] TXT_CRYPT_OPS = { (byte) 0x50, (byte) 0x72, (byte) 0x65, (byte) 0x73, (byte) 0x73, (byte) 0x20, (byte) 0x4f, (byte) 0x4b, (byte) 0x20, (byte) 0x74, (byte) 0x6f, (byte) 0x20, (byte) 0x64, (byte) 0x65, (byte) 0x63, (byte) 0x72, (byte) 0x79, (byte) 0x70, (byte) 0x74, (byte) 0x20, (byte) 0x64, (byte) 0x61, (byte) 0x74, (byte) 0x61, (byte) 0x20, (byte) 0x6f, (byte) 0x72, (byte) 0x20, (byte) 0x43, (byte) 0x20, (byte) 0x74, (byte) 0x6f, (byte) 0x20, (byte) 0x61, (byte) 0x62, (byte) 0x6f, (byte) 0x72, (byte) 0x74, (byte) 0x2e }; public static final byte[] TXT_SIG_OPS = { (byte) 0x50, (byte) 0x72, (byte) 0x65, (byte) 0x73, (byte) 0x73, (byte) 0x20, (byte) 0x4f, (byte) 0x4b, (byte) 0x20, (byte) 0x74, (byte) 0x6f, (byte) 0x20, (byte) 0x73, (byte) 0x69, (byte) 0x67, (byte) 0x6e, (byte) 0x20, (byte) 0x64, (byte) 0x61, (byte) 0x74, (byte) 0x61, (byte) 0x20, (byte) 0x6f, (byte) 0x72, (byte) 0x20, (byte) 0x43, (byte) 0x20, (byte) 0x74, (byte) 0x6f, (byte) 0x20, (byte) 0x61, (byte) 0x62, (byte) 0x6f, (byte) 0x72, (byte) 0x74, (byte) 0x2e }; public static final byte[] TXT_LOGIN_ADM_TITLE = { (byte) 0x4c, (byte) 0x6f, (byte) 0x67, (byte) 0x69, (byte) 0x6e, (byte) 0x20, (byte) 0x41, (byte) 0x64, (byte) 0x6d }; public static final byte[] TXT_LOGIN_USR_TITLE = { (byte) 0x4c, (byte) 0x6f, (byte) 0x67, (byte) 0x69, (byte) 0x6e, (byte) 0x20, (byte) 0x55, (byte) 0x73, (byte) 0x72 }; public static final byte[] TXT_LOGIN = { (byte) 0x50, (byte) 0x72, (byte) 0x65, (byte) 0x73, (byte) 0x73, (byte) 0x20, (byte) 0x4f, (byte) 0x4b, (byte) 0x20, (byte) 0x74, (byte) 0x6f, (byte) 0x20, (byte) 0x6c, (byte) 0x6f, (byte) 0x67, (byte) 0x69, (byte) 0x6e, (byte) 0x20, (byte) 0x6f, (byte) 0x72, (byte) 0x20, (byte) 0x43, (byte) 0x20, (byte) 0x74, (byte) 0x6f, (byte) 0x20, (byte) 0x61, (byte) 0x62, (byte) 0x6f, (byte) 0x72, (byte) 0x74, (byte) 0x2e }; public APIShim() { aocPin = new byte[8]; generateRandomAOCPin(aocPin, (short) 0, (short) aocPin.length); } private void generateRandomAOCPin(byte[] pin, short off, short len) { ThothPGPApplet.random_data.generateData(nonceBuffer, (short) 0, (short) len); for (short i = (short) 0; i < len; i++) { // Use the rightmost 4 nibbles of bytes from random byte and mod 10 to get a // numerical digit and then convert back to its byte form pin[(short) (i + off)] = (byte) (((short) ((byte) (nonceBuffer[i] & 0x0F) % (short) 10) & 0xFF) | 0x30); } } public byte[] getKeyHandle(byte pgpKeysOffset) { switch (pgpKeysOffset) { case Persistent.PGP_KEYS_OFFSET_SIG: return keyHandleSign; case Persistent.PGP_KEYS_OFFSET_DEC: return keyHandleCipher; case Persistent.PGP_KEYS_OFFSET_AUT: return keyHandleAuth; default: return keyHandleSM; } } private short rsaOps(byte mode, byte ind, byte[] input, short inOff, short inLen, byte[] output, short outOff, byte[] apduBuffer) { short uploadSize = 0; short downloadSize = 0; // Clear compute buffer clearUploadBuffer(apduBuffer); // Load input into compute buffer for (short i = 0; i < (short) (inLen - 1);) { if ((short) (inLen - i - 1) > (short) 200) { uploadSize = (short) 200; } else { uploadSize = (short) (inLen - i - 1); } if (i == 0) { if (!uploadToBuffer(false, (short) (inLen - 1), input, (short) (i + inOff), uploadSize, apduBuffer)) { return (short) -1; } } else { if (!uploadToBuffer(true, (short) 0, input, (short) (i + inOff), uploadSize, apduBuffer)) { return (short) -1; } } i += uploadSize; } // Load RSA decryption key if (executeObject(T101OpenAPI.EXEC_CRYPT_CONTENT_EXTRACT, T101OpenAPI.CRYPT_LOAD, mode, false, ind, appName, (short) 0, (short) 1, apduBuffer) == (short) -1) { return (short) -1; } // Execute RSA decrypt on buffer data downloadSize = executeObject(T101OpenAPI.EXEC_CRYPT_CONTENT_EXTRACT, T101OpenAPI.CRYPT_FINAL, mode, true, ind, input, (short) (inOff + inLen - 1), (short) 1, apduBuffer); if (downloadSize == (short) -1) { return (short) -1; } // Copy to output Util.arrayCopyNonAtomic(apduBuffer, (short) 0, output, outOff, downloadSize); // Clear temp buffer clearUploadBuffer(apduBuffer); return downloadSize; // return inLen; } /** * Decrypts RSA enciphered data. Output buffer cannot be an APDU buffer. * * @param keyHandle * @param handleOff * @param handleLen * @param input * @param inOff * @param inLen * @param output * @param outOff * @param apduBuffer * @return */ public short decryptRSA(byte ind, byte[] input, short inOff, short inLen, byte[] output, short outOff, byte[] apduBuffer) { if (confirmationUI(TXT_CRYPT_OPS_TITLE, (short) 0, (short) TXT_CRYPT_OPS_TITLE.length, TXT_CRYPT_OPS, (short) 0, (short) TXT_CRYPT_OPS.length, apduBuffer)) { return rsaOps((byte) 0x01, ind, input, inOff, inLen, output, outOff, apduBuffer); } return 0; } /** * Signing is done via raw RSA decrypt mode over raw (presumably formatted) * data. * * @param keyHandle * @param handleOff * @param handleLen * @param message * @param msgOff * @param msgLen * @param signature * @param sigOff * @param sigLen * @param output * @param outOff * @param apduBuffer * @return */ public short signRSA(byte ind, byte[] message, short msgOff, short msgLen, byte[] output, short outOff, byte[] apduBuffer) { if (confirmationUI(TXT_SIG_OPS_TITLE, (short) 0, (short) TXT_SIG_OPS_TITLE.length, TXT_SIG_OPS, (short) 0, (short) TXT_SIG_OPS.length, apduBuffer)) { return rsaOps((byte) 0x00, ind, message, msgOff, msgLen, output, outOff, apduBuffer); } return 0; } public short getPublicKey(byte[] keyHandle, short handleOff, short handleLen, byte[] apduBuffer) { Util.arrayCopyNonAtomic(keyHandle, handleOff, apduBuffer, (short) 0, handleLen); Util.arrayCopyNonAtomic(pukName, (short) 0, apduBuffer, handleLen, (short) pukName.length); if (ThothPGPApplet.api.getObjectMaterial(apduBuffer, (short) 0, handleLen, true, apduBuffer, (short) (handleLen + pukName.length), T101OpenAPI.CRED_FIELD_NAME, apduBuffer, handleLen, (short) pukName.length, T101OpenAPI.AUTH_INTERNAL) != (short) -1) { Util.arrayCopyNonAtomic(apduBuffer, (short) (handleLen + pukName.length), nonceBuffer, (short) 0, (short) 8); return authContainer(pukUserPin, (short) 0, (short) pukUserPin.length, nonceBuffer, (short) 0, apduBuffer); } return (short) 0; } public boolean initEnv(byte[] apduBuffer) { boolean isProceed = false; Util.arrayFillNonAtomic(apduBuffer, (short) 0, (short) 256, (byte) 0x00); apduBuffer[0] = T101OpenAPI.CRED_CLASS_PIN; Util.arrayCopyNonAtomic(aocPin, (short) 0, apduBuffer, (short) 1, (short) aocPin.length); Util.arrayCopyNonAtomic(appName, (short) 0, apduBuffer, (short) (1 + aocPin.length), (short) appName.length); Util.arrayCopyNonAtomic(defaultExpiryTime, (short) 0, apduBuffer, (short) (1 + aocPin.length + appName.length), (short) 4); isProceed = ThothPGPApplet.api.createAOCContainer(apduBuffer[0], apduBuffer, (short) 1, (short) aocPin.length, aocPinMaxRetry, apduBuffer, (short) (1 + aocPin.length), (short) appName.length, apduBuffer, (short) (1 + aocPin.length + appName.length)); // Enroll Admin if (isProceed) { isProceed = enrollNewAdminUsers(adminName, (short) 0, (short) adminName.length, Constants.ADMIN_PIN_DEFAULT, (short) 0, (short) Constants.ADMIN_PIN_DEFAULT.length, defaultExpiryTime, (short) 0, aocPin, (short) 0, (short) aocPin.length, apduBuffer); } // Enroll PUK while using the same Admin PIN as the Admin user. if (isProceed) { isProceed = enrollNewAdminUsers(pukName, (short) 0, (short) pukName.length, Constants.ADMIN_PIN_DEFAULT, (short) 0, (short) Constants.ADMIN_PIN_DEFAULT.length, defaultExpiryTime, (short) 0, aocPin, (short) 0, (short) aocPin.length, apduBuffer); if (isProceed) { JCSystem.beginTransaction(); pukUserPin = null; pukUserPin = new byte[(short) Constants.ADMIN_PIN_DEFAULT.length]; Util.arrayCopy(Constants.ADMIN_PIN_DEFAULT, (short) 0, pukUserPin, (short) 0, (short) Constants.ADMIN_PIN_DEFAULT.length); JCSystem.commitTransaction(); } } // Finalize container if (isProceed) { isProceed = finalizeContainer(aocPin, (short) 0, (short) aocPin.length, apduBuffer); } // Enroll interactive user if (isProceed) { isProceed = enrollNormalUser(userName, (short) 0, (short) userName.length, Constants.USER_PIN_DEFAULT, (short) 0, (short) Constants.USER_PIN_DEFAULT.length, defaultExpiryTime, (short) 0, Constants.ADMIN_PIN_DEFAULT, (short) 0, (short) Constants.ADMIN_PIN_DEFAULT.length, apduBuffer); } return isProceed; } public boolean destroyEnv() { return ThothPGPApplet.api.destroyAOCContainer(); } public short authContainer(byte[] secret, short secOffset, short secLen, byte[] nonce, short nonceOffset, byte[] apduBuffer) { apduBuffer[0] = MessageDigest.ALG_SHA_256; Util.arrayCopyNonAtomic(secret, secOffset, apduBuffer, (short) 1, secLen); Util.arrayCopyNonAtomic(nonce, nonceOffset, apduBuffer, (short) (1 + secLen), (short) 8); ThothPGPApplet.api.cryptoHMAC(apduBuffer[0], // hashType apduBuffer, (short) 1, secLen, // key apduBuffer, (short) (1 + secLen), (short) 8, // nonce apduBuffer, (short) (9 + secLen), // ipad apduBuffer, (short) (73 + secLen), // opad apduBuffer, (short) (137 + secLen), // secBuff apduBuffer, (short) 201); // output // Call extendedRequest to submit final signed nonce result return ThothPGPApplet.api.extendedRequest(apduBuffer, (short) 201, (short) 32, apduBuffer, (short) 0); } public boolean finalizeContainer(byte[] aocPin, short aocPinOffset, short aocPinLen, byte[] apduBuffer) { if (ThothPGPApplet.api.finalizeNewContainer(apduBuffer, (short) 0)) { Util.arrayCopyNonAtomic(apduBuffer, (short) 0, nonceBuffer, (short) 0, (short) 8); if (authContainer(aocPin, aocPinOffset, aocPinLen, nonceBuffer, (short) 0, apduBuffer) == 1) { return true; } } return false; } public boolean enrollNewAdminUsers(byte[] adminUser, short adminUserOffset, short adminUserLen, byte[] adminPin, short adminPinOffset, short adminPinLen, byte[] expiryTime, short expiryTimeOffset, byte[] aocPin, short aocPinOffset, short aocPinLen, byte[] apduBuffer) { apduBuffer[0] = T101OpenAPI.CRED_CLASS_PIN; apduBuffer[1] = T101OpenAPI.CRED_MGMT_FRONT_PANEL; Util.arrayCopyNonAtomic(adminPin, adminPinOffset, apduBuffer, (short) 2, adminPinLen); Util.arrayCopyNonAtomic(adminUser, adminUserOffset, apduBuffer, (short) (2 + adminPinLen), adminUserLen); Util.arrayCopyNonAtomic(expiryTime, expiryTimeOffset, apduBuffer, (short) (2 + adminPinLen + adminUserLen), (short) 4); if (ThothPGPApplet.api.newAOCUserCred(apduBuffer[0], apduBuffer, (short) 2, (short) adminPinLen, (short) 3, apduBuffer, (short) (2 + adminPinLen), (short) adminUserLen, apduBuffer, (short) (2 + adminPinLen + adminUserLen), T101OpenAPI.CRED_FIELD_NAME, null, (short) 0, (short) 0, T101OpenAPI.AUTH_INTERNAL, apduBuffer, (short) (6 + adminPinLen + adminUserLen))) { if (authContainer(aocPin, aocPinOffset, aocPinLen, apduBuffer, (short) (6 + adminPinLen + adminUserLen), apduBuffer) == 1) { return true; } } return false; } public boolean enrollNormalUser(byte[] username, short offset, short len, byte[] userPin, short pinOffset, short pinLen, byte[] expiryTime, short expiryTimeOffset, byte[] adminPin, short adminPinOffset, short adminPinLen, byte[] apduBuffer) { apduBuffer[0] = T101OpenAPI.CRED_CLASS_PIN; apduBuffer[1] = T101OpenAPI.CRED_MGMT_FRONT_PANEL; Util.arrayCopyNonAtomic(userPin, pinOffset, apduBuffer, (short) 2, pinLen); Util.arrayCopyNonAtomic(username, offset, apduBuffer, (short) (2 + pinLen), len); Util.arrayCopyNonAtomic(expiryTime, expiryTimeOffset, apduBuffer, (short) (2 + pinLen + len), (short) 4); Util.arrayCopyNonAtomic(adminName, (short) 0, apduBuffer, (short) (6 + pinLen + len), (short) adminName.length); if (ThothPGPApplet.api.newAOCUserCred(apduBuffer[0], apduBuffer, (short) 2, (short) pinLen, (short) 3, apduBuffer, (short) (2 + pinLen), (short) len, apduBuffer, (short) (2 + pinLen + len), T101OpenAPI.CRED_FIELD_NAME, apduBuffer, (short) (6 + pinLen + len), (short) adminName.length, T101OpenAPI.AUTH_INTERNAL, apduBuffer, (short) (6 + pinLen + len + adminName.length))) { Util.arrayCopyNonAtomic(apduBuffer, (short) (6 + pinLen + len + adminName.length), nonceBuffer, (short) 0, (short) 8); if (authContainer(adminPin, adminPinOffset, adminPinLen, nonceBuffer, (short) 0, apduBuffer) == 1) { return true; } } return false; } public short loginNormalUserAndGetTries(byte[] apduBuffer) { if (confirmationUI(TXT_LOGIN_USR_TITLE, (short) 0, (short) TXT_LOGIN_USR_TITLE.length, TXT_LOGIN, (short) 0, (short) TXT_LOGIN.length, apduBuffer)) { Util.arrayCopyNonAtomic(userName, (short) 0, apduBuffer, (short) 0, (short) userName.length); return ThothPGPApplet.api.getUserInfo(T101OpenAPI.CRED_FIELD_NAME, apduBuffer, (short) 0, (short) userName.length, T101OpenAPI.CRED_FIELD_NAME, apduBuffer, (short) 0, (short) userName.length, T101OpenAPI.CRED_FIELD_MAX_RETRIES, apduBuffer, (short) 0, T101OpenAPI.AUTH_FRONTPANEL); } return (short) -1; // return (short) 3; // Debugging use only } public short loginAdminUserAndGetTries(byte[] apduBuffer) { if (confirmationUI(TXT_LOGIN_ADM_TITLE, (short) 0, (short) TXT_LOGIN_ADM_TITLE.length, TXT_LOGIN, (short) 0, (short) TXT_LOGIN.length, apduBuffer)) { Util.arrayCopyNonAtomic(adminName, (short) 0, apduBuffer, (short) 0, (short) adminName.length); return ThothPGPApplet.api.getUserInfo(T101OpenAPI.CRED_FIELD_NAME, apduBuffer, (short) 0, (short) adminName.length, T101OpenAPI.CRED_FIELD_NAME, apduBuffer, (short) 0, (short) adminName.length, T101OpenAPI.CRED_FIELD_MAX_RETRIES, apduBuffer, (short) 0, T101OpenAPI.AUTH_FRONTPANEL); } return (short) -1; // return (short) 3; // Debugging use only } public boolean adminResetNormalUserPin(byte[] apduBuffer) { tempBuf = null; boolean isSuccess = false; // Use UX Render to accept new normal user pin short secLen = uxRender(T101OpenAPI.UI_TYPE_INPUT, (byte) 0x01, (byte) 0x01, (byte) 0xFF, (byte) 0x20, TXT_CHANGE_PIN_TITLE, (short) 0, (short) TXT_CHANGE_PIN_TITLE.length, TXT_NEW_PIN, (short) 0, (short) TXT_NEW_PIN.length, aocPin, (short) 0, (short) aocPin.length, apduBuffer); if (secLen >= 2) { tempBuf = new byte[secLen]; Util.arrayCopyNonAtomic(apduBuffer, (short) 0, tempBuf, (short) 0, secLen); Util.arrayCopyNonAtomic(tempBuf, (short) 0, apduBuffer, (short) 0, secLen); tempBuf = null; Util.arrayCopyNonAtomic(userName, (short) 0, apduBuffer, secLen, (short) userName.length); Util.arrayCopyNonAtomic(adminName, (short) 0, apduBuffer, (short) (secLen + userName.length), (short) adminName.length); isSuccess = ThothPGPApplet.api.resetAOCUserCred(apduBuffer, (short) 0, secLen, apduBuffer, secLen, (short) userName.length, T101OpenAPI.CRED_FIELD_NAME, apduBuffer, (short) (secLen + userName.length), (short) adminName.length, T101OpenAPI.AUTH_FRONTPANEL, null, (short) 0); Util.arrayFillNonAtomic(apduBuffer, (short) 0, (short) (secLen + userName.length + adminName.length), (byte) 0x00); } opsStatusUI(isSuccess, TXT_CHANGE_PIN_TITLE, (short) 0, (short) TXT_CHANGE_PIN_TITLE.length, apduBuffer); return isSuccess; } public boolean pukResetNormalUserPin(byte[] apduBuffer) { tempBuf = null; boolean isSuccess = false; // Use UX Render to accept new normal user pin short secLen = uxRender(T101OpenAPI.UI_TYPE_INPUT, (byte) 0x01, (byte) 0x01, (byte) 0xFF, (byte) 0x20, TXT_CHANGE_PIN_TITLE, (short) 0, (short) TXT_CHANGE_PIN_TITLE.length, TXT_NEW_PIN, (short) 0, (short) TXT_NEW_PIN.length, aocPin, (short) 0, (short) aocPin.length, apduBuffer); if (secLen >= 2) { tempBuf = new byte[secLen]; Util.arrayCopyNonAtomic(apduBuffer, (short) 0, tempBuf, (short) 0, secLen); Util.arrayCopyNonAtomic(tempBuf, (short) 0, apduBuffer, (short) 0, secLen); tempBuf = null; Util.arrayCopyNonAtomic(userName, (short) 0, apduBuffer, secLen, (short) userName.length); Util.arrayCopyNonAtomic(pukName, (short) 0, apduBuffer, (short) (secLen + userName.length), (short) pukName.length); isSuccess = ThothPGPApplet.api.resetAOCUserCred(apduBuffer, (short) 0, secLen, apduBuffer, secLen, (short) userName.length, T101OpenAPI.CRED_FIELD_NAME, apduBuffer, (short) (secLen + userName.length), (short) pukName.length, T101OpenAPI.AUTH_FRONTPANEL, null, (short) 0); Util.arrayFillNonAtomic(apduBuffer, (short) 0, (short) (secLen + userName.length + pukName.length), (byte) 0x00); } opsStatusUI(isSuccess, TXT_CHANGE_PIN_TITLE, (short) 0, (short) TXT_CHANGE_PIN_TITLE.length, apduBuffer); return isSuccess; } public boolean changeNormalUserPin(byte[] apduBuffer) { boolean isSuccess = false; // Use UX Render to accept new PIN short len = uxRender(T101OpenAPI.UI_TYPE_INPUT, (byte) 0x01, (byte) 0x01, (byte) 0xFF, (byte) 0x20, TXT_CHANGE_PIN_TITLE, (short) 0, (short) TXT_CHANGE_PIN_TITLE.length, TXT_NEW_PIN, (short) 0, (short) TXT_NEW_PIN.length, aocPin, (short) 0, (short) aocPin.length, apduBuffer); if (len >= 2) { Util.arrayCopyNonAtomic(userName, (short) 0, apduBuffer, len, (short) userName.length); isSuccess = ThothPGPApplet.api.manageUserCred(T101OpenAPI.CRED_FIELD_SECRET, apduBuffer, (short) 0, len, null, (short) 0, T101OpenAPI.CRED_FIELD_NAME, apduBuffer, len, (short) userName.length, T101OpenAPI.AUTH_FRONTPANEL); Util.arrayFillNonAtomic(apduBuffer, (short) 0, len, (byte) 0x00); } opsStatusUI(isSuccess, TXT_CHANGE_PIN_TITLE, (short) 0, (short) TXT_CHANGE_PIN_TITLE.length, apduBuffer); return isSuccess; } public boolean changeAdminPin(byte[] apduBuffer) { boolean isSuccess = false; // Use UX Render to accept new PIN short len = uxRender(T101OpenAPI.UI_TYPE_INPUT, (byte) 0x01, (byte) 0x01, (byte) 0xFF, (byte) 0x20, TXT_CHANGE_PIN_TITLE, (short) 0, (short) TXT_CHANGE_PIN_TITLE.length, TXT_NEW_PIN, (short) 0, (short) TXT_NEW_PIN.length, aocPin, (short) 0, (short) aocPin.length, apduBuffer); if (len >= 2) { Util.arrayCopyNonAtomic(adminName, (short) 0, apduBuffer, len, (short) adminName.length); isSuccess = ThothPGPApplet.api.manageUserCred(T101OpenAPI.CRED_FIELD_SECRET, apduBuffer, (short) 0, len, null, (short) 0, T101OpenAPI.CRED_FIELD_NAME, apduBuffer, len, (short) adminName.length, T101OpenAPI.AUTH_FRONTPANEL); Util.arrayFillNonAtomic(apduBuffer, (short) 0, len, (byte) 0x00); } opsStatusUI(isSuccess, TXT_CHANGE_PIN_TITLE, (short) 0, (short) TXT_CHANGE_PIN_TITLE.length, apduBuffer); return isSuccess; } public boolean pukChangePUKPinPin(byte[] apduBuffer) { tempBuf = null; boolean isSuccess = false; // Use UX Render to accept new PIN short secLen = uxRender(T101OpenAPI.UI_TYPE_INPUT, (byte) 0x01, (byte) 0x01, (byte) 0xFF, (byte) 0x20, TXT_CHANGE_PIN_TITLE, (short) 0, (short) TXT_CHANGE_PIN_TITLE.length, TXT_NEW_PIN, (short) 0, (short) TXT_NEW_PIN.length, aocPin, (short) 0, (short) aocPin.length, apduBuffer); if (secLen >= 2) { tempBuf = new byte[secLen]; Util.arrayCopyNonAtomic(apduBuffer, (short) 0, tempBuf, (short) 0, secLen); Util.arrayCopyNonAtomic(pukName, (short) 0, apduBuffer, secLen, (short) pukName.length); if (ThothPGPApplet.api.manageUserCred(T101OpenAPI.CRED_FIELD_SECRET, apduBuffer, (short) 0, secLen, apduBuffer, (short) 0, T101OpenAPI.CRED_FIELD_NAME, apduBuffer, secLen, (short) pukName.length, T101OpenAPI.AUTH_INTERNAL)) { Util.arrayCopyNonAtomic(apduBuffer, (short) 0, nonceBuffer, (short) 0, (short) 8); if (authContainer(pukUserPin, (short) 0, (short) pukUserPin.length, nonceBuffer, (short) 0, apduBuffer) != (short) -1) { JCSystem.beginTransaction(); pukUserPin = null; pukUserPin = new byte[secLen]; Util.arrayCopyNonAtomic(tempBuf, (short) 0, pukUserPin, (short) 0, secLen); JCSystem.commitTransaction(); tempBuf = null; isSuccess = true; } } } Util.arrayFillNonAtomic(apduBuffer, (short) 0, secLen, (byte) 0x00); tempBuf = null; opsStatusUI(isSuccess, TXT_CHANGE_PIN_TITLE, (short) 0, (short) TXT_CHANGE_PIN_TITLE.length, apduBuffer); return isSuccess; } public boolean newAsymmetricKeyObject(byte asymType, byte ind, byte[] expiryTS, short expiryOffset, byte[] buffer) { short nameLen = 4; Util.arrayCopyNonAtomic(getKeyHandle(ind), (short) 0, buffer, (short) 0, nameLen); Util.arrayCopyNonAtomic(expiryTS, expiryOffset, buffer, nameLen, (short) 4); Util.arrayCopyNonAtomic(pukName, (short) 0, buffer, (short) (4 + nameLen), (short) pukName.length); buffer[(short) (4 + nameLen + pukName.length)] = asymType; buffer[(short) (5 + nameLen + pukName.length)] = (byte) 0x07; if (ThothPGPApplet.api.newObject(T101OpenAPI.OBJ_TYPE_KEY, // objectType buffer, (short) 0, nameLen, // objectName null, (short) 0, (short) 0, // om1 null, (short) 0, (short) 0, // om2 T101OpenAPI.OBJ_PERM_EXPORT_ALLOW_FLAG, // export buffer[(short) (5 + nameLen + pukName.length)], // acl T101OpenAPI.KEY_CLASS_ASYMMETRIC, // keyClass buffer[(short) (4 + nameLen + pukName.length)], // keyType true, // requireAttestation buffer, nameLen, // expiry T101OpenAPI.CRED_FIELD_NAME, buffer, (short) (4 + nameLen), (short) pukName.length, // authUserCred buffer, (short) (6 + nameLen + pukName.length), // output T101OpenAPI.AUTH_INTERNAL) // authMethod ) { Util.arrayCopyNonAtomic(buffer, (short) (6 + nameLen + pukName.length), nonceBuffer, (short) 0, (short) 8); if (authContainer(pukUserPin, (short) 0, (short) pukUserPin.length, nonceBuffer, (short) 0, buffer) != (short) -1) { return true; } } return false; } public short executeObject(byte execMethod, byte subOpMode1, byte subOpMode2, boolean useBufferedData, byte ind, byte[] input, short offset, short len, byte[] buffer) { short nameLen = 4; short result = (short) -1; Util.arrayCopyNonAtomic(getKeyHandle(ind), (short) 0, buffer, (short) 0, nameLen); if (input != null) { Util.arrayCopyNonAtomic(input, offset, buffer, nameLen, len); } Util.arrayCopyNonAtomic(pukName, (short) 0, buffer, (short) (nameLen + len), (short) pukName.length); result = ThothPGPApplet.api.executeObject(execMethod, // execMethod subOpMode1, // subOpMode1 subOpMode2, // subOpMode2 useBufferedData, // useBufferData buffer, (short) 0, nameLen, // objectName buffer, nameLen, len, // input buffer, (short) (nameLen + len + pukName.length), // output KM101.T101OpenAPI.CRED_FIELD_NAME, buffer, (short) (nameLen + len), (short) pukName.length, // authUserCred KM101.T101OpenAPI.AUTH_INTERNAL // authMethod ); if (result != (short) -1) { Util.arrayCopyNonAtomic(buffer, (short) (nameLen + len + pukName.length), nonceBuffer, (short) 0, (short) 8); return authContainer(pukUserPin, (short) 0, (short) pukUserPin.length, nonceBuffer, (short) 0, buffer); } return result; } public short getObjectCryptoType(byte ind, byte[] buffer) { short nameLen = 4; // Copy object handle name into buffer for API call Util.arrayCopyNonAtomic(getKeyHandle(ind), (short) 0, buffer, (short) 0, nameLen); // Copy PUK username into buffer for API call Util.arrayCopyNonAtomic(pukName, (short) 0, buffer, (short) nameLen, (short) pukName.length); if (ThothPGPApplet.api.getObjectInfo(buffer, (short) 0, nameLen, T101OpenAPI.OBJ_FIELD_SUBTYPE_TYPE, buffer, (short) (nameLen + pukName.length), T101OpenAPI.CRED_FIELD_NAME, buffer, (short) nameLen, (short) pukName.length, KM101.T101OpenAPI.AUTH_INTERNAL) != (short) -1) { Util.arrayCopyNonAtomic(buffer, (short) (nameLen + pukName.length), nonceBuffer, (short) 0, (short) 8); return authContainer(pukUserPin, (short) 0, (short) pukUserPin.length, nonceBuffer, (short) 0, buffer); } return (short) -1; } public short getObjectCreationTS(byte ind, byte[] buffer) { short nameLen = 4; // Copy object handle name into buffer for API call Util.arrayCopyNonAtomic(getKeyHandle(ind), (short) 0, buffer, (short) 0, nameLen); // Copy PUK username into buffer for API call Util.arrayCopyNonAtomic(pukName, (short) 0, buffer, (short) nameLen, (short) pukName.length); if (ThothPGPApplet.api.getObjectInfo(buffer, (short) 0, nameLen, T101OpenAPI.OBJ_FIELD_CREATE, buffer, (short) (nameLen + pukName.length), T101OpenAPI.CRED_FIELD_NAME, buffer, (short) nameLen, (short) pukName.length, KM101.T101OpenAPI.AUTH_INTERNAL) != (short) -1) { Util.arrayCopyNonAtomic(buffer, (short) (nameLen + pukName.length), nonceBuffer, (short) 0, (short) 8); return authContainer(pukUserPin, (short) 0, (short) pukUserPin.length, nonceBuffer, (short) 0, buffer); } return (short) -1; } public boolean destroyObject(byte[] objName, short offset, short len, byte[] buffer) { Util.arrayCopyNonAtomic(pukName, (short) 0, buffer, len, (short) pukName.length); if (ThothPGPApplet.api.deleteObject(buffer, (short) 0, len, buffer, (short) (len + pukName.length), KM101.T101OpenAPI.CRED_FIELD_NAME, buffer, len, (short) pukName.length, KM101.T101OpenAPI.AUTH_INTERNAL)) { // Session auth nonce Util.arrayCopyNonAtomic(buffer, (short) (len + pukName.length), nonceBuffer, (short) 0, (short) 8); // Authenticate against auth nonce if (authContainer(pukUserPin, (short) 0, (short) pukUserPin.length, nonceBuffer, (short) 0, buffer) != (short) -1) { return true; } } return false; } public boolean confirmationUI(byte[] title, short titleOffset, short titleLen, byte[] input, short inOffset, short inLen, byte[] apduBuffer) { if (uxRender(T101OpenAPI.UI_TYPE_TEXT, T101OpenAPI.NULL, T101OpenAPI.NULL, T101OpenAPI.NULL, T101OpenAPI.NULL, title, titleOffset, titleLen, input, inOffset, inLen, aocPin, (short) 0, (short) aocPin.length, apduBuffer) == (short) 1) { return true; } return false; } public void opsStatusUI(boolean isSuccess, byte[] title, short titleOffset, short titleLen, byte[] apduBuffer) { if (isSuccess) { uxRender(T101OpenAPI.UI_TYPE_TEXT, T101OpenAPI.NULL, T101OpenAPI.NULL, T101OpenAPI.NULL, T101OpenAPI.NULL, title, titleOffset, titleLen, TXT_SUCCESS, (short) 0, (short) TXT_SUCCESS.length, aocPin, (short) 0, (short) aocPin.length, apduBuffer); } else { uxRender(T101OpenAPI.UI_TYPE_TEXT, T101OpenAPI.NULL, T101OpenAPI.NULL, T101OpenAPI.NULL, T101OpenAPI.NULL, title, titleOffset, titleLen, TXT_FAILED, (short) 0, (short) TXT_FAILED.length, aocPin, (short) 0, (short) aocPin.length, apduBuffer); } } public short uxRender(byte type, byte subMode, byte subMode1, byte subMode2, byte subMode3, byte[] title, short titleOffset, short titleLen, byte[] input, short inOffset, short inLen, byte[] aocPin, short aocPinOffset, short aocPinLen, byte[] apduBuffer) { apduBuffer[0] = type; short snonceBuffer = (short) 0; short sb1 = (short) 0; short sb2 = (short) 0; if (title != null && titleLen > 0) { Util.arrayCopyNonAtomic(title, titleOffset, apduBuffer, (short) 1, titleLen); sb1 = titleLen; } if (input != null && inLen > 0) { Util.arrayCopyNonAtomic(input, inOffset, apduBuffer, (short) (1 + sb1), inLen); sb2 = inLen; } snonceBuffer = ThothPGPApplet.api.uiSession(apduBuffer[0], subMode, subMode1, subMode2, subMode3, apduBuffer, (short) 1, sb1, apduBuffer, (short) (1 + sb1), sb2, apduBuffer, (short) (1 + sb1 + sb2)); if (snonceBuffer != -1) { Util.arrayCopyNonAtomic(apduBuffer, (short) (1 + sb1 + sb2), nonceBuffer, (short) 0, (short) 8); snonceBuffer = authContainer(aocPin, aocPinOffset, aocPinLen, nonceBuffer, (short) 0, apduBuffer); if (snonceBuffer > -1) { return snonceBuffer; } else { ISOException.throwIt(Util.makeShort((byte) 0x6f, (byte) 0xc2)); } } else { ISOException.throwIt(Util.makeShort((byte) 0x6f, (byte) 0xc1)); } return (short) -1; } public boolean clearUploadBuffer(byte[] buffer) { if (ThothPGPApplet.api.clearBuffer(buffer, (short) 0) != (short) -1) { // Session auth nonce Util.arrayCopyNonAtomic(buffer, (short) 0, nonceBuffer, (short) 0, (short) 8); // Authenticate against auth nonce if (authContainer(aocPin, (short) 0, (short) aocPin.length, nonceBuffer, (short) 0, buffer) != (short) -1) { return true; } } return false; } public boolean uploadToBuffer(boolean isAppend, short maxLen, byte[] input, short offset, short len, byte[] buffer) { Util.arrayCopyNonAtomic(input, offset, buffer, (short) 0, len); short sb0 = (short) 0; if (isAppend) { // Append to existing buffer with buffer offset since the last entry length sb0 = ThothPGPApplet.api.bufferData(true, (short) 0, buffer, (short) 0, len, getBufferLength(), buffer, len); } else { // New buffer sb0 = ThothPGPApplet.api.bufferData(true, maxLen, buffer, (short) 0, len, (short) 0, buffer, len); } if (sb0 != (short) -1) { // Session auth nonce Util.arrayCopyNonAtomic(buffer, len, nonceBuffer, (short) 0, (short) 8); // Authenticate against auth nonce if (authContainer(aocPin, (short) 0, (short) aocPin.length, nonceBuffer, (short) 0, buffer) != (short) -1) { return true; } } return false; } public short readFromBuffer(short readOff, short readLen, byte[] buffer) { if (ThothPGPApplet.api.bufferData(false, (short) 0, null, (short) 0, readLen, readOff, buffer, (short) 0) != (short) -1) { // Session auth nonce Util.arrayCopyNonAtomic(buffer, (short) 0, nonceBuffer, (short) 0, (short) 8); // Authenticate against auth nonce return authContainer(aocPin, (short) 0, (short) aocPin.length, nonceBuffer, (short) 0, buffer); } return (short) -1; } public short getBufferLength() { return ThothPGPApplet.api.getBufferDataLength(); } public boolean writeCert(byte ind, byte[] cert, short inOff, short storeOff, short len) { // Load input into certificate store short uploadSize = (short) 0; for (short i = 0; i < len;) { if ((short) (len - i) > (short) 261) { uploadSize = (short) 261; } else { uploadSize = (short) (len - i); } if (!ThothPGPApplet.csapi.writeCert(ind, cert, (short) (inOff + i), (short) (storeOff + i), uploadSize)) { return false; } i += uploadSize; } return true; } public short readCert(byte ind, byte[] output, short outOff, short storeOff, short len) { short readSize = (short) 0; short i = (short) 0; for (; i < len;) { if ((short) (len - i) > (short) 261) { readSize = (short) 261; } else { readSize = (short) (len - i); } if (ThothPGPApplet.csapi.readCert(ind, output, (short) (outOff + i), (short) (storeOff + i), readSize) != (short) -1) { return (short) -1; } i += readSize; } return i; } public void clearCert(byte ind) { ThothPGPApplet.csapi.clearCert(ind); } public short certLength(byte ind) { return ThothPGPApplet.csapi.certLength(ind); } public static void shortToBytes(short s, byte[] b, short offset) { b[offset] = (byte) ((s >> 8) & 0xFF); b[(short) (offset + 1)] = (byte) (s & 0xFF); } } ydmmocoo/MGM package com.fjx.mg.main.more.search; import android.content.Context; import android.content.Intent; import android.text.TextUtils; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.listener.OnItemClickListener; import com.fjx.mg.R; import com.fjx.mg.house.HouseHomeActivity; import com.fjx.mg.job.JobHomeActivity; import com.fjx.mg.main.payment.PayMentActivity; import com.fjx.mg.main.payment.PayMentContract; import com.fjx.mg.main.rate.RateActivity; import com.fjx.mg.main.translate.TranslateActivity; import com.fjx.mg.main.yellowpage.YellowPageActivityV1; import com.fjx.mg.recharge.center.RechargeCenterActivityx; import com.fjx.mg.setting.feedback.FeedBackActivity; import com.fjx.mg.utils.SharedPreferencesHelper; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.library.common.base.BaseMvpActivity; import com.library.common.base.adapter.decoration.SpacesItemDecoration; import com.library.common.utils.CommonToast; import com.library.common.utils.SoftInputUtil; import com.library.common.utils.StatusBarManager; import com.library.repository.models.AppModel; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.OnClick; public class SearchAppActivity extends BaseMvpActivity implements SearchAppContract.View { @BindView(R.id.listAllApp) RecyclerView listAllApp; @BindView(R.id.etSearch) EditText etSearch; @BindView(R.id.ivClear) ImageView ivClear; @BindView(R.id.tvSearch) TextView tvSearch; private ArrayList statusLs = new ArrayList<>(); private ArrayList AppAllList = new ArrayList<>(); private ArrayList aftersearch = new ArrayList<>(); private SearchAppAdapter allappAdapter; public static Intent newInstance(Context context) { return new Intent(context, SearchAppActivity.class); } @Override protected int layoutId() { return R.layout.activity_search_app; } @Override protected SearchAppPresenter createPresenter() { return new SearchAppPresenter(this); } @Override protected void initView() { super.initView(); SetToolBar(); SetAllData(AppAllList); ShowAll(); } private void ShowAll() { allappAdapter = new SearchAppAdapter(this); listAllApp.setLayoutManager(new GridLayoutManager(getCurContext(), 1)); listAllApp.addItemDecoration(new SpacesItemDecoration(0, 0)); listAllApp.setAdapter(allappAdapter); allappAdapter.setList(aftersearch); allappAdapter.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) { ItemClick(allappAdapter.getItem(position).getId()); } }); } private void SetToolBar() { StatusBarManager.setLightFontColor(this, R.color.colorAccent); mPresenter.bindTextWatcher(etSearch); } private void SetAllData(ArrayList appUsedList) { appUsedList.add(new AppModel(getResources().getString(R.string.recharge_center), R.drawable.ic_home_cz)); appUsedList.add(new AppModel(getResources().getString(R.string.house_rent), R.drawable.ic_home_zs)); appUsedList.add(new AppModel(getResources().getString(R.string.employment), R.drawable.ic_home_zp)); appUsedList.add(new AppModel(getResources().getString(R.string.yellow_page), R.drawable.ic_home_hy)); appUsedList.add(new AppModel(getResources().getString(R.string.exchange_rate_inquiry), R.drawable.ic_home_search)); appUsedList.add(new AppModel(getResources().getString(R.string.translate_online), R.drawable.ic_home_fy)); appUsedList.add(new AppModel(getResources().getString(R.string.feedback), R.drawable.home_feedback)); appUsedList.add(new AppModel(getResources().getString(R.string.payment_problem), R.drawable.payment_problem)); } private void ItemClick(int id) { switch (id) { case R.drawable.ic_home_cz://充值中心 mPresenter.recUseApp("1"); startActivity(RechargeCenterActivityx.newInstance(getCurContext())); break; case R.drawable.ic_home_zs://房屋租售 mPresenter.recUseApp("2"); startActivity(HouseHomeActivity.newInstance(getCurContext())); break; case R.drawable.ic_home_zp://求职招聘 mPresenter.recUseApp("3"); startActivity(JobHomeActivity.newInstance(getCurContext())); break; case R.drawable.ic_home_hy://企业黄页 mPresenter.recUseApp("4"); startActivity(YellowPageActivityV1.newInstance(getCurContext())); break; case R.drawable.ic_home_search://汇率查询 mPresenter.recUseApp("5"); startActivity(RateActivity.newInstance(getCurActivity())); break; case R.drawable.ic_home_fy://在线翻译 mPresenter.recUseApp("6"); startActivity(TranslateActivity.newInstance(getCurActivity())); break; case R.drawable.home_feedback://意见反馈 mPresenter.recUseApp("7"); startActivity(FeedBackActivity.newInstance(getCurContext())); break; case R.drawable.payment_problem://有偿问答 mPresenter.recUseApp("8"); startActivity(PayMentActivity.newInstance(getCurContext())); break; } } @OnClick({R.id.ivBack, R.id.ivClear, R.id.tvSearch}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.ivBack: onBackPressed(); break; case R.id.ivClear: etSearch.setText(""); break; case R.id.tvSearch: doSearch(); break; } } private void doSearch() { String content = etSearch.getText().toString(); if (TextUtils.isEmpty(content)) { CommonToast.toast(getString(R.string.hint_input_search_content)); return; } SearchLocal(content); SoftInputUtil.hideSoftInput(getCurActivity()); } private void SearchLocal(String content) { aftersearch.clear(); for (AppModel model : AppAllList) { if (model.getAppname().contains(content)) { aftersearch.add(model); } } allappAdapter.setList(aftersearch); } @Override public void showClearImage(boolean enableShow) { ivClear.setVisibility(enableShow ? View.VISIBLE : View.GONE); } @Override public void watchSearch(String search) { if (search.equals("")) { aftersearch.clear(); allappAdapter.setList(aftersearch); } else { SearchLocal(search); } } @Override public void showUsed(String s) { ItemClick(s); } private void ItemClick(String id) { switch (id) { case "1"://充值中心 startActivity(RechargeCenterActivityx.newInstance(getCurContext())); break; case "2"://房屋租售 startActivity(HouseHomeActivity.newInstance(getCurContext())); break; case "3"://求职招聘 startActivity(JobHomeActivity.newInstance(getCurContext())); break; case "4"://企业黄页 startActivity(YellowPageActivityV1.newInstance(getCurContext())); break; case "5"://汇率查询 startActivity(RateActivity.newInstance(getCurActivity())); break; case "6"://在线翻译 startActivity(TranslateActivity.newInstance(getCurActivity())); break; case "7"://意见反馈 startActivity(FeedBackActivity.newInstance(getCurContext())); break; case "8"://有偿问答 startActivity(PayMentActivity.newInstance(getCurContext())); break; } } } Interfaces and Abstraction - Excercise/birthdayCelebrations/Pet.java package birthdayCelebrations; public class Pet implements Birthable { private String name; private String birthDate; public Pet(String name, String birthDate) { this.name = name; this.birthDate = birthDate; } public String getName() { return name; } @Override public String getBirthDate() { // TODO Auto-generated method stub return this.birthDate; } }itroadlabs/apicross0 package apicross.demo.myspace.ports.adapters.db; import apicross.demo.myspace.domain.WorkFileReference; import apicross.demo.myspace.domain.WorkFileReferenceNotFoundException; import apicross.demo.myspace.domain.WorkFileReferenceRepository; import lombok.NonNull; import org.springframework.stereotype.Component; @Component class WorkFileReferenceRepositoryDbAdapter implements WorkFileReferenceRepository { private final WorkFileReferenceDao workFileReferenceDao; WorkFileReferenceRepositoryDbAdapter(WorkFileReferenceDao workFileReferenceDao) { this.workFileReferenceDao = workFileReferenceDao; } @Override public void add(@NonNull WorkFileReference workFileReference) { workFileReferenceDao.save(workFileReference); } @Override public void delete(@NonNull String username, @NonNull String fileId) { workFileReferenceDao.delete(findById(username, fileId)); } @Override public WorkFileReference findById(@NonNull String username, @NonNull String fileId) { return workFileReferenceDao.findById(fileId).orElseThrow(() -> new WorkFileReferenceNotFoundException(fileId)); } } package serialization; import org.apache.log4j.*; import common.messages.KVMessage; import common.messages.KVMessageImpl; import common.messages.KVMessage.StatusType; /** * Handles serialization and unserialization of requests and responses. */ public class Serialization { private static Logger logger = Logger.getRootLogger(); private static final int BUFFER_SIZE = 122880; private static final int DROP_SIZE = 128 * BUFFER_SIZE; /** * Serializes the given KVMessage into a string * @param message the KVMessage to serialize * @return the serialized string message */ public static String serialize(KVMessage message) { StatusType requestType = message.getStatus(); switch(requestType) { case GET: return "GET\n" + message.getKey() + "\n\n"; case PUT: return "PUT\n" + message.getKey() + "\n" + (message.getValue() == null ? "" : message.getValue() + "\n") + "\n"; case GET_SUCCESS: case PUT_SUCCESS: case PUT_UPDATE: case DELETE_SUCCESS: return requestType + "\n" + message.getKey() + "\n" + message.getValue() + "\n\n"; case GET_ERROR: case PUT_ERROR: case DELETE_ERROR: return requestType + "\n" + message.getValue() + "\n\n"; default: logger.error("Invalid request type for serialization: " + requestType); return ""; } } /** * Unserializes the given string into a KVMessage * @param lines the list of lines in the message to parse * (excluding trailing blank line at end) * @return the unserialized KVMessage */ public static KVMessage unserialize(String[] lines) throws IllegalArgumentException { if(lines.length < 1) { throw new IllegalArgumentException("Cannot process empty request"); } switch(lines[0]) { // Requests case "GET": return parseGetRequest(lines); case "PUT": return parsePutRequest(lines); // Responses case "GET_SUCCESS": case "PUT_SUCCESS": case "PUT_UPDATE": case "DELETE_SUCCESS": return parseSuccessResponse(lines); case "GET_ERROR": case "PUT_ERROR": case "DELETE_ERROR": return parseErrorResponse(lines); // Unrecognized default: throw new IllegalArgumentException("Invalid status type: '" + lines[0] + "'"); } } public static KVMessage parseGetRequest(String[] lines) throws IllegalArgumentException { if(lines.length != 2) { throw new IllegalArgumentException("Invalid number of arguments " + "for GET request: " + lines.length); } return new KVMessageImpl(lines[1], null, lines[0]); } public static KVMessage parsePutRequest(String[] lines) throws IllegalArgumentException { if(lines.length < 2 || lines.length > 3) { throw new IllegalArgumentException("Invalid number of arguments " + "for PUT request: " + lines.length); } return new KVMessageImpl(lines[1], lines.length == 3 ? lines[2] : null, lines[0]); } public static KVMessage parseSuccessResponse(String[] lines) throws IllegalArgumentException { if(lines.length != 3) { throw new IllegalArgumentException("Invalid number of arguments " + "for success response: " + lines.length); } return new KVMessageImpl(lines[1], lines[2], lines[0]); } public static KVMessage parseErrorResponse(String[] lines) throws IllegalArgumentException { if(lines.length != 2) { throw new IllegalArgumentException("Invalid number of arguments " + "for error response: " + lines.length); } return new KVMessageImpl(null, lines[1], lines[0]); } } package com.midorlo.k12.configuration; import lombok.experimental.UtilityClass; import java.net.URI; /** * Application constants. * * Reminder: These values are not environment ie dev,qa,stage specific and do not change throughout the lifecycle. */ @UtilityClass public final class ApplicationConstants { /** * Regex for acceptable logins */ public static final String LOGIN_REGEX = "^(?>[a-zA-Z0-9!$&*+=?^_`{|}~.-]+@[a-zA-Z0-9-]+(?:\\" + ".[a-zA-Z0-9-]+)*)|(?>[_" + ".@A-Za-z0-9-]+)$"; /** * Default System Identifier. */ public static final String SYSTEM = "system"; /** * Global system language. */ public static final String DEFAULT_LANGUAGE = "de"; /** * Http feature policy configuration. */ public static final String PERMISSIONS_POLICY_CONFIG = "geolocation 'none'; midi 'none'; sync-xhr " + "'none'; microphone 'none'; camera 'none'; " + "magnetometer 'none'; gyroscope 'none'; " + "fullscreen 'self'; payment 'none'"; public static final String REPOSITORY_PACKAGE = "com.midorlo.k12.repository"; public static final String SPRING_PROFILE_DEFAULT = "spring.profiles.default"; public static final class ContextConstants { /** * Constant SPRING_PROFILE_DEVELOPMENT="dev" */ public static final String SPRING_PROFILE_DEVELOPMENT = "dev"; /** * Constant SPRING_PROFILE_TEST="test" */ public static final String SPRING_PROFILE_TEST = "test"; /** * Constant SPRING_PROFILE_PRODUCTION="prod" */ public static final String SPRING_PROFILE_PRODUCTION = "prod"; /** * Spring profile used when deploying with Spring Cloud (used when deploying to CloudFoundry) * Constant SPRING_PROFILE_CLOUD="cloud" */ public static final String SPRING_PROFILE_CLOUD = "cloud"; /** * Spring profile used when deploying to Heroku * Constant SPRING_PROFILE_HEROKU="heroku" */ public static final String SPRING_PROFILE_HEROKU = "heroku"; /** * Spring profile used when deploying to Amazon ECS * Constant SPRING_PROFILE_AWS_ECS="aws-ecs" */ public static final String SPRING_PROFILE_AWS_ECS = "aws-ecs"; /** * Spring profile used when deploying to Microsoft Azure * Constant SPRING_PROFILE_AZURE="azure" */ public static final String SPRING_PROFILE_AZURE = "azure"; /** * Spring profile used to enable OpenAPI doc generation * Constant SPRING_PROFILE_API_DOCS="api-docs" */ public static final String SPRING_PROFILE_API_DOCS = "api-docs"; /** * Spring profile used when deploying to Kubernetes and OpenShift * Constant SPRING_PROFILE_K8S="k8s" */ public static final String SPRING_PROFILE_K8S = "k8s"; } public static final class SecurityConstants { public static final String ROLE_ADMIN = "ROLE_ADMIN"; public static final String ROLE_USER = "ROLE_USER"; public static final String ROLE_ANONYMOUS = "ROLE_ANONYMOUS"; } public static final class ErrorConstants { public static final String ERR_CONCURRENCY_FAILURE = "error.concurrencyFailure"; public static final String ERR_VALIDATION = "error.validation"; public static final String PROBLEM_BASE_URL = "https://www.application.tld/problem"; public static final URI DEFAULT_TYPE = URI.create(PROBLEM_BASE_URL + "/problem-with-message"); public static final URI CONSTRAINT_VIOLATION_TYPE = URI.create(PROBLEM_BASE_URL + "/constraint-violation"); public static final URI INVALID_PASSWORD_TYPE = URI.create(PROBLEM_BASE_URL + "/invalid-password"); public static final URI EMAIL_ALREADY_USED_TYPE = URI.create(PROBLEM_BASE_URL + "/email-already-used"); public static final URI LOGIN_ALREADY_USED_TYPE = URI.create(PROBLEM_BASE_URL + "/login-already-used"); private ErrorConstants() {} } public static final class TechConstants { public static final String AUDITOR_BEAN = "springSecurityAuditorAware"; } public static final class TableNames { public static final String CLEARANCES = "clearances"; public static final String ROLES = "roles"; public static final String USERS = "users"; public static final String MENUS = "menus"; public static final String MENU_ITEMS = "menu_items"; } public static final class ColumnNames {} public static final class RelationNames {} public static final class CacheNames { public static final String USERS_BY_LOGIN_CACHE = "usersByLogin"; public static final String USERS_BY_EMAIL_CACHE = "usersByEmail"; } } davidmeimoun/KAMI_GAME package com.example.david.myapplication; import android.content.Intent; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; /** * Created by david on 05/02/2018. */ public class LevelActivity extends AppCompatActivity { String level; String user; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_level); Bundle b = new Bundle(); b = getIntent().getExtras(); String level = b.getString("level"); String user = b.getString("user"); this.level = level; this.user = user; ajoutDesInfosDansBoutons(level); } private void ajoutDesInfosDansBoutons(final String level) { LinearLayout buttonContainer = (LinearLayout) findViewById(R.id.buttonContainer); buttonContainer.removeAllViews(); try { InputStream is = getClass().getResourceAsStream("/puzzles/" + level + ".xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(is); Element element = doc.getDocumentElement(); element.normalize(); NodeList nList = doc.getElementsByTagName("Puzzle"); for (int i = 0; i < nList.getLength(); i++) { Node node = nList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { final Element element2 = (Element) node; Button button = new Button(this); String tab[] = new String[2]; if (element2.getAttribute("name").contains("_")) { tab = element2.getAttribute("name").split("_"); boolean isNiveauValide = lireDansBaseDeDonnee(user, level, element2.getAttribute("name")); if (isNiveauValide) button.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.dimmedgrey)); button.setText(tab[1]);// + " - " + isNiveauValide ); } else { tab[0] = element2.getAttribute("name"); boolean isNiveauValide = lireDansBaseDeDonnee(user, level, element2.getAttribute("name")); if (isNiveauValide) button.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.dimmedgrey)); button.setText(tab[0]);//+ " - " + isNiveauValide); } button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(LevelActivity.this, GrilleActivity.class); i.putExtra("stage", element2.getAttribute("name")); i.putExtra("level", level); i.putExtra("user", user); startActivity(i); } }); buttonContainer.addView(button); } } } catch (Exception e) { e.printStackTrace(); } } private boolean lireDansBaseDeDonnee(String utilisateur, String level, String stage) { String path = getApplicationContext().getFilesDir().getPath() + "/" + "db.csv"; BufferedReader br = null; try { InputStream is = new FileInputStream(path); br = new BufferedReader(new InputStreamReader(is)); ; String line = ""; String cvsSplitBy = ","; while ((line = br.readLine()) != null) { // use comma as separator String[] data = line.split(cvsSplitBy); if (data[0].equals(utilisateur)) if (data[1].equals(stage)) if (data[2].equals(level)) return true; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } return false; } @Override protected void onResume() { super.onResume(); ajoutDesInfosDansBoutons(this.level); } } 0 package com.thinkgem.jeesite.modules.platform.web.account; import java.math.BigDecimal; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.thinkgem.jeesite.common.config.Global; import com.thinkgem.jeesite.common.persistence.Page; import com.thinkgem.jeesite.common.web.BaseController; import com.thinkgem.jeesite.common.utils.EhCacheUtils; import com.thinkgem.jeesite.common.utils.StringUtils; import com.thinkgem.jeesite.modules.platform.constants.Constants; import com.thinkgem.jeesite.modules.platform.entity.account.BitMexAccount; import com.thinkgem.jeesite.modules.platform.entity.account.BitOkAccount; import com.thinkgem.jeesite.modules.platform.service.account.BitMexAccountService; import com.thinkgem.jeesite.modules.sys.entity.User; import com.thinkgem.jeesite.modules.sys.utils.UserUtils; /** * mex 账户信息表Controller * @author hzf * @version 2017-09-13 */ @Controller @RequestMapping(value = "${adminPath}/platform/account/bitMexAccount") public class BitMexAccountController extends BaseController { @Autowired private BitMexAccountService bitMexAccountService; @ModelAttribute public BitMexAccount get(@RequestParam(required=false) String id) { BitMexAccount entity = null; if (StringUtils.isNotBlank(id)){ entity = bitMexAccountService.get(id); } if (entity == null){ entity = new BitMexAccount(); } return entity; } @RequiresPermissions("platform:account:bitMexAccount:view") @RequestMapping(value = {"list", ""}) public String list(BitMexAccount bitMexAccount, HttpServletRequest request, HttpServletResponse response, Model model) { Page page = bitMexAccountService.findPage(new Page(request, response), bitMexAccount); model.addAttribute("page", page); return "modules/platform/account/bitMexAccountList"; } @RequiresPermissions("platform:account:bitMexAccount:view") @RequestMapping(value = "form") public String form(BitMexAccount bitMexAccount, Model model) { model.addAttribute("bitMexAccount", bitMexAccount); return "modules/platform/account/bitMexAccountForm"; } @RequiresPermissions("platform:account:bitMexAccount:edit") @RequestMapping(value = "save") public String save(BitMexAccount bitMexAccount, Model model, RedirectAttributes redirectAttributes) { if (!beanValidator(model, bitMexAccount)){ return form(bitMexAccount, model); } bitMexAccountService.save(bitMexAccount); addMessage(redirectAttributes, "保存mex 账户信息表成功"); return "redirect:"+Global.getAdminPath()+"/platform/account/bitMexAccount/?repage"; } @RequiresPermissions("platform:account:bitMexAccount:edit") @RequestMapping(value = "delete") public String delete(BitMexAccount bitMexAccount, RedirectAttributes redirectAttributes) { bitMexAccountService.delete(bitMexAccount); addMessage(redirectAttributes, "删除mex 账户信息表成功"); return "redirect:"+Global.getAdminPath()+"/platform/account/bitMexAccount/?repage"; } @RequestMapping(value = "getAccount", method=RequestMethod.POST) @ResponseBody public BitMexAccount getAccount(String type){ BitMexAccount bitMexAccount = new BitMexAccount(); User user = UserUtils.getUser(); bitMexAccount.setUseId(user.getId()); bitMexAccount.setSymbol(type); logger.info(">> uid="+user.getId()+" ,type="+type); List ret = bitMexAccountService.findList(bitMexAccount); if(null != ret && !ret.isEmpty()){ bitMexAccount = ret.get(0); // XBT 转 USD, XBTUSD 实时价格从缓存取 Double curPrice = (Double)EhCacheUtils.get(Constants.PRICE_CACHE,Constants.CACHE_XBTUSDMEX_PRICE_KEY); BigDecimal usdPrice = bitMexAccount.getAccountBalance().multiply(new BigDecimal(curPrice)); bitMexAccount.setBond(usdPrice.setScale(4,BigDecimal.ROUND_HALF_UP)); }else{ bitMexAccount.setBalance(new BigDecimal(0)); bitMexAccount.setAccountBalance(new BigDecimal(0)); bitMexAccount.setBond(new BigDecimal(0)); } return bitMexAccount; } }/* * The MIT License * * Copyright (c) 2016, CloudBees, Inc. * * 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.cloudbees.jenkins.plugins.gitea.server.client; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.Collections; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import com.cloudbees.jenkins.plugins.gitea.api.*; import com.cloudbees.jenkins.plugins.gitea.server.client.repository.*; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.methods.DeleteMethod; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import com.cloudbees.jenkins.plugins.gitea.server.client.branch.GiteaServerBranch; import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials; import hudson.ProxyConfiguration; import hudson.util.Secret; import jenkins.model.Jenkins; import net.sf.json.JSONObject; import org.codehaus.jackson.map.type.CollectionType; /** * Gitea API client. * Developed and tested with Gitea TODO version */ public class GiteaServerAPIClient implements GiteaApi { private static final Logger LOGGER = Logger.getLogger(GiteaServerAPIClient.class.getName()); private static final String API_BASE_PATH = "/api/v1"; private static final String API_REPOSITORIES_PATH = API_BASE_PATH + "/users/%s/repos"; private static final String API_ORG_REPOSITORIES_PATH = API_BASE_PATH + "/orgs/%s/repos"; private static final String API_REPOSITORY_PATH = API_BASE_PATH + "/repos/%s/%s"; private static final String API_BRANCHES_PATH = API_BASE_PATH + "/repos/%s/%s/branches"; private static final String API_BRANCH_PATH = API_BASE_PATH + "/repos/%s/%s/branches/%s"; private static final String API_ORGANIZATION_PATH = API_BASE_PATH + "/orgs/%s"; private static final String API_USER_PATH = API_BASE_PATH + "/users/%s"; private static final String API_AUTHENTICATED_USER_PATH = API_BASE_PATH + "/user"; private static final String API_CONTENT_PATH = API_BASE_PATH + "/repos/%s/%s/raw/%s/%s"; private static final String API_ISSUES_PATH = API_BASE_PATH + "/repos/%s/%s/issues"; private static final String API_STATUS_CREATE_PATH = API_BASE_PATH + "/repos/%s/%s/statuses/%s"; private static final String API_REPO_HOOK_DELETE_PATH = "/repos/%s/%s/hooks/%d"; /** * Repository owner. * This must be null if organization is not null. */ private String owner; /** * Thre repository that this object is managing. */ private String repositoryName; /** * Indicates if the client is using user-centric API endpoints or project API otherwise. */ private boolean userCentric = false; /** * Credentials to access API services. * Almost @NonNull (but null is accepted for anonymous access). */ private UsernamePasswordCredentials credentials; private String baseURL; public GiteaServerAPIClient(String baseURL, String username, String password, String owner, String repositoryName) { if (!StringUtils.isBlank(username) && !StringUtils.isBlank(password)) { this.credentials = new UsernamePasswordCredentials(username, password); } this.owner = owner; this.repositoryName = repositoryName; this.baseURL = baseURL; } public GiteaServerAPIClient(String baseURL, String owner, String repositoryName, StandardUsernamePasswordCredentials creds) { if (creds != null) { this.credentials = new UsernamePasswordCredentials(creds.getUsername(), Secret.toString(creds.getPassword())); } this.owner = owner; this.repositoryName = repositoryName; this.baseURL = baseURL; } public GiteaServerAPIClient(String baseURL, String owner, StandardUsernamePasswordCredentials creds) { this(baseURL, owner, null, creds); } /** * Gitea manages two top level entities, owner and/or organization. * Only one of them makes sense for a specific client object. */ @Override public String getOwner() { return owner; } /** {@inheritDoc} */ @Override public String getRepositoryName() { return repositoryName; } /** {@inheritDoc} */ @Override public GiteaRepository getRepository() { if (repositoryName == null) { return null; } String response = getRequest(String.format(API_REPOSITORY_PATH, getOwner(), repositoryName)); try { return parse(response, GiteaServerRepository.class); } catch (IOException e) { LOGGER.log(Level.WARNING, "invalid repository response.", e); } return null; } /** {@inheritDoc} */ @Override public List getBranches() { String url = String.format(API_BRANCHES_PATH, getOwner(), repositoryName, 0); try { String response = getRequest(url); List branches = parseCollection(response, GiteaServerBranch.class); return branches; } catch (IOException e) { LOGGER.log(Level.SEVERE, "invalid branches response", e); } return Collections.EMPTY_LIST; } @Override public GiteaServerBranch getBranch(String name) { if (repositoryName == null) { return null; } String response = getRequest(String.format(API_BRANCH_PATH, getOwner(), repositoryName, name)); try { return parse(response, GiteaServerBranch.class); } catch (IOException e) { LOGGER.log(Level.WARNING, "invalid branch response.", e); } return null; } @Override public void registerCommitWebHook(GiteaWebHook hook) { try { postRequest(String.format(API_REPOSITORY_PATH, getOwner(), repositoryName) + "/hooks", asJson(hook)); } catch (IOException e) { LOGGER.log(Level.SEVERE, "cannot register webhook", e); } } @Override public void createIssue(GiteaIssue issue) { try { postRequest(String.format(API_ISSUES_PATH, getOwner(), repositoryName), serialize(issue)); } catch (IOException e) { LOGGER.log(Level.SEVERE, "cannot create issue", e); } } //TODO add interface to GiteaAPI public void createStatus(StatusOptions statusOptions, String sha) { try { postRequest(String.format(API_STATUS_CREATE_PATH, getOwner(), repositoryName, sha), serialize(statusOptions)); } catch (IOException e) { LOGGER.log(Level.SEVERE, "cannot create status", e); } } @Override public void removeCommitWebHook(GiteaWebHook hook) { deleteRequest(String.format(API_REPO_HOOK_DELETE_PATH, getOwner(), repositoryName, hook.getId())); } @Override public List getWebHooks() { try { String url = String.format(API_REPOSITORY_PATH, getOwner(), repositoryName) + "/hooks"; LOGGER.info("getWebHooks url: " + url); String response = getRequest(url); List repositoryHooks = parseCollection(response, GiteaHook.class); return repositoryHooks; } catch (IOException e) { LOGGER.log(Level.SEVERE, "invalid hooks response", e); } return Collections.EMPTY_LIST; } /** * Gitea Organization. */ @Override public GiteaOrganization getOrganization() { if (userCentric) { return null; } else { String response = getRequest(String.format(API_ORGANIZATION_PATH, getOwner())); try { return parse(response, GiteaServerOrganization.class); } catch (IOException e) { LOGGER.log(Level.WARNING, "invalid organization response.", e); } return null; } } @Override public void createOrgWebHook(GiteaWebHook hook) { try { postRequest(String.format(API_ORGANIZATION_PATH, getOwner()) + "/hooks", asJson(hook)); } catch (IOException e) { LOGGER.log(Level.SEVERE, "cannot register webhook", e); } } @Override public GiteaUser getUser(String username) { return null; } @Override public GiteaUser getAuthenticatedUser() { return null; } /** {@inheritDoc} */ @Override public List getRepositories() { String url = String.format(API_REPOSITORIES_PATH, getOwner()); try { String response = getRequest(url); List repos = parseCollection(response, GiteaServerRepository.class); return repos; } catch (IOException e) { LOGGER.log(Level.SEVERE, "invalid repositories response", e); } return Collections.EMPTY_LIST; } /** {@inheritDoc} */ @Override public List getOrgRepositories(GiteaOrganization organization) { String url = String.format(API_ORG_REPOSITORIES_PATH, organization.getName()); try { String response = getRequest(url); List repos = parseCollection(response, GiteaServerRepository.class); return repos; } catch (IOException e) { LOGGER.log(Level.SEVERE, "invalid repositories response", e); } return Collections.EMPTY_LIST; } /** {@inheritDoc} */ public GiteaUser getUser() { if (userCentric) { return null; } else { String response = getRequest(String.format(API_USER_PATH, getOwner())); try { return parse(response, GiteaServerRepositoryOwner.class); } catch (IOException e) { LOGGER.log(Level.WARNING, "invalid user response.", e); } return null; } } /** {@inheritDoc} */ @Override public boolean checkPathExists(String branch, String path) { String url = String.format(API_CONTENT_PATH, getOwner(), repositoryName, branch, path); LOGGER.info("checkPathExists url: " + url); int status = getRequestStatus(url); return status == HttpStatus.SC_OK; } @Override public boolean isPrivate() { GiteaRepository repo = getRepository(); return repo != null ? repo.isPrivate() : false; } private T parse(String response, Class clazz) throws IOException { ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(response, clazz); } private List parseCollection(String response, Class clazz) throws IOException { ObjectMapper mapper = new ObjectMapper(); final CollectionType javaType = mapper.getTypeFactory().constructCollectionType(List.class, clazz); return mapper.readValue(response, javaType); } private String getRequest(String path) { HttpClient client = getHttpClient(); client.getState().setCredentials(AuthScope.ANY, credentials); GetMethod httpget = new GetMethod(this.baseURL + path); client.getParams().setAuthenticationPreemptive(true); String response = null; InputStream responseBodyAsStream = null; try { client.executeMethod(httpget); responseBodyAsStream = httpget.getResponseBodyAsStream(); response = IOUtils.toString(responseBodyAsStream, "UTF-8"); if (httpget.getStatusCode() != HttpStatus.SC_OK) { throw new GiteaRequestException(httpget.getStatusCode(), "HTTP request error. GiteaStatusOptions: " + httpget.getStatusCode() + ": " + httpget.getStatusText() + ".\n" + response); } } catch (HttpException e) { throw new GiteaRequestException(0, "Communication error: " + e, e); } catch (IOException e) { throw new GiteaRequestException(0, "Communication error: " + e, e); } finally { httpget.releaseConnection(); if (responseBodyAsStream != null) { IOUtils.closeQuietly(responseBodyAsStream); } } if (response == null) { throw new GiteaRequestException(0, "HTTP request error " + httpget.getStatusCode() + ":" + httpget.getStatusText()); } return response; } private HttpClient getHttpClient() { HttpClient client = new HttpClient(); client.getParams().setConnectionManagerTimeout(10 * 1000); client.getParams().setSoTimeout(60 * 1000); Jenkins jenkins = Jenkins.getInstance(); ProxyConfiguration proxy = null; if (jenkins != null) { proxy = jenkins.proxy; } if (proxy != null) { LOGGER.info("Jenkins proxy: " + proxy.name + ":" + proxy.port); client.getHostConfiguration().setProxy(proxy.name, proxy.port); String username = proxy.getUserName(); String password = proxy.(); if (username != null && !"".equals(username.trim())) { LOGGER.info("Using proxy authentication (user=" + username + ")"); client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); } } return client; } private int getRequestStatus(String path) { HttpClient client = getHttpClient(); client.getState().setCredentials(AuthScope.ANY, credentials); GetMethod httpget = new GetMethod(this.baseURL + path); client.getParams().setAuthenticationPreemptive(true); try { client.executeMethod(httpget); return httpget.getStatusCode(); } catch (HttpException e) { LOGGER.log(Level.SEVERE, "Communication error", e); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Communication error", e); } finally { httpget.releaseConnection(); } return -1; } private String serialize(T o) throws IOException { ObjectMapper mapper = new ObjectMapper(); String valueAsString = mapper.writeValueAsString(o); LOGGER.info("serialized value: " + valueAsString); return valueAsString; } private String postRequest(String path, NameValuePair[] params) throws UnsupportedEncodingException { PostMethod httppost = new PostMethod(this.baseURL + path); httppost.setRequestEntity(new StringRequestEntity(nameValueToJson(params), "application/json", "UTF-8")); return postRequest(httppost); } private String postRequest(String path, String content) throws UnsupportedEncodingException { PostMethod httppost = new PostMethod(this.baseURL + path); httppost.setRequestEntity(new StringRequestEntity(content, "application/json", "UTF-8")); return postRequest(httppost); } private String nameValueToJson(NameValuePair[] params) { JSONObject o = new JSONObject(); for (NameValuePair pair : params) { o.put(pair.getName(), pair.getValue()); } return o.toString(); } private String postRequest(PostMethod httppost) throws UnsupportedEncodingException { HttpClient client = getHttpClient(); client.getState().setCredentials(AuthScope.ANY, credentials); client.getParams().setAuthenticationPreemptive(true); String response = null; InputStream responseBodyAsStream = null; try { client.executeMethod(httppost); if (httppost.getStatusCode() == HttpStatus.SC_NO_CONTENT) { // 204, no content return ""; } responseBodyAsStream = httppost.getResponseBodyAsStream(); if (responseBodyAsStream != null) { response = IOUtils.toString(responseBodyAsStream, "UTF-8"); } if (httppost.getStatusCode() != HttpStatus.SC_OK && httppost.getStatusCode() != HttpStatus.SC_CREATED) { throw new GiteaRequestException(httppost.getStatusCode(), "HTTP request error. GiteaStatusOptions: " + httppost.getStatusCode() + ": " + httppost.getStatusText() + ".\n" + response); } } catch (HttpException e) { throw new GiteaRequestException(0, "Communication error: " + e, e); } catch (IOException e) { throw new GiteaRequestException(0, "Communication error: " + e, e); } finally { httppost.releaseConnection(); if (responseBodyAsStream != null) { IOUtils.closeQuietly(responseBodyAsStream); } } if (response == null) { throw new GiteaRequestException(0, "HTTP request error"); } return response; } private String asJson(GiteaWebHook hook) throws JsonGenerationException, JsonMappingException, IOException { ObjectMapper mapper = new ObjectMapper(); return mapper.writeValueAsString(hook); } private String deleteRequest(String path) { HttpClient client = getHttpClient(); client.getState().setCredentials(AuthScope.ANY, credentials); DeleteMethod httpDelete = new DeleteMethod(this.baseURL + path); client.getParams().setAuthenticationPreemptive(true); String response = null; try { client.executeMethod(httpDelete); if (httpDelete.getStatusCode() != HttpStatus.SC_NO_CONTENT) { throw new GiteaRequestException(httpDelete.getStatusCode(), "HTTP request error. GiteaStatusOptions: " + httpDelete.getStatusCode() + ": " + httpDelete.getStatusText() + ".\n" + response); } } catch (HttpException e) { throw new GiteaRequestException(0, "Communication error: " + e, e); } catch (IOException e) { throw new GiteaRequestException(0, "Communication error: " + e, e); } finally { httpDelete.releaseConnection(); } if (response == null) { throw new GiteaRequestException(0, "HTTP request error " + httpDelete.getStatusCode() + ":" + httpDelete.getStatusText()); } return response; } } psakar/Resteasy0 package org.jboss.resteasy.skeleton.key.representations.idm; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * @author * @version $Revision: 1 $ */ public class ResourceRepresentation { protected String self; // link protected String name; protected boolean surrogateAuthRequired; protected Set roles; protected List roleMappings; protected List scopeMappings; public String getSelf() { return self; } public void setSelf(String self) { this.self = self; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isSurrogateAuthRequired() { return surrogateAuthRequired; } public void setSurrogateAuthRequired(boolean surrogateAuthRequired) { this.surrogateAuthRequired = surrogateAuthRequired; } public Set getRoles() { return roles; } public void setRoles(Set roles) { this.roles = roles; } public ResourceRepresentation role(String role) { if (this.roles == null) this.roles = new HashSet(); this.roles.add(role); return this; } public List getRoleMappings() { return roleMappings; } public RoleMappingRepresentation roleMapping(String username) { RoleMappingRepresentation mapping = new RoleMappingRepresentation(); mapping.setUsername(username); if (roleMappings == null) roleMappings = new ArrayList(); roleMappings.add(mapping); return mapping; } public List getScopeMappings() { return scopeMappings; } public ScopeMappingRepresentation scopeMapping(String username) { ScopeMappingRepresentation mapping = new ScopeMappingRepresentation(); mapping.setUsername(username); if (scopeMappings == null) scopeMappings = new ArrayList(); scopeMappings.add(mapping); return mapping; } } networknt/light-controller package com.networknt.controller; public final class ControllerConstants { public static int NONCE = 1; public static String HOST = "lightapi.net"; public static String CHECK = "check"; public static int CHECK_FREQUENCY = 10; // check the health every 10 seconds by default. /* Common Query Parameter Names */ public static final String PORT = "port"; public static final String PROTOCOL = "protocol"; public static final String ADDRESS = "address"; public static final String SERVICE_ID = "serviceId"; public static final String TAG = "tag"; /* Client Controller Path Strings */ public static final String SERVER_INFO_ENDPOINT = "/server/info"; public static final String LOGGER_ENDPOINT = "/logger"; public static final String LOGGER_CONTENT_ENDPOINT = "/logger/content"; public static final String CHAOS_MONKEY_ASSAULT_ENDPOINT = "/chaosmonkey/{assaultType}"; public static final String CHAOS_MONKEY_ENDPOINT = "/chaosmonkey"; } 0 package org.chemcalc.core; /** * An Exception cast if the molecular formula is not valid or if a certain * function cannot be used with the given molecular formula. * MFException is cast if: *
  • there is a syntax error in the formula *
  • a method that is designed for non-range formulae is called for a range * formula (except Atoms.getCount() - in this case a * RuntimeException is cast, because applications that allow range * formulae should never call this function).

* Generally, this exception is for reporting errors in user's input. *

MFException should not be cast if:

    *
  • a method is called with nonsense arguments, but the user's input was valid *
  • there is an SQL error *
  • any other errors not resulting from user's syntax errors
* * @author * @version 05 Jul 2002 */ public class MFException extends Exception { /** * Creates a new MFException with an error message. * * @param message error message */ public MFException(String message) { super(message); } }package com.wb.tool; import com.wb.util.StringUtil; import java.security.MessageDigest; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; public class Encrypter { private static final String des = "DES"; private static final String keyMap = "C2E8D9A3B5F14607"; public static String encrypt(String text, String key) throws Exception { return StringUtil.encodeBase64(encrypt(text.getBytes("utf-8"), key)); } public static String decrypt(String text, String key) throws Exception { return new String(decrypt(StringUtil.decodeBase64(text), key), "utf-8"); } public static byte[] encrypt(byte[] bytes, String key) throws Exception { byte[] keyBytes = key.getBytes("utf-8"); SecureRandom sr = new SecureRandom(); DESKeySpec dks = new DESKeySpec(keyBytes); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey securekey = keyFactory.generateSecret(dks); Cipher cipher = Cipher.getInstance("DES"); cipher.init(1, securekey, sr); return cipher.doFinal(bytes); } public static byte[] decrypt(byte[] bytes, String key) throws Exception { byte[] keyBytes = key.getBytes("utf-8"); SecureRandom sr = new SecureRandom(); DESKeySpec dks = new DESKeySpec(keyBytes); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey securekey = keyFactory.generateSecret(dks); Cipher cipher = Cipher.getInstance("DES"); cipher.init(2, securekey, sr); return cipher.doFinal(bytes); } public static String getMD5(String text) throws Exception { return getMD5(text.getBytes("utf-8")); } public static String getMD5(byte[] bytes) throws Exception { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(bytes); byte[] codes = md.digest(); char[] str = new char[32]; int j = 0; for (int i = 0; i < 16; ++i) { byte bt = codes[i]; str[j++] = "C2E8D9A3B5F14607".charAt(bt >>> 4 & 15); str[j++] = "C2E8D9A3B5F14607".charAt(bt & 15); } return new String(str); } }/** * 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.streamnative.pulsar.handlers.rocketmq.inner.producer; import io.netty.channel.Channel; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import lombok.extern.slf4j.Slf4j; import org.apache.rocketmq.broker.client.ClientChannelInfo; import org.apache.rocketmq.broker.util.PositiveAtomicCounter; import org.apache.rocketmq.remoting.common.RemotingHelper; import org.apache.rocketmq.remoting.common.RemotingUtil; /** * Producer Manager is responsible for processing producer-related operations. */ @Slf4j public class ProducerManager { private static final long CHANNEL_EXPIRED_TIMEOUT = 1000 * 120; private static final int GET_AVAILABLE_CHANNEL_RETRY_COUNT = 3; // groupName = [tenant/ns/groupName] private final ConcurrentHashMap> groupChannelTable = new ConcurrentHashMap<>(); private final ConcurrentHashMap clientIdChannelTable = new ConcurrentHashMap<>(); private final PositiveAtomicCounter positiveAtomicCounter = new PositiveAtomicCounter(); public ProducerManager() { } public ConcurrentHashMap> getGroupChannelTable() { return groupChannelTable; } public void scanNotActiveChannel() { for (final Entry> entry : this.groupChannelTable.entrySet()) { final String group = entry.getKey().getPulsarGroupName(); final ConcurrentHashMap chlMap = entry.getValue(); Iterator> it = chlMap.entrySet().iterator(); while (it.hasNext()) { Entry item = it.next(); // final Integer id = item.getKey(); final ClientChannelInfo info = item.getValue(); long diff = System.currentTimeMillis() - info.getLastUpdateTimestamp(); if (diff > CHANNEL_EXPIRED_TIMEOUT) { it.remove(); clientIdChannelTable.remove(info.getClientId()); log.warn( "SCAN: remove expired channel[{}] from ProducerManager groupChannelTable, " + "producer group name: {}", RemotingHelper.parseChannelRemoteAddr(info.getChannel()), group); RemotingUtil.closeChannel(info.getChannel()); } } } } public synchronized void doChannelCloseEvent(final String remoteAddr, final Channel channel) { if (channel != null) { for (final Entry> entry : this.groupChannelTable.entrySet()) { final String group = entry.getKey().getPulsarGroupName(); final ConcurrentHashMap clientChannelInfoTable = entry.getValue(); final ClientChannelInfo clientChannelInfo = clientChannelInfoTable.remove(channel); if (clientChannelInfo != null) { clientIdChannelTable.remove(clientChannelInfo.getClientId()); log.info( "NETTY EVENT: remove channel[{}][{}] from ProducerManager groupChannelTable, " + "producer group: {}", clientChannelInfo.toString(), remoteAddr, group); } } } } public synchronized void registerProducer(final String group, final ClientChannelInfo clientChannelInfo) { ClientChannelInfo clientChannelInfoFound; ClientGroupName clientGroupName = new ClientGroupName(group); ConcurrentHashMap channelTable = this.groupChannelTable.get(clientGroupName); if (null == channelTable) { channelTable = new ConcurrentHashMap<>(); this.groupChannelTable.put(clientGroupName, channelTable); } clientChannelInfoFound = channelTable.get(clientChannelInfo.getChannel()); if (null == clientChannelInfoFound) { channelTable.put(clientChannelInfo.getChannel(), clientChannelInfo); clientIdChannelTable.put(clientChannelInfo.getClientId(), clientChannelInfo.getChannel()); log.info("new producer connected, group: {} channel: {}", clientGroupName, clientChannelInfo.toString()); } if (clientChannelInfoFound != null) { clientChannelInfoFound.setLastUpdateTimestamp(System.currentTimeMillis()); } } public synchronized void unregisterProducer(final String group, final ClientChannelInfo clientChannelInfo) { ClientGroupName clientGroupName = new ClientGroupName(group); ConcurrentHashMap channelTable = this.groupChannelTable.get(clientGroupName); if (null != channelTable && !channelTable.isEmpty()) { ClientChannelInfo old = channelTable.remove(clientChannelInfo.getChannel()); clientIdChannelTable.remove(clientChannelInfo.getClientId()); if (old != null) { log.info("unregister a producer[{}] from groupChannelTable {}", clientGroupName, clientChannelInfo.toString()); } if (channelTable.isEmpty()) { this.groupChannelTable.remove(clientGroupName); log.info("unregister a producer group[{}] from groupChannelTable", clientGroupName); } } } public Channel getAvailableChannel(String groupName) { if (groupName == null) { return null; } ClientGroupName clientGroupName = new ClientGroupName(groupName); List channelList; ConcurrentHashMap channelClientChannelInfoHashMap = groupChannelTable .get(clientGroupName); if (channelClientChannelInfoHashMap != null) { channelList = new ArrayList<>(channelClientChannelInfoHashMap.keySet()); } else { log.warn("Check transaction failed, channel table is empty. groupId={}", clientGroupName); return null; } int size = channelList.size(); if (0 == size) { log.warn("Channel list is empty. groupId={}", clientGroupName); return null; } Channel lastActiveChannel = null; int index = positiveAtomicCounter.incrementAndGet() % size; Channel channel = channelList.get(index); int count = 0; boolean isOk = channel.isActive() && channel.isWritable(); while (count++ < GET_AVAILABLE_CHANNEL_RETRY_COUNT) { if (isOk) { return channel; } if (channel.isActive()) { lastActiveChannel = channel; } index = (++index) % size; channel = channelList.get(index); isOk = channel.isActive() && channel.isWritable(); } return lastActiveChannel; } public Channel findChannel(String clientId) { return clientIdChannelTable.get(clientId); } public ClientChannelInfo findChlInfo(String groupName, Channel channel) { ClientGroupName clientGroupName = new ClientGroupName(groupName); if (groupChannelTable.containsKey(clientGroupName)) { return groupChannelTable.get(clientGroupName).get(channel); } else { for (Map m : groupChannelTable.values()) { if (m.containsKey(channel)) { return m.get(channel); } } } return null; } } package org.frekele.fiscal.focus.nfe.client.repository.ncm; import org.frekele.fiscal.focus.nfe.client.auth.EnvironmentFocusNFeEnum; import org.frekele.fiscal.focus.nfe.client.auth.FocusNFeAuth; import org.frekele.fiscal.focus.nfe.client.model.request.ncm.param.NcmQueryParam; import org.frekele.fiscal.focus.nfe.client.model.response.ncm.NcmConsultarResponse; import org.frekele.fiscal.focus.nfe.client.model.response.ncm.NcmConsultarTodosResponse; import org.frekele.fiscal.focus.nfe.client.model.response.ncm.body.NcmBodyResponse; import org.frekele.fiscal.focus.nfe.client.model.response.ncm.body.NcmsBodyResponse; import org.frekele.fiscal.focus.nfe.client.testng.FocusTestNGUtils; import org.frekele.fiscal.focus.nfe.client.testng.InvokedMethodListener; import org.jboss.resteasy.client.jaxrs.ResteasyClient; import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.mockito.MockitoAnnotations; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.Listeners; import org.testng.annotations.Test; /** * O código NCM é formato por 8 dígitos no seguinte formato: *

* CCPPSÇII, sendo: *

    *
  • CC = Capitulo; *
  • PP = Posição; *
  • S = Subposição 1; *
  • Ç = Subposição 2; *
  • II = Item 1 e 2; *
* * @author frekele - */ @Listeners(InvokedMethodListener.class) public class FocusNcmV2RepositoryIT { private FocusNcmV2Repository repository; @BeforeClass public void init() throws Exception { MockitoAnnotations.initMocks(this); String accessToken = System.getenv("FOCUS_NFE_ACCESS_TOKEN"); EnvironmentFocusNFeEnum environment = EnvironmentFocusNFeEnum.HOMOLOGATION; FocusNFeAuth auth = FocusNFeAuth.newBuilder() .withAccessToken(accessToken) .withEnvironment(environment) .build(); ResteasyClient client = new ResteasyClientBuilder().build(); repository = new FocusNcmV2RepositoryImpl(client, auth); } @AfterMethod public void afterMethod() throws Exception { //After Method Sleep 3 seg, for prevent Error. FocusTestNGUtils.sleep(3); } @Test public void testConsultar() throws Exception { NcmConsultarResponse response = repository.consultar("94036000"); System.out.println("RateLimitLimit: " + response.getRateLimitLimit()); System.out.println("RateLimitRemaining: " + response.getRateLimitRemaining()); System.out.println("RateLimitReset: " + response.getRateLimitReset()); System.out.println("Status: " + response.getStatus()); NcmBodyResponse bodyResponse = response.getBody(); System.out.println("Body.Ncm.DescricaoCompleta: " + bodyResponse.getNcm().getDescricaoCompleta()); } @Test public void testConsultarTodos() throws Exception { NcmQueryParam queryParam = NcmQueryParam.newBuilder().build(); NcmConsultarTodosResponse response = repository.consultarTodos(queryParam); this.printNcmConsultarTodosResponse(response); } @Test public void testConsultarTodos2() throws Exception { NcmQueryParam queryParam = NcmQueryParam.newBuilder() .withCapitulo("94") .build(); NcmConsultarTodosResponse response = repository.consultarTodos(queryParam); this.printNcmConsultarTodosResponse(response); } @Test public void testConsultarTodos3() throws Exception { NcmQueryParam queryParam = NcmQueryParam.newBuilder() .withCapitulo("94") .withPosicao("03") .build(); NcmConsultarTodosResponse response = repository.consultarTodos(queryParam); this.printNcmConsultarTodosResponse(response); } @Test public void testConsultarTodos4() throws Exception { NcmQueryParam queryParam = NcmQueryParam.newBuilder() .withCapitulo("94") .withPosicao("03") .withSubposicao1("6") .build(); NcmConsultarTodosResponse response = repository.consultarTodos(queryParam); this.printNcmConsultarTodosResponse(response); } @Test public void testConsultarTodos5() throws Exception { NcmQueryParam queryParam = NcmQueryParam.newBuilder() .withCapitulo("94") .withPosicao("03") .withSubposicao1("6") .withSubposicao2("0") .build(); NcmConsultarTodosResponse response = repository.consultarTodos(queryParam); this.printNcmConsultarTodosResponse(response); } @Test public void testConsultarTodos6() throws Exception { NcmQueryParam queryParam = NcmQueryParam.newBuilder() .withCapitulo("94") .withPosicao("03") .withSubposicao1("6") .withSubposicao2("0") .withItem1("0") .build(); NcmConsultarTodosResponse response = repository.consultarTodos(queryParam); this.printNcmConsultarTodosResponse(response); } @Test public void testConsultarTodos7() throws Exception { NcmQueryParam queryParam = NcmQueryParam.newBuilder() .withCapitulo("94") .withPosicao("03") .withSubposicao1("6") .withSubposicao2("0") .withItem1("0") .withItem2("0") .build(); NcmConsultarTodosResponse response = repository.consultarTodos(queryParam); this.printNcmConsultarTodosResponse(response); } @Test public void testConsultarTodosOffset() throws Exception { NcmQueryParam queryParam = NcmQueryParam.newBuilder() .withCodigo("9") .withOffset("20") .build(); NcmConsultarTodosResponse response = repository.consultarTodos(queryParam); this.printNcmConsultarTodosResponse(response); } private void printNcmConsultarTodosResponse(NcmConsultarTodosResponse response) { System.out.println("RateLimitLimit: " + response.getRateLimitLimit()); System.out.println("RateLimitRemaining: " + response.getRateLimitRemaining()); System.out.println("RateLimitReset: " + response.getRateLimitReset()); System.out.println("TotalCount: " + response.getTotalCount()); System.out.println("Status: " + response.getStatus()); NcmsBodyResponse bodyResponse = response.getBody(); System.out.println("Body.Ncms.Size: " + bodyResponse.getNcms().size()); } } Sougata1233/MasterModule0 package com.example.master.component; import java.util.List; import javax.sql.DataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.example.master.entity.HolidayMaster; import com.example.master.repository.HolidayMasterRepository; @Component public class HolidayMasterDao { private static final Logger LOGGER = LoggerFactory.getLogger(HolidayMasterDao.class); @Autowired DataSource dataSource; @Autowired HolidayMasterRepository holidaymasterRepository; @Transactional(readOnly = true) public List findAll() throws Exception { LOGGER.info("DATASOURCE = " + dataSource); return holidaymasterRepository.findAll(); } @Transactional(readOnly = true) public HolidayMaster findHolidayMasterById(Long id) { return holidaymasterRepository.findOne(id); } @Transactional(propagation = Propagation.REQUIRED) public void addHolidayMaster(HolidayMaster holidaymaster) { holidaymasterRepository.save(holidaymaster); LOGGER.info("HolidayMaster added successfully " + holidaymaster.toString()); } @Transactional(propagation = Propagation.REQUIRED) public void deleteHolidayMaster(Long Id) { holidaymasterRepository.delete(Id); LOGGER.info("HolidayMaster with id " + Id + " deleted successfully "); } @Transactional(propagation = Propagation.REQUIRED) public void updateHolidayMaster(HolidayMaster holidaymaster) { holidaymasterRepository.save(holidaymaster); LOGGER.info("HolidayMaster added successfully " + holidaymaster.toString()); } } package alien4cloud.rest.application; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter @NoArgsConstructor @AllArgsConstructor @SuppressWarnings("PMD.UnusedPrivateField") public class CreateTopologyRequest { private String topologyId; } 0 package com.imbus.bank.componet.Entity; import lombok.Data; import java.math.BigDecimal; /** * Created by zhong on 2020-8-25. */ @Data public class TransferEntity { private String account; private String pwd; private BigDecimal amount; private String targetAccount; } wjw/src/main/java/com/wjw/controller/CountryTrainController.java package com.wjw.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.github.pagehelper.PageInfo; import com.ncme.springboot.footstone.constant.BusinessConst; import com.ncme.springboot.footstone.controller.Controller; import com.ncme.springboot.footstone.response.Record; import com.ncme.springboot.footstone.response.RtnBody; import com.ncme.springboot.footstone.util.StrKit; import com.ncme.springboot.model.CvSet; import com.ncme.springboot.model.SystemUser; import com.ncme.springboot.model.SystemUserConfig; import com.wjw.service.CvSetService; import com.wjw.service.SystemUserService; import com.wjw.util.SystemUserUtil; /** * ClassName:CountryTrainController * Function: 乡医培训Controller * Reason: TODO ADD REASON * * @author lxy * @version * @since version 1.0 * @Date 2017年11月1日 下午2:05:30 * * @see * */ @RestController @RequestMapping("/country") public class CountryTrainController extends Controller { @Autowired private CvSetService cvSetService; @Autowired SystemUserService systemUserService; /** * getCounTrainList:(查询乡医培训列表) * * @param @param userId * @param @return * @return RtnBody * @throws * @since  version 1.0 */ @RequestMapping(value="/getCounTrainList") public RtnBody getCounTrainList(String userId, String pageNum){ SystemUser user = SystemUserUtil.getLoginUser(request); SystemUserConfig userConfig = null; if (user != null) { userConfig = systemUserService.getConfigByUserId(user.getId()); } RtnBody rtn = new RtnBody(); //查询 page分页 //String pageNum = getPara("pageNum"); // 当前页 if (StrKit.isBlank(pageNum)) { return rtn.code(BusinessConst.CODE_PARAM_EMPTY).message("页数不能为空!"); } String pageSize = getPara("pageSize", "20"); // 每页条数 if (StrKit.isBlank(pageSize)) { return rtn.code(BusinessConst.CODE_PARAM_EMPTY).message("每页面条数未指定!"); } //1)未登录状态时,默认显示培训后台发布的授权到全国的乡医类型项目,按照发布时间倒叙排序; //2)已登录后,将根据用户注册所在地自动筛选更新,显示培训后台发布的授权到对应省份和全国的乡医类型项目,按照发布时间倒叙排序; CvSet cvSet = new CvSet(); cvSet.setStatus(5);//已发布 //cvSet.setCvSetType(1);//项目类型为乡医培训 cvSet.setSign("乡医培训");//改过授权后,乡医培训项目在授权信息表中 2017-12-29 String domainName = request.getServerName(); //取到 域名地址 PageInfo page = new PageInfo(); if (user != null && userConfig != null) { page = cvSetService.getCVSetPageListByNameAndProvice(cvSet, userConfig.getUserProvinceId(), pageNum, pageSize, domainName); } else { page = cvSetService.getCVSetPageListByNameAndProvice(cvSet, null, pageNum, pageSize, domainName); } rtn.code(BusinessConst.CODE_RESPONSE_SUCCESS).message("恭喜你,获取成功!").data(page);//{"code":200,"page":{....}} --可用,主要使用自定义数据体前缀,例如 :page return rtn; } } // // Decompiled by Procyon v0.5.36 // package org.netbeans.lib.cvsclient.command; import org.netbeans.lib.cvsclient.connection.AuthenticationException; import org.netbeans.lib.cvsclient.request.RootRequest; import org.netbeans.lib.cvsclient.event.EventManager; import org.netbeans.lib.cvsclient.request.ArgumentRequest; import org.netbeans.lib.cvsclient.request.StickyRequest; import org.netbeans.lib.cvsclient.request.DirectoryRequest; import java.util.Iterator; import org.netbeans.lib.cvsclient.request.QuestionableRequest; import java.util.Collection; import java.util.Arrays; import java.util.ArrayList; import java.util.Date; import org.netbeans.lib.cvsclient.request.ModifiedRequest; import org.netbeans.lib.cvsclient.request.UnchangedRequest; import org.netbeans.lib.cvsclient.admin.DateComparator; import org.netbeans.lib.cvsclient.request.Request; import org.netbeans.lib.cvsclient.request.EntryRequest; import org.netbeans.lib.cvsclient.admin.Entry; import java.io.IOException; import java.io.FileNotFoundException; import java.util.LinkedList; import java.io.File; import org.netbeans.lib.cvsclient.ClientServices; import java.util.List; public abstract class BasicCommand extends BuildableCommand { protected List requests; protected ClientServices clientServices; private boolean recursive; protected File[] files; public BasicCommand() { this.requests = new LinkedList(); this.recursive = true; } public boolean getRecursive() { return this.recursive; } public boolean isRecursive() { return this.recursive; } public void setRecursive(final boolean recursive) { this.recursive = recursive; } public void setFiles(final File[] files) { if (files == null) { this.files = files; return; } this.files = new File[files.length]; int n = 0; int n2 = 0; for (final File file : files) { if (file.isDirectory()) { final int length; this.files[length - (1 + n2)] = file; ++n2; } else { this.files[n] = file; ++n; } } } public File[] getFiles() { return this.files; } public File getXthFile(final int n) { if (n < 0 || n >= this.files.length) { return null; } final File file = this.files[n]; if (!file.isFile()) { return null; } return file; } public File getFileEndingWith(final String s) { final String replace = s.replace('\\', '/'); final String replace2 = this.getLocalDirectory().replace('\\', '/'); for (int i = 0; i < this.files.length; ++i) { final String absolutePath = this.files[i].getAbsolutePath(); final String replace3 = this.files[i].getParentFile().getAbsolutePath().replace('\\', '/'); if ((absolutePath.replace('\\', '/').endsWith(replace) && replace.indexOf(47) >= 0) || (this.files[i].getName().equals(replace) && replace3.equals(replace2))) { return this.files[i]; } } return null; } private void addRequests(final File file) throws FileNotFoundException, IOException, CommandAbortedException { if (file == null) { throw new IllegalArgumentException("Cannot add requests for a null path."); } if (!file.exists() || file.isFile()) { this.addRequestsForFile(file); } else { this.addRequestsForDirectory(file); } } protected boolean doesCheckFileTime() { return true; } protected void sendEntryAndModifiedRequests(Entry entry, final File file) { if (entry == null) { return; } if (file != null && !file.exists() && entry.isNewUserFile()) { return; } final Date lastModified = entry.getLastModified(); final boolean hadConflicts = entry.hadConflicts(); if (!hadConflicts) { entry.setConflict(null); } else if (this.fileRequiresConflictResolution(file, entry)) { final Entry entry2 = new Entry(entry.toString()); entry2.setConflict("+="); entry = entry2; } this.addRequest(new EntryRequest(entry)); if (file == null || !file.exists() || entry.isUserFileToBeRemoved()) { return; } if (this.doesCheckFileTime() && !hadConflicts && lastModified != null && DateComparator.getInstance().equals(file.lastModified(), lastModified.getTime())) { this.addRequest(new UnchangedRequest(file.getName())); return; } this.addRequest(new ModifiedRequest(file, entry.isBinary())); } private final boolean fileRequiresConflictResolution(final File file, final Entry entry) { if (file == null) { return false; } boolean b = false; if (entry.hadConflicts()) { b = (file.lastModified() / 1000L <= entry.getLastModified().getTime() / 1000L); } return b; } protected void addRequestsForDirectory(final File file) throws IOException, CommandAbortedException { if (!this.clientServices.exists(file)) { return; } if (this.clientServices.isAborted()) { throw new CommandAbortedException("Command aborted during request generation", "Command aborted during request generation"); } this.addDirectoryRequest(file); final File[] listFiles = file.listFiles(); ArrayList list; if (listFiles == null) { list = new ArrayList(0); } else { list = new ArrayList(Arrays.asList(listFiles)); list.remove(new File(file, "CVS")); } List list2 = null; if (this.isRecursive()) { list2 = new LinkedList(); } final Iterator entries = this.clientServices.getEntries(file); while (entries.hasNext()) { final Entry entry = entries.next(); final File file2 = new File(file, entry.getName()); if (entry.isDirectory()) { if (this.isRecursive()) { list2.add(new File(file, entry.getName())); } } else { this.addRequestForFile(file2, entry); } list.remove(file2); } if (this.isRecursive() && !new File(file, "CVS").exists()) { final File[] listFiles2 = file.listFiles(); if (listFiles2 != null) { for (int i = 0; i < listFiles2.length; ++i) { if (listFiles2[i].isDirectory() && new File(listFiles2[i], "CVS").exists()) { list2.add(listFiles2[i]); } } } } final Iterator iterator = list.iterator(); while (iterator.hasNext()) { final String name = iterator.next().getName(); if (!this.clientServices.shouldBeIgnored(file, name)) { this.addRequest(new QuestionableRequest(name)); } } if (this.isRecursive()) { for (final File parent : list2) { if (this.clientServices.exists(new File(parent, "CVS"))) { this.addRequestsForDirectory(parent); } } } } protected void addRequestForFile(final File file, final Entry entry) { this.sendEntryAndModifiedRequests(entry, file); } protected void addRequestsForFile(final File obj) throws IOException { this.addDirectoryRequest(obj.getParentFile()); try { final Entry entry = this.clientServices.getEntry(obj); if (entry != null) { this.addRequestForFile(obj, entry); } else if (obj.exists()) { this.addRequest(new ModifiedRequest(obj, false)); } } catch (IOException obj2) { System.err.println("An error occurred getting the Entry for file " + obj + ": " + obj2); obj2.printStackTrace(); } } protected final void addDirectoryRequest(final File file) { final String relativeToLocalPathInUnixStyle = this.getRelativeToLocalPathInUnixStyle(file); try { this.addRequest(new DirectoryRequest(relativeToLocalPathInUnixStyle, this.clientServices.getRepositoryForDirectory(file.getAbsolutePath()))); final String stickyTagForDirectory = this.clientServices.getStickyTagForDirectory(file); if (stickyTagForDirectory != null) { this.addRequest(new StickyRequest(stickyTagForDirectory)); } } catch (FileNotFoundException ex) {} catch (IOException obj) { System.err.println("An error occurred reading the respository for the directory " + relativeToLocalPathInUnixStyle + ": " + obj); obj.printStackTrace(); } } protected void addArgumentRequests() { if (this.files == null) { return; } for (int i = 0; i < this.files.length; ++i) { this.addRequest(new ArgumentRequest(this.getRelativeToLocalPathInUnixStyle(this.files[i]))); } } public void execute(final ClientServices clientServices, final EventManager eventManager) throws CommandException, AuthenticationException { this.requests.clear(); super.execute(this.clientServices = clientServices, eventManager); if (clientServices.isFirstCommand()) { this.addRequest(new RootRequest(clientServices.getRepository())); } this.addFileRequests(); } private void addFileRequests() throws CommandException { try { if (this.files != null && this.files.length > 0) { for (int i = 0; i < this.files.length; ++i) { this.addRequests(this.files[i]); } } else if (this.assumeLocalPathWhenUnspecified()) { this.addRequests(new File(this.getLocalDirectory())); } } catch (Exception ex) { throw new CommandException(ex, ex.getLocalizedMessage()); } } protected boolean assumeLocalPathWhenUnspecified() { return true; } protected final void addRequest(final Request request) { this.requests.add(request); } protected final void addRequestForWorkingDirectory(final ClientServices clientServices) throws IOException { this.addRequest(new DirectoryRequest(".", clientServices.getRepositoryForDirectory(this.getLocalDirectory()))); } protected final void addArgumentRequest(final boolean b, final String s) { if (!b) { return; } this.addRequest(new ArgumentRequest(s)); } protected final void appendFileArguments(final StringBuffer sb) { final File[] files = this.getFiles(); if (files == null) { return; } for (int i = 0; i < files.length; ++i) { if (i > 0) { sb.append(' '); } sb.append(files[i].getName()); } } } package org.koenighotze.jee7hotel.booking.business.json; import org.koenighotze.jee7hotel.booking.business.events.BookingMessageTO; import javax.json.Json; import javax.json.JsonObject; import javax.json.JsonReader; import javax.ws.rs.Consumes; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.Provider; import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.time.LocalDate; import java.time.format.DateTimeFormatter; /** * @author koenighotze */ @Provider @Consumes(MediaType.APPLICATION_JSON) public class BookingMessageTOReader implements MessageBodyReader { @Override public boolean isReadable(Class aClass, Type type, Annotation[] annotations, MediaType mediaType) { return BookingMessageTO.class.isAssignableFrom(aClass); } @Override public BookingMessageTO readFrom(Class aClass, Type type, Annotation[] annotations, MediaType mediaType, MultivaluedMap multivaluedMap, InputStream inputStream) throws IOException, WebApplicationException { JsonReader reader = Json.createReader(inputStream); JsonObject jsonObject = reader.readObject(); Long guestId = jsonObject.getJsonNumber("guestId").longValue(); String roomNumber = jsonObject.getString("roomNumber"); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); LocalDate checkin = LocalDate.parse(jsonObject.getString("checkin"), formatter); LocalDate checkout = LocalDate.parse(jsonObject.getString("checkout"), formatter); return new BookingMessageTO(guestId, roomNumber, checkin, checkout); } } package com.creadigol.inshort.Utils; /** * Created by ravi on 26-10-2016. */ import android.content.Context; import android.content.SharedPreferences; public class PreferenceSettings { private String NEWSAPP = "NewsApp"; private static final String KEY_NOTIFICATION_LAST_TIME = "last_sync_time"; private String IsFirst = "true"; private String Bookmark = "false"; private String IsNeeded = "false"; private static final String CURRENT_DATE = ""; private static final String PREVIES_DATE = ""; Context _context; private SharedPreferences sp; private SharedPreferences.Editor editor; public PreferenceSettings(Context context) { this._context = context; sp = _context.getSharedPreferences(NEWSAPP, context.MODE_PRIVATE); editor = sp.edit(); } public void setCurrentDate(String currentDate) { editor.putString(CURRENT_DATE, currentDate).commit(); } public String getCurrentDate() { return sp.getString(CURRENT_DATE, null); } public void setPreviesDate(String previesDate) { editor.putString(PREVIES_DATE, previesDate).commit(); } public String getPreviesDate() { return sp.getString(PREVIES_DATE, null); } public boolean getBookmark() { return sp.getBoolean(Bookmark, false); } public void setBookmark(boolean flag) { editor.putBoolean(Bookmark, flag).commit(); } public boolean getIsNeeded() { return sp.getBoolean(IsNeeded, true); } public void setIsNeeded(boolean flag) { editor.putBoolean(IsNeeded, flag).commit(); } public boolean getIsFirst() { return sp.getBoolean(IsFirst, true); } public void setIsFirst(boolean flag) { editor.putBoolean(IsFirst, flag).commit(); } public void setLastSyncTime(long id) { editor.putLong(KEY_NOTIFICATION_LAST_TIME, id).commit(); } public long getLastSyncTime() { return sp.getLong(KEY_NOTIFICATION_LAST_TIME, 0); } }src/Eclipse-IDE/org.robotframework.ide.eclipse.main.plugin/src/org/robotframework/ide/eclipse/main/plugin/refactoring/RedXmlChangesProcessor.java package org.robotframework.ide.eclipse.main.plugin.refactoring; import org.rf.ide.core.project.RobotProjectConfig; public interface RedXmlChangesProcessor { void pathModified(T affectedConfigModelPart, T newConfigModelPart); void pathRemoved(RobotProjectConfig config, T affectedConfigModelPart); }Vathasav/CatDatabase package controllers; import play.*; import play.data.*; import play.mvc.*; import play.mvc.Http.MultipartFormData.*; import play.mvc.Http.MultipartFormData.FilePart; import views.html.*; import models.Cat; import java.io.*; public class Application extends Controller { static play.data.Form catForm = Form.form(Cat.class); public Result index() { return redirect(routes.Application.cats()); } //show front page public Result cats(){ return ok(views.html.index.render(Cat.all(), catForm)); } // sends the empty catform public Result create(){ Form newCatForm = catForm; return ok( addcat.render(catForm) ); } //returns the image data for a cat based on its ID public Result getImage(long id) { Cat cat = Cat.find.byId(id); if (cat != null) { flash("success","Picture found"); /*** here happens the magic ***/ return ok(cat.picture).as("image"); /************************** ***/ } else { flash("error", "Picture not found."); return null;//redirect(routes.Application.index()); } } //extracts image data from multipart form and updates the cat object with it private void uploadCatImageData(Cat newCat){ //get multi-part data play.mvc.Http.MultipartFormData body = request().body().asMultipartFormData(); //get image from picture tag play.mvc.Http.MultipartFormData.FilePart imageFile = body.getFile("picture"); // check for null and update newCat if(imageFile != null){ File file = imageFile.getFile(); if(file != null){ newCat.imageFile = file; } } } //handles the creation of new cat public Result newCat(){ Form filledForm = catForm.bindFromRequest(); //if form has errors return if(filledForm.hasErrors()){ return badRequest(addcat.render(filledForm)); } else if(filledForm.get().color.trim().isEmpty()){ return badRequest(addcat.render(filledForm)); } else { //if form is OK process it // load image data and save the cat Cat newCat = filledForm.get(); uploadCatImageData(newCat); Cat.create(newCat); //return to front page return redirect(routes.Application.cats()); } } // deletes a cat based on its ID public Result deleteCat(Long id){ Cat.delete(id); return redirect(routes.Application.cats()); } // sends the edit form for cat based on its data public Result editCat(Long id){ Form filledForm = catForm.fill(Cat.find.byId(id)); return ok( editcat.render(Cat.find.byId(id), filledForm) ); } //updates the cat information based on modified data public Result updateCat(Long id) { Form filledForm = catForm.bindFromRequest(); // if form is error-prone then send bad request if(filledForm.hasErrors()) { return badRequest(editcat.render(Cat.find.byId(id), filledForm)); } else{ //process the form and update cat data Cat catFromForm = filledForm.get(); uploadCatImageData(catFromForm); // save cat information to DB Cat.save(id,catFromForm); return redirect(routes.Application.cats()); } } } package serp.bytecode; import java.io.*; import serp.bytecode.visitor.*; /** * Loads a value from the locals table to the stack. * * @author */ public class LoadInstruction extends LocalVariableInstruction { private static final Class[][] _mappings = new Class[][] { { byte.class, int.class }, { boolean.class, int.class }, { char.class, int.class }, { short.class, int.class }, { void.class, int.class }, }; String _type = null; LoadInstruction(Code owner) { super(owner); } LoadInstruction(Code owner, int opcode) { super(owner, opcode); } int getLength() { switch (getOpcode()) { case Constants.ILOAD: case Constants.LLOAD: case Constants.FLOAD: case Constants.DLOAD: case Constants.ALOAD: return super.getLength() + 1; default: return super.getLength(); } } public int getStackChange() { switch (getOpcode()) { case Constants.LLOAD: case Constants.LLOAD0: case Constants.LLOAD1: case Constants.LLOAD2: case Constants.LLOAD3: case Constants.DLOAD: case Constants.DLOAD0: case Constants.DLOAD1: case Constants.DLOAD2: case Constants.DLOAD3: return 2; case Constants.NOP: return 0; default: return 1; } } public int getLogicalStackChange() { switch (getOpcode()) { case Constants.NOP: return 0; default: return 1; } } public String getTypeName() { switch (getOpcode()) { case Constants.ILOAD: case Constants.ILOAD0: case Constants.ILOAD1: case Constants.ILOAD2: case Constants.ILOAD3: return int.class.getName(); case Constants.LLOAD: case Constants.LLOAD0: case Constants.LLOAD1: case Constants.LLOAD2: case Constants.LLOAD3: return long.class.getName(); case Constants.FLOAD: case Constants.FLOAD0: case Constants.FLOAD1: case Constants.FLOAD2: case Constants.FLOAD3: return float.class.getName(); case Constants.DLOAD: case Constants.DLOAD0: case Constants.DLOAD1: case Constants.DLOAD2: case Constants.DLOAD3: return double.class.getName(); case Constants.ALOAD: case Constants.ALOAD0: case Constants.ALOAD1: case Constants.ALOAD2: case Constants.ALOAD3: return Object.class.getName(); default: return _type; } } public TypedInstruction setType(String type) { type = mapType(type, _mappings, true); int local = getLocal(); int len = getLength(); // if an invalid type or local, revert to nop if (type == null || local < 0) { _type = type; setOpcode(Constants.NOP); } else { // valid opcode, unset saved type _type = null; switch (type.charAt(0)) { case 'i': setOpcode((local > 3) ? Constants.ILOAD : (Constants.ILOAD0 + local)); break; case 'l': setOpcode((local > 3) ? Constants.LLOAD : (Constants.LLOAD0 + local)); break; case 'f': setOpcode((local > 3) ? Constants.FLOAD : (Constants.FLOAD0 + local)); break; case 'd': setOpcode((local > 3) ? Constants.DLOAD : (Constants.DLOAD0 + local)); break; default: setOpcode((local > 3) ? Constants.ALOAD : (Constants.ALOAD0 + local)); } } if (len != getLength()) invalidateByteIndexes(); return this; } /** * Equivalent to setLocal (0).setType (Object.class); the * this ptr is always passed in local variable 0. * * @return this instruction, for method chaining */ public LoadInstruction setThis() { return (LoadInstruction) setLocal(0).setType(Object.class); } /** * Equivalent to getLocal () == 0 && getType () == * Object.class; the this ptr * is always passed in local variable 0. * * @return true if the first local is 'this' */ public boolean isThis() { return getLocal() == 0 && getType() == Object.class; } /** * LoadInstructions are equal if the type they reference the same * type and locals index or if either is unset. */ public boolean equalsInstruction(Instruction other) { if (other == this) return true; if (!super.equalsInstruction(other)) return false; String type = getTypeName(); String otherType = ((LoadInstruction) other).getTypeName(); return type == null || otherType == null || type.equals(otherType); } public void acceptVisit(BCVisitor visit) { visit.enterLoadInstruction(this); visit.exitLoadInstruction(this); } void read(Instruction orig) { super.read(orig); LoadInstruction ins = (LoadInstruction) orig; _type = ins._type; } void read(DataInput in) throws IOException { super.read(in); switch (getOpcode()) { case Constants.ILOAD: case Constants.LLOAD: case Constants.FLOAD: case Constants.DLOAD: case Constants.ALOAD: setLocal(in.readUnsignedByte()); break; } } void write(DataOutput out) throws IOException { super.write(out); switch (getOpcode()) { case Constants.ILOAD: case Constants.LLOAD: case Constants.FLOAD: case Constants.DLOAD: case Constants.ALOAD: out.writeByte(getLocal()); } } void calculateOpcode() { // taken care of when setting type setType(getTypeName()); } void calculateLocal() { switch (getOpcode()) { case Constants.ILOAD0: case Constants.LLOAD0: case Constants.FLOAD0: case Constants.DLOAD0: case Constants.ALOAD0: setLocal(0); break; case Constants.ILOAD1: case Constants.LLOAD1: case Constants.FLOAD1: case Constants.DLOAD1: case Constants.ALOAD1: setLocal(1); break; case Constants.ILOAD2: case Constants.LLOAD2: case Constants.FLOAD2: case Constants.DLOAD2: case Constants.ALOAD2: setLocal(2); break; case Constants.ILOAD3: case Constants.LLOAD3: case Constants.FLOAD3: case Constants.DLOAD3: case Constants.ALOAD3: setLocal(3); break; } } } package com.qianlq.customer.service; import com.qianlq.customer.common.exception.BusinessException; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @SpringBootTest @RunWith(SpringRunner.class) public class TestServiceTest { @Autowired private TestService testService; @Test public void test() { Assert.assertEquals(testService.test("hello"), "hello"); } @Test(expected = BusinessException.class) public void testException() { testService.testException("test exception"); } } 0 package com.spring.mq.mqtt; import org.springframework.integration.annotation.MessagingGateway; import org.springframework.integration.mqtt.support.MqttHeaders; import org.springframework.messaging.handler.annotation.Header; /** * @author 赵小超 */ //defaultRequestChannel 对应 @MessagingGateway(defaultRequestChannel = "mqttOutputChannel") public interface MqttGateway { void sendToMqtt(String data, @Header(MqttHeaders.TOPIC) String topic); }0 import javafx.application.Application; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.image.Image; import javafx.scene.input.MouseEvent; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.Stage; import java.sql.SQLException; import java.util.ArrayList; public class MainFrame extends Application { private static Stage addStage; private static EventHandler createNewNoteHandler; private static EventHandler editNotesCreatedHandler; private static ArrayList notesСreated; private static VBox rootMain = new VBox(); private static Scene sceneMain; private static Button createNewNote = new Button(" create new note "); public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws SQLException, ClassNotFoundException { initIcon(primaryStage); initHandlers(primaryStage); setCreateNewNote(); showNotesCreated(); setRootMain(); setPrimaryStage(primaryStage); } private static void setCreateNewNote() { createNewNote.addEventFilter(javafx.scene.input.MouseEvent.MOUSE_CLICKED, createNewNoteHandler); createNewNote.setMinSize(500, 50); } private static void initIcon(Stage stage) { stage.getIcons().add(new Image("style/icon.jpg")); } private static void showNotesCreated() throws SQLException, ClassNotFoundException { initNotesCreated(); for (int i = 0; i < NoteFrame.returnLenNotePanel(); i++) { // notesСreated.get(i).addEventFilter(javafx.scene.input.MouseEvent.MOUSE_CLICKED, editNotesCreatedHandler); rootMain.getChildren().add(notesСreated.get(i)); } } private static void updateShowNoteCreated() throws SQLException, ClassNotFoundException { initNotesCreated(); rootMain.getChildren().add(notesСreated.get(notesСreated.size()-1)); rootMain.getChildren().remove(createNewNote); addStage=new Stage(); createNewNote = new Button(" create new note "); initCreateNewNoteHandler(addStage); setCreateNewNote(); rootMain.getChildren().add(createNewNote); } private static void initHandlers(Stage primaryStage) { initCreateNewNoteHandler(primaryStage); // initEditNotesCreatedHandler(primaryStage); } private static void initCreateNewNoteHandler(Stage primaryStage) { createNewNoteHandler = event -> { new WriteNoteFrame(); }; } /* private static void initEditNotesCreatedHandler(Stage primaryStage) { editNotesCreatedHandler = event -> { new EditNoteFrame(); }; } */ private static void initNotesCreated() throws SQLException, ClassNotFoundException { notesСreated = NoteFrame.getNotePanel(); } //private static void delNotesCreated(){ // rootMain.getChildren().removeAll(notesСreated); // } public static void updateNotesCreated() throws SQLException, ClassNotFoundException { //notesСreated=new ArrayList<>(); updateShowNoteCreated(); } private static void setRootMain() { rootMain.setSpacing(10); rootMain.getChildren().add(createNewNote); } private static void setPrimaryStage(Stage primaryStage) { // primaryStage.setResizable(false); primaryStage.setTitle("Zen.Note"); setSceneMain(); primaryStage.setScene(sceneMain); primaryStage.show(); } private static void setSceneMain() { sceneMain = new Scene(rootMain, 500, 600); sceneMain.getStylesheets().add(MainFrame.class.getResource("style/style.css").toExternalForm()); } private static Stage transStage(Stage primaryStage) { return primaryStage; } } fujaba/SDMLibsrc/test/java/org/sdmlib/test/examples/features/model/all/util/HousePO.java package org.sdmlib.test.examples.features.model.all.util; import org.sdmlib.models.pattern.PatternObject; import org.sdmlib.test.examples.features.model.all.Door; import org.sdmlib.test.examples.features.model.all.House; import org.sdmlib.test.examples.features.model.all.Window; public class HousePO extends PatternObject { public HouseSet allMatches() { this.setDoAllMatches(true); HouseSet matches = new HouseSet(); while (this.getPattern().getHasMatch()) { matches.add((House) this.getCurrentMatch()); this.getPattern().findMatch(); } return matches; } public HousePO(){ newInstance(org.sdmlib.test.examples.features.model.all.util.CreatorCreator.createIdMap("PatternObjectType")); } public HousePO(House... hostGraphObject) { if(hostGraphObject==null || hostGraphObject.length<1){ return ; } newInstance(org.sdmlib.test.examples.features.model.all.util.CreatorCreator.createIdMap("PatternObjectType"), hostGraphObject); } public DoorPO hasDoors() { DoorPO result = new DoorPO(new Door[]{}); result.setModifier(this.getPattern().getModifier()); super.hasLink(House.PROPERTY_DOORS, result); return result; } public DoorPO createDoors() { return this.startCreate().hasDoors().endCreate(); } public HousePO hasDoors(DoorPO tgt) { return hasLinkConstraint(tgt, House.PROPERTY_DOORS); } public HousePO createDoors(DoorPO tgt) { return this.startCreate().hasDoors(tgt).endCreate(); } public DoorSet getDoors() { if (this.getPattern().getHasMatch()) { return ((House) this.getCurrentMatch()).getDoors(); } return null; } public WindowPO hasWindows() { WindowPO result = new WindowPO(new Window[]{}); result.setModifier(this.getPattern().getModifier()); super.hasLink(House.PROPERTY_WINDOWS, result); return result; } public WindowPO createWindows() { return this.startCreate().hasWindows().endCreate(); } public HousePO hasWindows(WindowPO tgt) { return hasLinkConstraint(tgt, House.PROPERTY_WINDOWS); } public HousePO createWindows(WindowPO tgt) { return this.startCreate().hasWindows(tgt).endCreate(); } public WindowSet getWindows() { if (this.getPattern().getHasMatch()) { return ((House) this.getCurrentMatch()).getWindows(); } return null; } public DoorPO filterDoors() { DoorPO result = new DoorPO(new Door[]{}); result.setModifier(this.getPattern().getModifier()); super.hasLink(House.PROPERTY_DOORS, result); return result; } public HousePO filterDoors(DoorPO tgt) { return hasLinkConstraint(tgt, House.PROPERTY_DOORS); } public WindowPO filterWindows() { WindowPO result = new WindowPO(new Window[]{}); result.setModifier(this.getPattern().getModifier()); super.hasLink(House.PROPERTY_WINDOWS, result); return result; } public HousePO filterWindows(WindowPO tgt) { return hasLinkConstraint(tgt, House.PROPERTY_WINDOWS); } public HousePO(String modifier) { this.setModifier(modifier); } public DoorPO createDoorsPO() { DoorPO result = new DoorPO(new Door[]{}); result.setModifier(this.getPattern().getModifier()); super.hasLink(House.PROPERTY_DOORS, result); return result; } public DoorPO createDoorsPO(String modifier) { DoorPO result = new DoorPO(new Door[]{}); result.setModifier(modifier); super.hasLink(House.PROPERTY_DOORS, result); return result; } public HousePO createDoorsLink(DoorPO tgt) { return hasLinkConstraint(tgt, House.PROPERTY_DOORS); } public HousePO createDoorsLink(DoorPO tgt, String modifier) { return hasLinkConstraint(tgt, House.PROPERTY_DOORS, modifier); } public WindowPO createWindowsPO() { WindowPO result = new WindowPO(new Window[]{}); result.setModifier(this.getPattern().getModifier()); super.hasLink(House.PROPERTY_WINDOWS, result); return result; } public WindowPO createWindowsPO(String modifier) { WindowPO result = new WindowPO(new Window[]{}); result.setModifier(modifier); super.hasLink(House.PROPERTY_WINDOWS, result); return result; } public HousePO createWindowsLink(WindowPO tgt) { return hasLinkConstraint(tgt, House.PROPERTY_WINDOWS); } public HousePO createWindowsLink(WindowPO tgt, String modifier) { return hasLinkConstraint(tgt, House.PROPERTY_WINDOWS, modifier); } } 1-10 // Dstl (c) Crown Copyright 2017 package uk.gov.dstl.baleen.annotators.regex; import org.junit.Test; import uk.gov.dstl.baleen.annotators.testing.AbstractAnnotatorTest; import uk.gov.dstl.baleen.annotators.testing.types.TestCoordinate; import uk.gov.dstl.baleen.types.geo.Coordinate; /** */ public class OrdnanceSurveyTest extends AbstractAnnotatorTest { public OrdnanceSurveyTest() { super(Osgb.class); } @Test public void test() throws Exception { jCas.setDocumentText( " is located at NN 166 712. The car park is located at NN126729."); processJCas(); // Values tested against here are based on the output, rather than the correct value, due to // inaccuracies in our coordinate conversion // Actual values are -5.0713526,56.809745 and -5.0047120,56.796088 respectively assertAnnotations( 2, Coordinate.class, new TestCoordinate( 1, "NN126729", "osgb", "{\"type\": \"Point\", \"coordinates\": [-5.071352,56.808457]}"), new TestCoordinate( 0, "NN 166 712", "osgb", "{\"type\": \"Point\", \"coordinates\": [-5.004712,56.794800]}")); } @Test public void test10Figure() throws Exception { jCas.setDocumentText("The event took place at GR SU 02194 45374"); processJCas(); // Values tested against here are based on the output, rather than the correct value, due to // inaccuracies in our coordinate conversion // Actual value is -1.9699750,51.207570 assertAnnotations( 1, Coordinate.class, new TestCoordinate( 0, "SU 02194 45374", "osgb", "{\"type\": \"Point\", \"coordinates\": [-1.969975,51.206197]}")); } } lduening/jldmud /** * Copyright (C) 2016 jLDMud Developers. * This file is free software under the MIT License - see the file LICENSE for details. */ package org.ldmud.jldmud.rt.net; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertNull; import org.ldmud.jldmud.rt.object.MudObject; import org.testng.annotations.Test; /** * Unit tests for {@link Commmunicator}. */ public class CommunicatorTest { @Test public void testInteractiveClassification() { Communicator communicator = new Communicator(null); Interactive interactive = mock(Interactive.class); when(interactive.getState()).thenReturn(Interactive.State.NEW); assertTrue(communicator.isInteractivePending(interactive)); when(interactive.getState()).thenReturn(Interactive.State.CONNECTION_LOST); assertTrue(communicator.isInteractivePending(interactive)); when(interactive.getState()).thenReturn(Interactive.State.CLOSED); assertFalse(communicator.isInteractivePending(interactive)); when(interactive.getState()).thenReturn(Interactive.State.ACTIVE); when(interactive.isDataPending()).thenReturn(false); assertFalse(communicator.isInteractivePending(interactive)); when(interactive.getState()).thenReturn(Interactive.State.ACTIVE); when(interactive.isDataPending()).thenReturn(true); assertTrue(communicator.isInteractivePending(interactive)); } @Test public void testInteractiveLifecycle() { Communicator communicator = new Communicator(null); MudObject obj = mock(MudObject.class); when(obj.ref()).thenReturn(new MudObject.Ref(obj)); Interactive interactive1 = mock(Interactive.class); Interactive interactive2 = mock(Interactive.class); when(interactive1.getName()).thenReturn("Interactive #1"); when(interactive2.getName()).thenReturn("Interactive #2"); communicator.add(interactive1); communicator.add(interactive2); // No data pending when(interactive1.getState()).thenReturn(Interactive.State.ACTIVE); when(interactive1.isDataPending()).thenReturn(false); when(interactive2.getState()).thenReturn(Interactive.State.ACTIVE); when(interactive2.isDataPending()).thenReturn(false); assertFalse(communicator.areInteractivesPending()); assertNull(communicator.nextPendingInteractive()); // Interactive 2 has data pending when(interactive1.getState()).thenReturn(Interactive.State.ACTIVE); when(interactive1.isDataPending()).thenReturn(false); when(interactive2.getState()).thenReturn(Interactive.State.ACTIVE); when(interactive2.isDataPending()).thenReturn(true); assertTrue(communicator.areInteractivesPending()); assertEquals(communicator.nextPendingInteractive(), interactive2); when(interactive2.isDataPending()).thenReturn(false); assertNull(communicator.nextPendingInteractive()); // Interactive 2 closed when(interactive1.getState()).thenReturn(Interactive.State.ACTIVE); when(interactive1.isDataPending()).thenReturn(false); when(interactive2.getState()).thenReturn(Interactive.State.CLOSED); assertFalse(communicator.areInteractivesPending()); assertNull(communicator.nextPendingInteractive()); // Removes interactive2 assertFalse(communicator.getAllInteractives().contains(interactive2)); } } SpyrosDellas/algorithms-ii /* ***************************************************************************** * Name: * Date: 27/05/2020 * * Description: * Analysis of the bipartite graph from movies.txt * **************************************************************************** */ import edu.princeton.cs.algs4.Stack; public class MoviesAnalysis { private SymbolGraph sg; // the symbol graph private boolean hasCycle; // is there a cycle in the graph? private int count; // number of connected components private boolean isConnected; // is the graph connected? private int V; // number of vertices private int E; // number of edges private int[] id; public MoviesAnalysis(String file, String delimiter) { sg = new SymbolGraph(file, delimiter); V = sg.graph().V(); E = sg.graph().E(); } public void analyse() { if (sg.graph().V() == 0) throw new IllegalArgumentException("Graph is empty"); cc(); cycles(); } // Compute the size of the largest component, and the number of components // of size less than 10. // Find the eccentricity, diameter, radius, a center, and the girth of the // largest component in the graph. // Does it contain Kevin Bacon? public void analyseBacon() { int[] sizes = new int[count]; int largestID = 0; int largestSize = 0; int lessThan10 = 0; for (int v = 0; v < V; v++) { sizes[id[v]]++; } for (int i = 0; i < count; i++) { if (sizes[i] > largestSize) { largestID = i; largestSize = sizes[i]; } if (sizes[i] < 10) { lessThan10++; } } System.out.println("Largest component id: " + largestID); System.out.println("Largest component size: " + largestSize); System.out.println("Components of size less than 10: " + lessThan10); int baconV = sg.indexOf("Bacon, Kevin"); if (id[baconV] == largestID) { System.out.println("The largest component contains "); } else { System.out.println("The largest component DOES NOT contain "); } System.out.println("Analysing the largest component..."); GraphProperties properties = new GraphProperties(sg.graph(), baconV); System.out.println("Diameter of largest component = " + properties.diameter()); System.out.println("Radius of largest component = " + properties.radius()); System.out.println("Girth of largest component = " + properties.girth()); System.out.println("Center: " + properties.center()); } // is the graph acyclic? private void cycles() { Cycles c = new Cycles(sg.graph()); this.hasCycle = c.hasCycle(); } // is the graph connected? private void cc() { count = 0; id = new int[V]; boolean[] marked = new boolean[V]; for (int s = 0; s < V; s++) { // If vertex s belongs already to a connected component ignore it if (marked[s]) continue; // Find all vertices connected to s and update marked[] and id[] Stack vertexStack = new Stack<>(); vertexStack.push(s); marked[s] = true; id[s] = count; while (!vertexStack.isEmpty()) { int v = vertexStack.pop(); for (int w : sg.graph().adj(v)) { if (!marked[w]) { vertexStack.push(w); marked[w] = true; id[w] = count; } } } count++; } isConnected = (count == 1); } public int getE() { return E; } public int getV() { return V; } public int getcComponents() { return count; } public boolean isConnected() { return isConnected; } public boolean hasCycle() { return hasCycle; } public static void main(String[] args) { String file = "movies.txt"; String delimiter = "/"; System.out.println("Generating bipartite graph from 'movies.txt'..."); MoviesAnalysis movies = new MoviesAnalysis(file, delimiter); System.out.println("\nAnalysing graph..."); movies.analyse(); System.out.println("Number of vertices = " + movies.getV()); System.out.println("Number of edges = " + movies.getE()); System.out.println("Is the graph connected? " + movies.isConnected()); System.out.println("Number of connected components = " + movies.getcComponents()); System.out.println("Is the graph acyclic? " + !movies.hasCycle()); System.out.println("\nRunning Kevin Bacon analysis..."); movies.analyseBacon(); } } CarilKing/apipackages/src/main/java/org/polkadot/types/codec/Enum.java package org.polkadot.types.codec; import org.polkadot.types.Codec; import org.polkadot.utils.Utils; import java.util.List; /** * A codec wrapper for an enum. Enums are encoded as a single byte, where the byte * is a zero-indexed value. This class allows you to retrieve the value either * by `toNumber()` exposing the actual raw index, or `toString()` returning a * string representation (as provided as part of the constructor) */ // TODO: // - It would be great if this could actually wrap actual TS enums public class Enum extends Base implements Codec { private List enumList; // type EnumDef = { // [index: string]: number //} | Array; // static decodeEnum (def: EnumDef, value: Enum | Uint8Array | string | number): number | undefined { public Enum(List def, Object value) { super(decodeEnum(def, value)); this.enumList = def; } private static Number decodeEnum(List def, Object value) { if (value instanceof Enum) { return ((Enum) value).raw; } else if (Utils.isU8a(value)) { return ((byte[]) value)[0]; } else if (value instanceof String) { // return Array.isArray(def) // ? def.indexOf(value) // : def[value] || -1; return def.indexOf(value); } return (Number) value; } /** * The length of the value when encoded as a Uint8Array */ @Override public int getEncodedLength() { return 1; } /** * Returns the index for this value (equivalent to toNumber) */ public int getIndex() { return this.raw.intValue(); } /** * Checks if the value is an empty value (always false) */ @Override public boolean isEmpty() { return false; } /** * Compares the value of the input to see if there is a match */ @Override public boolean eq(Object other) { if (other instanceof Enum) { return ((Enum) other).raw.equals(this.raw); } if (other instanceof String) { return this.toString().equals(other); } return this.raw.equals(other); } /** * Returns a hex string representation of the value */ @Override public String toHex() { return Utils.u8aToHex(this.toU8a(false)); } /** * Converts the Object to JSON, typically used for RPC transfers */ @Override public Object toJson() { return this.raw; } /** * Returns the number representation for the value */ public int toNumber() { return this.raw.intValue(); } /** * Returns the string representation of the value */ @Override public String toString() { if (this.enumList.size() > this.raw.intValue()) { return this.enumList.get(this.raw.intValue()); } return this.raw.toString(); } /** * Encodes the value as a Uint8Array as per the parity-codec specifications * @param isBare true when the value has none of the type-specific prefixes (internal) */ @Override public byte[] toU8a(boolean isBare) { //return new Uint8Array([this.raw]); return new byte[]{this.raw.byteValue()}; } } /** * Copyright 2004-2014 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * 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.kuali.kpme.pm.api.positionreporttype; import org.kuali.kpme.core.api.mo.KpmeEffectiveDataTransferObject; /** *

PositionReportTypeContract interface

* */ public interface PositionReportTypeContract extends KpmeEffectiveDataTransferObject { /** * The text used to identify the PositionReportType * *

* positionReportType of a PositionReportType *

* * @return positionReportType for PositionReportType */ public String getPositionReportType(); /** * The descriptive text of the types of reporting categories that will be defined * *

* description of a PositionReportType. *

* * @return description for PositionReportType */ public String getDescription(); /** * The position reportType id associated with the PositionReportType * *

* pmPositionReportTypeId of a PositionReportType. *

* * @return pmPositionReportTypeId for PositionReportType */ public String getPmPositionReportTypeId(); } package com.example.patriciaouyang.instagram; import android.content.Context; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.example.patriciaouyang.instagram.model.Post; import java.util.List; public class PostAdapter extends RecyclerView.Adapter { List mPosts; Context context; //private final ClickListener listener; public PostAdapter(List posts) { mPosts = posts; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { context = parent.getContext(); LayoutInflater inflater = LayoutInflater.from(context); View postView = inflater.inflate(R.layout.item_post, parent, false); ViewHolder viewHolder = new ViewHolder(postView); return viewHolder; } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { Post post = mPosts.get(position); holder.tvUser.setText(post.getUser().getUsername()); holder.tvCaption.setText(post.getUser().getUsername()); holder.tvRealCaption.setText(post.getDescription()); Glide.with(context).load(post.getImage().getUrl()).into(holder.ivPostImage); } @Override public int getItemCount() { return mPosts.size(); } public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { public ImageView ivPostImage; public TextView tvCaption; public TextView tvUser; public TextView tvRealCaption; public ViewHolder(@NonNull View itemView) { super(itemView); ivPostImage = itemView.findViewById(R.id.ivPostImage); tvCaption = itemView.findViewById(R.id.tvCaption); tvUser = itemView.findViewById(R.id.tvUser); tvRealCaption = itemView.findViewById(R.id.tvRealCaption); itemView.setOnClickListener(this); } // onClick Listener for view @Override public void onClick(View v) { int position = getAdapterPosition(); if (position != RecyclerView.NO_POSITION) { Post post = mPosts.get(position); Intent i = new Intent(context, PostDetailsActivity.class); Toast.makeText(context, "DetailsView launched", Toast.LENGTH_SHORT).show(); i.putExtra("caption", post.getDescription()); i.putExtra("imageUrl", post.getImage().getUrl()); i.putExtra("username", post.getUser().getUsername()); i.putExtra("timestamp", post.getRelativeTime()); context.startActivity(i); } } } // Clean all elements of the recycler public void clear() { mPosts.clear(); notifyDataSetChanged(); } // Add a list of items -- change to type used public void addAll(List list) { mPosts.addAll(list); notifyDataSetChanged(); } } src/sample/LoginController.java package sample; public class LoginController { } app/src/main/java/com/iasmar/rome/ui/views/main/schedules/SchedulesContract.java package com.iasmar.rome.ui.views.main.schedules; import com.iasmar.rome.data.modules.Schedule; import com.iasmar.rome.data.modules.ModulesHolder; import com.iasmar.rome.ui.views.base.IBasePresenter; import com.iasmar.rome.ui.views.base.IBaseView; /** * Created by Asmar on 01/7/2018. *

* This specifies the contract between the view and the presenter. * * @author Asmar * @version 1 * @see IBaseView * @see IBasePresenter * @see ModulesHolder * @see Schedule * @since 1.0 */ interface SchedulesContract { //*********************************** The schedules view ***********************************// /** * The schedules view must implement this interface. */ interface View extends IBaseView { /** * Display schedules on the UI. */ void showSchedules(ModulesHolder schedules); /** * Display no schedules on the UI. */ void showNoSchedules(); } //*********************************** The schedules presenter ***********************************// /** * The schedules presenter must implement this interface. * * @param the schedules view. */ interface Presenter extends IBasePresenter { /** * load schedules. * * @param forceUpdate true to force update from the server false load from cash or DB, * if there is a problem with th connection will return from cash or DB. */ void loadSchedules(boolean forceUpdate); } } package uk.gov.hmcts.reform.fpl.service; import org.junit.jupiter.api.Test; import uk.gov.hmcts.reform.fpl.model.DocumentsSentToParty; import uk.gov.hmcts.reform.fpl.model.SentDocument; import uk.gov.hmcts.reform.fpl.model.common.Element; import java.util.ArrayList; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static uk.gov.hmcts.reform.fpl.utils.ElementUtils.unwrapElements; import static uk.gov.hmcts.reform.fpl.utils.ElementUtils.wrapElements; import static uk.gov.hmcts.reform.fpl.utils.TestDataHelper.testDocumentReference; public class SentDocumentHistoryServiceTest { private static final String PARTY_1 = ""; private static final String PARTY_2 = ""; SentDocumentHistoryService sentDocumentHistoryService = new SentDocumentHistoryService(); @Test public void shouldCreateHistoricalRecordIfAbsent() { SentDocument documentSentToParty1 = sentDocument(PARTY_1); SentDocument documentSentToParty2 = sentDocument(PARTY_2); List> history = new ArrayList<>(); List sentDocuments = List.of(documentSentToParty1, documentSentToParty2); List updatedHistory = unwrapElements(sentDocumentHistoryService .addToHistory(history, sentDocuments)); assertThat(updatedHistory).hasSize(2); assertThat(updatedHistory.get(0).getPartyName()).isEqualTo(PARTY_1); assertThat(unwrapElements(updatedHistory.get(0).getDocumentsSentToParty())) .containsExactly(documentSentToParty1); assertThat(updatedHistory.get(1).getPartyName()).isEqualTo(PARTY_2); assertThat(unwrapElements(updatedHistory.get(1).getDocumentsSentToParty())) .containsExactly(documentSentToParty2); } @Test public void shouldCreateHistoricalRecordWithMultipleDocuments() { SentDocument document1SentToParty = sentDocument(PARTY_1); SentDocument document2SentToParty = sentDocument(PARTY_1); List> history = new ArrayList<>(); List sentDocuments = List.of(document1SentToParty, document2SentToParty); List updatedHistory = unwrapElements(sentDocumentHistoryService .addToHistory(history, sentDocuments)); assertThat(updatedHistory).hasSize(1); assertThat(updatedHistory.get(0).getPartyName()).isEqualTo(PARTY_1); assertThat(unwrapElements(updatedHistory.get(0).getDocumentsSentToParty())) .containsExactly(document1SentToParty, document2SentToParty); } @Test public void shouldUpdateHistoricalRecordIfPresent() { SentDocument document1SentToParty1 = sentDocument(PARTY_1); SentDocument document2SentToParty1 = sentDocument(PARTY_1); SentDocument document1SentToParty2 = sentDocument(PARTY_2); DocumentsSentToParty documentsSentToParty1 = sentDocumentsHistory(PARTY_1, document1SentToParty1); DocumentsSentToParty documentsSentToParty2 = sentDocumentsHistory(PARTY_2, document1SentToParty2); List> history = wrapElements(documentsSentToParty1, documentsSentToParty2); List sentDocuments = List.of(document2SentToParty1); List updatedHistory = unwrapElements(sentDocumentHistoryService .addToHistory(history, sentDocuments)); assertThat(updatedHistory).hasSize(2); assertThat(updatedHistory.get(0).getPartyName()).isEqualTo(PARTY_1); assertThat(unwrapElements(updatedHistory.get(0).getDocumentsSentToParty())) .containsExactly(document1SentToParty1, document2SentToParty1); assertThat(updatedHistory.get(1)).isEqualTo(documentsSentToParty2); } private static SentDocument sentDocument(String partyName) { return SentDocument.builder() .partyName(partyName) .document(testDocumentReference()) .build(); } private static DocumentsSentToParty sentDocumentsHistory(String partyName, SentDocument... sentDocuments) { return DocumentsSentToParty.builder() .partyName(partyName) .documentsSentToParty(wrapElements(sentDocuments)) .build(); } } Cydhra/refinedstorage package com.raoulvdberge.refinedstorage.integration.jei; import com.raoulvdberge.refinedstorage.RSItems; import com.raoulvdberge.refinedstorage.apiimpl.network.node.cover.CoverManager; import com.raoulvdberge.refinedstorage.item.ItemCover; import mezz.jei.api.recipe.*; import net.minecraft.item.ItemStack; import java.util.Collections; import java.util.List; public class RecipeRegistryPluginCover implements IRecipeRegistryPlugin { @Override public List getRecipeCategoryUids(IFocus focus) { if (focus.getValue() instanceof ItemStack) { ItemStack stack = (ItemStack) focus.getValue(); if (focus.getMode() == IFocus.Mode.INPUT) { if (CoverManager.isValidCover(stack)) { return Collections.singletonList(VanillaRecipeCategoryUid.CRAFTING); } } else if (focus.getMode() == IFocus.Mode.OUTPUT) { if (stack.getItem() == RSItems.COVER) { return Collections.singletonList(VanillaRecipeCategoryUid.CRAFTING); } } } return Collections.emptyList(); } @Override public List getRecipeWrappers(IRecipeCategory recipeCategory, IFocus focus) { if (focus.getValue() instanceof ItemStack) { ItemStack stack = (ItemStack) focus.getValue(); if (focus.getMode() == IFocus.Mode.INPUT) { if (CoverManager.isValidCover(stack)) { ItemStack cover = new ItemStack(RSItems.COVER); ItemCover.setItem(cover, stack); return Collections.singletonList((T) new RecipeWrapperCover(stack, cover)); } } else if (focus.getMode() == IFocus.Mode.OUTPUT) { if (stack.getItem() == RSItems.COVER) { return Collections.singletonList((T) new RecipeWrapperCover(ItemCover.getItem(stack), stack)); } } } return Collections.emptyList(); } @Override public List getRecipeWrappers(IRecipeCategory recipeCategory) { return Collections.emptyList(); } } src/RepGenerator.java /** * RepGenerator * This class generates some examples of an abstract representation of code. * It can be used to make sample input to test with the music engine, * or to make samples against which the code analysis engine can compare output. * */ public class RepGenerator { // public ExecutionPath ifCondition(){ // /* int x = 5; // if (x < 7) { // x = x + 4; // }else if(x > 7) { // x = x + 8; // }else { // x = x + 1; // } // */ // // ExecutionPath path = new ExecutionPath(); // // DataStructureNode d1 = new DataStructureNode(null, DataStructureNodeType.INT, Operation.NONE); // path.addNode(d1); // // ScopeNode s1 = new ScopeNode(null, 1); // s1.setType(ScopeNodeType.IF); // DataStructureNode s1d1 = new DataStructureNode(s1, DataStructureNodeType.INT, Operation.ADD); // s1.addChild(s1d1); // path.addNode(s1); // // return path; // } // // public ExecutionPath elseIfCondition(){ // /* int x = 10; // if (x < 7) { // x = x + 4; // }else if(x > 7) { // x = x + 8; // }else { // x = x + 1; // } // */ // // ExecutionPath path = new ExecutionPath(); // // DataStructureNode d1 = new DataStructureNode(null, DataStructureNodeType.INT, Operation.NONE); // path.addNode(d1); // // ScopeNode s2 = new ScopeNode(null,1); // s2.setType(ScopeNodeType.IF); // path.addNode(s2); // // ScopeNode s1 = new ScopeNode(null, 1); // s1.setType(ScopeNodeType.ELSEIF); // DataStructureNode s1d1 = new DataStructureNode(s1, DataStructureNodeType.INT, Operation.ADD); // s1.addChild(s1d1); // path.addNode(s1); // // return path; // } // // public ExecutionPath elseCondition(){ // /* int x = 7; // if (x < 7) { // x = x + 4; // }else if(x > 7) { // x = x + 8; // }else { // x = x + 1; // } // */ // // ExecutionPath path = new ExecutionPath(); // // DataStructureNode d1 = new DataStructureNode(null, DataStructureNodeType.INT, Operation.NONE); // path.addNode(d1); // // ScopeNode s2 = new ScopeNode(null,1); // s2.setType(ScopeNodeType.IF); // path.addNode(s2); // // ScopeNode s3 = new ScopeNode(null,1); // s3.setType(ScopeNodeType.ELSEIF); // path.addNode(s3); // // ScopeNode s1 = new ScopeNode(null, 1); // s1.setType(ScopeNodeType.ELSE); // DataStructureNode s1d1 = new DataStructureNode(s1, DataStructureNodeType.INT, Operation.ADD); // s1.addChild(s1d1); // path.addNode(s1); // // return path; // } // // public ExecutionPath noCondition(){ // /* int x = 7; // if (x < 7) { // x = x + 4; // }else if(x > 7) { // x = x + 8; // } // */ // // ExecutionPath path = new ExecutionPath(); // // DataStructureNode d1 = new DataStructureNode(null, DataStructureNodeType.INT, Operation.NONE); // path.addNode(d1); // // ScopeNode s2 = new ScopeNode(null,1); // s2.setType(ScopeNodeType.IF); // path.addNode(s2); // // ScopeNode s3 = new ScopeNode(null,1); // s3.setType(ScopeNodeType.ELSEIF); // path.addNode(s3); // // return path; // } // // public ExecutionPath switchCascade(){ // /* int x = 4; // switch(x){ // // case 2: // int d = 7 - 3; // case 4: // int a = 1 + 2; // case 1: // int b = 3 + x; // break; // case 23: // int c = 5; // default: // int e = 4; // int f = 6; // // } // */ // // ExecutionPath path = new ExecutionPath(); // // DataStructureNode d1 = new DataStructureNode(null, DataStructureNodeType.INT, Operation.NONE); // path.addNode(d1); // // ScopeNode s1 = new ScopeNode(null, 1); // s1.setType(ScopeNodeType.SWITCHBODY); // DataStructureNode s1d1 = new DataStructureNode(s1, DataStructureNodeType.INT, Operation.ADD); // DataStructureNode s1d2 = new DataStructureNode(s1, DataStructureNodeType.INT, Operation.ADD); // s1.addChild(s1d1); // s1.addChild(s1d2); // path.addNode(s1); // // return path; // } // // public ExecutionPath switchNoCascade(){ // /* int x = 4; // switch(x){ // // case 2: // int d = 7 - 3; // case 4: // int a = 1 + 2; // break; // case 1: // int b = 3 + x; // break; // case 23: // int c = 5; // break; // default: // int e = 4; // int f = 6; // // } // */ // // ExecutionPath path = new ExecutionPath(); // // DataStructureNode d1 = new DataStructureNode(null, DataStructureNodeType.INT, Operation.NONE); // path.addNode(d1); // // ScopeNode s1 = new ScopeNode(null, 1); // s1.setType(ScopeNodeType.SWITCHBODY); // DataStructureNode s1d1 = new DataStructureNode(s1, DataStructureNodeType.INT, Operation.ADD); // s1.addChild(s1d1); // path.addNode(s1); // // return path; // } // // public ExecutionPath switchNoCases(){ // /* int x = 5; // switch(x){ // // case 2: // int d = 7 - 3; // break; // case 4: // int a = 1 + 2; // break; // case 1: // int b = 3 + x; // break; // case 23: // int c = 5; // break; // } // */ // // ExecutionPath path = new ExecutionPath(); // // DataStructureNode d1 = new DataStructureNode(null, DataStructureNodeType.INT, Operation.NONE); // path.addNode(d1); // // ScopeNode s1 = new ScopeNode(null, 1); // s1.setType(ScopeNodeType.SWITCHBODY); // path.addNode(s1); // // return path; // } // // public ExecutionPath whileAddition(){ // /* int i = 0; // int x = 1; // while (i < 5) { // x = x + i; // i = i + 1; // } // */ // // ExecutionPath path = new ExecutionPath(); // // DataStructureNode d1 = new DataStructureNode(null, DataStructureNodeType.INT, Operation.NONE); // path.addNode(d1); // // DataStructureNode d2 = new DataStructureNode(null, DataStructureNodeType.INT, Operation.NONE); // path.addNode(d2); // // ScopeNode s1 = new ScopeNode(null, 5); // s1.setType(ScopeNodeType.WHILE); // DataStructureNode s1d1 = new DataStructureNode(s1, DataStructureNodeType.INT, Operation.ADD); // DataStructureNode s1d2 = new DataStructureNode(s1, DataStructureNodeType.INT, Operation.ADD); // s1.addChild(s1d1); // s1.addChild(s1d2); // path.addNode(s1); // // return path; // } // // public ExecutionPath whileSubtraction(){ // /* int i = 0; // double x = 20; // while (i < 5) { // x = x - i; // i = i + 1; // } // */ // // ExecutionPath path = new ExecutionPath(); // // DataStructureNode d1 = new DataStructureNode(null, DataStructureNodeType.INT, Operation.NONE); // path.addNode(d1); // // DataStructureNode d2 = new DataStructureNode(null, DataStructureNodeType.DOUBLE, Operation.NONE); // path.addNode(d2); // // ScopeNode s1 = new ScopeNode(null, 5); // s1.setType(ScopeNodeType.WHILE); // DataStructureNode s1d1 = new DataStructureNode(s1, DataStructureNodeType.DOUBLE, Operation.SUBTRACT); // DataStructureNode s1d2 = new DataStructureNode(s1, DataStructureNodeType.INT, Operation.ADD); // s1.addChild(s1d1); // s1.addChild(s1d2); // path.addNode(s1); // // return path; // } // // public ExecutionPath stringTest(){ // /* int i = 0; // String s = "a"; // while (i < 5) { // s = s + "a"; // i = i + 1; // } // */ // // ExecutionPath path = new ExecutionPath(); // // DataStructureNode d1 = new DataStructureNode(null, DataStructureNodeType.INT, Operation.NONE); // path.addNode(d1); // // DataStructureNode d2 = new DataStructureNode(null, DataStructureNodeType.STRING, Operation.NONE); // path.addNode(d2); // // ScopeNode s1 = new ScopeNode(null, 5); // s1.setType(ScopeNodeType.WHILE); // DataStructureNode s1d1 = new DataStructureNode(s1, DataStructureNodeType.STRING, Operation.ADD); // DataStructureNode s1d2 = new DataStructureNode(s1, DataStructureNodeType.INT, Operation.ADD); // s1.addChild(s1d1); // s1.addChild(s1d2); // path.addNode(s1); // // return path; // } // // public ExecutionPath noWhile(){ // /* int i = 0; // int x = 20; // while (i > 5) { // x = x - i; // i = i + 1; // } // */ // // ExecutionPath path = new ExecutionPath(); // // DataStructureNode d1 = new DataStructureNode(null, DataStructureNodeType.INT, Operation.NONE); // path.addNode(d1); // // DataStructureNode d2 = new DataStructureNode(null, DataStructureNodeType.INT, Operation.NONE); // path.addNode(d2); // // ScopeNode s1 = new ScopeNode(null, 0); // s1.setType(ScopeNodeType.WHILE); // // path.addNode(s1); // // return path; // } // // public ExecutionPath doWhileDivision(){ // /* int i = 0; // float x = 32; // do { // x = x / 2; // i = i + 1; // } while (i < 5); // */ // // ExecutionPath path = new ExecutionPath(); // // DataStructureNode d1 = new DataStructureNode(null, DataStructureNodeType.INT, Operation.NONE); // path.addNode(d1); // DataStructureNode d2 = new DataStructureNode(null, DataStructureNodeType.FLOAT, Operation.NONE); // path.addNode(d2); // // ScopeNode s1 = new ScopeNode(null, 5); // s1.setType(ScopeNodeType.DOWHILE); // DataStructureNode s1d1 = new DataStructureNode(s1, DataStructureNodeType.FLOAT, Operation.DIVIDE); // DataStructureNode s1d2 = new DataStructureNode(s1, DataStructureNodeType.INT, Operation.ADD); // s1.addChild(s1d1); // s1.addChild(s1d2); // path.addNode(s1); // // return path; // } // // public ExecutionPath doWhileMultiplication(){ // /* int i = 0; // byte x = 1; // do { // x = (byte) (2 * x); // i = i + 1; // } while (i < 5); // */ // // ExecutionPath path = new ExecutionPath(); // // DataStructureNode d1 = new DataStructureNode(null, DataStructureNodeType.INT, Operation.NONE); // path.addNode(d1); // DataStructureNode d2 = new DataStructureNode(null, DataStructureNodeType.BYTE, Operation.NONE); // path.addNode(d2); // // ScopeNode s1 = new ScopeNode(null, 5); // s1.setType(ScopeNodeType.DOWHILE); // DataStructureNode s1d1 = new DataStructureNode(s1, DataStructureNodeType.BYTE, Operation.MULTIPLY); // DataStructureNode s1d2 = new DataStructureNode(s1, DataStructureNodeType.INT, Operation.ADD); // s1.addChild(s1d1); // s1.addChild(s1d2); // path.addNode(s1); // // return path; // } // // public ExecutionPath stringTestDo(){ // /* int i = 0; // String s = "a"; // do { // s = s + "a"; // i = i + 1; // } while (i < 5); // */ // // ExecutionPath path = new ExecutionPath(); // // DataStructureNode d1 = new DataStructureNode(null, DataStructureNodeType.INT, Operation.NONE); // path.addNode(d1); // DataStructureNode d2 = new DataStructureNode(null, DataStructureNodeType.STRING, Operation.NONE); // path.addNode(d2); // // ScopeNode s1 = new ScopeNode(null, 5); // s1.setType(ScopeNodeType.DOWHILE); // DataStructureNode s1d1 = new DataStructureNode(s1, DataStructureNodeType.STRING, Operation.ADD); // DataStructureNode s1d2 = new DataStructureNode(s1, DataStructureNodeType.INT, Operation.ADD); // s1.addChild(s1d1); // s1.addChild(s1d2); // path.addNode(s1); // // return path; // } // // public ExecutionPath noDoWhile(){ // /* int i = 0; // int x = 20; // do { // x = x - i; // i = i + 1; // } while (i > 5); // */ // // ExecutionPath path = new ExecutionPath(); // // DataStructureNode d1 = new DataStructureNode(null, DataStructureNodeType.INT, Operation.NONE); // path.addNode(d1); // DataStructureNode d2 = new DataStructureNode(null, DataStructureNodeType.INT, Operation.NONE); // path.addNode(d2); // // ScopeNode s1 = new ScopeNode(null, 1); // s1.setType(ScopeNodeType.DOWHILE); // DataStructureNode s1d1 = new DataStructureNode(s1, DataStructureNodeType.INT, Operation.SUBTRACT); // DataStructureNode s1d2 = new DataStructureNode(s1, DataStructureNodeType.INT, Operation.ADD); // s1.addChild(s1d1); // s1.addChild(s1d2); // path.addNode(s1); // // return path; // } // // public ExecutionPath forAddition(){ // /* int x = 1; // for (int i = 0; i < 5; i++) { // x = x + i; // } // */ // // ExecutionPath path = new ExecutionPath(); // // DataStructureNode d1 = new DataStructureNode(null, DataStructureNodeType.INT, Operation.NONE); // path.addNode(d1); // // ScopeNode s1 = new ScopeNode(null, 5); // s1.setType(ScopeNodeType.FOR); // DataStructureNode s1d1 = new DataStructureNode(s1, DataStructureNodeType.INT, Operation.ADD); // s1.addChild(s1d1); // path.addNode(s1); // // return path; // } // // public ExecutionPath forMultiplication(){ // /* byte x = 1; // for(int i = 0; i < 5; i++) { // x = (byte ) (x * 2); // } // */ // // ExecutionPath path = new ExecutionPath(); // // DataStructureNode d1 = new DataStructureNode(null, DataStructureNodeType.BYTE, Operation.NONE); // path.addNode(d1); // // ScopeNode s1 = new ScopeNode(null, 5); // s1.setType(ScopeNodeType.FOR); // DataStructureNode s1d1 = new DataStructureNode(s1, DataStructureNodeType.BYTE, Operation.MULTIPLY); // s1.addChild(s1d1); // path.addNode(s1); // // return path; // } // // public ExecutionPath forSubtraction(){ // /* double x = 20; // for (int i = 0; i < 5; i++) { // x = x - i; // } // */ // // ExecutionPath path = new ExecutionPath(); // // DataStructureNode d1 = new DataStructureNode(null, DataStructureNodeType.DOUBLE, Operation.NONE); // path.addNode(d1); // // ScopeNode s1 = new ScopeNode(null, 5); // s1.setType(ScopeNodeType.FOR); // DataStructureNode s1d1 = new DataStructureNode(s1, DataStructureNodeType.DOUBLE, Operation.SUBTRACT); // s1.addChild(s1d1); // path.addNode(s1); // // return path; // } // // public ExecutionPath noFor(){ // /* int x = 20; // for (int i = 0; i > 5; i++) { // x = x - i; // } // */ // // ExecutionPath path = new ExecutionPath(); // // DataStructureNode d1 = new DataStructureNode(null, DataStructureNodeType.INT, Operation.NONE); // path.addNode(d1); // // ScopeNode s1 = new ScopeNode(null, 0); // s1.setType(ScopeNodeType.FOR); // path.addNode(s1); // // return path; // } // // public ExecutionPath noStructure(){ // /* int x = 1; // x = x + 0; // x = x + 1; // x = x + 2; // x = x + 3; // x = x + 4; // */ // // ExecutionPath path = new ExecutionPath(); // // DataStructureNode d1 = new DataStructureNode(null, DataStructureNodeType.INT, Operation.NONE); // path.addNode(d1); // DataStructureNode d2 = new DataStructureNode(null, DataStructureNodeType.INT, Operation.ADD); // path.addNode(d2); // DataStructureNode d3 = new DataStructureNode(null, DataStructureNodeType.INT, Operation.ADD); // path.addNode(d3); // DataStructureNode d4 = new DataStructureNode(null, DataStructureNodeType.INT, Operation.ADD); // path.addNode(d4); // DataStructureNode d5 = new DataStructureNode(null, DataStructureNodeType.INT, Operation.ADD); // path.addNode(d5); // DataStructureNode d6 = new DataStructureNode(null, DataStructureNodeType.INT, Operation.ADD); // path.addNode(d6); // // return path; // } } package org.springblade.modules.task.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import org.apache.poi.ss.formula.functions.T; import java.util.List; import java.util.Map; public interface MyMapper extends BaseMapper { List> getTaskInfo(@Param("taskId") String taskId, @Param("tableName") String tableName); void createTable(String sql); List> fetchFileData(@Param("tableName") String tableName, @Param("attachId") String attachId, @Param("limit") Long limit); Long getDataTotal(String tableName, String attachId); @Select("select column_name, column_comment from information_schema.columns where table_name='mannual_test'") List> getTableColumns(@Param("tableName") String tableName); } /* * Copyright (c) 2018, * All rights reserved. * * Licensed under: Creative Commons Attribution-NonCommercial 4.0 International Public License * See LICENSE.TXT included with this code to read the full license agreement. * 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 PolyGlot; import java.awt.Font; import java.awt.GraphicsEnvironment; import java.io.IOException; import java.io.InputStream; import javax.imageio.ImageIO; import org.junit.Test; import static org.junit.Assert.*; /** * * @author */ public class InternalResourcesTest { @Test public void testImageResources() { String problemFiles = ""; String[] testImagePaths = { "/PolyGlot/ImageAssets/add_button.png", "/PolyGlot/ImageAssets/delete_button.png", "/PolyGlot/ImageAssets/add_button_pressed.png", "/PolyGlot/ImageAssets/delete_button_pressed.png", "/PolyGlot/ImageAssets/EmptyImage.png", "/PolyGlot/ImageAssets/IPA_Vowels.png", "/PolyGlot/ImageAssets/not-found.png", "/PolyGlot/ImageAssets/recording_ON_BIG.png", "/PolyGlot/ImageAssets/IPA_NonPulmonicConsonants.png", "/PolyGlot/ImageAssets/play_OFF_BIG.png", "/PolyGlot/ImageAssets/PolyGlot About.png", "/PolyGlot/ImageAssets/treeNode.png", "/PolyGlot/ImageAssets/IPA_Other.png", "/PolyGlot/ImageAssets/PolyGlotBG.png", "/PolyGlot/ImageAssets/play_ON_BIG.png", "/PolyGlot/ImageAssets/IPA_Pulmonic_Consonants.png", "/PolyGlot/ImageAssets/n0rara_draque.png", "/PolyGlot/ImageAssets/recording_OFF_BIG.png", PGTUtil.emptyLogoImage, PGTUtil.IPAOtherSounds, PGTUtil.treeNodeImage, PGTUtil.notFoundImage}; for (String imageFile : testImagePaths) { try { ImageIO.read(getClass().getResource(PGTUtil.notFoundImage)); } catch (IOException e) { problemFiles += imageFile + ", "; } } assertTrue("Problem with image files: " + problemFiles, problemFiles.isEmpty()); } @Test public void testFontResources() { String problemFiles = ""; String[] fontFileLocations = {PGTUtil.LCDFontLocation, PGTUtil.UnicodeFontLocation, PGTUtil.UnicodeFontBoldLocation, PGTUtil.UnicodeFontItalicLocation, PGTUtil.UnicodeFontBoldItalicLocation, PGTUtil.ButtonFontLocation}; for (String fontFileLocation : fontFileLocations) { try (InputStream tmp = this.getClass().getResourceAsStream(fontFileLocation)) { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); Font.createFont(Font.TRUETYPE_FONT, tmp); } catch (Exception e) { problemFiles += fontFileLocation + ", "; } } assertTrue("Problem with font files: " + problemFiles, problemFiles.isEmpty()); } } package com.company.View; import com.company.Model.Model; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.*; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.JTextField; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import java.lang.Integer; /** * Created by bartek_w on 2015-06-06. */ public class AktualizacjaOfert extends JFrame{ private JButton Aktualizuj; private JComboBox comboBox1; private JTextArea Wymagania; private JTextArea Obowiazki; private JTextField Wynagrodzenie; private JTextField MiejscePracy; private JTextField Stanowisko; private JPanel MainPane; String dane; private static Connection ActualConnection; private static String user_login; public AktualizacjaOfert(){ setContentPane(MainPane); setMinimumSize(new Dimension(500,500)); WczytajOferty(); Aktualizuj.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Aktualizuj")) { AktualizujDane(); } } }); } public static void Prep(String login, Connection con){ user_login = login; ActualConnection = con; } public void WczytajOferty(){ int user_id=0; try { System.out.println("Wczytuje oferty..."); ResultSet rs = null; String sql_query; PreparedStatement prepStmt; sql_query = "SELECT id_oferty FROM oferta_pracy"; prepStmt = ActualConnection.prepareStatement(sql_query); rs = prepStmt.executeQuery(); JComboBox comboBox1 = new JComboBox(); while(rs.next()) { dane=rs.getString(1); comboBox1.addItem(dane); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(Model.class.getName()); lgr.log(Level.SEVERE, ex.getMessage(), ex); } } public ResultSet AktualizujDane(){ if(Wymagania.getText() != "") { int user_id=0; try { System.out.println("Aktualizuje wymagania..."); ResultSet rs = null; String sql_query; PreparedStatement prepStmt; sql_query = "UPDATE wymaganie SET nazwa_wymagania="+Wymagania.getText()+" FROM wiersz_wymagan, oferta_pracy WHERE wiersz_wymagan.id_wymagania=wymaganie.id_wymagania AND wiersz_wymagan.id_oferty=oferta_pracy.id_oferty AND oferta_pracy.id_oferty="+Integer.parseInt(comboBox1.getSelectedItem().toString()); prepStmt = ActualConnection.prepareStatement(sql_query); prepStmt.setInt(1, user_id); rs = prepStmt.executeQuery(); return rs; } catch (SQLException ex) { Logger lgr = Logger.getLogger(Model.class.getName()); lgr.log(Level.SEVERE, ex.getMessage(), ex); } } if(Obowiazki.getText() != "") { int user_id=0; try { System.out.println("Aktualizuje obowiazki..."); ResultSet rs = null; String sql_query; PreparedStatement prepStmt; sql_query = "UPDATE obowiazki SET nazwa_obowiazku="+Obowiazki.getText()+" FROM wiersz_obowiazki, oferta_pracy WHERE wiersz_obowiazki.id_obowiazki=obowiazki.id_obowiazki AND wiersz_obowiazki.id_oferty=oferta_pracy.id_oferty AND oferta_pracy.id_oferty="+Integer.parseInt(comboBox1.getSelectedItem().toString()); prepStmt = ActualConnection.prepareStatement(sql_query); prepStmt.setInt(1, user_id); rs = prepStmt.executeQuery(); return rs; } catch (SQLException ex) { Logger lgr = Logger.getLogger(Model.class.getName()); lgr.log(Level.SEVERE, ex.getMessage(), ex); } } if(Wynagrodzenie.getText() != "") { int user_id=0; try { System.out.println("Aktualizuje wynagrodzenie..."); ResultSet rs = null; String sql_query; PreparedStatement prepStmt; sql_query = "UPDATE wynagrodzenie SET Wynagodzenie="+Wynagrodzenie.getText()+" FROM Wynagrodzenie, oferta_pracy WHERE wynagrodzenie.Wynagrodzenie=wynagrodzenie.Wynagrodzenie AND Wynagrodzenie.id_oferty=oferta_pracy.id_oferty AND oferta_pracy.id_oferty="+Integer.parseInt(comboBox1.getSelectedItem().toString()); prepStmt = ActualConnection.prepareStatement(sql_query); prepStmt.setInt(1, user_id); rs = prepStmt.executeQuery(); return rs; } catch (SQLException ex) { Logger lgr = Logger.getLogger(Model.class.getName()); lgr.log(Level.SEVERE, ex.getMessage(), ex); } } if(Stanowisko.getText() != "") { int user_id=0; try { System.out.println("Aktualizuje stanowisko..."); ResultSet rs = null; String sql_query; PreparedStatement prepStmt; sql_query = "UPDATE stanowisko SET nazwa_stanowiska="+Stanowisko.getText()+" FROM stanowisko, oferta_pracy WHERE stanowisko.id_stanowisko=stnowisko.id_stanowisko AND stanowisko.id_stanowisko=oferta_pracy.id_oferty AND oferta_pracy.id_oferty="+Integer.parseInt(comboBox1.getSelectedItem().toString()); prepStmt = ActualConnection.prepareStatement(sql_query); prepStmt.setInt(1, user_id); rs = prepStmt.executeQuery(); return rs; } catch (SQLException ex) { Logger lgr = Logger.getLogger(Model.class.getName()); lgr.log(Level.SEVERE, ex.getMessage(), ex); } } return null; } } 10-100 package com.bytecompute.tankms; import com.bytecompute.tankms.messaging.TopicMessageHandlerBeanPostProcessor; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Role; /** * Created by Longer on 2016/12/1. */ @Configurable public class TankMessageServiceBootstrapConfiguration { @SuppressWarnings("rawtypes") @Bean(name = TankMessageServiceConfigUtils.TOPIC_HANDLER_ANNOTATION_PROCESSOR_BEAN_NAME) @Role(BeanDefinition.ROLE_INFRASTRUCTURE) public TopicMessageHandlerBeanPostProcessor topicHandlerAnnotationProcessor() { return new TopicMessageHandlerBeanPostProcessor(); } } Peer/src/FileRestore.java import java.util.ArrayList; import java.util.List; /** * Created by andremachado on 29/03/2018. */ public class FileRestore { private String fileId; private String version; private String fileName; private List chunks; public FileRestore(String fileId, String version, String fileName){ this.fileId = fileId; this.version = version; this.fileName = fileName; chunks = new ArrayList(); } public void Add(GetChunkMessage rm){ } } src/test/java/com/roylaurie/subcomm/test/DataGenerator.java package com.roylaurie.subcomm.test; import java.math.BigInteger; import java.security.SecureRandom; public final class DataGenerator { private static final SecureRandom mRandom = new SecureRandom(); /** * Makes random 32-character dummy data. * @return String */ public static String generate() { return new BigInteger(130, mRandom).toString(32); } } Planmodeller/src/de.uni_kassel.cn.planDesigner.utility.ui/src/de/uni_kassel/cn/planDesigner/utility/ui/tree/nodes/MPlanTreeNode.java0 // Copyright 2009 Distributed Systems Group, University of Kassel // This program is distributed under the GNU Lesser General Public License (LGPL). // // This file is part of the Carpe Noctem Software Framework. // // The Carpe Noctem Software Framework is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The Carpe Noctem Software Framework 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. /** * */ package de.uni_kassel.cn.planDesigner.utility.ui.tree.nodes; import java.util.List; import org.eclipse.emf.common.command.CommandStack; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.transaction.RunnableWithResult; import de.uni_kassel.cn.alica.AbstractPlan; import de.uni_kassel.cn.alica.Utility; import de.uni_kassel.cn.alica.UtilityMode; import de.uni_kassel.cn.alica.UtilityModeExpression; import de.uni_kassel.cn.alica.UtilityReference; import de.uni_kassel.cn.planDesigner.ui.edit.PMLTransactionalEditingDomain; import de.uni_kassel.cn.planDesigner.ui.properties.EditController; import de.uni_kassel.cn.planDesigner.utility.ui.tree.nodes.AbstractEMFTreeNode; import de.uni_kassel.cn.planDesigner.utility.ui.tree.nodes.MUtilityTreeNode; /** * @author till * */ public class MPlanTreeNode extends AbstractEMFTreeNode { public MPlanTreeNode(PMLTransactionalEditingDomain editingDomain, CommandStack stack, EditController editController, ITreeNode parent, EObject modelObject) { super(editingDomain, stack, editController, parent, modelObject); } @Override protected String doGetName() { return ((AbstractPlan) getData()).getName(); } @Override public boolean hasChildren() { boolean result = true; try { result = (Boolean) getEditingDomain().runExclusive(new RunnableWithResult.Impl() { public void run() { setResult(!((AbstractPlan) getData()).getUtilities().isEmpty()); } }); } catch (InterruptedException e) { e.printStackTrace(); } return result; } @SuppressWarnings("unchecked") @Override protected void createChildren(List children) { EList urs = null; try { urs = (EList)getEditingDomain().runExclusive(new RunnableWithResult.Impl>() { public void run() { setResult(((AbstractPlan) getData()).getUtilities()); } }); } catch (InterruptedException e) { e.printStackTrace(); } // Add the editController to each UtilityReference, // Utility, UtilityMode and Utility IDTasks // thus making it listen to model changes for (UtilityReference ur : urs) { Utility u = ur.getUtility(); getEditController().addToObject(ur); getEditController().addToObject(u); for (UtilityMode um : u.getModes()) { getEditController().addToObject(um); for (UtilityModeExpression idt : um.getExpression()) { getEditController().addToObject(idt); } } children.add(new MUtilityTreeNode(getEditingDomain(), getCommandStack(), getEditController(), this, ur)); } } } AlexRogalskiy/java4you package com.sensiblemetrics.api.alpenidos.pattern.bridge.model; import com.sensiblemetrics.api.alpenidos.pattern.bridge.iface.Color; public class Blue implements Color { @Override public String fill() { return "Color is Blue"; } } sho25/hbase begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/** * 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. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|regionserver package|; end_package begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|assertEquals import|; end_import begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|assertTrue import|; end_import begin_import import|import name|java operator|. name|io operator|. name|IOException import|; end_import begin_import import|import name|java operator|. name|util operator|. name|ArrayList import|; end_import begin_import import|import name|java operator|. name|util operator|. name|List import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Optional import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|conf operator|. name|Configuration import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|ArrayBackedTag import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|Cell import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|CellScanner import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|CellUtil import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|HBaseClassTestRule import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|HBaseTestingUtility import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|HConstants import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|KeyValue import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|KeyValueUtil import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|PrivateCellUtil import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|TableName import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|Tag import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|client operator|. name|Admin import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|client operator|. name|Append import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|client operator|. name|ColumnFamilyDescriptorBuilder import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|client operator|. name|CompactionState import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|client operator|. name|Durability import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|client operator|. name|Increment import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|client operator|. name|Mutation import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|client operator|. name|Put import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|client operator|. name|Result import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|client operator|. name|ResultScanner import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|client operator|. name|Scan import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|client operator|. name|Table import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|client operator|. name|TableDescriptorBuilder import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|coprocessor operator|. name|CoprocessorHost import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|coprocessor operator|. name|ObserverContext import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|coprocessor operator|. name|RegionCoprocessor import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|coprocessor operator|. name|RegionCoprocessorEnvironment import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|coprocessor operator|. name|RegionObserver import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|io operator|. name|encoding operator|. name|DataBlockEncoding import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|testclassification operator|. name|MediumTests import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|testclassification operator|. name|RegionServerTests import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|util operator|. name|Bytes import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|wal operator|. name|WALEdit import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|After import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|AfterClass import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|BeforeClass import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|ClassRule import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Rule import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Test import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|experimental operator|. name|categories operator|. name|Category import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|rules operator|. name|TestName import|; end_import begin_comment comment|/** * Class that test tags */ end_comment begin_class annotation|@ name|Category argument_list|( block|{ name|RegionServerTests operator|. name|class block|, name|MediumTests operator|. name|class block|} argument_list|) specifier|public class|class name|TestTags block|{ annotation|@ name|ClassRule specifier|public specifier|static specifier|final name|HBaseClassTestRule name|CLASS_RULE init|= name|HBaseClassTestRule operator|. name|forClass argument_list|( name|TestTags operator|. name|class argument_list|) decl_stmt|; specifier|static name|boolean name|useFilter init|= literal|false decl_stmt|; specifier|private specifier|final specifier|static name|HBaseTestingUtility name|TEST_UTIL init|= operator|new name|HBaseTestingUtility argument_list|() decl_stmt|; annotation|@ name|Rule specifier|public specifier|final name|TestName name|TEST_NAME init|= operator|new name|TestName argument_list|() decl_stmt|; annotation|@ name|BeforeClass specifier|public specifier|static name|void name|setUpBeforeClass parameter_list|() throws|throws name|Exception block|{ name|Configuration name|conf init|= name|TEST_UTIL operator|. name|getConfiguration argument_list|() decl_stmt|; name|conf operator|. name|setInt argument_list|( literal|"hfile.format.version" argument_list|, literal|3 argument_list|) expr_stmt|; name|conf operator|. name|setStrings argument_list|( name|CoprocessorHost operator|. name|USER_REGION_COPROCESSOR_CONF_KEY argument_list|, name|TestCoprocessorForTags operator|. name|class operator|. name|getName argument_list|() argument_list|) expr_stmt|; name|TEST_UTIL operator|. name|startMiniCluster argument_list|( literal|2 argument_list|) expr_stmt|; block|} annotation|@ name|AfterClass specifier|public specifier|static name|void name|tearDownAfterClass parameter_list|() throws|throws name|Exception block|{ name|TEST_UTIL operator|. name|shutdownMiniCluster argument_list|() expr_stmt|; block|} annotation|@ name|After specifier|public name|void name|tearDown parameter_list|() block|{ name|useFilter operator|= literal|false expr_stmt|; block|} annotation|@ name|Test specifier|public name|void name|testTags parameter_list|() throws|throws name|Exception block|{ name|Table name|table init|= literal|null decl_stmt|; try|try block|{ name|TableName name|tableName init|= name|TableName operator|. name|valueOf argument_list|( name|TEST_NAME operator|. name|getMethodName argument_list|() argument_list|) decl_stmt|; name|byte index|[] name|fam init|= name|Bytes operator|. name|toBytes argument_list|( literal|"info" argument_list|) decl_stmt|; name|byte index|[] name|row init|= name|Bytes operator|. name|toBytes argument_list|( literal|"rowa" argument_list|) decl_stmt|; comment|// column names name|byte index|[] name|qual init|= name|Bytes operator|. name|toBytes argument_list|( literal|"qual" argument_list|) decl_stmt|; name|byte index|[] name|row1 init|= name|Bytes operator|. name|toBytes argument_list|( literal|"rowb" argument_list|) decl_stmt|; name|byte index|[] name|row2 init|= name|Bytes operator|. name|toBytes argument_list|( literal|"rowc" argument_list|) decl_stmt|; name|TableDescriptorBuilder operator|. name|ModifyableTableDescriptor name|tableDescriptor init|= operator|new name|TableDescriptorBuilder operator|. name|ModifyableTableDescriptor argument_list|( name|tableName argument_list|) decl_stmt|; name|ColumnFamilyDescriptorBuilder operator|. name|ModifyableColumnFamilyDescriptor name|familyDescriptor init|= operator|new name|ColumnFamilyDescriptorBuilder operator|. name|ModifyableColumnFamilyDescriptor argument_list|( name|fam argument_list|) decl_stmt|; name|familyDescriptor operator|. name|setBlockCacheEnabled argument_list|( literal|true argument_list|) expr_stmt|; name|familyDescriptor operator|. name|setDataBlockEncoding argument_list|( name|DataBlockEncoding operator|. name|NONE argument_list|) expr_stmt|; name|tableDescriptor operator|. name|setColumnFamily argument_list|( name|familyDescriptor argument_list|) expr_stmt|; name|Admin name|admin init|= name|TEST_UTIL operator|. name|getAdmin argument_list|() decl_stmt|; name|admin operator|. name|createTable argument_list|( name|tableDescriptor argument_list|) expr_stmt|; name|byte index|[] name|value init|= name|Bytes operator|. name|toBytes argument_list|( literal|"value" argument_list|) decl_stmt|; name|table operator|= name|TEST_UTIL operator|. name|getConnection argument_list|() operator|. name|getTable argument_list|( name|tableName argument_list|) expr_stmt|; name|Put name|put init|= operator|new name|Put argument_list|( name|row argument_list|) decl_stmt|; name|put operator|. name|addColumn argument_list|( name|fam argument_list|, name|qual argument_list|, name|HConstants operator|. name|LATEST_TIMESTAMP argument_list|, name|value argument_list|) expr_stmt|; name|put operator|. name|setAttribute argument_list|( literal|"visibility" argument_list|, name|Bytes operator|. name|toBytes argument_list|( literal|"myTag" argument_list|) argument_list|) expr_stmt|; name|table operator|. name|put argument_list|( name|put argument_list|) expr_stmt|; name|admin operator|. name|flush argument_list|( name|tableName argument_list|) expr_stmt|; comment|// We are lacking an API for confirming flush request compaction. comment|// Just sleep for a short time. We won't be able to confirm flush comment|// completion but the test won't hang now or in the future if comment|// default compaction policy causes compaction between flush and comment|// when we go to confirm it. name|Thread operator|. name|sleep argument_list|( literal|1000 argument_list|) expr_stmt|; name|Put name|put1 init|= operator|new name|Put argument_list|( name|row1 argument_list|) decl_stmt|; name|byte index|[] name|value1 init|= name|Bytes operator|. name|toBytes argument_list|( literal|"1000dfsdf" argument_list|) decl_stmt|; name|put1 operator|. name|addColumn argument_list|( name|fam argument_list|, name|qual argument_list|, name|HConstants operator|. name|LATEST_TIMESTAMP argument_list|, name|value1 argument_list|) expr_stmt|; comment|// put1.setAttribute("visibility", Bytes.toBytes("myTag3")); name|table operator|. name|put argument_list|( name|put1 argument_list|) expr_stmt|; name|admin operator|. name|flush argument_list|( name|tableName argument_list|) expr_stmt|; name|Thread operator|. name|sleep argument_list|( literal|1000 argument_list|) expr_stmt|; name|Put name|put2 init|= operator|new name|Put argument_list|( name|row2 argument_list|) decl_stmt|; name|byte index|[] name|value2 init|= name|Bytes operator|. name|toBytes argument_list|( literal|"1000dfsdf" argument_list|) decl_stmt|; name|put2 operator|. name|addColumn argument_list|( name|fam argument_list|, name|qual argument_list|, name|HConstants operator|. name|LATEST_TIMESTAMP argument_list|, name|value2 argument_list|) expr_stmt|; name|put2 operator|. name|setAttribute argument_list|( literal|"visibility" argument_list|, name|Bytes operator|. name|toBytes argument_list|( literal|"myTag3" argument_list|) argument_list|) expr_stmt|; name|table operator|. name|put argument_list|( name|put2 argument_list|) expr_stmt|; name|admin operator|. name|flush argument_list|( name|tableName argument_list|) expr_stmt|; name|Thread operator|. name|sleep argument_list|( literal|1000 argument_list|) expr_stmt|; name|result argument_list|( name|fam argument_list|, name|row argument_list|, name|qual argument_list|, name|row2 argument_list|, name|table argument_list|, name|value argument_list|, name|value2 argument_list|, name|row1 argument_list|, name|value1 argument_list|) expr_stmt|; name|admin operator|. name|compact argument_list|( name|tableName argument_list|) expr_stmt|; while|while condition|( name|admin operator|. name|getCompactionState argument_list|( name|tableName argument_list|) operator|!= name|CompactionState operator|. name|NONE condition|) block|{ name|Thread operator|. name|sleep argument_list|( literal|10 argument_list|) expr_stmt|; block|} name|result argument_list|( name|fam argument_list|, name|row argument_list|, name|qual argument_list|, name|row2 argument_list|, name|table argument_list|, name|value argument_list|, name|value2 argument_list|, name|row1 argument_list|, name|value1 argument_list|) expr_stmt|; block|} finally|finally block|{ if|if condition|( name|table operator|!= literal|null condition|) block|{ name|table operator|. name|close argument_list|() expr_stmt|; block|} block|} block|} annotation|@ name|Test specifier|public name|void name|testFlushAndCompactionWithoutTags parameter_list|() throws|throws name|Exception block|{ name|Table name|table init|= literal|null decl_stmt|; try|try block|{ name|TableName name|tableName init|= name|TableName operator|. name|valueOf argument_list|( name|TEST_NAME operator|. name|getMethodName argument_list|() argument_list|) decl_stmt|; name|byte index|[] name|fam init|= name|Bytes operator|. name|toBytes argument_list|( literal|"info" argument_list|) decl_stmt|; name|byte index|[] name|row init|= name|Bytes operator|. name|toBytes argument_list|( literal|"rowa" argument_list|) decl_stmt|; comment|// column names name|byte index|[] name|qual init|= name|Bytes operator|. name|toBytes argument_list|( literal|"qual" argument_list|) decl_stmt|; name|byte index|[] name|row1 init|= name|Bytes operator|. name|toBytes argument_list|( literal|"rowb" argument_list|) decl_stmt|; name|byte index|[] name|row2 init|= name|Bytes operator|. name|toBytes argument_list|( literal|"rowc" argument_list|) decl_stmt|; name|TableDescriptorBuilder operator|. name|ModifyableTableDescriptor name|tableDescriptor init|= operator|new name|TableDescriptorBuilder operator|. name|ModifyableTableDescriptor argument_list|( name|tableName argument_list|) decl_stmt|; name|ColumnFamilyDescriptorBuilder operator|. name|ModifyableColumnFamilyDescriptor name|familyDescriptor init|= operator|new name|ColumnFamilyDescriptorBuilder operator|. name|ModifyableColumnFamilyDescriptor argument_list|( name|fam argument_list|) decl_stmt|; name|familyDescriptor operator|. name|setBlockCacheEnabled argument_list|( literal|true argument_list|) expr_stmt|; name|tableDescriptor operator|. name|setColumnFamily argument_list|( name|familyDescriptor argument_list|) expr_stmt|; name|Admin name|admin init|= name|TEST_UTIL operator|. name|getAdmin argument_list|() decl_stmt|; name|admin operator|. name|createTable argument_list|( name|tableDescriptor argument_list|) expr_stmt|; name|table operator|= name|TEST_UTIL operator|. name|getConnection argument_list|() operator|. name|getTable argument_list|( name|tableName argument_list|) expr_stmt|; name|Put name|put init|= operator|new name|Put argument_list|( name|row argument_list|) decl_stmt|; name|byte index|[] name|value init|= name|Bytes operator|. name|toBytes argument_list|( literal|"value" argument_list|) decl_stmt|; name|put operator|. name|addColumn argument_list|( name|fam argument_list|, name|qual argument_list|, name|HConstants operator|. name|LATEST_TIMESTAMP argument_list|, name|value argument_list|) expr_stmt|; name|table operator|. name|put argument_list|( name|put argument_list|) expr_stmt|; name|admin operator|. name|flush argument_list|( name|tableName argument_list|) expr_stmt|; comment|// We are lacking an API for confirming flush request compaction. comment|// Just sleep for a short time. We won't be able to confirm flush comment|// completion but the test won't hang now or in the future if comment|// default compaction policy causes compaction between flush and comment|// when we go to confirm it. name|Thread operator|. name|sleep argument_list|( literal|1000 argument_list|) expr_stmt|; name|Put name|put1 init|= operator|new name|Put argument_list|( name|row1 argument_list|) decl_stmt|; name|byte index|[] name|value1 init|= name|Bytes operator|. name|toBytes argument_list|( literal|"1000dfsdf" argument_list|) decl_stmt|; name|put1 operator|. name|addColumn argument_list|( name|fam argument_list|, name|qual argument_list|, name|HConstants operator|. name|LATEST_TIMESTAMP argument_list|, name|value1 argument_list|) expr_stmt|; name|table operator|. name|put argument_list|( name|put1 argument_list|) expr_stmt|; name|admin operator|. name|flush argument_list|( name|tableName argument_list|) expr_stmt|; name|Thread operator|. name|sleep argument_list|( literal|1000 argument_list|) expr_stmt|; name|Put name|put2 init|= operator|new name|Put argument_list|( name|row2 argument_list|) decl_stmt|; name|byte index|[] name|value2 init|= name|Bytes operator|. name|toBytes argument_list|( literal|"1000dfsdf" argument_list|) decl_stmt|; name|put2 operator|. name|addColumn argument_list|( name|fam argument_list|, name|qual argument_list|, name|HConstants operator|. name|LATEST_TIMESTAMP argument_list|, name|value2 argument_list|) expr_stmt|; name|table operator|. name|put argument_list|( name|put2 argument_list|) expr_stmt|; name|admin operator|. name|flush argument_list|( name|tableName argument_list|) expr_stmt|; name|Thread operator|. name|sleep argument_list|( literal|1000 argument_list|) expr_stmt|; name|Scan name|s init|= operator|new name|Scan argument_list|( name|row argument_list|) decl_stmt|; name|ResultScanner name|scanner init|= name|table operator|. name|getScanner argument_list|( name|s argument_list|) decl_stmt|; try|try block|{ name|Result index|[] name|next init|= name|scanner operator|. name|next argument_list|( literal|3 argument_list|) decl_stmt|; for|for control|( name|Result name|result range|: name|next control|) block|{ name|CellScanner name|cellScanner init|= name|result operator|. name|cellScanner argument_list|() decl_stmt|; name|cellScanner operator|. name|advance argument_list|() expr_stmt|; name|Cell name|current init|= name|cellScanner operator|. name|current argument_list|() decl_stmt|; name|assertEquals argument_list|( literal|0 argument_list|, name|current operator|. name|getTagsLength argument_list|() argument_list|) expr_stmt|; block|} block|} finally|finally block|{ if|if condition|( name|scanner operator|!= literal|null condition|) name|scanner operator|. name|close argument_list|() expr_stmt|; block|} name|admin operator|. name|compact argument_list|( name|tableName argument_list|) expr_stmt|; while|while condition|( name|admin operator|. name|getCompactionState argument_list|( name|tableName argument_list|) operator|!= name|CompactionState operator|. name|NONE condition|) block|{ name|Thread operator|. name|sleep argument_list|( literal|10 argument_list|) expr_stmt|; block|} name|s operator|= operator|new name|Scan argument_list|( name|row argument_list|) expr_stmt|; name|scanner operator|= name|table operator|. name|getScanner argument_list|( name|s argument_list|) expr_stmt|; try|try block|{ name|Result index|[] name|next init|= name|scanner operator|. name|next argument_list|( literal|3 argument_list|) decl_stmt|; for|for control|( name|Result name|result range|: name|next control|) block|{ name|CellScanner name|cellScanner init|= name|result operator|. name|cellScanner argument_list|() decl_stmt|; name|cellScanner operator|. name|advance argument_list|() expr_stmt|; name|Cell name|current init|= name|cellScanner operator|. name|current argument_list|() decl_stmt|; name|assertEquals argument_list|( literal|0 argument_list|, name|current operator|. name|getTagsLength argument_list|() argument_list|) expr_stmt|; block|} block|} finally|finally block|{ if|if condition|( name|scanner operator|!= literal|null condition|) block|{ name|scanner operator|. name|close argument_list|() expr_stmt|; block|} block|} block|} finally|finally block|{ if|if condition|( name|table operator|!= literal|null condition|) block|{ name|table operator|. name|close argument_list|() expr_stmt|; block|} block|} block|} annotation|@ name|Test specifier|public name|void name|testFlushAndCompactionwithCombinations parameter_list|() throws|throws name|Exception block|{ name|TableName name|tableName init|= name|TableName operator|. name|valueOf argument_list|( name|TEST_NAME operator|. name|getMethodName argument_list|() argument_list|) decl_stmt|; name|byte index|[] name|fam init|= name|Bytes operator|. name|toBytes argument_list|( literal|"info" argument_list|) decl_stmt|; name|byte index|[] name|row init|= name|Bytes operator|. name|toBytes argument_list|( literal|"rowa" argument_list|) decl_stmt|; comment|// column names name|byte index|[] name|qual init|= name|Bytes operator|. name|toBytes argument_list|( literal|"qual" argument_list|) decl_stmt|; name|byte index|[] name|row1 init|= name|Bytes operator|. name|toBytes argument_list|( literal|"rowb" argument_list|) decl_stmt|; name|byte index|[] name|row2 init|= name|Bytes operator|. name|toBytes argument_list|( literal|"rowc" argument_list|) decl_stmt|; name|byte index|[] name|rowd init|= name|Bytes operator|. name|toBytes argument_list|( literal|"rowd" argument_list|) decl_stmt|; name|byte index|[] name|rowe init|= name|Bytes operator|. name|toBytes argument_list|( literal|"rowe" argument_list|) decl_stmt|; name|Table name|table init|= literal|null decl_stmt|; for|for control|( name|DataBlockEncoding name|encoding range|: name|DataBlockEncoding operator|. name|values argument_list|() control|) block|{ name|TableDescriptorBuilder operator|. name|ModifyableTableDescriptor name|tableDescriptor init|= operator|new name|TableDescriptorBuilder operator|. name|ModifyableTableDescriptor argument_list|( name|tableName argument_list|) decl_stmt|; name|ColumnFamilyDescriptorBuilder operator|. name|ModifyableColumnFamilyDescriptor name|familyDescriptor init|= operator|new name|ColumnFamilyDescriptorBuilder operator|. name|ModifyableColumnFamilyDescriptor argument_list|( name|fam argument_list|) decl_stmt|; name|familyDescriptor operator|. name|setBlockCacheEnabled argument_list|( literal|true argument_list|) expr_stmt|; name|familyDescriptor operator|. name|setDataBlockEncoding argument_list|( name|encoding argument_list|) expr_stmt|; name|tableDescriptor operator|. name|setColumnFamily argument_list|( name|familyDescriptor argument_list|) expr_stmt|; name|Admin name|admin init|= name|TEST_UTIL operator|. name|getAdmin argument_list|() decl_stmt|; name|admin operator|. name|createTable argument_list|( name|tableDescriptor argument_list|) expr_stmt|; try|try block|{ name|table operator|= name|TEST_UTIL operator|. name|getConnection argument_list|() operator|. name|getTable argument_list|( name|tableName argument_list|) expr_stmt|; name|Put name|put init|= operator|new name|Put argument_list|( name|row argument_list|) decl_stmt|; name|byte index|[] name|value init|= name|Bytes operator|. name|toBytes argument_list|( literal|"value" argument_list|) decl_stmt|; name|put operator|. name|addColumn argument_list|( name|fam argument_list|, name|qual argument_list|, name|HConstants operator|. name|LATEST_TIMESTAMP argument_list|, name|value argument_list|) expr_stmt|; name|int name|bigTagLen init|= name|Short operator|. name|MAX_VALUE operator|- literal|5 decl_stmt|; name|put operator|. name|setAttribute argument_list|( literal|"visibility" argument_list|, operator|new name|byte index|[ name|bigTagLen index|] argument_list|) expr_stmt|; name|table operator|. name|put argument_list|( name|put argument_list|) expr_stmt|; name|Put name|put1 init|= operator|new name|Put argument_list|( name|row1 argument_list|) decl_stmt|; name|byte index|[] name|value1 init|= name|Bytes operator|. name|toBytes argument_list|( literal|"1000dfsdf" argument_list|) decl_stmt|; name|put1 operator|. name|addColumn argument_list|( name|fam argument_list|, name|qual argument_list|, name|HConstants operator|. name|LATEST_TIMESTAMP argument_list|, name|value1 argument_list|) expr_stmt|; name|table operator|. name|put argument_list|( name|put1 argument_list|) expr_stmt|; name|admin operator|. name|flush argument_list|( name|tableName argument_list|) expr_stmt|; comment|// We are lacking an API for confirming flush request compaction. comment|// Just sleep for a short time. We won't be able to confirm flush comment|// completion but the test won't hang now or in the future if comment|// default compaction policy causes compaction between flush and comment|// when we go to confirm it. name|Thread operator|. name|sleep argument_list|( literal|1000 argument_list|) expr_stmt|; name|put1 operator|= operator|new name|Put argument_list|( name|row2 argument_list|) expr_stmt|; name|value1 operator|= name|Bytes operator|. name|toBytes argument_list|( literal|"1000dfsdf" argument_list|) expr_stmt|; name|put1 operator|. name|addColumn argument_list|( name|fam argument_list|, name|qual argument_list|, name|HConstants operator|. name|LATEST_TIMESTAMP argument_list|, name|value1 argument_list|) expr_stmt|; name|table operator|. name|put argument_list|( name|put1 argument_list|) expr_stmt|; name|admin operator|. name|flush argument_list|( name|tableName argument_list|) expr_stmt|; name|Thread operator|. name|sleep argument_list|( literal|1000 argument_list|) expr_stmt|; name|Put name|put2 init|= operator|new name|Put argument_list|( name|rowd argument_list|) decl_stmt|; name|byte index|[] name|value2 init|= name|Bytes operator|. name|toBytes argument_list|( literal|"1000dfsdf" argument_list|) decl_stmt|; name|put2 operator|. name|addColumn argument_list|( name|fam argument_list|, name|qual argument_list|, name|HConstants operator|. name|LATEST_TIMESTAMP argument_list|, name|value2 argument_list|) expr_stmt|; name|table operator|. name|put argument_list|( name|put2 argument_list|) expr_stmt|; name|put2 operator|= operator|new name|Put argument_list|( name|rowe argument_list|) expr_stmt|; name|value2 operator|= name|Bytes operator|. name|toBytes argument_list|( literal|"1000dfsddfdf" argument_list|) expr_stmt|; name|put2 operator|. name|addColumn argument_list|( name|fam argument_list|, name|qual argument_list|, name|HConstants operator|. name|LATEST_TIMESTAMP argument_list|, name|value2 argument_list|) expr_stmt|; name|put operator|. name|setAttribute argument_list|( literal|"visibility" argument_list|, name|Bytes operator|. name|toBytes argument_list|( literal|"ram" argument_list|) argument_list|) expr_stmt|; name|table operator|. name|put argument_list|( name|put2 argument_list|) expr_stmt|; name|admin operator|. name|flush argument_list|( name|tableName argument_list|) expr_stmt|; name|Thread operator|. name|sleep argument_list|( literal|1000 argument_list|) expr_stmt|; name|TestCoprocessorForTags operator|. name|checkTagPresence operator|= literal|true expr_stmt|; name|Scan name|s init|= operator|new name|Scan argument_list|( name|row argument_list|) decl_stmt|; name|s operator|. name|setCaching argument_list|( literal|1 argument_list|) expr_stmt|; name|ResultScanner name|scanner init|= name|table operator|. name|getScanner argument_list|( name|s argument_list|) decl_stmt|; try|try block|{ name|Result name|next init|= literal|null decl_stmt|; while|while condition|( operator|( name|next operator|= name|scanner operator|. name|next argument_list|() operator|) operator|!= literal|null condition|) block|{ name|CellScanner name|cellScanner init|= name|next operator|. name|cellScanner argument_list|() decl_stmt|; name|cellScanner operator|. name|advance argument_list|() expr_stmt|; name|Cell name|current init|= name|cellScanner operator|. name|current argument_list|() decl_stmt|; if|if condition|( name|CellUtil operator|. name|matchingRows argument_list|( name|current argument_list|, name|row argument_list|) condition|) block|{ name|assertEquals argument_list|( literal|1 argument_list|, name|TestCoprocessorForTags operator|. name|tags operator|. name|size argument_list|() argument_list|) expr_stmt|; name|Tag name|tag init|= name|TestCoprocessorForTags operator|. name|tags operator|. name|get argument_list|( literal|0 argument_list|) decl_stmt|; name|assertEquals argument_list|( name|bigTagLen argument_list|, name|tag operator|. name|getValueLength argument_list|() argument_list|) expr_stmt|; block|} else|else block|{ name|assertEquals argument_list|( literal|0 argument_list|, name|TestCoprocessorForTags operator|. name|tags operator|. name|size argument_list|() argument_list|) expr_stmt|; block|} block|} block|} finally|finally block|{ if|if condition|( name|scanner operator|!= literal|null condition|) block|{ name|scanner operator|. name|close argument_list|() expr_stmt|; block|} name|TestCoprocessorForTags operator|. name|checkTagPresence operator|= literal|false expr_stmt|; block|} while|while condition|( name|admin operator|. name|getCompactionState argument_list|( name|tableName argument_list|) operator|!= name|CompactionState operator|. name|NONE condition|) block|{ name|Thread operator|. name|sleep argument_list|( literal|10 argument_list|) expr_stmt|; block|} name|TestCoprocessorForTags operator|. name|checkTagPresence operator|= literal|true expr_stmt|; name|scanner operator|= name|table operator|. name|getScanner argument_list|( name|s argument_list|) expr_stmt|; try|try block|{ name|Result name|next init|= literal|null decl_stmt|; while|while condition|( operator|( name|next operator|= name|scanner operator|. name|next argument_list|() operator|) operator|!= literal|null condition|) block|{ name|CellScanner name|cellScanner init|= name|next operator|. name|cellScanner argument_list|() decl_stmt|; name|cellScanner operator|. name|advance argument_list|() expr_stmt|; name|Cell name|current init|= name|cellScanner operator|. name|current argument_list|() decl_stmt|; if|if condition|( name|CellUtil operator|. name|matchingRows argument_list|( name|current argument_list|, name|row argument_list|) condition|) block|{ name|assertEquals argument_list|( literal|1 argument_list|, name|TestCoprocessorForTags operator|. name|tags operator|. name|size argument_list|() argument_list|) expr_stmt|; name|Tag name|tag init|= name|TestCoprocessorForTags operator|. name|tags operator|. name|get argument_list|( literal|0 argument_list|) decl_stmt|; name|assertEquals argument_list|( name|bigTagLen argument_list|, name|tag operator|. name|getValueLength argument_list|() argument_list|) expr_stmt|; block|} else|else block|{ name|assertEquals argument_list|( literal|0 argument_list|, name|TestCoprocessorForTags operator|. name|tags operator|. name|size argument_list|() argument_list|) expr_stmt|; block|} block|} block|} finally|finally block|{ if|if condition|( name|scanner operator|!= literal|null condition|) block|{ name|scanner operator|. name|close argument_list|() expr_stmt|; block|} name|TestCoprocessorForTags operator|. name|checkTagPresence operator|= literal|false expr_stmt|; block|} block|} finally|finally block|{ if|if condition|( name|table operator|!= literal|null condition|) block|{ name|table operator|. name|close argument_list|() expr_stmt|; block|} comment|// delete the table name|admin operator|. name|disableTable argument_list|( name|tableName argument_list|) expr_stmt|; name|admin operator|. name|deleteTable argument_list|( name|tableName argument_list|) expr_stmt|; block|} block|} block|} annotation|@ name|Test specifier|public name|void name|testTagsWithAppendAndIncrement parameter_list|() throws|throws name|Exception block|{ name|TableName name|tableName init|= name|TableName operator|. name|valueOf argument_list|( name|TEST_NAME operator|. name|getMethodName argument_list|() argument_list|) decl_stmt|; name|byte index|[] name|f init|= name|Bytes operator|. name|toBytes argument_list|( literal|"f" argument_list|) decl_stmt|; name|byte index|[] name|q init|= name|Bytes operator|. name|toBytes argument_list|( literal|"q" argument_list|) decl_stmt|; name|byte index|[] name|row1 init|= name|Bytes operator|. name|toBytes argument_list|( literal|"r1" argument_list|) decl_stmt|; name|byte index|[] name|row2 init|= name|Bytes operator|. name|toBytes argument_list|( literal|"r2" argument_list|) decl_stmt|; name|TableDescriptorBuilder operator|. name|ModifyableTableDescriptor name|tableDescriptor init|= operator|new name|TableDescriptorBuilder operator|. name|ModifyableTableDescriptor argument_list|( name|tableName argument_list|) decl_stmt|; name|ColumnFamilyDescriptorBuilder operator|. name|ModifyableColumnFamilyDescriptor name|colDesc init|= operator|new name|ColumnFamilyDescriptorBuilder operator|. name|ModifyableColumnFamilyDescriptor argument_list|( name|f argument_list|) decl_stmt|; name|tableDescriptor operator|. name|setColumnFamily argument_list|( name|colDesc argument_list|) expr_stmt|; name|TEST_UTIL operator|. name|getAdmin argument_list|() operator|. name|createTable argument_list|( name|tableDescriptor argument_list|) expr_stmt|; name|Table name|table init|= literal|null decl_stmt|; try|try block|{ name|table operator|= name|TEST_UTIL operator|. name|getConnection argument_list|() operator|. name|getTable argument_list|( name|tableName argument_list|) expr_stmt|; name|Put name|put init|= operator|new name|Put argument_list|( name|row1 argument_list|) decl_stmt|; name|byte index|[] name|v init|= name|Bytes operator|. name|toBytes argument_list|( literal|2L argument_list|) decl_stmt|; name|put operator|. name|addColumn argument_list|( name|f argument_list|, name|q argument_list|, name|v argument_list|) expr_stmt|; name|put operator|. name|setAttribute argument_list|( literal|"visibility" argument_list|, name|Bytes operator|. name|toBytes argument_list|( literal|"tag1" argument_list|) argument_list|) expr_stmt|; name|table operator|. name|put argument_list|( name|put argument_list|) expr_stmt|; name|Increment name|increment init|= operator|new name|Increment argument_list|( name|row1 argument_list|) decl_stmt|; name|increment operator|. name|addColumn argument_list|( name|f argument_list|, name|q argument_list|, literal|1L argument_list|) expr_stmt|; name|table operator|. name|increment argument_list|( name|increment argument_list|) expr_stmt|; name|TestCoprocessorForTags operator|. name|checkTagPresence operator|= literal|true expr_stmt|; name|ResultScanner name|scanner init|= name|table operator|. name|getScanner argument_list|( operator|new name|Scan argument_list|() argument_list|) decl_stmt|; name|Result name|result init|= name|scanner operator|. name|next argument_list|() decl_stmt|; name|KeyValue name|kv init|= name|KeyValueUtil operator|. name|ensureKeyValue argument_list|( name|result operator|. name|getColumnLatestCell argument_list|( name|f argument_list|, name|q argument_list|) argument_list|) decl_stmt|; name|List argument_list|< name|Tag argument_list|> name|tags init|= name|TestCoprocessorForTags operator|. name|tags decl_stmt|; name|assertEquals argument_list|( literal|3L argument_list|, name|Bytes operator|. name|toLong argument_list|( name|kv operator|. name|getValueArray argument_list|() argument_list|, name|kv operator|. name|getValueOffset argument_list|() argument_list|, name|kv operator|. name|getValueLength argument_list|() argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|1 argument_list|, name|tags operator|. name|size argument_list|() argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"tag1" argument_list|, name|Bytes operator|. name|toString argument_list|( name|Tag operator|. name|cloneValue argument_list|( name|tags operator|. name|get argument_list|( literal|0 argument_list|) argument_list|) argument_list|) argument_list|) expr_stmt|; name|TestCoprocessorForTags operator|. name|checkTagPresence operator|= literal|false expr_stmt|; name|TestCoprocessorForTags operator|. name|tags operator|= literal|null expr_stmt|; name|increment operator|= operator|new name|Increment argument_list|( name|row1 argument_list|) expr_stmt|; name|increment operator|. name|add argument_list|( operator|new name|KeyValue argument_list|( name|row1 argument_list|, name|f argument_list|, name|q argument_list|, literal|1234L argument_list|, name|v argument_list|) argument_list|) expr_stmt|; name|increment operator|. name|setAttribute argument_list|( literal|"visibility" argument_list|, name|Bytes operator|. name|toBytes argument_list|( literal|"tag2" argument_list|) argument_list|) expr_stmt|; name|table operator|. name|increment argument_list|( name|increment argument_list|) expr_stmt|; name|TestCoprocessorForTags operator|. name|checkTagPresence operator|= literal|true expr_stmt|; name|scanner operator|= name|table operator|. name|getScanner argument_list|( operator|new name|Scan argument_list|() argument_list|) expr_stmt|; name|result operator|= name|scanner operator|. name|next argument_list|() expr_stmt|; name|kv operator|= name|KeyValueUtil operator|. name|ensureKeyValue argument_list|( name|result operator|. name|getColumnLatestCell argument_list|( name|f argument_list|, name|q argument_list|) argument_list|) expr_stmt|; name|tags operator|= name|TestCoprocessorForTags operator|. name|tags expr_stmt|; name|assertEquals argument_list|( literal|5L argument_list|, name|Bytes operator|. name|toLong argument_list|( name|kv operator|. name|getValueArray argument_list|() argument_list|, name|kv operator|. name|getValueOffset argument_list|() argument_list|, name|kv operator|. name|getValueLength argument_list|() argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|2 argument_list|, name|tags operator|. name|size argument_list|() argument_list|) expr_stmt|; comment|// We cannot assume the ordering of tags name|List argument_list|< name|String argument_list|> name|tagValues init|= operator|new name|ArrayList argument_list|<> argument_list|() decl_stmt|; for|for control|( name|Tag name|tag range|: name|tags control|) block|{ name|tagValues operator|. name|add argument_list|( name|Bytes operator|. name|toString argument_list|( name|Tag operator|. name|cloneValue argument_list|( name|tag argument_list|) argument_list|) argument_list|) expr_stmt|; block|} name|assertTrue argument_list|( name|tagValues operator|. name|contains argument_list|( literal|"tag1" argument_list|) argument_list|) expr_stmt|; name|assertTrue argument_list|( name|tagValues operator|. name|contains argument_list|( literal|"tag2" argument_list|) argument_list|) expr_stmt|; name|TestCoprocessorForTags operator|. name|checkTagPresence operator|= literal|false expr_stmt|; name|TestCoprocessorForTags operator|. name|tags operator|= literal|null expr_stmt|; name|put operator|= operator|new name|Put argument_list|( name|row2 argument_list|) expr_stmt|; name|v operator|= name|Bytes operator|. name|toBytes argument_list|( literal|2L argument_list|) expr_stmt|; name|put operator|. name|addColumn argument_list|( name|f argument_list|, name|q argument_list|, name|v argument_list|) expr_stmt|; name|table operator|. name|put argument_list|( name|put argument_list|) expr_stmt|; name|increment operator|= operator|new name|Increment argument_list|( name|row2 argument_list|) expr_stmt|; name|increment operator|. name|add argument_list|( operator|new name|KeyValue argument_list|( name|row2 argument_list|, name|f argument_list|, name|q argument_list|, literal|1234L argument_list|, name|v argument_list|) argument_list|) expr_stmt|; name|increment operator|. name|setAttribute argument_list|( literal|"visibility" argument_list|, name|Bytes operator|. name|toBytes argument_list|( literal|"tag2" argument_list|) argument_list|) expr_stmt|; name|table operator|. name|increment argument_list|( name|increment argument_list|) expr_stmt|; name|TestCoprocessorForTags operator|. name|checkTagPresence operator|= literal|true expr_stmt|; name|scanner operator|= name|table operator|. name|getScanner argument_list|( operator|new name|Scan argument_list|() operator|. name|withStartRow argument_list|( name|row2 argument_list|) argument_list|) expr_stmt|; name|result operator|= name|scanner operator|. name|next argument_list|() expr_stmt|; name|kv operator|= name|KeyValueUtil operator|. name|ensureKeyValue argument_list|( name|result operator|. name|getColumnLatestCell argument_list|( name|f argument_list|, name|q argument_list|) argument_list|) expr_stmt|; name|tags operator|= name|TestCoprocessorForTags operator|. name|tags expr_stmt|; name|assertEquals argument_list|( literal|4L argument_list|, name|Bytes operator|. name|toLong argument_list|( name|kv operator|. name|getValueArray argument_list|() argument_list|, name|kv operator|. name|getValueOffset argument_list|() argument_list|, name|kv operator|. name|getValueLength argument_list|() argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|1 argument_list|, name|tags operator|. name|size argument_list|() argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"tag2" argument_list|, name|Bytes operator|. name|toString argument_list|( name|Tag operator|. name|cloneValue argument_list|( name|tags operator|. name|get argument_list|( literal|0 argument_list|) argument_list|) argument_list|) argument_list|) expr_stmt|; name|TestCoprocessorForTags operator|. name|checkTagPresence operator|= literal|false expr_stmt|; name|TestCoprocessorForTags operator|. name|tags operator|= literal|null expr_stmt|; comment|// Test Append name|byte index|[] name|row3 init|= name|Bytes operator|. name|toBytes argument_list|( literal|"r3" argument_list|) decl_stmt|; name|put operator|= operator|new name|Put argument_list|( name|row3 argument_list|) expr_stmt|; name|put operator|. name|addColumn argument_list|( name|f argument_list|, name|q argument_list|, name|Bytes operator|. name|toBytes argument_list|( literal|"a" argument_list|) argument_list|) expr_stmt|; name|put operator|. name|setAttribute argument_list|( literal|"visibility" argument_list|, name|Bytes operator|. name|toBytes argument_list|( literal|"tag1" argument_list|) argument_list|) expr_stmt|; name|table operator|. name|put argument_list|( name|put argument_list|) expr_stmt|; name|Append name|append init|= operator|new name|Append argument_list|( name|row3 argument_list|) decl_stmt|; name|append operator|. name|addColumn argument_list|( name|f argument_list|, name|q argument_list|, name|Bytes operator|. name|toBytes argument_list|( literal|"b" argument_list|) argument_list|) expr_stmt|; name|table operator|. name|append argument_list|( name|append argument_list|) expr_stmt|; name|TestCoprocessorForTags operator|. name|checkTagPresence operator|= literal|true expr_stmt|; name|scanner operator|= name|table operator|. name|getScanner argument_list|( operator|new name|Scan argument_list|() operator|. name|withStartRow argument_list|( name|row3 argument_list|) argument_list|) expr_stmt|; name|result operator|= name|scanner operator|. name|next argument_list|() expr_stmt|; name|kv operator|= name|KeyValueUtil operator|. name|ensureKeyValue argument_list|( name|result operator|. name|getColumnLatestCell argument_list|( name|f argument_list|, name|q argument_list|) argument_list|) expr_stmt|; name|tags operator|= name|TestCoprocessorForTags operator|. name|tags expr_stmt|; name|assertEquals argument_list|( literal|1 argument_list|, name|tags operator|. name|size argument_list|() argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"tag1" argument_list|, name|Bytes operator|. name|toString argument_list|( name|Tag operator|. name|cloneValue argument_list|( name|tags operator|. name|get argument_list|( literal|0 argument_list|) argument_list|) argument_list|) argument_list|) expr_stmt|; name|TestCoprocessorForTags operator|. name|checkTagPresence operator|= literal|false expr_stmt|; name|TestCoprocessorForTags operator|. name|tags operator|= literal|null expr_stmt|; name|append operator|= operator|new name|Append argument_list|( name|row3 argument_list|) expr_stmt|; name|append operator|. name|add argument_list|( operator|new name|KeyValue argument_list|( name|row3 argument_list|, name|f argument_list|, name|q argument_list|, literal|1234L argument_list|, name|v argument_list|) argument_list|) expr_stmt|; name|append operator|. name|setAttribute argument_list|( literal|"visibility" argument_list|, name|Bytes operator|. name|toBytes argument_list|( literal|"tag2" argument_list|) argument_list|) expr_stmt|; name|table operator|. name|append argument_list|( name|append argument_list|) expr_stmt|; name|TestCoprocessorForTags operator|. name|checkTagPresence operator|= literal|true expr_stmt|; name|scanner operator|= name|table operator|. name|getScanner argument_list|( operator|new name|Scan argument_list|() operator|. name|withStartRow argument_list|( name|row3 argument_list|) argument_list|) expr_stmt|; name|result operator|= name|scanner operator|. name|next argument_list|() expr_stmt|; name|kv operator|= name|KeyValueUtil operator|. name|ensureKeyValue argument_list|( name|result operator|. name|getColumnLatestCell argument_list|( name|f argument_list|, name|q argument_list|) argument_list|) expr_stmt|; name|tags operator|= name|TestCoprocessorForTags operator|. name|tags expr_stmt|; name|assertEquals argument_list|( literal|2 argument_list|, name|tags operator|. name|size argument_list|() argument_list|) expr_stmt|; comment|// We cannot assume the ordering of tags name|tagValues operator|. name|clear argument_list|() expr_stmt|; for|for control|( name|Tag name|tag range|: name|tags control|) block|{ name|tagValues operator|. name|add argument_list|( name|Bytes operator|. name|toString argument_list|( name|Tag operator|. name|cloneValue argument_list|( name|tag argument_list|) argument_list|) argument_list|) expr_stmt|; block|} name|assertTrue argument_list|( name|tagValues operator|. name|contains argument_list|( literal|"tag1" argument_list|) argument_list|) expr_stmt|; name|assertTrue argument_list|( name|tagValues operator|. name|contains argument_list|( literal|"tag2" argument_list|) argument_list|) expr_stmt|; name|TestCoprocessorForTags operator|. name|checkTagPresence operator|= literal|false expr_stmt|; name|TestCoprocessorForTags operator|. name|tags operator|= literal|null expr_stmt|; name|byte index|[] name|row4 init|= name|Bytes operator|. name|toBytes argument_list|( literal|"r4" argument_list|) decl_stmt|; name|put operator|= operator|new name|Put argument_list|( name|row4 argument_list|) expr_stmt|; name|put operator|. name|addColumn argument_list|( name|f argument_list|, name|q argument_list|, name|Bytes operator|. name|toBytes argument_list|( literal|"a" argument_list|) argument_list|) expr_stmt|; name|table operator|. name|put argument_list|( name|put argument_list|) expr_stmt|; name|append operator|= operator|new name|Append argument_list|( name|row4 argument_list|) expr_stmt|; name|append operator|. name|add argument_list|( operator|new name|KeyValue argument_list|( name|row4 argument_list|, name|f argument_list|, name|q argument_list|, literal|1234L argument_list|, name|v argument_list|) argument_list|) expr_stmt|; name|append operator|. name|setAttribute argument_list|( literal|"visibility" argument_list|, name|Bytes operator|. name|toBytes argument_list|( literal|"tag2" argument_list|) argument_list|) expr_stmt|; name|table operator|. name|append argument_list|( name|append argument_list|) expr_stmt|; name|TestCoprocessorForTags operator|. name|checkTagPresence operator|= literal|true expr_stmt|; name|scanner operator|= name|table operator|. name|getScanner argument_list|( operator|new name|Scan argument_list|() operator|. name|withStartRow argument_list|( name|row4 argument_list|) argument_list|) expr_stmt|; name|result operator|= name|scanner operator|. name|next argument_list|() expr_stmt|; name|kv operator|= name|KeyValueUtil operator|. name|ensureKeyValue argument_list|( name|result operator|. name|getColumnLatestCell argument_list|( name|f argument_list|, name|q argument_list|) argument_list|) expr_stmt|; name|tags operator|= name|TestCoprocessorForTags operator|. name|tags expr_stmt|; name|assertEquals argument_list|( literal|1 argument_list|, name|tags operator|. name|size argument_list|() argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"tag2" argument_list|, name|Bytes operator|. name|toString argument_list|( name|Tag operator|. name|cloneValue argument_list|( name|tags operator|. name|get argument_list|( literal|0 argument_list|) argument_list|) argument_list|) argument_list|) expr_stmt|; block|} finally|finally block|{ name|TestCoprocessorForTags operator|. name|checkTagPresence operator|= literal|false expr_stmt|; name|TestCoprocessorForTags operator|. name|tags operator|= literal|null expr_stmt|; if|if condition|( name|table operator|!= literal|null condition|) block|{ name|table operator|. name|close argument_list|() expr_stmt|; block|} block|} block|} specifier|private name|void name|result parameter_list|( name|byte index|[] name|fam parameter_list|, name|byte index|[] name|row parameter_list|, name|byte index|[] name|qual parameter_list|, name|byte index|[] name|row2 parameter_list|, name|Table name|table parameter_list|, name|byte index|[] name|value parameter_list|, name|byte index|[] name|value2 parameter_list|, name|byte index|[] name|row1 parameter_list|, name|byte index|[] name|value1 parameter_list|) throws|throws name|IOException block|{ name|Scan name|s init|= operator|new name|Scan argument_list|( name|row argument_list|) decl_stmt|; comment|// If filters are used this attribute can be specifically check for in comment|// filterKV method and comment|// kvs can be filtered out if the tags of interest is not found in that kv name|s operator|. name|setAttribute argument_list|( literal|"visibility" argument_list|, name|Bytes operator|. name|toBytes argument_list|( literal|"myTag" argument_list|) argument_list|) expr_stmt|; name|ResultScanner name|scanner init|= literal|null decl_stmt|; try|try block|{ name|scanner operator|= name|table operator|. name|getScanner argument_list|( name|s argument_list|) expr_stmt|; name|Result name|next init|= name|scanner operator|. name|next argument_list|() decl_stmt|; name|assertTrue argument_list|( name|Bytes operator|. name|equals argument_list|( name|next operator|. name|getRow argument_list|() argument_list|, name|row argument_list|) argument_list|) expr_stmt|; name|assertTrue argument_list|( name|Bytes operator|. name|equals argument_list|( name|next operator|. name|getValue argument_list|( name|fam argument_list|, name|qual argument_list|) argument_list|, name|value argument_list|) argument_list|) expr_stmt|; name|Result name|next2 init|= name|scanner operator|. name|next argument_list|() decl_stmt|; name|assertTrue argument_list|( name|next2 operator|!= literal|null argument_list|) expr_stmt|; name|assertTrue argument_list|( name|Bytes operator|. name|equals argument_list|( name|next2 operator|. name|getRow argument_list|() argument_list|, name|row1 argument_list|) argument_list|) expr_stmt|; name|assertTrue argument_list|( name|Bytes operator|. name|equals argument_list|( name|next2 operator|. name|getValue argument_list|( name|fam argument_list|, name|qual argument_list|) argument_list|, name|value1 argument_list|) argument_list|) expr_stmt|; name|next2 operator|= name|scanner operator|. name|next argument_list|() expr_stmt|; name|assertTrue argument_list|( name|next2 operator|!= literal|null argument_list|) expr_stmt|; name|assertTrue argument_list|( name|Bytes operator|. name|equals argument_list|( name|next2 operator|. name|getRow argument_list|() argument_list|, name|row2 argument_list|) argument_list|) expr_stmt|; name|assertTrue argument_list|( name|Bytes operator|. name|equals argument_list|( name|next2 operator|. name|getValue argument_list|( name|fam argument_list|, name|qual argument_list|) argument_list|, name|value2 argument_list|) argument_list|) expr_stmt|; block|} finally|finally block|{ if|if condition|( name|scanner operator|!= literal|null condition|) name|scanner operator|. name|close argument_list|() expr_stmt|; block|} block|} specifier|public specifier|static class|class name|TestCoprocessorForTags implements|implements name|RegionCoprocessor implements|, name|RegionObserver block|{ specifier|public specifier|static specifier|volatile name|boolean name|checkTagPresence init|= literal|false decl_stmt|; specifier|public specifier|static name|List argument_list|< name|Tag argument_list|> name|tags init|= literal|null decl_stmt|; annotation|@ name|Override specifier|public name|Optional argument_list|< name|RegionObserver argument_list|> name|getRegionObserver parameter_list|() block|{ return|return name|Optional operator|. name|of argument_list|( name|this argument_list|) return|; block|} annotation|@ name|Override specifier|public name|void name|prePut parameter_list|( specifier|final name|ObserverContext argument_list|< name|RegionCoprocessorEnvironment argument_list|> name|e parameter_list|, specifier|final name|Put name|put parameter_list|, specifier|final name|WALEdit name|edit parameter_list|, specifier|final name|Durability name|durability parameter_list|) throws|throws name|IOException block|{ name|updateMutationAddingTags argument_list|( name|put argument_list|) expr_stmt|; block|} specifier|private name|void name|updateMutationAddingTags parameter_list|( specifier|final name|Mutation name|m parameter_list|) block|{ name|byte index|[] name|attribute init|= name|m operator|. name|getAttribute argument_list|( literal|"visibility" argument_list|) decl_stmt|; name|byte index|[] name|cf init|= literal|null decl_stmt|; name|List argument_list|< name|Cell argument_list|> name|updatedCells init|= operator|new name|ArrayList argument_list|<> argument_list|() decl_stmt|; if|if condition|( name|attribute operator|!= literal|null condition|) block|{ for|for control|( name|List argument_list|< name|? extends|extends name|Cell argument_list|> name|edits range|: name|m operator|. name|getFamilyCellMap argument_list|() operator|. name|values argument_list|() control|) block|{ for|for control|( name|Cell name|cell range|: name|edits control|) block|{ name|KeyValue name|kv init|= name|KeyValueUtil operator|. name|ensureKeyValue argument_list|( name|cell argument_list|) decl_stmt|; if|if condition|( name|cf operator|== literal|null condition|) block|{ name|cf operator|= name|CellUtil operator|. name|cloneFamily argument_list|( name|kv argument_list|) expr_stmt|; block|} name|Tag name|tag init|= operator|new name|ArrayBackedTag argument_list|( operator|( name|byte operator|) literal|1 argument_list|, name|attribute argument_list|) decl_stmt|; name|List argument_list|< name|Tag argument_list|> name|tagList init|= operator|new name|ArrayList argument_list|<> argument_list|() decl_stmt|; name|tagList operator|. name|add argument_list|( name|tag argument_list|) expr_stmt|; name|KeyValue name|newKV init|= operator|new name|KeyValue argument_list|( name|CellUtil operator|. name|cloneRow argument_list|( name|kv argument_list|) argument_list|, literal|0 argument_list|, name|kv operator|. name|getRowLength argument_list|() argument_list|, name|CellUtil operator|. name|cloneFamily argument_list|( name|kv argument_list|) argument_list|, literal|0 argument_list|, name|kv operator|. name|getFamilyLength argument_list|() argument_list|, name|CellUtil operator|. name|cloneQualifier argument_list|( name|kv argument_list|) argument_list|, literal|0 argument_list|, name|kv operator|. name|getQualifierLength argument_list|() argument_list|, name|kv operator|. name|getTimestamp argument_list|() argument_list|, name|KeyValue operator|. name|Type operator|. name|codeToType argument_list|( name|kv operator|. name|getTypeByte argument_list|() argument_list|) argument_list|, name|CellUtil operator|. name|cloneValue argument_list|( name|kv argument_list|) argument_list|, literal|0 argument_list|, name|kv operator|. name|getValueLength argument_list|() argument_list|, name|tagList argument_list|) decl_stmt|; operator|( operator|( name|List argument_list|< name|Cell argument_list|> operator|) name|updatedCells operator|) operator|. name|add argument_list|( name|newKV argument_list|) expr_stmt|; block|} block|} name|m operator|. name|getFamilyCellMap argument_list|() operator|. name|remove argument_list|( name|cf argument_list|) expr_stmt|; comment|// Update the family map name|m operator|. name|getFamilyCellMap argument_list|() operator|. name|put argument_list|( name|cf argument_list|, name|updatedCells argument_list|) expr_stmt|; block|} block|} annotation|@ name|Override specifier|public name|Result name|preIncrement parameter_list|( name|ObserverContext argument_list|< name|RegionCoprocessorEnvironment argument_list|> name|e parameter_list|, name|Increment name|increment parameter_list|) throws|throws name|IOException block|{ name|updateMutationAddingTags argument_list|( name|increment argument_list|) expr_stmt|; return|return literal|null return|; block|} annotation|@ name|Override specifier|public name|Result name|preAppend parameter_list|( name|ObserverContext argument_list|< name|RegionCoprocessorEnvironment argument_list|> name|e parameter_list|, name|Append name|append parameter_list|) throws|throws name|IOException block|{ name|updateMutationAddingTags argument_list|( name|append argument_list|) expr_stmt|; return|return literal|null return|; block|} annotation|@ name|Override specifier|public name|boolean name|postScannerNext parameter_list|( name|ObserverContext argument_list|< name|RegionCoprocessorEnvironment argument_list|> name|e parameter_list|, name|InternalScanner name|s parameter_list|, name|List argument_list|< name|Result argument_list|> name|results parameter_list|, name|int name|limit parameter_list|, name|boolean name|hasMore parameter_list|) throws|throws name|IOException block|{ if|if condition|( name|checkTagPresence condition|) block|{ if|if condition|( name|results operator|. name|size argument_list|() operator|> literal|0 condition|) block|{ comment|// Check tag presence in the 1st cell in 1st Result name|Result name|result init|= name|results operator|. name|get argument_list|( literal|0 argument_list|) decl_stmt|; name|CellScanner name|cellScanner init|= name|result operator|. name|cellScanner argument_list|() decl_stmt|; if|if condition|( name|cellScanner operator|. name|advance argument_list|() condition|) block|{ name|Cell name|cell init|= name|cellScanner operator|. name|current argument_list|() decl_stmt|; name|tags operator|= name|PrivateCellUtil operator|. name|getTags argument_list|( name|cell argument_list|) expr_stmt|; block|} block|} block|} return|return name|hasMore return|; block|} block|} block|} end_class end_unit package application.context.async; import java.lang.reflect.InvocationTargetException; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; /** * * @author * */ public class AsyncContext { private static List asyncClasses = new ArrayList<>(); private AsyncContext() {} public static void addAsync(Class asyncClass) { asyncClasses.add(asyncClass); } public static void runAsync() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { if(asyncClasses.isEmpty()) { return; } invokeAsyncMethods(); printMessage(); } private static void invokeAsyncMethods() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { for (Class config : asyncClasses) { AsyncInvoker.invoke(config); } } private static void printMessage() { System.out.printf("[INFO] %s Async init finished, found %d async class(-es)%n", LocalDateTime.now().toString(), asyncClasses.size()); } } package cn.ztuo.bitrade.core; import org.apache.commons.lang.StringUtils; /** * @description: SqlInfusion * @author: MrGao * @create: 2019/07/04 14:50 */ public class SqlInfusion { public SqlInfusion() { } public static String FilterSqlInfusion(String input) { if (input != null && input.trim() != "") { return !StringUtils.isNumeric(input) ? input.replaceAll("\\b(drop|exec|execute|create|truncate|delete|insert|update)\\b", "`$1`") : input; } else { return ""; } } } 1-10 /* * Jicofo, the Jitsi Conference Focus. * * Copyright @ 2015-Present 8x8, 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 org.jitsi.impl.reservation.rest; import edu.umd.cs.findbugs.annotations.*; import org.apache.http.*; import org.apache.http.NameValuePair; import org.apache.http.client.entity.*; import org.apache.http.client.methods.*; import org.apache.http.impl.client.*; import org.apache.http.message.*; import org.apache.http.util.*; import org.jitsi.impl.reservation.rest.json.*; import org.jitsi.utils.logging2.*; import org.json.simple.parser.*; import org.json.simple.parser.ParseException; import org.jxmpp.jid.*; import java.io.*; import java.lang.Object; import java.util.*; /** * Class deals with JSON objects serialization and sending requests to REST * API endpoint. * * @author */ @SuppressFBWarnings("DM_DEFAULT_ENCODING") public class ApiHandler { /** * The logger */ private static final Logger logger = new LoggerImpl(ApiHandler.class.getName()); /** * Base URL of the REST API. */ private final String baseUrl; /** * HTTP client used for sending requests. */ private final CloseableHttpClient client = HttpClientBuilder.create().build(); /** * JSONParser instance used for parsing JSON. */ private final JSONParser jsonParser = new JSONParser(); /** * JSON handler for Conference objects. */ private final ConferenceJsonHandler conferenceJson = new ConferenceJsonHandler(); /** * JSON handler for error responses. */ private final ErrorJsonHandler errorJson = new ErrorJsonHandler(); /** * Creates new instance of ApiHandler. * * @param baseUrl the base URL of REST API. */ public ApiHandler(String baseUrl) { this.baseUrl = baseUrl; } /** * Send Conference POST request to API endpoint which is used for * allocating new conferences in reservation system. * * @param ownerEmail email of new conference owner * @param mucRoomName full name of MUC room that is hosting the conference. * {}@{} * * @return ApiResult that contains system response. It will contain * Conference instance filled with data from * the reservation system if everything goes OK. * * @throws IOException IO exception if connectivity issues have occurred. * @throws ParseException parse exception if any problems during JSON * parsing have occurred. */ public ApiResult createNewConference(String ownerEmail, EntityBareJid mucRoomName) throws IOException, ParseException { Conference conference = new Conference(mucRoomName, ownerEmail, new Date()); HttpPost post = new HttpPost(baseUrl + "/conference"); List nameValuePairs = new ArrayList<>(1); Map jsonMap = conference.createJSonMap(); for (Map.Entry entry : jsonMap.entrySet()) { nameValuePairs.add( new BasicNameValuePair( entry.getKey(), String.valueOf(entry.getValue()))); } post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF8")); logger.info("Sending post: " + jsonMap); HttpResponse response = null; try { response = client.execute(post); int statusCode = response.getStatusLine().getStatusCode(); logger.info("STATUS CODE: " + statusCode); if (200 == statusCode || 201 == statusCode) { // OK readConferenceResponse(conference, response); return new ApiResult(statusCode, conference); } else { ErrorResponse error = readErrorResponse(response); return new ApiResult(statusCode, error); } } finally { if (response != null && response.getEntity() != null) { EntityUtils.consume(response.getEntity()); } } } /** * Sends Conference GET request to the REST API endpoint. Is used to read * info about the conference from the reservation system. * * @param conferenceId the identifier of the conference for which we want * to read the data. * * @return ApiResult which describes the response. It will contain * Conference if data has been read successfully. * * @throws IOException if any IO problems occur. * @throws ParseException if any problems during JSON parsing occur. */ public ApiResult getConference(Number conferenceId) throws IOException, ParseException { HttpGet get = new HttpGet(baseUrl + "/conference/" + conferenceId); HttpResponse response = null; try { response = client.execute(get); int statusCode = response.getStatusLine().getStatusCode(); if (200 == statusCode || 201 == statusCode) { // OK Conference conference = readConferenceResponse(null, response); return new ApiResult(statusCode, conference); } else { ErrorResponse error = readErrorResponse(response); return new ApiResult(statusCode, error); } } finally { if (response != null && response.getEntity() != null) { EntityUtils.consume(response.getEntity()); } } } /** * Sends conference DELETE request to the REST API endpoint. * * @param conferenceId the identifier of the conference to be destroyed. * * @return ApiResult that describes the response. Check * ApiResult#statusCode to see if it went OK. * * @throws IOException if any IO problems have occurred. * @throws ParseException if there were any problems when parsing JSON data */ public ApiResult deleteConference(Number conferenceId) throws IOException, ParseException { HttpDelete delete = new HttpDelete(baseUrl + "/conference/" + conferenceId); HttpResponse response = null; try { response = client.execute(delete); int statusCode = response.getStatusLine().getStatusCode(); if (200 == statusCode || 201 == statusCode) { // OK return new ApiResult(statusCode); } else { ErrorResponse error = readErrorResponse(response); return new ApiResult(statusCode, error); } } finally { if (response != null && response.getEntity() != null) { EntityUtils.consume(response.getEntity()); } } } /** * Parses error response. * * @param response parsed ErrorResponse * * @return ErrorResponse parsed from HTTP content stream. * * @throws IOException if any IO issues occur. * @throws ParseException if any issues with JSON parsing occur. */ private ErrorResponse readErrorResponse(HttpResponse response) throws IOException, ParseException { BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); jsonParser.parse(rd, errorJson); return errorJson.getResult(); } /** * Parses JSON string returned in HTTP response and * converts it to Conference instance. * * @param conference Conference instance that contains the data * returned by API endpoint. * @param response HTTP response returned by the API endpoint. * * @return Conference instance that contains the data * returned by API endpoint. * * @throws IOException if any IO problems occur. * @throws ParseException if any problems with JSON parsing occur. */ private Conference readConferenceResponse(Conference conference, HttpResponse response) throws IOException, ParseException { BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); if (conference != null) { conferenceJson.setForUpdate(conference); } jsonParser.parse(rd, conferenceJson); if (conference == null) { conference = conferenceJson.getResult(); } logger.info("ID: " + conference.getId()); logger.info("PIN: " + conference.getPin()); logger.info("URL: " + conference.getUrl()); logger.info("SIP ID: " + conference.getSipId()); logger.info("START TIME: " + conference.getStartTime()); logger.info("DURATION: " + conference.getDuration()); return conference; } /** * Structure used for holding processing results. It contains HTTP status * code, Conference instance which represents the data retrieved * from the API or ErrorResponse which contains error details. */ static class ApiResult { /** * HTTP status code returned by the API. */ int statusCode; /** * Conference instance filled with data retrieved from the API. */ Conference conference; /** * ErrorResponse which contains API error description. */ ErrorResponse error; /** * Creates new ApiResult insatnce for given HTTP status code. * * @param statusCode HTTP status code returned by the API endpoint. */ public ApiResult(int statusCode) { this.statusCode = statusCode; } /** * Creates ApiResult which contains Conference data * read from the API. * * @param statusCode HTTP status code returned by the API. * @param conference Conference instance which contains the * data read from the API. */ public ApiResult(int statusCode, Conference conference) { this.statusCode = statusCode; this.conference = conference; } /** * Creates new ApiResult for given ErrorResponse. * * @param statusCode HTTP status code returned by API endpoint. * @param error ErrorResponse that contains error details * returned by API endpoint. */ public ApiResult(int statusCode, ErrorResponse error) { this.statusCode = statusCode; this.error = error; } /** * {@inheritDoc} */ @Override public String toString() { return "ApiError[" + statusCode + "](" + error + ")"; } } } /* * Copyright (c) 2021 - Manifold Systems LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package manifold.ext.structural; import junit.framework.TestCase; import java.math.BigDecimal; public class DefaultMethodTest extends TestCase { public void testDefaultMethod() { // uses test BigDecimalExt and BigDecimal_To_SqlNumber IProxyFactory SqlNumber n1 = new BigDecimal("1"); SqlNumber n2 = new BigDecimal("2"); SqlNumber n3 = n1.plus(n2); assertEquals( new BigDecimal("3"), n3 ); SqlNumber sum = n1 + n2; assertEquals( new BigDecimal("3"), sum ); SqlNumber f = (SqlNumber)new FooNumber("9"); sum = f.plus(n2); assertEquals( new BigDecimal("11"), sum ); } } package com.rainsty.test; public class Test { public static void main(String[] args) { Student s = new Student(); s.run(); String sa = s.getName(); Print.println(sa); s.eat(); String sb = s.getSey(); Print.println(sb); Print.println(s.getAge()); // Print.println(Student.getAge()); 静态方法可以直接通过class.method调用 // Print.println(Student.getWordYear()); // Print.println(Students.getWordYear()); Students ss = new Students(19); ss.eat(); ss.run(); Print.println(ss.getName()); Print.println(ss.getSey()); Print.println(ss.getAge()); Print.println(ss.getWordYear()); } } package multiplication; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import java.io.IOException; import java.util.Random; public class MatrixMapper extends Mapper { @Override public void map(Object key, Text value, Context context) throws IOException, InterruptedException { String entry[] = value.toString().split("\\s"); Configuration conf = context.getConfiguration(); int a = Integer.parseInt(conf.get("a")); int b = Integer.parseInt(conf.get("b")); Random random1 = new Random(); int row = random1.nextInt(a); int col = random1.nextInt(b); int k; Text outputKey = new Text(); MatrixTuple outputValue = new MatrixTuple(); // Partitioning using 1-Bucket Random Algorithm for (k = row * b; k <= row * b + b - 1; k++) { outputKey.set(new Text(Integer.toString(k))); outputValue.set(new Text("A"), new LongWritable(Long.parseLong(entry[0])), new LongWritable(Long.parseLong(entry[1])), new LongWritable(Long.parseLong(entry[2]))); context.write(outputKey, outputValue); } for (k = col; k <= (a - 1) * b + col; k = k + b) { outputKey.set(new Text(Integer.toString(k))); outputValue.set(new Text("B"), new LongWritable(Long.parseLong(entry[0])), new LongWritable(Long.parseLong(entry[1])), new LongWritable(Long.parseLong(entry[2]))); context.write(outputKey, outputValue); } } } package org.apache.hadoop.hdfs.server.balancer; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.*; import org.apache.hadoop.fs.shell.FsCommand; import org.apache.hadoop.hdfs.DFSClient; import org.apache.hadoop.hdfs.DFSConfigKeys; import org.apache.hadoop.hdfs.DFSUtilClient; import org.apache.hadoop.hdfs.DistributedFileSystem; import org.apache.hadoop.hdfs.protocol.*; import org.apache.hadoop.hdfs.protocol.datatransfer.DataTransferProtoUtil; import org.apache.hadoop.hdfs.protocol.datatransfer.IOStreamPair; import org.apache.hadoop.hdfs.protocol.datatransfer.Sender; import org.apache.hadoop.hdfs.protocol.datatransfer.TrustedChannelResolver; import org.apache.hadoop.hdfs.protocol.datatransfer.sasl.DataTransferSaslUtil; import org.apache.hadoop.hdfs.protocol.datatransfer.sasl.SaslDataTransferClient; import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos; import org.apache.hadoop.hdfs.security.token.block.BlockTokenIdentifier; import org.apache.hadoop.hdfs.server.protocol.DataNodeUsageReport; import org.apache.hadoop.hdfs.server.protocol.DatanodeStorage; import org.apache.hadoop.hdfs.server.protocol.DatanodeStorageReport; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.util.Time; import org.apache.hadoop.util.hash.Hash; import java.io.*; import java.net.Socket; import java.util.*; import static org.apache.hadoop.hdfs.protocolPB.PBHelperClient.vintPrefixed; public class FileBalancer { private final Configuration configuration; public FileBalancer(Configuration configuration) { this.configuration = configuration; } public boolean moveBlocks(List connectors) { Map> locationMap = ReadFromFile(); for (NameNodeConnector nameNodeConnector : connectors) { DistributedFileSystem distributedFileSystem = nameNodeConnector.getDistributedFileSystem(); DFSClient dfsClient = distributedFileSystem.getClient(); for (Map.Entry> filesMap : locationMap.entrySet()) { String fileNameExt = filesMap.getKey(); String fileName = fileNameExt.substring(0, fileNameExt.lastIndexOf(".")); String path = "/user/hive/warehouse/" + fileName + "/" + fileNameExt; printIntoMoveBlocksLog("\n\nFile: " + path); List blockList = filesMap.getValue(); try { FileSystem fileSystem = FileSystem.get(configuration); if (fileSystem != null) { ContentSummary contentSummary = fileSystem.getContentSummary(new Path(path)); long fileSize = contentSummary.getLength(); int i = 0; List locatedBlocks = dfsClient.getLocatedBlocks(path, 0, fileSize).getLocatedBlocks(); for (LocatedBlock block : locatedBlocks) { List nodes = blockList.get(i++).getNodes(); List targetNodes = new ArrayList<>(); try { dfsClient.setReplication(path, (short) nodes.size()); } catch (IOException e) { printIntoMoveBlocksLog("Set new Replication factor Error"); return true; //Return true if node not exists and then exit } for (String s : nodes) { DatanodeStorageReport node = checkIfTargetNodeExists(nameNodeConnector, s); if (node != null) { targetNodes.add(node); } else { printIntoMoveBlocksLog("Node is NULL"); return true; //Return true if node not exists and then exit } } DatanodeInfo[] sourceNodes = getBlockSourceNode(block); Map replicaToMove = checkIfBlocksAreAlreadyInPosition(sourceNodes, targetNodes, nodes); if (!replicaToMove.isEmpty()) { for (Map.Entry map : replicaToMove.entrySet()) { BlockToMove blockToMove = new BlockToMove(map.getKey(), map.getValue(), block, nameNodeConnector); if (!moveBlock(blockToMove)) { printIntoMoveBlocksLog("Block move error"); return true; //Return true if moveBlock fail and then exit } } } else { printIntoMoveBlocksLog("All Blocks are already in position"); } } } } catch (IOException e) { printIntoMoveBlocksLog("File " + fileNameExt + "not found"); } } } return false; } private Map checkIfBlocksAreAlreadyInPosition(DatanodeInfo[] sourceNodes, List targetNodes, List targetNodesString) { List sourcesList = new LinkedList<>(Arrays.asList(sourceNodes)); for (DatanodeInfo sourceNode : sourceNodes) { if (targetNodesString.contains(sourceNode.getName())) { targetNodesString.remove(sourceNode.getName()); sourcesList.remove(sourceNode); } } List targetsList = new ArrayList<>(); for (DatanodeStorageReport datanodeStorageReport : targetNodes) { if (targetNodesString.contains(datanodeStorageReport.getDatanodeInfo().getName())) { targetsList.add(datanodeStorageReport); } } Map map = new HashMap<>(); for (int i = 0; i < sourcesList.size(); i++) { map.put(sourcesList.get(i), targetsList.get(i)); } return map; } private DatanodeStorageReport checkIfTargetNodeExists(NameNodeConnector nameNodeConnector, String targetNode) { DatanodeStorageReport node = null; try { DatanodeStorageReport[] datanodeStorageReportList = nameNodeConnector.getLiveDatanodeStorageReport(); for (DatanodeStorageReport datanodeStorageReport : datanodeStorageReportList) { if (datanodeStorageReport.getDatanodeInfo().getName().equals(targetNode)) { node = datanodeStorageReport; } } } catch (IOException e) { } return node; } //TODO How Hadoop choose replica? private DatanodeInfo[] getBlockSourceNode(LocatedBlock locatedBlock) { return locatedBlock.getLocations(); } //TODO Add Check on StorageType private boolean moveBlock(BlockToMove blockToMove) { printIntoMoveBlocksLog(blockToMove.toString()); Socket sock = new Socket(); DataOutputStream out = null; DataInputStream in = null; SaslDataTransferClient saslClient = new SaslDataTransferClient(configuration, DataTransferSaslUtil.getSaslPropertiesResolver(configuration), TrustedChannelResolver.getInstance(configuration), blockToMove.nameNodeConnector.fallbackToSimpleAuth); int ioFileBufferSize = DFSUtilClient.getIoFileBufferSize(configuration); DatanodeInfo datanodeInfo = blockToMove.dataNodeTarget.getDatanodeInfo(); ExtendedBlock extendedBlock = blockToMove.block.getBlock(); try { sock.connect(NetUtils.createSocketAddr(datanodeInfo.getName()), HdfsConstants.READ_TIMEOUT); sock.setSoTimeout(HdfsConstants.READ_TIMEOUT * 5); sock.setKeepAlive(true); OutputStream unbufOut = sock.getOutputStream(); InputStream unbufIn = sock.getInputStream(); final KeyManager km = blockToMove.nameNodeConnector.getKeyManager(); Token accessToken = km.getAccessToken(extendedBlock, new StorageType[]{blockToMove.block.getStorageTypes()[0]}, new String[0]); IOStreamPair saslStreams = saslClient.socketSend(sock, unbufOut, unbufIn, km, accessToken, datanodeInfo); unbufOut = saslStreams.out; unbufIn = saslStreams.in; out = new DataOutputStream(new BufferedOutputStream(unbufOut, ioFileBufferSize)); in = new DataInputStream(new BufferedInputStream(unbufIn, ioFileBufferSize)); sendRequest(out, blockToMove, accessToken); receiveResponse(in); blockToMove.nameNodeConnector.getBytesMoved().addAndGet(extendedBlock.getNumBytes()); printIntoMoveBlocksLog("- Block Moved"); } catch (IOException e) { printIntoMoveBlocksLog("- Move Failed"); return false; } finally { IOUtils.closeStream(out); IOUtils.closeStream(in); IOUtils.closeSocket(sock); } return true; } /** Send a reportedBlock replace request to the output stream */ private void sendRequest(DataOutputStream out, BlockToMove blockToMove, Token accessToken) throws IOException { new Sender(out).replaceBlock(blockToMove.block.getBlock(), blockToMove.block.getStorageTypes()[0], accessToken, blockToMove.dataNodeSource.getDatanodeUuid(), blockToMove.dataNodeSource, null); } /** Receive a reportedBlock copy response from the input stream */ private void receiveResponse(DataInputStream in) throws IOException { long startTime = Time.monotonicNow(); DataTransferProtos.BlockOpResponseProto response = DataTransferProtos.BlockOpResponseProto.parseFrom(vintPrefixed(in)); while (response.getStatus() == DataTransferProtos.Status.IN_PROGRESS) { // read intermediate responses response = DataTransferProtos.BlockOpResponseProto.parseFrom(vintPrefixed(in)); // Stop waiting for slow block moves. Even if it stops waiting, // the actual move may continue. if (stopWaitingForResponse(startTime)) { throw new IOException("Block move timed out"); } } String logInfo = "reportedBlock move is failed"; DataTransferProtoUtil.checkBlockOpStatus(response, logInfo, true); } /** Check whether to continue waiting for response */ private boolean stopWaitingForResponse(long startTime) { final int blockMoveTimeout = configuration.getInt( DFSConfigKeys.DFS_BALANCER_BLOCK_MOVE_TIMEOUT, DFSConfigKeys.DFS_BALANCER_BLOCK_MOVE_TIMEOUT_DEFAULT); return (blockMoveTimeout > 0 && (Time.monotonicNow() - startTime > blockMoveTimeout)); } private Map> ReadFromFile() { Map> map = new HashMap<>(); try { BufferedReader bufferedReader = new BufferedReader(new FileReader(System.getProperty("user.home") + File.separator + "test-data" + File.separator + "FilesLocation.txt")); String line; while ((line = bufferedReader.readLine()) != null) { String[] tmp = line.split(","); if (tmp.length < 2) break; String fileName = tmp[0]; BlockFromFile blockFromFile = new BlockFromFile(new ArrayList<>(Arrays.asList(tmp).subList(1, tmp.length))); List blockList; if (map.containsKey(fileName)) { blockList = map.get(fileName); blockList.add(blockFromFile); map.replace(fileName, blockList); } else { blockList = new ArrayList<>(); blockList.add(blockFromFile); map.put(fileName, blockList); } } bufferedReader.close(); } catch (IOException e) { printIntoMoveBlocksLog("File FileLocation.txt not found"); } return map; } private void printIntoMoveBlocksLog(String line) { File file = new File(System.getProperty("user.home") + File.separator + "MoveBlocks.txt"); FileWriter fr = null; try { fr = new FileWriter(file, true); fr.write(line + "\n"); fr.close(); } catch (IOException e) { e.printStackTrace(); } } private static class BlockFromFile { private List nodes; public BlockFromFile(List nodes) { this.nodes = nodes; } public List getNodes() { return nodes; } public void setNodes(List nodes) { this.nodes = nodes; } } private static class BlockToMove { private DatanodeInfo dataNodeSource; private DatanodeStorageReport dataNodeTarget; private LocatedBlock block; private NameNodeConnector nameNodeConnector; public BlockToMove(DatanodeInfo dataNodeSource, DatanodeStorageReport dataNodeTarget, LocatedBlock block, NameNodeConnector nameNodeConnector) { this.dataNodeSource = dataNodeSource; this.dataNodeTarget = dataNodeTarget; this.block = block; this.nameNodeConnector = nameNodeConnector; } public String toString() { return "Moving block: " + block.getBlock().getBlockName() + " From: " + dataNodeSource.getName() + " -> To: " + dataNodeTarget.getDatanodeInfo().getName(); } } } package cn.squatam.api.event.bus.impl; import cn.squatam.api.event.EventMark; import cn.squatam.api.event.invoker.impl.ASMInvoker; import com.esotericsoftware.reflectasm.MethodAccess; import cn.squatam.api.event.bus.Bus; import java.lang.reflect.Method; import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; public class ASMBus implements Bus { protected Map accesses = new HashMap<>(); protected Map> registry = new HashMap<>(); @Override public Object call(Object object) { final String CASE = object.getClass().getName(); if(registry.containsKey(CASE)) registry.get(CASE).forEach(asmInvoker -> asmInvoker.invoke(object)); return object; } @Override public void register(Object object) { final String CASE = object.getClass().getName(); MethodAccess access; if(accesses.containsKey(CASE)) { access = accesses.get(object.getClass()); } else{ access = MethodAccess.get(object.getClass()); accesses.put(CASE, access); } for(Method method :object.getClass().getDeclaredMethods()) { if(!isMarkedMethod(method)) continue; makeInvoker(method, access, object); } sortList(); } @Override public void unregister(Object object) { registry.values().forEach(asmInvokers -> { asmInvokers.removeIf(asmInvoker -> asmInvoker.isInInstance(object)); }); } private void makeInvoker(Method method, final MethodAccess access, final Object instance) { final int priority = method.getAnnotation(EventMark.class).value(); final int index = access.getIndex(method.getName(), method.getParameterCount()); final String paramName = method.getParameterTypes()[0].getName(); final ASMInvoker invoker = new ASMInvoker(access, instance, index, priority); if(registry.containsKey(paramName)) { registry.get(paramName).add(invoker); return; } registry.put(paramName, new CopyOnWriteArrayList(){ private static final long serialVersionUID = 666L; { add(invoker); } }); } private void sortList(){ Iterator> listIterator = registry.values().iterator(); while (listIterator.hasNext()){ List list = listIterator.next(); list.sort(Comparator.comparingInt(ASMInvoker::getPriority)); } } private boolean isMarkedMethod(Method method){ return method.isAnnotationPresent(EventMark.class) && method.getParameterCount() == 1; } } /** * */ package com.dup.core.xls; import java.io.InputStream; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.jxls.transformer.XLSTransformer; import org.apache.poi.ss.usermodel.Workbook; import org.junit.Before; /** * @author hugoyang * */ public class XLSExport { private XLSTransformer transformer = new XLSTransformer(); private Workbook workbook; @Before public void before() { } public ExcelData getData() { Map map = new HashMap(); map.put("dailys", getUserList()); map.put("startDate", "2015-09-23"); map.put("endDate", "2015-09-24"); map.put("now", Calendar.getInstance().getTime()); map.put("list", getUserList()); ExcelData data = new ExcelData(); String fileName = "cardStat" + new Date() + ".xls"; data.setTemplateFileName("cardStat.xls"); data.setSheetModels(getUserList()); List list2= new ArrayList(); list2.add("wangbadan"); data.setSheetNames(list2); data.setOtherModel(map); data.setSheetModelName("test"); data.setStartSheetNum(1); return data; } public List getUserList() { List list = new ArrayList(); for (int i = 0; i < 3; i++) { UserModel userModel = new UserModel(); userModel.setName("name_" + i); list.add(userModel); } return list; } public void exportXLXS2() { try { ExcelData data = getData(); List sheetNames = data.getSheetNames(); if (sheetNames.isEmpty()) { int i = 0; for (Object sheetModel : data.getSheetModels()) { sheetNames.add("wangbadan_" + i++); } } InputStream in = getClass().getResourceAsStream("巡检商户满意度报表模板.xlsx"); workbook = transformer.transformMultipleSheetsList(in, data.getSheetModels(), sheetNames, data.getSheetModelName(), data.getOtherModel(), data.getStartSheetNum()); in.close(); } catch (Exception e) { e.printStackTrace(); } } } jason-jiangjs/dbDesign package org.dbm.dbd.dao; import org.springframework.data.mongodb.core.query.Query; import org.springframework.stereotype.Repository; import org.dbm.common.base.dao.mongo.BaseMongoDao; import java.util.List; import java.util.Map; import static org.springframework.data.mongodb.core.query.Criteria.where; /** * 系统属性配置 */ @Repository public class ComConfigDao extends BaseMongoDao { //mongo表名 private static final String COLL_NAME = "com_config"; /** * 取得配置属性值 */ public Object getProperty(String key) { Query query = new Query(where("propName").is(key)); query.fields().exclude("_id"); query.fields().include("propValue"); Map rst = mongoTemplate.findOne(query, Map.class, COLL_NAME); if (rst == null) { return null; } return rst.get("propValue"); } } _src/Chapter06/Java/PointsDictionary.java package main.java; import java.util.HashMap; /** * Created by on 9/7/16. */ public class PointsDictionary { HashMap _points; public PointsDictionary() { _points = new HashMap<>(); } //This method accepts negative values private Integer UpdateCustomerPoints(String customerName, int points) { if (this.CustomerExists(customerName)) { _points.put(customerName, _points.get(customerName) + points); return _points.get(customerName); } return 0; } //Add public void RegisterCustomer(String customerName) { this.RegisterCustomer(customerName, 0); } public void RegisterCustomer(String customerName, int previousBalance) { _points.put(customerName, previousBalance); } //Get public Integer GetCustomerPoints(String customerName) { return _points.get(customerName) == null ? 0 : _points.get(customerName); } //Update public Integer AddCustomerPoints(String customerName, int points) { return this.UpdateCustomerPoints(customerName, points); } public Integer RemoveCustomerPoints(String customerName, int points) { return this.UpdateCustomerPoints(customerName, -points); } public Integer RedeemCustomerPoints(String customerName, int points) { return this.UpdateCustomerPoints(customerName, -points); } //Remove public Integer CustomerCheckout(String customerName) { Integer points = this.GetCustomerPoints(customerName); _points.remove(customerName); return points; } //Contains public boolean CustomerExists(String customerName) { return _points.containsKey(customerName); } //Count public int CustomersOnPremises() { return _points.size(); } //Clear public void ClosingTime() { //Perform accounting actions _points.clear(); } } package com.xnx3.wangmarket.admin.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Id; import javax.persistence.Table; import com.xnx3.j2ee.util.Sql; /** * site entitiy * @author 管雷鸣 */ @Entity @Table(name = "site") public class Site implements java.io.Serializable { /** * 隐藏手机端首页的Banner */ public final static Short MSHOWBANNER_HIDDEN = 0; /** * 显示手机端首页的Banner */ public final static Short MSHOWBANNER_SHOW = 1; /** * 客户端类型:PC电脑端 */ public static final Short CLIENT_PC = 1; /** * 客户端类型:WAP手机端 */ public static final Short CLIENT_WAP = 2; /** * 高级自定义模版CMS */ public static final Short CLIENT_CMS = 3; /** * 站点状态,1:正常 */ public static final Short STATE_NORMAL = 1; /** * 站点状态,2:冻结、暂停 */ public static final Short STATE_FREEZE = 2; private Integer id; private String name; private Integer userid; private Integer addtime; private Short mShowBanner; private String phone; private String qq; private Integer templateId; private String domain; private Integer aboutUsCid; private String logo; private Short client; private String keywords; private String address; private String username; //联系人姓名 private String companyName; //公司名、工作室名字、团体名字 private String bindDomain; //用户自己绑定的域名 private String columnId; //栏目id,这里暂时只记录栏目类型的ID,方便生成页面时,生成Nav标签的填充,方便搜索引擎抓取 private Short state; //站点状态,1正常;2冻结 private String templateName; //自定义模版的模版名字,位于 /template/模版名字,这里的模版单纯修改HTML,没有动态后台 private Integer expiretime; private Short useKefu; //是否开启在线客服功能。0不开启,默认; 1开启 public Site() { this.state = STATE_NORMAL; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "id", unique = true, nullable = false) public Integer getId() { if(this.id == null){ return 0; } return this.id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getUserid() { return userid; } public void setUserid(Integer userid) { this.userid = userid; } public Integer getAddtime() { return addtime; } public void setAddtime(Integer addtime) { this.addtime = addtime; } @Column(name = "m_show_banner") public Short getmShowBanner() { return mShowBanner; } public void setmShowBanner(Short mShowBanner) { this.mShowBanner = mShowBanner; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getQq() { return qq; } public void setQq(String qq) { this.qq = qq; } @Column(name = "template_id") public Integer getTemplateId() { return templateId; } public void setTemplateId(Integer templateId) { this.templateId = templateId; } @Column(name = "domain") public String getDomain() { if(domain == null || domain.equals("")){ domain = id+""; } return domain; } public void setDomain(String domain) { this.domain = domain; } @Column(name = "about_us_cid") public Integer getAboutUsCid() { return aboutUsCid; } public void setAboutUsCid(Integer aboutUsCid) { this.aboutUsCid = aboutUsCid; } public String getLogo() { return logo; } public void setLogo(String logo) { this.logo = logo; } public Short getClient() { return client; } public void setClient(Short client) { this.client = client; } public String getKeywords() { return keywords; } public void setKeywords(String keywords) { this.keywords = keywords; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Column(name = "company_name") public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } @Column(name = "bind_domain") public String getBindDomain() { return bindDomain; } public void setBindDomain(String bindDomain) { this.bindDomain = bindDomain; } @Column(name = "column_id") public String getColumnId() { return columnId; } /** * * @param columnId 传入如 345, */ public void setColumnId(String columnId) { this.columnId = columnId; } @Column(name = "state") public Short getState() { return state; } public void setState(Short state) { this.state = state; } public String getTemplateName() { return templateName; } public void setTemplateName(String templateName) { this.templateName = Sql.filter(templateName); } public Integer getExpiretime() { return expiretime; } public void setExpiretime(Integer expiretime) { this.expiretime = expiretime; } public Short getUseKefu() { return useKefu; } public void setUseKefu(Short useKefu) { this.useKefu = useKefu; } @Override public String toString() { return "Site [id=" + id + ", name=" + name + ", userid=" + userid + ", addtime=" + addtime + ", mShowBanner=" + mShowBanner + ", phone=" + phone + ", qq=" + qq + ", templateId=" + templateId + ", domain=" + domain + ", aboutUsCid=" + aboutUsCid + ", logo=" + logo + ", client=" + client + ", keywords=" + keywords + ", address=" + address + ", username=" + username + ", companyName=" + companyName + ", bindDomain=" + bindDomain + ", columnId=" + columnId + ", state=" + state + ", templateName=" + templateName + ", expiretime=" + expiretime + "]"; } }package thoughtnote.com.utilz; import androidx.databinding.BindingAdapter; import android.graphics.Typeface; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import javax.inject.Inject; /** * Created by root on 9/25/17. */ public class EmptyViewModel { //EmptyViewModel created if we are not gng to access viewmodel.. @Inject public EmptyViewModel(){ } @BindingAdapter({"bind:textfont"}) public static void settextFont(TextView textView, String fontName) { textView.setTypeface(Typeface.createFromAsset(textView.getContext().getAssets(), "fonts/" + fontName)); } @BindingAdapter({"bind:Editfont"}) public static void setEditFont(EditText textView, String fontName) { textView.setTypeface(Typeface.createFromAsset(textView.getContext().getAssets(), "fonts/" + fontName)); } @BindingAdapter({"bind:Buttonfont"}) public static void setButtonFont(Button textView, String fontName) { textView.setTypeface(Typeface.createFromAsset(textView.getContext().getAssets(), "fonts/" + fontName)); } } /* * Copyright (C) 2020-2022 OpusCapita * Copyright (C) 2022 (www.helger.com) * philip[at]helger[dot]com * * 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.helger.phase4.profile.eespa; import javax.annotation.Nonnull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.helger.commons.annotation.IsSPIImplementation; import com.helger.phase4.model.pmode.IPModeIDProvider; import com.helger.phase4.profile.AS4Profile; import com.helger.phase4.profile.IAS4ProfilePModeProvider; import com.helger.phase4.profile.IAS4ProfileRegistrar; import com.helger.phase4.profile.IAS4ProfileRegistrarSPI; /** * Library specific implementation of {@link IAS4ProfileRegistrarSPI}. * * @author OpusCapita */ @IsSPIImplementation public final class AS4EESPAProfileRegistarSPI implements IAS4ProfileRegistrarSPI { public static final String AS4_PROFILE_ID_ACCEPTANCE = "eespa-acc"; public static final String AS4_PROFILE_NAME_ACCEPTANCE = "EESPA Acceptance"; public static final String AS4_PROFILE_ID_PROD = "eespa-prod"; public static final String AS4_PROFILE_NAME_PROD = "EESPA Production"; public static final IPModeIDProvider PMODE_ID_PROVIDER = IPModeIDProvider.DEFAULT_DYNAMIC; private static final Logger LOGGER = LoggerFactory.getLogger (AS4EESPAProfileRegistarSPI.class); public void registerAS4Profile (@Nonnull final IAS4ProfileRegistrar aRegistrar) { final IAS4ProfilePModeProvider aDefaultPModeProviderAcc = (i, r, a) -> EESPAPMode.createEESPAPMode (i, r, a, PMODE_ID_PROVIDER, true, false); final IAS4ProfilePModeProvider aDefaultPModeProviderProd = (i, r, a) -> EESPAPMode.createEESPAPMode (i, r, a, PMODE_ID_PROVIDER, false, false); if (LOGGER.isDebugEnabled ()) LOGGER.debug ("Registering phase4 profile '" + AS4_PROFILE_ID_ACCEPTANCE + "'"); final AS4Profile aProfileAcc = new AS4Profile (AS4_PROFILE_ID_ACCEPTANCE, AS4_PROFILE_NAME_ACCEPTANCE, EESPACompatibilityValidator::new, aDefaultPModeProviderAcc, PMODE_ID_PROVIDER, false); aRegistrar.registerProfile (aProfileAcc); if (LOGGER.isDebugEnabled ()) LOGGER.debug ("Registering phase4 profile '" + AS4_PROFILE_ID_PROD + "'"); final AS4Profile aProfileProd = new AS4Profile (AS4_PROFILE_ID_PROD, AS4_PROFILE_NAME_PROD, EESPACompatibilityValidator::new, aDefaultPModeProviderProd, PMODE_ID_PROVIDER, false); aRegistrar.registerProfile (aProfileProd); // Default to acc aRegistrar.setDefaultProfile (aProfileAcc); } } package com.dcits.dcwlt.pay.api.domain.dcep.comconf; import com.alibaba.fastjson.annotation.JSONField; import com.dcits.dcwlt.common.pay.enums.ProcessStatusCodeEnum; import com.dcits.dcwlt.pay.api.domain.dcep.DCEPHeader; import com.dcits.dcwlt.pay.api.domain.dcep.DCEPRspBody; import com.dcits.dcwlt.pay.api.domain.dcep.common.GrpHdr; import javax.validation.Valid; /** * * @desc 通信级响应体 */ public class ComConfDTO extends DCEPRspBody { @Valid private ComConf comConf; /* * 初始化通信级确认报文 * @Param: GrpHdr * @Param: DCEPHeader * */ public static ComConfDTO newInstance(GrpHdr grpHdr, DCEPHeader dcepHeader, String remark ) { ComConfDTO comConfDTO = new ComConfDTO(); ComConf comConf = new ComConf(); ConfInf confInf = new ConfInf(); confInf.setPrcSts(ProcessStatusCodeEnum.PR00.getValue()); confInf.setOrigSndDtTm(dcepHeader.getSndDtTm()); confInf.setOrgnlInstgPty(grpHdr.getInstgPty().getInstgDrctPty()); confInf.setOrgnlMsgId(grpHdr.getMsgId()); confInf.setOrgnlMT(dcepHeader.getMsgTp()); confInf.setRemark(remark); comConf.setConfInf(confInf); comConfDTO.setComConf(comConf); return comConfDTO; } /* * 初始化通信级确认报文 * @Param: GrpHdr * @Param: DCEPHeader * */ public static ComConfDTO newInstance(GrpHdr grpHdr, DCEPHeader dcepHeader ) { ComConfDTO comConfDTO = new ComConfDTO(); ComConf comConf = new ComConf(); ConfInf confInf = new ConfInf(); confInf.setPrcSts(ProcessStatusCodeEnum.PR00.getValue()); confInf.setOrigSndDtTm(dcepHeader.getSndDtTm()); confInf.setOrgnlInstgPty(grpHdr.getInstgPty().getInstgDrctPty()); confInf.setOrgnlMsgId(grpHdr.getMsgId()); confInf.setOrgnlMT(dcepHeader.getMsgTp()); comConf.setConfInf(confInf); comConfDTO.setComConf(comConf); return comConfDTO; } @JSONField(name = "ComConf") public ComConf getComConf() { return comConf; } public void setComConf(ComConf comConf) { this.comConf = comConf; } @Override public String toString() { return "ComConfDTO{" + "ComConf=" + comConf + '}'; } } /* * Copyright 2013 . * * 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.gs.collections.impl.partition.bag.sorted; import com.gs.collections.api.bag.sorted.ImmutableSortedBag; import com.gs.collections.api.partition.bag.sorted.PartitionImmutableSortedBag; import com.gs.collections.api.partition.bag.sorted.PartitionSortedBag; import net.jcip.annotations.Immutable; /** * @since 4.2 */ @Immutable public class PartitionImmutableSortedBagImpl implements PartitionImmutableSortedBag { private final ImmutableSortedBag selected; private final ImmutableSortedBag rejected; public PartitionImmutableSortedBagImpl(PartitionSortedBag partitionImmutableSortedBag) { this.selected = partitionImmutableSortedBag.getSelected().toImmutable(); this.rejected = partitionImmutableSortedBag.getRejected().toImmutable(); } public ImmutableSortedBag getSelected() { return this.selected; } public ImmutableSortedBag getRejected() { return this.rejected; } } greekwelfaresa/idempiere-test /** Generated Assertion Class - DO NOT CHANGE */ package au.org.greekwelfaresa.idempiere.test.assertj.m_rmaline; import au.org.greekwelfaresa.idempiere.test.assertj.po.AbstractPOAssert; import java.util.Objects; import javax.annotation.Generated; import org.compiere.model.X_M_RMALine; /** Generated assertion class for M_RMALine * @author idempiere-test (generated) * @version Release 6.2 - $Id: ca799ffd2984376ff96885caae71704351a0f15c $ */ @Generated("class au.org.greekwelfaresa.idempiere.test.generator.ModelAssertionGenerator") public abstract class AbstractM_RMALineAssert, ACTUAL extends X_M_RMALine> extends AbstractPOAssert { /** Standard Constructor */ public AbstractM_RMALineAssert (ACTUAL actual, Class selfType) { super (actual, selfType); } public SELF hasAmt(Object expected) { isNotNull(); bdAssert("Amt", actual.getAmt(), expected); return myself; } public SELF hasC_Charge_ID(int expected) { isNotNull(); int actualField = actual.getC_Charge_ID(); if (expected != actualField) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have C_Charge_ID: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasC_Tax_ID(int expected) { isNotNull(); int actualField = actual.getC_Tax_ID(); if (expected != actualField) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have C_Tax_ID: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasDescription(String expected) { isNotNull(); String actualField = actual.getDescription(); if (!Objects.equals(expected, actualField)) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have Description: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasLine(int expected) { isNotNull(); int actualField = actual.getLine(); if (expected != actualField) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have Line: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasLineNetAmt(Object expected) { isNotNull(); bdAssert("LineNetAmt", actual.getLineNetAmt(), expected); return myself; } public SELF hasM_InOutLine_ID(int expected) { isNotNull(); int actualField = actual.getM_InOutLine_ID(); if (expected != actualField) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have M_InOutLine_ID: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasM_Product_ID(int expected) { isNotNull(); int actualField = actual.getM_Product_ID(); if (expected != actualField) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have M_Product_ID: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasM_RMA_ID(int expected) { isNotNull(); int actualField = actual.getM_RMA_ID(); if (expected != actualField) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have M_RMA_ID: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasM_RMALine_ID(int expected) { isNotNull(); int actualField = actual.getM_RMALine_ID(); if (expected != actualField) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have M_RMALine_ID: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF hasM_RMALine_UU(String expected) { isNotNull(); String actualField = actual.getM_RMALine_UU(); if (!Objects.equals(expected, actualField)) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have M_RMALine_UU: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } public SELF isProcessed() { isNotNull(); if (!actual.isProcessed()) { failWithMessage("\nExpecting PO:\n <%s>\nto be Processed\nbut it was not", getPODescription()); } return myself; } public SELF isNotProcessed() { isNotNull(); if (actual.isProcessed()) { failWithMessage("\nExpecting PO: \n <%s>\n to not be Processed\nbut it was", getPODescription()); } return myself; } public SELF hasQty(Object expected) { isNotNull(); bdAssert("Qty", actual.getQty(), expected); return myself; } public SELF hasQtyDelivered(Object expected) { isNotNull(); bdAssert("QtyDelivered", actual.getQtyDelivered(), expected); return myself; } public SELF hasQtyInvoiced(Object expected) { isNotNull(); bdAssert("QtyInvoiced", actual.getQtyInvoiced(), expected); return myself; } public SELF hasRef_RMALine_ID(int expected) { isNotNull(); int actualField = actual.getRef_RMALine_ID(); if (expected != actualField) { failWithActualExpectedAndMessage(actualField, expected, "\nExpecting PO: \n <%s>\n to have Ref_RMALine_ID: <%s>\nbut it was: <%s>", getPODescription(), expected, actualField); } return myself; } }1-10 package com.susstore.pojo.chat; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; @Data @AllArgsConstructor @NoArgsConstructor @Builder public class InitChat { private Integer userId; private String userName; private String picturePath; private List chatHistories; } EliottSimon17/PlayItNice1-10 package GameTree; import View.Line; import Controller.Controller; import Controller.GridController; import View.Square; import View.Player; import java.util.*; public class State { private ArrayList players; private String hashedId = ""; private int turn; private static State currentState; private ArrayList children; private ArrayList lines; private static int nbOfids =0; /** * @param g set of line * @param players assign an array list which contains all the player to a state */ public State(ArrayList g, ArrayList players) { this.lines = g; this.players = players; } public void setLines(ArrayList lines) { this.lines = lines; } //use this state constructor only for the current state! public State(ArrayList players, int turn) { this.players = players; this.turn = turn; } /** * @return the player which is actually playing (which is why this is static) */ public static Player getCurrentActualPlayer() { return currentState.getActualPlayer(); } public static ArrayList getCurrentPlayers() { return currentState.getPlayers(); } //get the children of the State public ArrayList getChildren() { return this.children; } public ArrayList getChildrenStupid() { ArrayList result = new ArrayList<>(); //System.out.println("lines size: "+this.lines.size()); for (int l : this.lines) { Line line= GridController.findLine(l); if (line.isEmpty()) { if (!GridController.isThirdLine(line)) { State child = computeAChild(line.getId()); result.add(child); } for (Square sq : line.getSquares()) { if (sq.getValence() == 1) { result = new ArrayList<>(); result.add(computeAChild(line.getId())); return result; } } } } if (result.size()==0) { for (int l:this.lines) { State child = computeAChild(l); result.add(child); } } this.children=result; return result; } public static int isEqual(ArrayList lines, State other){ int nbOfDifferences = 0; for (Integer l : lines) { if (!other.getLines().contains(l)) { nbOfDifferences++; //System.out.println("nbOfDifferences = " + l.getid()); } } return nbOfDifferences; } public ArrayList computeAndGetChildren() { if (this.children == null) { computeChildren(); } return this.children; } public ArrayList computeAndGetChildrenPruning() { if (this.children == null) { computeChildrenPruning(); } return this.children; } public void setChildren(ArrayList children) { this.children = children; } public ArrayList getPlayers() { return players; } public void computeChildren() { ArrayList result = new ArrayList<>(); for (int line : this.lines) { State child = computeAChild(line); result.add(child); } this.children=result; } public void computeChildrenPruning() { ArrayList result = new ArrayList<>(); ArrayList> symmetricStates = new ArrayList<>(); for (int line : this.lines) { State child = computeAChild(line); if (!inList(GridController.getUnEmptyLines(child), symmetricStates)) { result.add(child); symmetricStates.addAll(GridController.checkStateSymmetry(GridController.getUnEmptyLines(child))); } } this.children=result; } public static void display(ArrayList lines) { for (Integer line:lines) { System.out.print(line+", "); } } public boolean inList(ArrayList lines, ArrayList> symmetricStates) { for (ArrayList setOfLines:symmetricStates) { boolean inList=true; for (Integer line: lines) { if (!setOfLines.contains(line)) { inList= false; } } if (inList){ return true; } } return false; } public void display() { for (int l : lines) { System.out.print(l + ", "); } System.out.println(); } public static State currentState() { return currentState; } public static void setCurrentState(State currentState) { State.currentState = currentState; } //returns a cloned state public State cloned() { State result = new State(State.cloned(this.getLines()), Player.cloned(this.players)); result.setTurn(this.getTurn()); if (this.children != null) { result.setChildren(this.clonedChildren()); } return result; } //returns a cloned arraylist of lines public static ArrayList cloned(ArrayList lines) { ArrayList result = new ArrayList<>(); result.addAll(lines); return result; } //finds the lines that needs to be colored for mcts public static int findDiffLine(ArrayList parent, ArrayList child) { Integer randomEmptyLine = null; for (int line : parent) { if (!child.contains(line)) { return line; } } if (randomEmptyLine == null) { // System.out.println("parent and child are identical"); return child.get(0); } return randomEmptyLine; } public static int findDiffLine(State parent, State child) { // System.out.println("parent"); //parent.display(); //System.out.println("child"); //child.display(); return findDiffLine(parent.getLines(), child.getLines()); } //clears a state public void reset() { this.getLines().clear(); this.getPlayers().clear(); if (getChildren() != null) { this.getChildren().clear(); } this.turn = 0; } public void setPlayable() { currentState().setLines(GridController.getLinesIds()); } public int numberOfAvailableMoves() { return lines.size(); } public ArrayList getAvailableMoves() { return lines; } public int isEqual(State other) { int nbOfDifferences = 0; for (Integer l : this.getLines()) { if (!other.getLines().contains(l)) { nbOfDifferences++; //System.out.println("nbOfDifferences = " + l.getid()); } } return nbOfDifferences; } public ArrayList getLines() { return lines; } /* public ArrayList getSquares() { return squares; }*/ public int getScore(int turn) { return players.get(turn).getScore(); } public Player getActualPlayer() { return players.get(turn); } public int getTurn() { return turn; } public void setTurn(int turn) { this.turn = turn; } public void setPlayers(ArrayList newPlayers, int turn) { this.players = newPlayers; this.turn = turn; } public int getScore(Player player) { //-1 is just an arbitrary value int result = -1; for (Player p : players) { if (p.getName().equals(player.getName())) { return p.getScore(); } } if (result == -1) { System.out.println("player not found"); } return result; } public ArrayList clonedChildren() { ArrayList result = new ArrayList<>(); for (State state : this.children) { result.add(state.cloned()); } return result; } public int getValence(int k) { int counter = 0; for (Square sq : GridController.getSquares()) { if (sq.getValence() == k) { counter++; } } // System.out.println(counter); return counter; } public int getNextTurn(int turn){ if (turn==1){ return 0; } else{ return 1; } } public static int inverseTurn(int turn){ if (turn ==0){ return 1; } else { return 0; } } public void nextTurn() { this.turn = this.turn + 1; } public boolean isComplete() { return getScore(players.get(0)) + getScore(players.get(1)) == getLines().size() - 2; } public State computeAChild(int line) { State childState = this.cloned(); childState.getLines().remove(Integer.valueOf(line)); Controller.updateTurn(line, childState); return childState; } public String getHashedID() { int id = 0; Random rand = new Random(); // for(int i = 0 ; i < QTraining.width * QTraining.height; i ++ ){ // id = id * QTraining.width; // id += rand.nextInt(1); // } if(this.hashedId!="") { return this.hashedId; }else{ this.hashedId= toInt(this.orderedLines()); return this.hashedId; } } public boolean isPlayable(int index, State parent) { /** * TODO * at a given state, check if the index is a valid mode * which means it checks if the line which correseponds to * the index is possible to play */ // // System.out.println("parent"); // parent.display(); // System.out.println("child"); // this.display(); boolean playable = false; for(Integer i : getLines()){ if(i==index){ playable = true; } if(!parent.getLines().contains(i)){ //System.out.println("this state is not playable"); return false; } } if(!playable) { // System.out.println("line " + index + " is not playable"); }else{ // System.out.println("line " + index + " is playable"); } return playable; } public String toInt(ArrayList a){ String toConvert = ""; for(Integer t : a){ toConvert+= t.toString(); } return toConvert; } public ArrayList orderedLines(){ ArrayList result = new ArrayList<>(); for(Integer i : this.lines){ result.add(i); } return result; } public boolean isPlayable(int index) { /** * TODO * at a given state, check if the index is a valid mode * which means it checks if the line which correseponds to * the index is possible to play */ for(Integer itg : getLines()){ if(itg==index){ return true; } } return false; } }1-10 package com.xceptance.xlt.nocoding.parser; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.xceptance.xlt.api.util.XltLogger; import com.xceptance.xlt.nocoding.parser.csv.CsvParser; import com.xceptance.xlt.nocoding.parser.yaml.YamlParser; /** * The class for getting the accepted extensions and the associated {@link Parser} for the extension * * @author ckeiner */ public class ParserFactory { /** * The singleton instance of ParserFactory */ private static ParserFactory factoryInstance; /** * The map, that maps the extension to a concrete parser */ private final Map extensionsMap; /** * Creates a new instance of ParserFactory and fills {@link #extensionsMap} with the known Parsers and * its extensions */ private ParserFactory() { extensionsMap = new HashMap<>(); final CsvParser csvParser = new CsvParser(); final YamlParser yamlParser = new YamlParser(); for (final String extension : csvParser.getExtensions()) { extensionsMap.put(extension, csvParser); } for (final String extension : yamlParser.getExtensions()) { extensionsMap.put(extension, yamlParser); } } /** * Either creates an instance of ParserFactory if {@link #factoryInstance} is null or * returns factoryInstance. * * @return the singleton instance of ParserFactory */ public static synchronized ParserFactory getInstance() { if (factoryInstance == null) { factoryInstance = new ParserFactory(); } return factoryInstance; } /** * Returns a list of all known file extensions for the parser, therefore it returns the {@link Map#keySet()} of * {@link #extensionsMap}. * * @return A list with the content of {@link Map#keySet()} of {@link #extensionsMap}. */ public List getExtensions() { return new ArrayList<>(extensionsMap.keySet()); } /** * Checks the parser for its file extensions and then creates the parser is the extension fits * * @param file * @return The Parser associated with the extension of file */ public Parser getParser(final String file) { // Extract the extension of the file, that is the last position of the . +1, so we cut out the dot final String extension = file.substring(file.lastIndexOf('.') + 1); // Get the Parser instance from the extensionsMap final Parser parser = extensionsMap.get(extension); // If the parser is null, the extensions could not be found if (parser == null) { throw new IllegalArgumentException("Could not find appropriate parser for the extension " + extension + " with the path " + file); } XltLogger.runTimeLogger.debug("Using " + parser.getClass().getSimpleName() + " for " + file); return parser; } } /* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.toolresults.model; /** * A set of similar suggestions that we suspect are closely related. * * This proto and most of the nested protos are branched from * foxandcrown.prelaunchreport.service.SuggestionClusterProto, replacing PLR's dependencies with * FTL's. * *

This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Cloud Tool Results API. For a detailed explanation * see: * https://developers.google.com/api-client-library/java/google-http-java-client/json *

* * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class SuggestionClusterProto extends com.google.api.client.json.GenericJson { /** * Category in which these types of suggestions should appear. Always set. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String category; /** * A sequence of suggestions. All of the suggestions within a cluster must have the same * SuggestionPriority and belong to the same SuggestionCategory. Suggestions with the same * screenshot URL should be adjacent. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List suggestions; /** * Category in which these types of suggestions should appear. Always set. * @return value or {@code null} for none */ public java.lang.String getCategory() { return category; } /** * Category in which these types of suggestions should appear. Always set. * @param category category or {@code null} for none */ public SuggestionClusterProto setCategory(java.lang.String category) { this.category = category; return this; } /** * A sequence of suggestions. All of the suggestions within a cluster must have the same * SuggestionPriority and belong to the same SuggestionCategory. Suggestions with the same * screenshot URL should be adjacent. * @return value or {@code null} for none */ public java.util.List getSuggestions() { return suggestions; } /** * A sequence of suggestions. All of the suggestions within a cluster must have the same * SuggestionPriority and belong to the same SuggestionCategory. Suggestions with the same * screenshot URL should be adjacent. * @param suggestions suggestions or {@code null} for none */ public SuggestionClusterProto setSuggestions(java.util.List suggestions) { this.suggestions = suggestions; return this; } @Override public SuggestionClusterProto set(String fieldName, Object value) { return (SuggestionClusterProto) super.set(fieldName, value); } @Override public SuggestionClusterProto clone() { return (SuggestionClusterProto) super.clone(); } } src/main/java/xyz/snwjas/blog/mapper/UserMapper.java1-10 package xyz.snwjas.blog.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import xyz.snwjas.blog.model.entity.UserEntity; /** *

* 用户 Mapper 接口 *

* * @author */ public interface UserMapper extends BaseMapper { } package hudson.remoting; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; import java.util.concurrent.ExecutionException; import javax.annotation.Nonnull; /** * {@link ResourceImageRef} that points to a resource inside a jar file. * *

* The jar file is identified by its checksum, and the receiver can use {@link JarLoader} * to retrieve the jar file if necessary. * * @author */ class ResourceImageInJar extends ResourceImageRef { /** * Check sum of the jar file that contains the resource. */ final long sum1,sum2; /** * This field is null if the resource being requested is in the 'sane' location inside the jar file * (the path that {@link URLClassLoader} will find when given a jar file.) Otherwise this specifies * the exact path inside the jar file of the resource. */ final String path; ResourceImageInJar(long sum1, long sum2, String path) { this.sum1 = sum1; this.sum2 = sum2; this.path = path; } ResourceImageInJar(Checksum sum, String path) { this(sum.sum1,sum.sum2,path); } @Override Future resolve(Channel channel, final String resourcePath) throws IOException, InterruptedException { return new FutureAdapter(_resolveJarURL(channel)) { @Override @SuppressFBWarnings(value = "URLCONNECTION_SSRF_FD", justification = "This is only used for managing the jar cache as files.") protected byte[] adapt(URL jar) throws ExecutionException { try { return Util.readFully(toResourceURL(jar,resourcePath).openStream()); } catch (IOException e) { throw new ExecutionException(e); } } }; } @Override Future resolveURL(Channel channel, final String resourcePath) throws IOException, InterruptedException { return new FutureAdapter(_resolveJarURL(channel)) { @Override protected URLish adapt(URL jar) throws ExecutionException { try { return URLish.from(toResourceURL(jar, resourcePath)); } catch (IOException e) { throw new ExecutionException(e); } } }; } @Nonnull private URL toResourceURL(URL jar, String resourcePath) throws IOException { if (path!=null) resourcePath = path; /* & Kohsuke: Note that when we open a stream from this jar:// URL, it internally caches open jar file (see sun.net.www.protocol.jar.JarURLConnection.JarURLInputStream.close()) and leave it open. During unit test, this pins the file, and it prevents the test tear down code from deleting the file. */ return new URL("jar:"+ jar +"!/"+resourcePath); } Future _resolveJarURL(Channel channel) throws IOException, InterruptedException { JarCache c = channel.getJarCache(); if (c == null) { throw new IOException(String.format("Failed to resolve a jar %016x%016x. JAR Cache is disabled for the channel %s", sum1, sum2, channel.getName())); } return c.resolve(channel, sum1, sum2); // throw (IOException)new IOException(String.format("Failed to resolve a jar %016x%016x",sum1,sum2)).initCause(e); } private static final long serialVersionUID = 1L; } /* * Copyright 2018 herd-mdl contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ package org.finra.herd.metastore.managed.jobProcessor; import com.google.common.base.Strings; import lombok.extern.slf4j.Slf4j; import org.finra.herd.metastore.managed.JobDefinition; import org.finra.herd.metastore.managed.conf.HerdMetastoreConfig; import org.finra.herd.metastore.managed.datamgmt.DataMgmtSvc; import org.finra.herd.sdk.invoker.ApiException; import org.finra.herd.sdk.model.BusinessObjectFormat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component @Slf4j public class ManagedObjStatsProcessor extends JobProcessor { private static final String SCRIPT_PATH = HerdMetastoreConfig.homeDir + "/metastor/deploy/common/scripts/stats/emr_gather_stats.sh"; @Autowired DataMgmtSvc dataMgmtSvc; @Override protected ProcessBuilder createProcessBuilder( JobDefinition od ) { String dbName = od.getObjectDefinition().getDbName(); String tblName = od.getObjectDefinition().getObjectName() + "_" + od.getObjectDefinition().getUsageCode() + "_" + od.getObjectDefinition().getFileType(); tblName = tblName.replaceAll( "\\.", "_" ).replaceAll( " ", "_" ).replaceAll( "-", "_" ); ProcessBuilder pb = null; try { BusinessObjectFormat dmFormat = dataMgmtSvc.getDMFormat( od ); String quotedPartitionKeys = quotedPartitionKeys( dmFormat.getSchema() ); if ( Strings.isNullOrEmpty( quotedPartitionKeys ) ) { log.error( "ERROR: PARTITION_COLUMNS is empty for {}", tblName ); return pb; } pb = new ProcessBuilder( "sh", SCRIPT_PATH, dbName, tblName, quotedPartitionKeys ); } catch ( ApiException e ) { log.error( "Could not get BO format due to: {}", e.getMessage(), e ); } return pb; } } geode-connectors/src/main/java/org/apache/geode/connectors/jdbc/internal/AbstractJdbcCallback.java /* * 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.geode.connectors.jdbc.internal; import org.apache.geode.annotations.Experimental; import org.apache.geode.cache.CacheCallback; import org.apache.geode.cache.Operation; import org.apache.geode.cache.Region; import org.apache.geode.internal.cache.InternalCache; @Experimental public abstract class AbstractJdbcCallback implements CacheCallback { private volatile SqlHandler sqlHandler; protected InternalCache cache; protected AbstractJdbcCallback() { // nothing } protected AbstractJdbcCallback(SqlHandler sqlHandler, InternalCache cache) { this.sqlHandler = sqlHandler; this.cache = cache; } protected SqlHandler getSqlHandler() { return sqlHandler; } protected void checkInitialized(Region region) { if (sqlHandler == null) { initialize(region); } } protected boolean eventCanBeIgnored(Operation operation) { return operation.isLoad(); } private synchronized void initialize(Region region) { if (sqlHandler == null) { cache = (InternalCache) region.getRegionService(); JdbcConnectorService service = cache.getService(JdbcConnectorService.class); TableMetaDataManager tableMetaDataManager = new TableMetaDataManager(); sqlHandler = createSqlHandler(cache, region.getName(), tableMetaDataManager, service); } } SqlHandler createSqlHandler(InternalCache cache, String regionName, TableMetaDataManager tableMetaDataManager, JdbcConnectorService service) { return new SqlHandler(cache, regionName, tableMetaDataManager, service); } } /** * Copyright 2008 The Scribble Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.scribble.parser.scribble.ast; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.stream.Collectors; import org.antlr.runtime.tree.CommonTree; import org.scribble.ast.AstFactory; import org.scribble.ast.ImportDecl; import org.scribble.ast.Module; import org.scribble.ast.ModuleDecl; import org.scribble.ast.NonProtocolDecl; import org.scribble.ast.ProtocolDecl; import org.scribble.parser.scribble.ScribParser; import org.scribble.parser.scribble.ScribParserUtil; import org.scribble.parser.scribble.AntlrConstants.AntlrNodeType; import org.scribble.util.ScribParserException; public class AntlrModule { public static final int MODULEDECL_CHILD_INDEX = 0; public static Module parseModule(ScribParser parser, CommonTree ct, AstFactory af) throws ScribParserException { ModuleDecl md = (ModuleDecl) parser.parse(getModuleDeclChild(ct), af); List> ids = new LinkedList<>(); List> ptds = new LinkedList<>(); List> pds = new LinkedList<>(); for (CommonTree id : getImportDeclChildren(ct)) { ImportDecl tmp = (ImportDecl) parser.parse(id, af); ids.add(tmp); } for (CommonTree ptd : getDataTypeDeclChildren(ct)) { NonProtocolDecl tmp = (NonProtocolDecl) parser.parse(ptd, af); ptds.add(tmp); } for (CommonTree pd : getProtocolDeclChildren(ct)) { ProtocolDecl tmp = (ProtocolDecl) parser.parse(pd, af); pds.add(tmp); } return af.Module(ct, md, ids, ptds, pds); } public static CommonTree getModuleDeclChild(CommonTree ct) { return (CommonTree) ct.getChild(MODULEDECL_CHILD_INDEX); } public static List getImportDeclChildren(CommonTree ct) { return filterChildren(ct, AntlrNodeType.IMPORTMODULE, AntlrNodeType.IMPORTMEMBER); } public static List getDataTypeDeclChildren(CommonTree ct) { return filterChildren(ct, AntlrNodeType.PAYLOADTYPEDECL, AntlrNodeType.MESSAGESIGNATUREDECL); } public static List getProtocolDeclChildren(CommonTree ct) { return filterChildren(ct, AntlrNodeType.GLOBALPROTOCOLDECL, AntlrNodeType.LOCALPROTOCOLDECL); } private static List filterChildren(CommonTree ct, AntlrNodeType... types) { List tmp = Arrays.asList(types); List children = ScribParserUtil.toCommonTreeList(ct.getChildren()); return children.subList(1, children.size()).stream() .filter((c) -> tmp.contains(ScribParserUtil.getAntlrNodeType(c))).collect(Collectors.toList()); } } 1-10 package edu.unh.cs; import edu.unh.cs.treccar_v2.Data; import org.apache.lucene.document.Document; import org.jetbrains.annotations.NotNull; import java.util.HashMap; import java.util.List; import java.util.Map; /** * User: dietz * Date: 1/5/18 * Time: 3:22 PM */ public interface TrecCarPageRepr extends TrecCarRepr { @NotNull Map>> convertPage(Data.Page p); @NotNull List pageToLuceneDoc(Data.Page paragraph); @Override default TrecCarSearchField[] getSearchFields() { return TrecCarSearchField.values(); } } SingleShu/HelloV3branches/branch3_0_5/app/src/main/java/com/abings/baby/ui/measuredata/teachingplan/RecyclerViewAdapterTeachPlanningList.java1-10 package com.abings.baby.ui.measuredata.teachingplan; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Parcelable; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.abings.baby.ui.event.EventDetailActivity; import com.hellobaby.library.R; import com.hellobaby.library.data.model.EventModel; import com.hellobaby.library.data.model.TeachingPlanModel; import com.hellobaby.library.ui.slide.SlideActivity; import com.hellobaby.library.ui.slide.SlideBean; import com.hellobaby.library.utils.DateUtil; import com.hellobaby.library.utils.ImageLoader; import com.hellobaby.library.widget.baseadapter.BaseAdapter; import com.hellobaby.library.widget.baseadapter.ViewHolder; import java.util.ArrayList; import java.util.Date; import java.util.List; import static com.hellobaby.library.Const.NORMAL_ACTIVITY_RESULT; public class RecyclerViewAdapterTeachPlanningList extends BaseAdapter { public RecyclerViewAdapterTeachPlanningList(Context context, List datas, boolean isOpenLoadMore) { super(context, datas, isOpenLoadMore); } @Override protected void convert(ViewHolder holder, final TeachingPlanModel data) { final RelativeLayout rl=(RelativeLayout) holder.getView(R.id.tplist_rl_root); TextView textView=(TextView)holder.getView(R.id.tp_tv_createTime); ImageView imageView=(ImageView) holder.getView(R.id.tp_im); ImageLoader.load(mContext,data.getImageurlAbs(),imageView); textView.setText("来自"+data.getTeacherName()+" "+data.getPlanningTime()); } @Override protected int getItemLayoutId() { return R.layout.librecyler_item_teachingplist; } } /* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.test.util; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtilRt; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.psi.PsiFileFactory; import com.intellij.psi.impl.PsiFileFactoryImpl; import com.intellij.testFramework.LightVirtualFile; import com.intellij.util.PathUtil; import com.intellij.util.containers.ContainerUtil; import kotlin.collections.SetsKt; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.kotlin.idea.KotlinLanguage; import org.jetbrains.kotlin.psi.KtFile; import org.jetbrains.kotlin.test.KtAssert; import org.jetbrains.kotlin.test.TargetBackend; import org.jetbrains.kotlin.test.TestMetadata; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.Method; import java.util.HashSet; import java.util.Set; import java.util.regex.Pattern; import static org.jetbrains.kotlin.test.InTextDirectivesUtils.isCompatibleTarget; public class KtTestUtil { private static String homeDir = computeHomeDirectory(); @NotNull public static File tmpDirForTest(@NotNull String testClassName, @NotNull String testName) throws IOException { return normalizeFile(FileUtil.createTempDirectory(testClassName, testName, false)); } @NotNull public static File tmpDir(String name) throws IOException { return normalizeFile(FileUtil.createTempDirectory(name, "", false)); } @NotNull public static File tmpDirForReusableFolder(String name) throws IOException { return normalizeFile(FileUtil.createTempDirectory(new File(System.getProperty("java.io.tmpdir")), name, "", true)); } private static File normalizeFile(File file) throws IOException { // Get canonical file to be sure that it's the same as inside the compiler, // for example, on Windows, if a canonical path contains any space from FileUtil.createTempDirectory we will get // a File with short names (8.3) in its path and it will break some normalization passes in tests. return file.getCanonicalFile(); } @NotNull public static KtFile createFile(@NotNull @NonNls String name, @NotNull String text, @NotNull Project project) { String shortName = name.substring(name.lastIndexOf('/') + 1); shortName = shortName.substring(shortName.lastIndexOf('\\') + 1); LightVirtualFile virtualFile = new LightVirtualFile(shortName, KotlinLanguage.INSTANCE, StringUtilRt.convertLineSeparators(text)); virtualFile.setCharset(CharsetToolkit.UTF8_CHARSET); PsiFileFactoryImpl factory = (PsiFileFactoryImpl) PsiFileFactory.getInstance(project); //noinspection ConstantConditions return (KtFile) factory.trySetupPsiForFile(virtualFile, KotlinLanguage.INSTANCE, true, false); } public static String doLoadFile(String myFullDataPath, String name) throws IOException { String fullName = myFullDataPath + File.separatorChar + name; return doLoadFile(new File(fullName)); } public static String doLoadFile(@NotNull File file) throws IOException { try { return FileUtil.loadFile(file, CharsetToolkit.UTF8, true); } catch (FileNotFoundException fileNotFoundException) { /* * Unfortunately, the FileNotFoundException will only show the relative path in it's exception message. * This clarifies the exception by showing the full path. */ String messageWithFullPath = file.getAbsolutePath() + " (No such file or directory)"; throw new IOException( "Ensure you have your 'Working Directory' configured correctly as the root " + "Kotlin project directory in your test configuration\n\t" + messageWithFullPath, fileNotFoundException); } } public static String getFilePath(File file) { return FileUtil.toSystemIndependentName(file.getPath()); } @NotNull public static File getJdk9Home() { String jdk9 = System.getenv("JDK_9"); if (jdk9 == null) { jdk9 = System.getenv("JDK_19"); if (jdk9 == null) { throw new AssertionError("Environment variable JDK_9 is not set!"); } } return new File(jdk9); } @Nullable public static File getJdk11Home() { String jdk11 = System.getenv("JDK_11"); if (jdk11 == null) { return null; } return new File(jdk11); } @NotNull public static File getJdk15Home() { String jdk15 = System.getenv("JDK_15"); if (jdk15 == null) { jdk15 = System.getenv("JDK_15_0"); } if (jdk15 == null) { throw new AssertionError("Environment variable JDK_15 is not set!"); } return new File(jdk15); } @NotNull public static String getTestDataPathBase() { return getHomeDirectory() + "/compiler/testData"; } @NotNull public static String getHomeDirectory() { return homeDir; } @NotNull private static String computeHomeDirectory() { String userDir = System.getProperty("user.dir"); File dir = new File(userDir == null ? "." : userDir); return FileUtil.toCanonicalPath(dir.getAbsolutePath()); } public static File findMockJdkRtJar() { return new File(getHomeDirectory(), "compiler/testData/mockJDK/jre/lib/rt.jar"); } // Differs from common mock JDK only by one additional 'nonExistingMethod' in Collection and constructor from Double in Throwable // It's needed to test the way we load additional built-ins members that neither in black nor white lists public static File findMockJdkRtModified() { return new File(getHomeDirectory(), "compiler/testData/mockJDKModified/rt.jar"); } public static File findAndroidApiJar() { String androidJarProp = System.getProperty("android.jar"); File androidJarFile = androidJarProp == null ? null : new File(androidJarProp); if (androidJarFile == null || !androidJarFile.isFile()) { throw new RuntimeException( "Unable to get a valid path from 'android.jar' property (" + androidJarProp + "), please point it to the 'android.jar' file location"); } return androidJarFile; } @NotNull public static File findAndroidSdk() { String androidSdkProp = System.getProperty("android.sdk"); File androidSdkDir = androidSdkProp == null ? null : new File(androidSdkProp); if (androidSdkDir == null || !androidSdkDir.isDirectory()) { throw new RuntimeException( "Unable to get a valid path from 'android.sdk' property (" + androidSdkProp + "), please point it to the android SDK location"); } return androidSdkDir; } public static String getAndroidSdkSystemIndependentPath() { return PathUtil.toSystemIndependentName(findAndroidSdk().getAbsolutePath()); } public static File getAnnotationsJar() { return new File(getHomeDirectory(), "compiler/testData/mockJDK/jre/lib/annotations.jar"); } public static void mkdirs(@NotNull File file) { if (file.isDirectory()) { return; } if (!file.mkdirs()) { if (file.exists()) { throw new IllegalStateException("Failed to create " + file + ": file exists and not a directory"); } throw new IllegalStateException("Failed to create " + file); } } // ---------------------- assert testdata presented by metadata ---------------------- private static final String PLEASE_REGENERATE_TESTS = "Please regenerate tests (GenerateTests.kt)"; public static void assertAllTestsPresentByMetadataWithExcluded( @NotNull Class testCaseClass, @NotNull File testDataDir, @NotNull Pattern filenamePattern, @Nullable Pattern excludedPattern, boolean recursive, @NotNull String... excludeDirs ) { assertAllTestsPresentByMetadataWithExcluded(testCaseClass, testDataDir, filenamePattern, excludedPattern, TargetBackend.ANY, recursive, excludeDirs); } public static void assertAllTestsPresentByMetadata( @NotNull Class testCaseClass, @NotNull File testDataDir, @NotNull Pattern filenamePattern, boolean recursive, @NotNull String... excludeDirs ) { assertAllTestsPresentByMetadata( testCaseClass, testDataDir, filenamePattern, TargetBackend.ANY, recursive, excludeDirs ); } public static void assertAllTestsPresentByMetadataWithExcluded( @NotNull Class testCaseClass, @NotNull File testDataDir, @NotNull Pattern filenamePattern, @Nullable Pattern excludedPattern, @NotNull TargetBackend targetBackend, boolean recursive, @NotNull String... excludeDirs ) { File rootFile = new File(getTestsRoot(testCaseClass)); Set filePaths = collectPathsMetadata(testCaseClass); Set exclude = SetsKt.setOf(excludeDirs); File[] files = testDataDir.listFiles(); if (files != null) { for (File file : files) { if (file.isDirectory()) { if (recursive && containsTestData(file, filenamePattern, excludedPattern) && !exclude.contains(file.getName())) { assertTestClassPresentByMetadata(testCaseClass, file); } } else { boolean excluded = excludedPattern != null && excludedPattern.matcher(file.getName()).matches(); if (!excluded && filenamePattern.matcher(file.getName()).matches() && isCompatibleTarget(targetBackend, file)) { assertFilePathPresent(file, rootFile, filePaths); } } } } } public static void assertAllTestsPresentByMetadata( @NotNull Class testCaseClass, @NotNull File testDataDir, @NotNull Pattern filenamePattern, @NotNull TargetBackend targetBackend, boolean recursive, @NotNull String... excludeDirs ) { assertAllTestsPresentByMetadataWithExcluded(testCaseClass, testDataDir, filenamePattern, null, targetBackend, recursive, excludeDirs); } public static void assertAllTestsPresentInSingleGeneratedClass( @NotNull Class testCaseClass, @NotNull File testDataDir, @NotNull Pattern filenamePattern ) { assertAllTestsPresentInSingleGeneratedClass(testCaseClass, testDataDir, filenamePattern, TargetBackend.ANY); } public static void assertAllTestsPresentInSingleGeneratedClassWithExcluded( @NotNull Class testCaseClass, @NotNull File testDataDir, @NotNull Pattern filenamePattern, @Nullable Pattern excludePattern ) { assertAllTestsPresentInSingleGeneratedClass(testCaseClass, testDataDir, filenamePattern, excludePattern, TargetBackend.ANY); } public static void assertAllTestsPresentInSingleGeneratedClass( @NotNull Class testCaseClass, @NotNull File testDataDir, @NotNull Pattern filenamePattern, @NotNull TargetBackend targetBackend ) { assertAllTestsPresentInSingleGeneratedClass(testCaseClass, testDataDir, filenamePattern, null, targetBackend); } public static void assertAllTestsPresentInSingleGeneratedClass( @NotNull Class testCaseClass, @NotNull File testDataDir, @NotNull Pattern filenamePattern, @Nullable Pattern excludePattern, @NotNull TargetBackend targetBackend ) { File rootFile = new File(getTestsRoot(testCaseClass)); Set filePaths = collectPathsMetadata(testCaseClass); FileUtil.processFilesRecursively(testDataDir, file -> { boolean excluded = excludePattern != null && excludePattern.matcher(file.getName()).matches(); if (file.isFile() && !excluded && filenamePattern.matcher(file.getName()).matches() && isCompatibleTarget(targetBackend, file)) { assertFilePathPresent(file, rootFile, filePaths); } return true; }); } private static void assertFilePathPresent(File file, File rootFile, Set filePaths) { String path = FileUtil.getRelativePath(rootFile, file); if (path != null) { String relativePath = nameToCompare(path); if (!filePaths.contains(relativePath)) { KtAssert.fail("Test data file missing from the generated test class: " + file + "\n" + PLEASE_REGENERATE_TESTS); } } } private static Set collectPathsMetadata(Class testCaseClass) { return new HashSet<>(ContainerUtil.map(collectMethodsMetadata(testCaseClass), KtTestUtil::nameToCompare)); } @Nullable public static String getMethodMetadata(Method method) { TestMetadata testMetadata = method.getAnnotation(TestMetadata.class); return (testMetadata != null) ? testMetadata.value() : null; } private static Set collectMethodsMetadata(Class testCaseClass) { Set filePaths = new HashSet<>(); for (Method method : testCaseClass.getDeclaredMethods()) { String path = getMethodMetadata(method); if (path != null) { filePaths.add(path); } } return filePaths; } private static boolean containsTestData(File dir, Pattern filenamePattern, @Nullable Pattern excludedPattern) { File[] files = dir.listFiles(); assert files != null; for (File file : files) { if (file.isDirectory()) { if (containsTestData(file, filenamePattern, excludedPattern)) { return true; } } else { boolean excluded = excludedPattern != null && excludedPattern.matcher(file.getName()).matches(); if (! excluded && filenamePattern.matcher(file.getName()).matches()) { return true; } } } return false; } private static void assertTestClassPresentByMetadata(@NotNull Class outerClass, @NotNull File testDataDir) { for (Class nestedClass : outerClass.getDeclaredClasses()) { TestMetadata testMetadata = nestedClass.getAnnotation(TestMetadata.class); if (testMetadata != null && testMetadata.value().equals(KtTestUtil.getFilePath(testDataDir))) { return; } } KtAssert.fail("Test data directory missing from the generated test class: " + testDataDir + "\n" + PLEASE_REGENERATE_TESTS); } public static String getTestsRoot(@NotNull Class testCaseClass) { TestMetadata testClassMetadata = testCaseClass.getAnnotation(TestMetadata.class); KtAssert.assertNotNull("No metadata for class: " + testCaseClass, testClassMetadata); return testClassMetadata.value(); } public static String nameToCompare(@NotNull String name) { return (SystemInfo.isFileSystemCaseSensitive ? name : name.toLowerCase()).replace('\\', '/'); } } package me.bscal.game.events.eventTypes; public class MouseReleasedEvent extends MouseButtonEvent{ public MouseReleasedEvent(int x, int y, int button) { super(button, x, y, EventType.MOUSE_RELEASED); } } /* Copyright (C) 2017 - All Rights Reserved */ package com.graham.passvaultplus.model; import com.graham.passvaultplus.PvpContext; import com.graham.passvaultplus.model.core.PvpField; import com.graham.passvaultplus.model.core.PvpRecord; /** * Different types. */ public class BCTableModelHeter implements BCTableModel { final RecordFilter filter; final PvpContext context; public BCTableModelHeter(final RecordFilter f, final PvpContext contextParam) { filter = f; context = contextParam; } public void flushCache() { // nothing to do } public int getColumnCount() { return 2; } public int getRowCount() { return filter.getRecordCount() * 4; } public Object getValueAt(int rowIndex, int columnIndex) { int fieldIndex = rowIndex % 4; if (columnIndex == 0) { switch (fieldIndex) { case 0: return "Type"; case 1: return "Category"; case 2: return "Summary"; case 3: return ""; } } else if (columnIndex == 1) { PvpRecord rec = getRecordAtRow(rowIndex); switch (fieldIndex) { case 0: return rec.getType(); case 1: if (rec.getCategory() == null) { return PvpRecord.NO_CATEGORY; } return rec.getCategory().getCustomField(PvpField.USR_CATEGORY_TITLE); case 2: return rec.toString(); case 3: return ""; } } return null; } public PvpRecord getRecordAtRow(final int rowIndex) { return filter.getRecordAtIndex(rowIndex / 4); } } /* * Copyright 2020 StreamSets 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.streamsets.datacollector.restapi.rbean.lang; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; public abstract class RBean extends RType { private Long dataVersion; private String readOnlySignature; private boolean failed; /** * RBean subclasses, different than EBean/OLEBean subclasses, must implement this method in order to define * the @UiProperty annotated 'id' instance property. * @return */ public abstract RString getId(); /** * Get acl Id for a resource */ @JsonIgnore public RString getAclId() { return getId(); } public void setAclId(RString id) { // NOP } /** * We don't use the fluent pattern for this setter because SELMA generator gets confused * @param id */ public abstract void setId(RString id); @JsonInclude(JsonInclude.Include.NON_NULL) public Long getDataVersion() { return dataVersion; } /** * We don't use the fluent pattern for this setter because SELMA generator gets confused */ public void setDataVersion(Long dataVersion) { this.dataVersion = dataVersion; } @JsonInclude(JsonInclude.Include.NON_NULL) public String getReadOnlySignature() { return readOnlySignature; } public void setReadOnlySignature(String readOnlySignature) { this.readOnlySignature = readOnlySignature; } /* * Not using getter syntax to stop Jackson and Selma for processing it as a property */ @JsonIgnore public boolean hasFailed() { return failed; } /** * To indicate the backend operation failed on the bean and trigger an HTTP 499 * (RestResponseFilter.X_HTTP_DATA_VALIDATION_ERROR) */ public void fail() { failed = true; } } package cli; import java.io.*; public class JobReader { static String dbPath = System.getProperty("user.dir") + "/db/"; static JobList jobList; public static void main(String[] args) throws IOException { jobList = readJobList(); System.out.println(dbPath); File jobs = new File(dbPath + "text_job_applied_2021.txt"); BufferedReader bufferedReader = new BufferedReader(new FileReader(jobs)); while(bufferedReader.ready()) { String[] job = bufferedReader.readLine().split(String.valueOf('\u2028')); String role = job[0]; boolean rejected = false; if(role.contains("(Rejected)")) { role = role.substring(0, role.length() - 11); rejected = true; } String company = job[1]; String link = job[2]; JobNode node = new JobNode(role, company, link); if(rejected) { node.setStatus("Rejected"); } jobList.add(node); } quit(); } private static JobList readJobList() throws IOException { JobList jobList = null; try { FileInputStream fileIn = new FileInputStream(dbPath + "main.JobList.ser"); ObjectInputStream inStream = new ObjectInputStream(fileIn); jobList = (JobList) inStream.readObject(); inStream.close(); fileIn.close(); } catch (FileNotFoundException e) { System.out.println("main.JobList Not Found."); System.out.println("Initiating.."); File f = new File(dbPath + "main.JobList.ser"); new File(dbPath).mkdir(); f.createNewFile(); jobList = new JobList(); System.out.println("done"); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (EOFException e) { jobList = new JobList(); } return jobList; } private static void quit() { try { FileOutputStream fileOut = new FileOutputStream(dbPath + "main.JobList.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(jobList); out.close(); fileOut.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.exit(0); } } package com.github.javarushcommunity.jrtb.dto; /** * DTO, which represents like's information. */ public class LikesInfo { private Integer count; private LikeStatus status; } integrations/jetty-websockets/src/main/java/de/quantummaid/httpmaid/jetty/JettyHttpMaidWebsocketServlet.java /* * Copyright (c) 2020 - https://quantummaid.de/. * * 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 de.quantummaid.httpmaid.jetty; import de.quantummaid.httpmaid.HttpMaid; import lombok.AccessLevel; import lombok.EqualsAndHashCode; import lombok.RequiredArgsConstructor; import lombok.ToString; import org.eclipse.jetty.websocket.servlet.WebSocketServlet; import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import static de.quantummaid.httpmaid.jetty.JettyHttpMaidWebsocketCreator.fakeLambdaWebsocketCreator; import static de.quantummaid.httpmaid.servlet.ServletHandling.handle; @ToString @EqualsAndHashCode(callSuper = true) @RequiredArgsConstructor(access = AccessLevel.PRIVATE) public final class JettyHttpMaidWebsocketServlet extends WebSocketServlet { private static final long serialVersionUID = 1L; private final transient HttpMaid httpMaid; public static JettyHttpMaidWebsocketServlet jettyHttpMaidWebsocketServlet(final HttpMaid httpMaid) { return new JettyHttpMaidWebsocketServlet(httpMaid); } @Override public void configure(final WebSocketServletFactory webSocketServletFactory) { webSocketServletFactory.setCreator(fakeLambdaWebsocketCreator(httpMaid)); } @Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) { handle(httpMaid, request, response); } @Override protected void doPost(final HttpServletRequest request, final HttpServletResponse response) { handle(httpMaid, request, response); } @Override protected void doPut(final HttpServletRequest request, final HttpServletResponse response) { handle(httpMaid, request, response); } @Override protected void doDelete(final HttpServletRequest request, final HttpServletResponse response) { handle(httpMaid, request, response); } @Override protected void doOptions(final HttpServletRequest request, final HttpServletResponse response) { handle(httpMaid, request, response); } } package com.vany.SMS.controller; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import com.vany.SMS.dto.ResultSMS; import com.vany.SMS.dto.SMSMoulde; import com.vany.SMS.service.LogService; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.*; import java.util.Collections; import javax.validation.Valid; import org.apache.log4j.Logger; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; @RestController @CrossOrigin(origins = "*") public class SMSController { private static final Logger logger = Logger.getLogger(SMSController.class); @Value("${app.sms.key}") private String devKey; @GetMapping(value = "/") public String getIndex() { // logs debug message if (logger.isDebugEnabled()) { logger.debug("Welcome | SMS Service is executed!"); } return "Welcome to SMS Service Applications"; } @PostMapping(value = "/sendSMS") private ResultSMS sendSMS(@Valid @RequestBody SMSMoulde smsMoulde) { return this.sendCustomSMS(smsMoulde); } // --------------- custome method // This method setting custome headers for request private HttpEntity setHeaders(SMSMoulde smsMoulde) { // create headers HttpHeaders headers = new HttpHeaders(); // set `accept` header headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); // set custom header headers.set("authorization",devKey); // build the request return new HttpEntity(smsMoulde, headers); } // this method sending SMS private ResultSMS sendCustomSMS(SMSMoulde smsMoulde) { ResultSMS result = null; try { final String uri = "https://www.fast2sms.com/dev/bulk"; RestTemplate restTemplate = new RestTemplate(); result = restTemplate.postForObject(uri, this.setHeaders(smsMoulde), ResultSMS.class); System.out.println(result); } catch (Exception e) { LogService.setLogger(e.getMessage()); } return result; } }wyzfzu/myframemyframe-core/src/main/java/com/myframe/core/util/StringUtils.java0 package com.myframe.core.util; import com.google.common.base.Splitter; import java.util.List; import java.util.regex.Pattern; /** * 字符串工具类。 * * @author wyzfzu () */ public final class StringUtils extends org.apache.commons.lang3.StringUtils { public static String fromCamelCase(String input, char separator) { int length = input.length(); StringBuilder result = new StringBuilder(length * 2); int resultLength = 0; boolean prevTranslated = false; for (int i = 0; i < length; i++) { char c = input.charAt(i); if (i > 0 || c != separator) {// skip first starting separator if (Character.isUpperCase(c)) { if (!prevTranslated && resultLength > 0 && result.charAt(resultLength - 1) != separator) { result.append(separator); resultLength++; } c = Character.toLowerCase(c); prevTranslated = true; } else { prevTranslated = false; } result.append(c); resultLength++; } } return resultLength > 0 ? result.toString() : input; } public static String toCamelCase(String input, boolean firstCharUppercase, char separator) { int length = input.length(); StringBuilder sb = new StringBuilder(length); boolean upperCase = firstCharUppercase; for (int i = 0; i < length; i++) { char ch = input.charAt(i); if (ch == separator) { upperCase = true; } else if (upperCase) { sb.append(Character.toUpperCase(ch)); upperCase = false; } else { sb.append(ch); } } return sb.toString(); } public static List splitToList(String str, String split) { return Splitter.on(split) .omitEmptyStrings() .trimResults() .splitToList(str); } public static List splitToList(String str, char splitChart) { return Splitter.on(splitChart) .omitEmptyStrings() .trimResults() .splitToList(str); } public static List splitToList(String str, Pattern splitPattern) { return Splitter.on(splitPattern) .omitEmptyStrings() .trimResults() .splitToList(str); } public static short toShort(String str) { return Short.parseShort(str); } public static short toShort(String str, short defaultValue) { try { return toShort(str); } catch (Exception e) { return defaultValue; } } public static int toInt(String str) { return Integer.parseInt(str); } public static int toInt(String str, int defaultValue) { try { return toInt(str); } catch (Exception e) { return defaultValue; } } public static long toLong(String str) { return Long.parseLong(str); } public static long toLong(String str, long defaultValue) { try { return toLong(str); } catch (Exception e) { return defaultValue; } } public static float toFloat(String str) { return Float.parseFloat(str); } public static float toFloat(String str, float defaultValue) { try { return toFloat(str); } catch (Exception e) { return defaultValue; } } public static double toDouble(String str) { return Double.parseDouble(str); } public static double toDouble(String str, double defaultValue) { try { return toDouble(str); } catch (Exception e) { return defaultValue; } } public static boolean toBoolean(String str) { return Boolean.parseBoolean(str); } public static boolean toBoolean(String str, boolean defaultValue) { try { return toBoolean(str); } catch (Exception e) { return defaultValue; } } } package com.bewitchment.client.render.entity.model; import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; import net.minecraft.entity.Entity; /** * werewolf5quad - cybercat5555 * Created using Tabula 5.1.0 */ public class ModelWerewolfQuadruped extends ModelBase { public ModelRenderer bipedRightArm; public ModelRenderer bipedRightLeg; public ModelRenderer bipedHead; public ModelRenderer bipedBody; public ModelRenderer bipedLeftArm; public ModelRenderer bipedLeftLeg; public ModelRenderer rArm02; public ModelRenderer rClaw01; public ModelRenderer rArmFur; public ModelRenderer rClaw02; public ModelRenderer rClaw03; public ModelRenderer rClaw04; public ModelRenderer rLeg02; public ModelRenderer rLeg03; public ModelRenderer rFoot; public ModelRenderer wolfHead; public ModelRenderer fur01; public ModelRenderer jawUpper01; public ModelRenderer jawLower; public ModelRenderer lEarFeral01; public ModelRenderer rEarFeral01; public ModelRenderer lCheekFur; public ModelRenderer rCheekFur; public ModelRenderer lEarClassic; public ModelRenderer rEarClassic; public ModelRenderer snout; public ModelRenderer jawUpper02; public ModelRenderer upperTeeth01; public ModelRenderer upperTeeth02; public ModelRenderer upperTeeth03; public ModelRenderer lowerTeeth01; public ModelRenderer lowerTeeth02; public ModelRenderer lEarFeral02; public ModelRenderer lEarFeral03; public ModelRenderer rEarFeral02; public ModelRenderer lEarFeral03_1; public ModelRenderer chest; public ModelRenderer fur05; public ModelRenderer fur06; public ModelRenderer tail01; public ModelRenderer fur02; public ModelRenderer fur03; public ModelRenderer fur04; public ModelRenderer tail01Floof; public ModelRenderer tail02; public ModelRenderer tail03; public ModelRenderer tail02Floof; public ModelRenderer tail03Floof; public ModelRenderer lArm02; public ModelRenderer lClaw01; public ModelRenderer lArmFur; public ModelRenderer lClaw02; public ModelRenderer lClaw03; public ModelRenderer lClaw04; public ModelRenderer lLeg02; public ModelRenderer lLeg03; public ModelRenderer lFoot; public ModelWerewolfQuadruped() { this.textureWidth = 128; this.textureHeight = 64; this.lArm02 = new ModelRenderer(this, 49, 46); this.lArm02.setRotationPoint(0.0F, 7.9F, 0.0F); this.lArm02.addBox(-1.5F, -1.0F, -1.5F, 3, 13, 3, 0.0F); this.setRotateAngle(lArm02, -0.41887902047863906F, 0.0F, 0.2792526803190927F); this.rEarFeral01 = new ModelRenderer(this, 70, 0); this.rEarFeral01.mirror = true; this.rEarFeral01.setRotationPoint(-2.7F, -2.2F, 1.0F); this.rEarFeral01.addBox(-1.0F, 0.0F, -0.9F, 1, 3, 2, 0.0F); this.setRotateAngle(rEarFeral01, 0.5462880558742251F, 0.0F, 0.5462880558742251F); this.lEarFeral03_1 = new ModelRenderer(this, 77, 0); this.lEarFeral03_1.mirror = true; this.lEarFeral03_1.setRotationPoint(0.3F, 0.0F, 0.0F); this.lEarFeral03_1.addBox(-0.5F, 0.0F, -0.5F, 1, 3, 1, 0.0F); this.setRotateAngle(lEarFeral03_1, 0.091106186954104F, 0.0F, 0.22759093446006054F); this.fur04 = new ModelRenderer(this, 90, 35); this.fur04.setRotationPoint(0.0F, -3.4F, 2.9F); this.fur04.addBox(-2.5F, -1.0F, 0.0F, 5, 5, 2, 0.0F); this.setRotateAngle(fur04, 0.2792526803190927F, 0.0F, 0.0F); this.tail03 = new ModelRenderer(this, 116, 7); this.tail03.setRotationPoint(0.0F, 3.8F, 0.1F); this.tail03.addBox(-0.5F, 0.0F, -0.5F, 1, 5, 1, 0.0F); this.setRotateAngle(tail03, -0.18203784098300857F, 0.0F, 0.0F); this.tail01 = new ModelRenderer(this, 116, 0); this.tail01.setRotationPoint(0.0F, 3.9F, 2.0F); this.tail01.addBox(-1.0F, 0.0F, -1.0F, 2, 4, 2, 0.0F); this.setRotateAngle(tail01, -0.7853981633974483F, 0.0F, 0.0F); this.fur05 = new ModelRenderer(this, 90, 43); this.fur05.setRotationPoint(0.0F, -2.4F, 1.7F); this.fur05.addBox(-2.0F, -1.0F, 0.0F, 4, 5, 2, 0.0F); this.setRotateAngle(fur05, 0.40980330836826856F, 0.0F, 0.0F); this.lClaw04 = new ModelRenderer(this, 36, 0); this.lClaw04.setRotationPoint(-0.9F, 0.0F, 0.0F); this.lClaw04.addBox(-0.5F, 0.0F, -0.5F, 1, 4, 2, 0.0F); this.setRotateAngle(lClaw04, 0.0F, 0.0F, 0.091106186954104F); this.rClaw04 = new ModelRenderer(this, 36, 0); this.rClaw04.mirror = true; this.rClaw04.setRotationPoint(0.9F, 0.0F, 0.0F); this.rClaw04.addBox(-0.5F, 0.0F, -0.5F, 1, 4, 2, 0.0F); this.setRotateAngle(rClaw04, 0.0F, 0.0F, -0.091106186954104F); this.lEarFeral01 = new ModelRenderer(this, 70, 0); this.lEarFeral01.setRotationPoint(2.7F, -2.2F, 1.0F); this.lEarFeral01.addBox(0.0F, 0.0F, -0.9F, 1, 3, 2, 0.0F); this.setRotateAngle(lEarFeral01, 0.5462880558742251F, 0.0F, -0.5462880558742251F); this.rClaw02 = new ModelRenderer(this, 27, 0); this.rClaw02.mirror = true; this.rClaw02.setRotationPoint(1.0F, 0.0F, 0.0F); this.rClaw02.addBox(-0.5F, 0.0F, -0.5F, 1, 4, 2, 0.0F); this.setRotateAngle(rClaw02, 0.0F, 0.0F, -0.091106186954104F); this.lowerTeeth02 = new ModelRenderer(this, 63, 41); this.lowerTeeth02.setRotationPoint(0.0F, 0.0F, 0.0F); this.lowerTeeth02.addBox(-1.3F, 0.0F, 0.0F, 1, 3, 1, 0.0F); this.rLeg03 = new ModelRenderer(this, 0, 23); this.rLeg03.mirror = true; this.rLeg03.setRotationPoint(0.0F, 9.1F, 0.5F); this.rLeg03.addBox(-1.5F, 0.0F, -1.5F, 3, 7, 3, 0.0F); this.setRotateAngle(rLeg03, -1.0016444577195458F, 0.05235987755982988F, -0.10471975511965977F); this.rFoot = new ModelRenderer(this, 0, 14); this.rFoot.mirror = true; this.rFoot.setRotationPoint(0.0F, 6.8F, 0.0F); this.rFoot.addBox(-2.0F, 0.0F, -4.3F, 4, 2, 6, 0.0F); this.setRotateAngle(rFoot, 0.20943951023931953F, 0.0F, 0.0F); this.lEarFeral02 = new ModelRenderer(this, 77, 0); this.lEarFeral02.setRotationPoint(0.0F, 2.8F, 0.1F); this.lEarFeral02.addBox(0.0F, 0.0F, -0.5F, 1, 2, 1, 0.0F); this.setRotateAngle(lEarFeral02, 0.36425021489121656F, 0.0F, 0.0F); this.lArmFur = new ModelRenderer(this, 62, 50); this.lArmFur.setRotationPoint(0.6F, 1.6F, 0.0F); this.lArmFur.addBox(0.0F, 0.0F, 0.0F, 1, 7, 4, 0.0F); this.setRotateAngle(lArmFur, 0.0F, 0.091106186954104F, 0.091106186954104F); this.rClaw03 = new ModelRenderer(this, 27, 0); this.rClaw03.mirror = true; this.rClaw03.setRotationPoint(0.9F, 0.0F, 0.0F); this.rClaw03.addBox(-0.5F, 0.0F, -0.5F, 1, 4, 2, 0.0F); this.setRotateAngle(rClaw03, 0.0F, 0.0F, -0.091106186954104F); this.bipedLeftLeg = new ModelRenderer(this, 13, 48); this.bipedLeftLeg.setRotationPoint(2.5F, 2.7F, 0.1F); this.bipedLeftLeg.addBox(-2.0F, 0.0F, -2.0F, 4, 10, 5, 0.0F); this.setRotateAngle(bipedLeftLeg, -0.45378560551852565F, 0.0F, -0.2792526803190927F); this.bipedRightLeg = new ModelRenderer(this, 13, 48); this.bipedRightLeg.mirror = true; this.bipedRightLeg.setRotationPoint(-2.5F, 2.7F, 0.1F); this.bipedRightLeg.addBox(-2.0F, 0.0F, -2.0F, 4, 10, 5, 0.0F); this.setRotateAngle(bipedRightLeg, -0.45378560551852565F, 0.0F, 0.2792526803190927F); this.lClaw03 = new ModelRenderer(this, 27, 0); this.lClaw03.setRotationPoint(-0.9F, 0.0F, 0.0F); this.lClaw03.addBox(-0.5F, 0.0F, -0.5F, 1, 4, 2, 0.0F); this.setRotateAngle(lClaw03, 0.0F, 0.0F, 0.091106186954104F); this.snout = new ModelRenderer(this, 29, 35); this.snout.setRotationPoint(0.0F, -4.6F, 0.1F); this.snout.addBox(-1.0F, -4.5F, -1.0F, 2, 5, 2, 0.0F); this.setRotateAngle(snout, 0.18203784098300857F, 0.0F, 0.0F); this.lowerTeeth01 = new ModelRenderer(this, 68, 41); this.lowerTeeth01.setRotationPoint(0.0F, -3.8F, 0.1F); this.lowerTeeth01.addBox(-0.6F, 0.0F, 0.0F, 2, 3, 1, 0.0F); this.chest = new ModelRenderer(this, 46, 15); this.chest.setRotationPoint(0.0F, -4.9F, -0.7F); this.chest.addBox(-4.5F, -9.0F, -4.0F, 9, 10, 8, 0.0F); this.setRotateAngle(chest, 0.20943951023931953F, 0.0F, 0.0F); this.upperTeeth03 = new ModelRenderer(this, 63, 38); this.upperTeeth03.setRotationPoint(0.0F, -3.2F, -1.0F); this.upperTeeth03.addBox(-2.27F, -0.7F, -0.8F, 3, 0, 1, 0.0F); this.setRotateAngle(upperTeeth03, 0.0F, 0.0F, 0.136659280431156F); this.tail02Floof = new ModelRenderer(this, 112, 28); this.tail02Floof.setRotationPoint(0.0F, 0.0F, 0.0F); this.tail02Floof.addBox(-2.0F, 0.0F, -2.0F, 4, 5, 4, 0.0F); this.lClaw01 = new ModelRenderer(this, 27, 0); this.lClaw01.setRotationPoint(1.1F, 10.6F, -1.2F); this.lClaw01.addBox(-0.5F, 0.0F, -0.5F, 1, 4, 2, 0.0F); this.setRotateAngle(lClaw01, -1.3962634015954636F, 0.0F, 0.0F); this.lEarClassic = new ModelRenderer(this, 73, 8); this.lEarClassic.setRotationPoint(2.2F, -2.0F, 3.0F); this.lEarClassic.addBox(-1.0F, -0.5F, 0.0F, 2, 1, 3, 0.0F); this.setRotateAngle(lEarClassic, -0.18203784098300857F, 0.091106186954104F, 0.0F); this.upperTeeth01 = new ModelRenderer(this, 56, 37); this.upperTeeth01.setRotationPoint(0.0F, -3.2F, -1.0F); this.upperTeeth01.addBox(-0.3F, -0.7F, -0.7F, 1, 3, 1, 0.0F); this.setRotateAngle(upperTeeth01, 0.0F, 0.0F, 0.136659280431156F); this.rClaw01 = new ModelRenderer(this, 27, 0); this.rClaw01.mirror = true; this.rClaw01.setRotationPoint(-1.1F, 10.6F, -1.2F); this.rClaw01.addBox(-0.5F, 0.0F, -0.5F, 1, 4, 2, 0.0F); this.setRotateAngle(rClaw01, -1.3962634015954636F, 0.0F, 0.0F); this.fur01 = new ModelRenderer(this, 90, 0); this.fur01.setRotationPoint(0.0F, -1.0F, -2.9F); this.fur01.addBox(-3.0F, -1.0F, 0.0F, 6, 7, 2, 0.0F); this.setRotateAngle(fur01, 2.86844862565268F, 0.0F, 0.0F); this.lLeg03 = new ModelRenderer(this, 0, 23); this.lLeg03.setRotationPoint(0.0F, 9.1F, 0.5F); this.lLeg03.addBox(-1.5F, 0.0F, -1.5F, 3, 7, 3, 0.0F); this.setRotateAngle(lLeg03, -1.0016444577195458F, -0.05235987755982988F, 0.10471975511965977F); this.fur02 = new ModelRenderer(this, 90, 11); this.fur02.setRotationPoint(0.0F, -8.1F, 2.0F); this.fur02.addBox(-4.0F, -1.0F, 0.0F, 8, 10, 2, 0.0F); this.setRotateAngle(fur02, 0.5235987755982988F, 0.0F, 0.0F); this.bipedBody = new ModelRenderer(this, 16, 16); this.bipedBody.setRotationPoint(0.0F, 4.1F, -2.2F); this.bipedBody.addBox(-4.0F, -6.5F, -3.0F, 8, 11, 6, 0.0F); this.setRotateAngle(bipedBody, 1.3962634015954636F, 0.0F, 0.0F); this.fur06 = new ModelRenderer(this, 90, 52); this.fur06.setRotationPoint(0.0F, -0.2F, 1.5F); this.fur06.addBox(-2.0F, -1.0F, 0.0F, 4, 5, 2, 0.0F); this.setRotateAngle(fur06, 0.36425021489121656F, 0.0F, 0.0F); this.fur03 = new ModelRenderer(this, 90, 24); this.fur03.setRotationPoint(0.0F, -5.9F, 2.5F); this.fur03.addBox(-3.0F, -1.0F, 0.0F, 6, 8, 2, 0.0F); this.setRotateAngle(fur03, 0.27314402793711257F, 0.0F, 0.0F); this.wolfHead = new ModelRenderer(this, 44, 0); this.wolfHead.setRotationPoint(0.0F, -0.1F, -4.0F); this.wolfHead.addBox(-3.5F, -5.0F, -3.0F, 7, 5, 6, 0.0F); this.setRotateAngle(wolfHead, 2.1816615649929116F, 0.0F, 0.0F); this.rEarClassic = new ModelRenderer(this, 73, 8); this.rEarClassic.mirror = true; this.rEarClassic.setRotationPoint(-2.2F, -2.0F, 3.0F); this.rEarClassic.addBox(-1.0F, -0.5F, 0.0F, 2, 1, 3, 0.0F); this.setRotateAngle(rEarClassic, -0.18203784098300857F, -0.091106186954104F, 0.0F); this.bipedHead = new ModelRenderer(this, 0, 0); this.bipedHead.setRotationPoint(0.0F, 5.0F, -14.7F); this.bipedHead.addBox(-3.0F, -2.5F, -5.0F, 6, 5, 5, 0.0F); this.setRotateAngle(bipedHead, -0.5235987755982988F, 0.0F, 0.0F); this.jawUpper02 = new ModelRenderer(this, 20, 36); this.jawUpper02.mirror = true; this.jawUpper02.setRotationPoint(0.0F, 0.0F, 0.0F); this.jawUpper02.addBox(-3.2F, -3.67F, -1.0F, 2, 4, 2, 0.0F); this.setRotateAngle(jawUpper02, 0.0F, 0.0F, 0.2792526803190927F); this.bipedRightArm = new ModelRenderer(this, 32, 48); this.bipedRightArm.mirror = true; this.bipedRightArm.setRotationPoint(-5.0F, 5.0F, -12.5F); this.bipedRightArm.addBox(-2.0F, -2.0F, -2.0F, 4, 10, 4, 0.0F); this.setRotateAngle(bipedRightArm, 0.2792526803190927F, 0.0F, 0.2792526803190927F); this.bipedLeftArm = new ModelRenderer(this, 32, 48); this.bipedLeftArm.setRotationPoint(5.0F, 5.0F, -12.5F); this.bipedLeftArm.addBox(-2.0F, -2.0F, -2.0F, 4, 10, 4, 0.0F); this.setRotateAngle(bipedLeftArm, 0.2792526803190927F, 0.0F, -0.2792526803190927F); this.rEarFeral02 = new ModelRenderer(this, 77, 0); this.rEarFeral02.mirror = true; this.rEarFeral02.setRotationPoint(0.0F, 2.8F, 0.1F); this.rEarFeral02.addBox(-1.0F, 0.0F, -0.5F, 1, 2, 1, 0.0F); this.setRotateAngle(rEarFeral02, 0.36425021489121656F, 0.0F, 0.0F); this.lEarFeral03 = new ModelRenderer(this, 77, 0); this.lEarFeral03.setRotationPoint(-0.3F, 0.0F, 0.0F); this.lEarFeral03.addBox(-0.5F, 0.0F, -0.5F, 1, 3, 1, 0.0F); this.setRotateAngle(lEarFeral03, 0.091106186954104F, 0.0F, -0.22759093446006054F); this.tail01Floof = new ModelRenderer(this, 112, 18); this.tail01Floof.setRotationPoint(0.0F, 0.0F, 0.0F); this.tail01Floof.addBox(-1.5F, 0.0F, -1.5F, 3, 5, 3, 0.0F); this.lClaw02 = new ModelRenderer(this, 27, 0); this.lClaw02.setRotationPoint(-1.0F, 0.0F, 0.0F); this.lClaw02.addBox(-0.5F, 0.0F, -0.5F, 1, 4, 2, 0.0F); this.setRotateAngle(lClaw02, 0.0F, 0.0F, 0.091106186954104F); this.tail03Floof = new ModelRenderer(this, 112, 44); this.tail03Floof.setRotationPoint(0.0F, 0.0F, 0.0F); this.tail03Floof.addBox(-2.0F, 0.7F, -2.0F, 4, 7, 4, 0.0F); this.tail02 = new ModelRenderer(this, 116, 0); this.tail02.setRotationPoint(0.0F, 3.8F, 0.1F); this.tail02.addBox(-1.0F, 0.0F, -1.0F, 2, 4, 2, 0.0F); this.setRotateAngle(tail02, -0.31869712141416456F, 0.0F, 0.0F); this.lLeg02 = new ModelRenderer(this, 0, 34); this.lLeg02.setRotationPoint(0.0F, 8.2F, -1.2F); this.lLeg02.addBox(-2.01F, 0.0F, -2.0F, 4, 10, 4, 0.0F); this.setRotateAngle(lLeg02, 1.2292353921796064F, 0.0F, 0.2792526803190927F); this.rLeg02 = new ModelRenderer(this, 0, 34); this.rLeg02.mirror = true; this.rLeg02.setRotationPoint(0.0F, 8.2F, -1.2F); this.rLeg02.addBox(-1.99F, 0.0F, -2.0F, 4, 10, 4, 0.0F); this.setRotateAngle(rLeg02, 1.2292353921796064F, 0.0F, -0.2792526803190927F); this.lCheekFur = new ModelRenderer(this, 38, 4); this.lCheekFur.setRotationPoint(3.5F, -2.5F, 1.1F); this.lCheekFur.addBox(0.0F, -0.5F, -7.5F, 0, 4, 8, 0.0F); this.setRotateAngle(lCheekFur, -0.18203784098300857F, -0.091106186954104F, -0.36425021489121656F); this.rArmFur = new ModelRenderer(this, 62, 50); this.rArmFur.mirror = true; this.rArmFur.setRotationPoint(-1.6F, 1.6F, 0.0F); this.rArmFur.addBox(0.0F, 0.0F, 0.0F, 1, 7, 4, 0.0F); this.setRotateAngle(rArmFur, 0.0F, -0.091106186954104F, -0.091106186954104F); this.jawUpper01 = new ModelRenderer(this, 20, 36); this.jawUpper01.setRotationPoint(1.2F, -4.9F, -1.1F); this.jawUpper01.addBox(-1.2F, -4.0F, -1.0F, 2, 4, 2, 0.0F); this.setRotateAngle(jawUpper01, 0.0F, 0.0F, -0.13962634015954636F); this.lFoot = new ModelRenderer(this, 0, 14); this.lFoot.setRotationPoint(0.0F, 6.8F, 0.0F); this.lFoot.addBox(-2.0F, 0.0F, -4.3F, 4, 2, 6, 0.0F); this.setRotateAngle(lFoot, 0.20943951023931953F, 0.0F, 0.0F); this.rArm02 = new ModelRenderer(this, 49, 46); this.rArm02.mirror = true; this.rArm02.setRotationPoint(0.0F, 7.9F, 0.0F); this.rArm02.addBox(-1.5F, -1.0F, -1.5F, 3, 13, 3, 0.0F); this.setRotateAngle(rArm02, -0.41887902047863906F, 0.0F, -0.2792526803190927F); this.upperTeeth02 = new ModelRenderer(this, 50, 37); this.upperTeeth02.setRotationPoint(0.0F, -3.2F, -1.0F); this.upperTeeth02.addBox(-2.2F, -0.7F, -0.7F, 1, 3, 1, 0.0F); this.setRotateAngle(upperTeeth02, 0.0F, 0.0F, 0.136659280431156F); this.jawLower = new ModelRenderer(this, 39, 37); this.jawLower.setRotationPoint(0.0F, -4.8F, -2.5F); this.jawLower.addBox(-1.5F, -4.0F, -0.5F, 3, 4, 1, 0.0F); this.rCheekFur = new ModelRenderer(this, 38, 4); this.rCheekFur.mirror = true; this.rCheekFur.setRotationPoint(-3.5F, -2.5F, 1.1F); this.rCheekFur.addBox(0.0F, -0.5F, -7.5F, 0, 4, 8, 0.0F); this.setRotateAngle(rCheekFur, -0.18203784098300857F, 0.091106186954104F, 0.36425021489121656F); this.bipedLeftArm.addChild(this.lArm02); this.wolfHead.addChild(this.rEarFeral01); this.rEarFeral01.addChild(this.lEarFeral03_1); this.chest.addChild(this.fur04); this.tail02.addChild(this.tail03); this.bipedBody.addChild(this.tail01); this.bipedBody.addChild(this.fur05); this.lClaw03.addChild(this.lClaw04); this.rClaw03.addChild(this.rClaw04); this.wolfHead.addChild(this.lEarFeral01); this.rClaw01.addChild(this.rClaw02); this.lowerTeeth01.addChild(this.lowerTeeth02); this.rLeg02.addChild(this.rLeg03); this.rLeg03.addChild(this.rFoot); this.lEarFeral01.addChild(this.lEarFeral02); this.lArm02.addChild(this.lArmFur); this.rClaw02.addChild(this.rClaw03); this.lClaw02.addChild(this.lClaw03); this.wolfHead.addChild(this.snout); this.jawLower.addChild(this.lowerTeeth01); this.bipedBody.addChild(this.chest); this.jawUpper01.addChild(this.upperTeeth03); this.tail02.addChild(this.tail02Floof); this.lArm02.addChild(this.lClaw01); this.wolfHead.addChild(this.lEarClassic); this.jawUpper01.addChild(this.upperTeeth01); this.rArm02.addChild(this.rClaw01); this.bipedHead.addChild(this.fur01); this.lLeg02.addChild(this.lLeg03); this.chest.addChild(this.fur02); this.bipedBody.addChild(this.fur06); this.chest.addChild(this.fur03); this.bipedHead.addChild(this.wolfHead); this.wolfHead.addChild(this.rEarClassic); this.jawUpper01.addChild(this.jawUpper02); this.rEarFeral01.addChild(this.rEarFeral02); this.lEarFeral01.addChild(this.lEarFeral03); this.tail01.addChild(this.tail01Floof); this.lClaw01.addChild(this.lClaw02); this.tail03.addChild(this.tail03Floof); this.tail01.addChild(this.tail02); this.bipedLeftLeg.addChild(this.lLeg02); this.bipedRightLeg.addChild(this.rLeg02); this.wolfHead.addChild(this.lCheekFur); this.rArm02.addChild(this.rArmFur); this.wolfHead.addChild(this.jawUpper01); this.lLeg03.addChild(this.lFoot); this.bipedRightArm.addChild(this.rArm02); this.jawUpper01.addChild(this.upperTeeth02); this.wolfHead.addChild(this.jawLower); this.wolfHead.addChild(this.rCheekFur); } @Override public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { this.bipedLeftLeg.render(f5); this.bipedRightLeg.render(f5); this.bipedBody.render(f5); this.bipedHead.render(f5); this.bipedRightArm.render(f5); this.bipedLeftArm.render(f5); } /** * This is a helper function from Tabula to set the rotation of model parts */ public void setRotateAngle(ModelRenderer modelRenderer, float x, float y, float z) { modelRenderer.rotateAngleX = x; modelRenderer.rotateAngleY = y; modelRenderer.rotateAngleZ = z; } } halzhang/BDMyTracks /* * 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.android.apps.mytracks.io.backup; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.TrackPointsColumns; import com.google.android.apps.mytracks.content.TracksColumns; import com.google.android.apps.mytracks.content.WaypointsColumns; import com.google.android.apps.mytracks.util.FileUtils; import android.content.ContentResolver; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.util.Log; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.TimeZone; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; /** * Handler for writing or reading single-file backups. * * @author */ class ExternalFileBackup { // Filename format - in UTC private static final SimpleDateFormat BACKUP_FILENAME_FORMAT = new SimpleDateFormat("'backup-'yyyy-MM-dd_HH-mm-ss'.zip'"); static { BACKUP_FILENAME_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); } private static final String BACKUPS_SUBDIR = "backups"; private static final int BACKUP_FORMAT_VERSION = 1; private static final String ZIP_ENTRY_NAME = "backup.mytracks.v" + BACKUP_FORMAT_VERSION; private static final int COMPRESSION_LEVEL = 8; private final Context context; public ExternalFileBackup(Context context) { this.context = context; } /** * Returns whether the backups directory is (or can be made) available. * * @param create whether to try creating the directory if it doesn't exist */ public boolean isBackupsDirectoryAvailable(boolean create) { return getBackupsDirectory(create) != null; } /** * Returns the backup directory, or null if not available. * * @param create whether to try creating the directory if it doesn't exist */ private File getBackupsDirectory(boolean create) { String dirName = FileUtils.buildExternalDirectoryPath(BACKUPS_SUBDIR); final File dir = new File(dirName); Log.d(Constants.TAG, "Dir: " + dir.getAbsolutePath()); if (create) { // Try to create - if that fails, return null return FileUtils.ensureDirectoryExists(dir) ? dir : null; } else { // Return it if it already exists, otherwise return null return dir.isDirectory() ? dir : null; } } /** * Returns a list of available backups to be restored. */ public Date[] getAvailableBackups() { File dir = getBackupsDirectory(false); if (dir == null) { return null; } String[] fileNames = dir.list(); List backupDates = new ArrayList(fileNames.length); for (int i = 0; i < fileNames.length; i++) { String fileName = fileNames[i]; try { backupDates.add(BACKUP_FILENAME_FORMAT.parse(fileName)); } catch (ParseException e) { // Not a backup file, ignore } } return backupDates.toArray(new Date[backupDates.size()]); } /** * Writes the backup to the default file. */ public void writeToDefaultFile() throws IOException { writeToFile(getFileForDate(new Date())); } /** * Restores the backup from the given date. */ public void restoreFromDate(Date when) throws IOException { restoreFromFile(getFileForDate(when)); } /** * Produces the proper file descriptor for the given backup date. */ private File getFileForDate(Date when) { File dir = getBackupsDirectory(false); String fileName = BACKUP_FILENAME_FORMAT.format(when); File file = new File(dir, fileName); return file; } /** * Synchronously writes a backup to the given file. */ private void writeToFile(File outputFile) throws IOException { Log.d(Constants.TAG, "Writing backup to file " + outputFile.getAbsolutePath()); // Create all the auxiliary classes that will do the writing PreferenceBackupHelper preferencesHelper = new PreferenceBackupHelper(); DatabaseDumper trackDumper = new DatabaseDumper( TracksColumns.COLUMNS, TracksColumns.COLUMN_TYPES, false); DatabaseDumper waypointDumper = new DatabaseDumper( WaypointsColumns.COLUMNS, WaypointsColumns.COLUMN_TYPES, false); DatabaseDumper pointDumper = new DatabaseDumper( TrackPointsColumns.COLUMNS, TrackPointsColumns.COLUMN_TYPES, false); // Open the target for writing FileOutputStream outputStream = new FileOutputStream(outputFile); ZipOutputStream compressedStream = new ZipOutputStream(outputStream); compressedStream.setLevel(COMPRESSION_LEVEL); compressedStream.putNextEntry(new ZipEntry(ZIP_ENTRY_NAME)); DataOutputStream outWriter = new DataOutputStream(compressedStream); try { // Dump the entire contents of each table ContentResolver contentResolver = context.getContentResolver(); Cursor tracksCursor = contentResolver.query( TracksColumns.CONTENT_URI, null, null, null, null); try { trackDumper.writeAllRows(tracksCursor, outWriter); } finally { tracksCursor.close(); } Cursor waypointsCursor = contentResolver.query( WaypointsColumns.CONTENT_URI, null, null, null, null); try { waypointDumper.writeAllRows(waypointsCursor, outWriter); } finally { waypointsCursor.close(); } Cursor pointsCursor = contentResolver.query( TrackPointsColumns.CONTENT_URI, null, null, null, null); try { pointDumper.writeAllRows(pointsCursor, outWriter); } finally { pointsCursor.close(); } // Dump preferences SharedPreferences preferences = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); preferencesHelper.exportPreferences(preferences, outWriter); } catch (IOException e) { // We tried to delete the partially created file, but do nothing // if that also fails. if (!outputFile.delete()) { Log.w(TAG, "Failed to delete file " + outputFile.getAbsolutePath()); } throw e; } finally { compressedStream.closeEntry(); compressedStream.close(); } } /** * Synchronously restores the backup from the given file. */ private void restoreFromFile(File inputFile) throws IOException { Log.d(Constants.TAG, "Restoring from file " + inputFile.getAbsolutePath()); PreferenceBackupHelper preferencesHelper = new PreferenceBackupHelper(); ContentResolver resolver = context.getContentResolver(); DatabaseImporter trackImporter = new DatabaseImporter(TracksColumns.CONTENT_URI, resolver, false); DatabaseImporter waypointImporter = new DatabaseImporter(WaypointsColumns.CONTENT_URI, resolver, false); DatabaseImporter pointImporter = new DatabaseImporter(TrackPointsColumns.CONTENT_URI, resolver, false); ZipFile zipFile = new ZipFile(inputFile, ZipFile.OPEN_READ); ZipEntry zipEntry = zipFile.getEntry(ZIP_ENTRY_NAME); if (zipEntry == null) { throw new IOException("Invalid backup ZIP file"); } InputStream compressedStream = zipFile.getInputStream(zipEntry); DataInputStream reader = new DataInputStream(compressedStream); try { // Delete all previous contents of the tables and preferences. resolver.delete(TracksColumns.CONTENT_URI, null, null); resolver.delete(TrackPointsColumns.CONTENT_URI, null, null); resolver.delete(WaypointsColumns.CONTENT_URI, null, null); // Import the new contents of each table trackImporter.importAllRows(reader); waypointImporter.importAllRows(reader); pointImporter.importAllRows(reader); // Restore preferences SharedPreferences preferences = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); preferencesHelper.importPreferences(reader, preferences); } finally { compressedStream.close(); zipFile.close(); } } } package com.github.hugh; import com.github.hugh.util.StringUtils; import org.junit.Test; /** * @author AS * @date 2020/9/11 16:05 */ public class StringTest { @Test public void test01() { // String str = "https://github.com/HughWick/toolbox"; String fName = "C:\\Users\\Lenovo\\Desktop\\0e9f4beeb6a5423585c6eabda21a63ee.jpg"; //或者 // String fileName = fName.substring(fName.lastIndexOf("\\") + 1); String value = "startDate"; // System.out.println("fileName = " + fileName); System.out.println("---1>>>" + StringUtils.after(fName, "\\")); System.out.println("--2->>>" + StringUtils.before(fName, "\\")); System.out.println("--3->>>" + StringUtils.isContainChinese(fName)); System.out.println("--4->>>" + StringUtils.getNumber(fName)); System.out.println("--5>>" + StringUtils.varcharSize(value)); } @Test public void test02() { System.out.println("--->" + StringUtils.leftPadding("1", 8, 'a')); System.out.println("--->" + StringUtils.leftPadding("1", 8)); } @Test public void test03() { String value = "startDate"; String str1 = "getCamelCaseString"; String camel = StringUtils.camelToUnderline(str1); System.out.println("--1-->>" + camel); System.out.println("--2-->>" + StringUtils.camelToUnderlineUppercase(camel)); System.out.println("--2-->>" + StringUtils.getCamelCase(camel, false)); } @Test public void test04() { System.out.println("--1-->>" + StringUtils.replaceAnyBlank("entity is error !")); System.out.println("--2-->>" + StringUtils.replaceAnyBlank("entity is error !", "_")); } @Test public void test05() { String str = "[a, b, [c]]]"; System.out.println("==2=>>>" + StringUtils.trim(str, "]")); System.out.println("==2=>>>" + StringUtils.trim(str, "[")); System.out.println("--4-->>" + StringUtils.isContainChinese(";")); System.out.println("--5-->>" + StringUtils.isContainChinese("中文")); System.out.println("--6-->>" + StringUtils.isNotContainChinese("中文2")); System.out.println("--7-->>" + StringUtils.isNotContainChinese("中文")); } @Test public void test06() { String string = "http://hyga.hnlot.com.cn:8000/capture/DaHua/capture/6G0BEB9GA12F70A/2021/1/17/9946090cb09b4986af8615174e862b9e.jpg"; String string2 = "https://www.hnlot.com.cn/DaHua/capture/4M061F3PAA33D78/2020/10/27/e242edb022494a12a778c4cddecf2a48.jpg"; System.out.println("--1-->>" + StringUtils.after(string, "/", 4)); System.out.println("--2-->>" + StringUtils.after(string2, "/", 4)); } public static void main(String[] args) { String init = "Bob is a Bird... Bob is a Plane... Bob is Superman!"; String changed = init.replace("Bob is", "It's"); // Noncompliant   System.out.println(changed); // changed = changed.replaceAll("\\.\\.\\.", ";"); // Noncompliant // double threadcount = DoubleMathUtils.mul(16, 3); // System.out.println("-=-threadcount ->>" + threadcount); } } src/test/java/tests/AddingItemToCart.java package tests; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import model.Product; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(DataProviderRunner.class) public class AddingItemToCart extends TestBase { @Test @UseDataProvider(value = "validProducts", location = DataProviders.class) public void testAddingAndRemoveItemFromCart(Product product) { for (int i = 0; i < 3 ; i++) { app.addProductToCart(product); } app.goToCart(); app.removeProductFromCart(); } } package ulysses.apps.drugsreminder.provider; import androidx.core.content.FileProvider; import ulysses.apps.drugsreminder.BuildConfig; public class LogProvider extends FileProvider { public static String AUTHORITY = BuildConfig.APPLICATION_ID + ".providers.LogProvider"; } package de.byteagenten.ldr2; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import de.byteagenten.ldr2.writer.ConsoleOutputLogWriter; import de.byteagenten.ldr2.writer.LogWriter; import de.byteagenten.ldr2.writer.WriterException; import java.beans.IntrospectionException; import java.beans.Introspector; import java.io.*; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; /** * Created by knooma2e on 21.07.2016. */ public class Logger { private static final String APPLICATION_ID_PROPERTY = "srsng.log.app.id"; public static final String DAY_OF_WEEK_PATTERN = "EEEE"; public static final String TIME_PATTERN = "HH:mm:ss.S"; public static final String DATE_PATTERN = "YYYY-MM-dd"; public static final String LONG_DATE_PATTERN = DAY_OF_WEEK_PATTERN + "',' YYYY-MM-dd"; public static final String ISO_UTC = DATE_PATTERN + "'T'" + TIME_PATTERN; public static final TimeZone UTC = TimeZone.getTimeZone("utc"); private static final ThreadLocal sessionContext = new ThreadLocal() { @Override protected SessionContext initialValue() { return null; } }; private static final ThreadLocal requestContext = new ThreadLocal() { @Override protected RequestContext initialValue() { return null; } }; private static final ThreadLocal scopeStack = new ThreadLocal() { @Override protected ScopeStack initialValue() { return new ScopeStack(); } }; private static List logWriter = new ArrayList<>(); private static String applicationId; private static boolean initialized; public static void setSessionContext(SessionContext sessionContext) { Logger.sessionContext.set(sessionContext); sessionContext.getScopeMap().values().forEach(scope -> scopeStack.get().push(scope)); } public static void setRequestContext(RequestContext requestContext) { Logger.requestContext.set(requestContext); } public static ScopeStack createChildScopeStack() { return scopeStack.get().createChild(); } public static String getApplicationId() { return applicationId; } public static void log(String message, LogEvent.Level logLevel) { LogEventConfig logEventConfig = LogEventConfig.create(); logEventConfig.setLevel(logLevel); log(message, logEventConfig); } public static void log() { log(null); } public static void log(Object evt) { log(evt, null); } public static boolean isInitialized() { return initialized; } public static synchronized void log(Throwable t, String message, LogEventConfig logConfig) { log(new ExceptionLog(t, message), logConfig != null ? logConfig : LogEventConfig.create().setLevel(LogEvent.Level.ERROR)); } public static synchronized void log(Throwable t, String message) { log(t, message, null); } public static synchronized void log(Object inEvent, LogEventConfig specificLogEventConfig) { if (!isInitialized()) throw new IllegalStateException("Logger not initialized. Please call Logger.init() first."); if (inEvent == null) inEvent = new NullLog(); if (inEvent instanceof LogEventConfig && specificLogEventConfig == null) { specificLogEventConfig = (LogEventConfig) inEvent; inEvent = null; } if (inEvent instanceof Class) { try { Constructor constructor = ((Class) inEvent).getConstructor(); inEvent = constructor.newInstance(); } catch (Exception e) { return; } } else if (inEvent instanceof Throwable) { inEvent = new ExceptionLog((Throwable) inEvent); } else if (inEvent instanceof String) { inEvent = new MessageLog((String) inEvent); } final Object event = inEvent; LogEvent logEvent = event != null ? event.getClass().getAnnotation(LogEvent.class) : null; LogEventConfig logEventConfig = LogEventConfig.fromLogEvent(logEvent); logEventConfig.merge(specificLogEventConfig); if (logEventConfig.getName().length() == 0) logEventConfig.setName(event != null ? event.getClass().getName() : "unknown"); GenericLogEvent genericLogEvent = GenericLogEvent.create( Logger.applicationId, logEventConfig.getName(), event != null ? event.getClass() : null, logEventConfig.getLevel()); JsonObject jsonObject = genericLogEvent.getJsonObject(); DateFormat df = new SimpleDateFormat(ISO_UTC); df.setTimeZone(UTC); if (logEventConfig.isSessionAware() && Logger.sessionContext.get() != null) { jsonObject.addProperty(GenericLogEvent.SESSION_ID, Logger.sessionContext.get().getSessionId()); jsonObject.addProperty(GenericLogEvent.SESSION_START_TIMESTAMP, df.format(Logger.sessionContext.get().getStartTimestamp())); } if (logEventConfig.isRequestAware() && Logger.requestContext.get() != null) { jsonObject.addProperty(GenericLogEvent.REQUEST_INDEX, Logger.requestContext.get().getIndex()); jsonObject.addProperty(GenericLogEvent.REQUEST_URL, Logger.requestContext.get().getUrl()); jsonObject.addProperty(GenericLogEvent.REQUEST_START_TIMESTAMP, df.format(Logger.requestContext.get().getStartTimestamp())); } if (logEventConfig.isThreadAware()) { jsonObject.addProperty(GenericLogEvent.THREAD_ID, Thread.currentThread().getId()); jsonObject.addProperty(GenericLogEvent.THREAD_NAME, Thread.currentThread().getName()); } if (logEventConfig.getMessage() != null && logEventConfig.getMessage().length() > 0) { jsonObject.addProperty(GenericLogEvent.MESSAGE, buildMessage(event, logEventConfig.getMessage())); } Logger.scopeStack.get().all().stream().forEach(scope -> { jsonObject.addProperty("$" + scope.getName(), scope.getValue()); }); try { if (event != null) { Arrays.asList(Introspector.getBeanInfo(event.getClass()) .getPropertyDescriptors()).stream() .filter(pd -> { Method readMethod = pd.getReadMethod(); if (readMethod == null) return false; if (readMethod.getName().contains("getClass")) return false; NoLog noLogAnnotation = readMethod.getAnnotation(NoLog.class); if (noLogAnnotation != null) return false; return true; }).forEach(pd -> { try { Class pt = pd.getReadMethod().getReturnType(); if (pt.isAssignableFrom(String.class)) { jsonObject.addProperty(pd.getName(), (String) pd.getReadMethod().invoke(event)); } else if (pt.isAssignableFrom(Long.class) || (pt.isPrimitive() && (pt == Long.TYPE))) { if (pd.getName().equalsIgnoreCase("timestamp")) { Long timestamp = (Long) pd.getReadMethod().invoke(event); if (timestamp != null) { jsonObject.addProperty(GenericLogEvent.TIMESTAMP_MILLIS, timestamp); jsonObject.addProperty(GenericLogEvent.TIMESTAMP, df.format(timestamp)); } } else { jsonObject.addProperty(pd.getName(), (Long) pd.getReadMethod().invoke(event)); } } else if (pt.isAssignableFrom(Integer.class) || (pt.isPrimitive() && pt == Integer.TYPE)) { jsonObject.addProperty(pd.getName(), (Integer) pd.getReadMethod().invoke(event)); } else if (pt.isAssignableFrom(Double.class) || (pt.isPrimitive() && pt == Double.TYPE)) { jsonObject.addProperty(pd.getName(), (Double) pd.getReadMethod().invoke(event)); } else if (pt.isAssignableFrom(Float.class) || (pt.isPrimitive() && pt == Float.TYPE)) { jsonObject.addProperty(pd.getName(), (Float) pd.getReadMethod().invoke(event)); } else if (pt.isAssignableFrom(Date.class)) { Date value = (Date) pd.getReadMethod().invoke(event); jsonObject.addProperty(pd.getName(), value != null ? df.format(value) : null); } else if (pt.isAssignableFrom(Boolean.class) || (pt.isPrimitive() && pt == Boolean.TYPE)) { jsonObject.addProperty(pd.getName(), (Boolean) pd.getReadMethod().invoke(event)); } else if (pt.isAssignableFrom(Throwable.class)) { jsonObject.addProperty(pd.getName(), ((Throwable) pd.getReadMethod().invoke(event)).toString()); } } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } }); } logWriter.forEach(writer -> { try { writer.write(genericLogEvent); } catch (Throwable e) { //bad luck } }); } catch (IntrospectionException e) { e.printStackTrace(); } } private static String buildMessage(Object event, String message) { if (event == null || message == null || message.trim().length() == 0) return message; if (!message.contains("{")) return message; List placeholders = new ArrayList<>(); StringBuilder sb = new StringBuilder(); boolean in = false; for (char c : message.toCharArray()) { if (!in && c == '{') { in = true; continue; } if (in) { if (c == '}') { in = false; placeholders.add(sb.toString()); sb = new StringBuilder(); continue; } sb.append(c); } } for (String placeholder : placeholders) { String firstChar = placeholder.substring(0, 1); String getterName = "get" + firstChar.toUpperCase() + placeholder.substring(1, placeholder.length()); Object o = null; try { Method method = event.getClass().getMethod(getterName); o = method.invoke(event); } catch (Exception e) { e.printStackTrace(); } String replacement = o != null ? o.toString() : ""; message = message.replace("{" + placeholder + "}", replacement); } return message; } public static LogEvent.Level getDefaultLogLevel() { return LogEvent.Level.ERROR; } public static void clear() { } public static void setScopeStack(ScopeStack scopeStack) { Logger.scopeStack.set(scopeStack); } public static void pushScope(String scopeName, String scopeValue, boolean sessionPersistent) { Scope newScope = new Scope(scopeName, scopeValue, sessionPersistent); Logger.scopeStack.get().push(newScope); if (sessionContext.get() != null && newScope.isSessionPersistent()) { sessionContext.get().addScope(newScope); } } public static void pushScope(String scopeName, String scopeValue) { Logger.pushScope(scopeName, scopeValue, false); } public static void popScope() { Scope removedScope = Logger.scopeStack.get().pop(); } public static void removeScope(String scopeName) { Scope removedScope = Logger.scopeStack.get().remove(scopeName); if (sessionContext.get() != null && removedScope != null && removedScope.isSessionPersistent()) { sessionContext.get().removeScope(removedScope.getName()); } } public static LogWriter getLogWriter(String name) { return logWriter.stream().filter(w -> w.getName().equalsIgnoreCase(name)).findFirst().orElse(null); } public static void init(File config) throws InitializeException { try { init(new FileInputStream(config)); } catch (FileNotFoundException e) { throw new InitializeException(String.format("No config file found at: %s", config.getAbsolutePath())); } } public static synchronized void init(InputStream inputStream) throws InitializeException { if (isInitialized()) { System.out.println("Logger is initialized already."); return; } StringBuilder stringBuilder = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { reader.lines().forEach(stringBuilder::append); } catch (IOException e) { e.printStackTrace(); } JsonParser parser = new JsonParser(); JsonObject json = (JsonObject) parser.parse(stringBuilder.toString()); if (!json.has("appKey")) throw new InitializeException("No 'appKey' specified in configuration."); applicationId = json.get("appKey").getAsString(); //todo: check that it is a string primitive if (!json.has("writer")) { logWriter.add(new ConsoleOutputLogWriter()); System.out.println(String.format("No writer specified. Adding a default one -> %s", ConsoleOutputLogWriter.class.getName())); } if (!json.get("writer").isJsonArray()) { throw new InitializeException("Config attribute 'writer' has to be an array."); } JsonArray writerJsonArray = (JsonArray) json.get("writer"); writerJsonArray.iterator().forEachRemaining(writerConfig -> { if (!writerConfig.isJsonObject()) return; JsonObject writerConfigJson = (JsonObject) writerConfig; String loggerName = "logger_" + logWriter.size(); if (writerConfigJson.has("name") && writerConfigJson.get("name").isJsonPrimitive() && writerConfigJson.get("name").getAsJsonPrimitive().isString()) { loggerName = writerConfigJson.get("name").getAsString(); } if (!writerConfigJson.has("class")) { //todo: log message return; } if (!writerConfigJson.get("class").isJsonPrimitive()) { //todo: log return; } String clazz = writerConfigJson.get("class").getAsString(); System.out.println(String.format("Try to create log writer instance for '%s' [%s]", loggerName, clazz)); LogWriter lwr = null; try { lwr = (LogWriter) Class.forName(clazz).getConstructor().newInstance(); } catch (Exception e) { //throw new InitializeException("LogWriter can't be instantiated.", e); //todo: log e.printStackTrace(); return; } JsonObject writerConfigJsonObject = null; if (writerConfigJson.has("config")) { if (!writerConfigJson.get("config").isJsonObject()) { //todo: log return; } writerConfigJsonObject = writerConfigJson.get("config").getAsJsonObject(); } try { lwr.init(applicationId, loggerName, writerConfigJsonObject); } catch (WriterException e) { //todo: log return; } logWriter.add(lwr); }); initialized = true; } public static void dispose() { for (LogWriter writer : logWriter) { try { writer.dispose(); } catch (Exception e) { e.printStackTrace(); } } } } spm-monitor-redis/src/main/java/com/sematext/spm/client/redis/RedisStatsCollectorsFactory.java /* * Licensed to Sematext Group, Inc * * See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Sematext Group, Inc licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.sematext.spm.client.redis; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Properties; import java.util.Set; import com.sematext.spm.client.HeartbeatStatsCollector; import com.sematext.spm.client.MonitorConfig; import com.sematext.spm.client.MonitorUtil; import com.sematext.spm.client.Serializer; import com.sematext.spm.client.StatsCollector; import com.sematext.spm.client.StatsCollectorBadConfigurationException; import com.sematext.spm.client.StatsCollectorsFactory; import com.sematext.spm.client.util.CollectionUtils.FunctionT; public class RedisStatsCollectorsFactory extends StatsCollectorsFactory { private static String makeId(String host, String port, String password) { return host + ":" + port + "@" + password; } private static Set makeCollectorIds(String collectorIdentifier) { Set ids = new HashSet(); ids.add(StatsCollector.calculateIdForCollector(RedisStatsCollector.class, collectorIdentifier)); ids.add(StatsCollector.calculateIdForCollector(RedisDbStatsCollector.class, collectorIdentifier)); return ids; } @Override public Collection create(Properties monitorProperties, List existingCollectors, MonitorConfig monitorConfig) throws StatsCollectorBadConfigurationException { Integer redisPort = null; String hostParam = MonitorUtil.stripQuotes( MonitorUtil.getPropertyFromAnyNameVariant(monitorProperties, "REDIS_HOST", "localhost").trim()).trim(); String passwordParam = MonitorUtil.stripQuotesIfEnclosed( MonitorUtil.getPropertyFromAnyNameVariant(monitorProperties, "REDIS_PASSWORD", "")); String portParam = MonitorUtil.stripQuotes( MonitorUtil.getPropertyFromAnyNameVariant(monitorProperties, "REDIS_PORT", "6379").trim()).trim(); if (portParam != null && !portParam.isEmpty()) { try { redisPort = Integer.parseInt(portParam); } catch (NumberFormatException e) { throw new StatsCollectorBadConfigurationException("Can't parse redisPort parameter " + portParam + "."); } } final String id = makeId(hostParam, portParam, passwordParam); final Set collectorIds = makeCollectorIds(id); if (existingCollectors != null) { for (StatsCollector collector : existingCollectors) { collectorIds.remove(collector.getId()); } } if (collectorIds.isEmpty()) { return existingCollectors; } else { final RedisInfoSource infoSource = RedisInfoSource.collector(hostParam, redisPort, passwordParam); return Arrays .asList(new RedisStatsCollector(infoSource, id, monitorConfig.getAppToken(), monitorConfig.getJvmName(), monitorConfig.getSubType()), new RedisDbStatsCollector(infoSource, id, monitorConfig.getAppToken(),monitorConfig.getJvmName(), monitorConfig.getSubType()), // as last collector add HeartbeatCollector new HeartbeatStatsCollector( Serializer.INFLUX, monitorConfig.getAppToken(), monitorConfig.getJvmName(), monitorConfig.getSubType())); } } } package com.businesscard.ui.main.viewModel; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashMap; import org.kobjects.base64.Base64; import webservice.MemoWebPara; import webservice.WebServiceDelegate; import webservice.WebServiceUtils; import com.businesscard.mobile.R; import com.businesscard.ui.main.SlidingActivity; import com.businesscard.ui.main.ViewPagerActivity; import com.businesscard.ui.main.systemManagement.LoginAndRegistActivity; import android.annotation.SuppressLint; import android.app.Dialog; import android.app.Fragment; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MenuFragment extends Fragment implements WebServiceDelegate { int index = 0; TextView txt_account_management, txt_check_version, txt_setting, txt_opinion, txt_news, txt_share, txt_weibo, txt_about_us, txt_card_management, txt_card_holder, txt_return, txt_exit, tv_backup_cloud, tv_synchronization; private Dialog dialog_card_management, dialog_account_management, dialog_synchronization, dialog_about_us; private Context context; private String get_userPhone; private boolean webflag = false; private WebServiceUtils webService; private static final String user_warning = "此版本适用于Android2.3及以上固件手机。本软件的下载、安装完全免费,适用过程中产生的GPRS数据流量费用,由运营商收取。"; private static final String copyright = "CanFly团队 版权所有 \n" + "Copyright © 2012-2013 CanFly \n" + "All rights reserved."; private static final String version = "版本V1.0"; private TextView text_version; private TextView text_user_warning; private TextView text_copyright; @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); context = ((SlidingActivity) getActivity()); get_userPhone = ((SlidingActivity) getActivity()).getUserPhone(); webService = new WebServiceUtils(MemoWebPara.MM_NAMESPACE, MemoWebPara.MM_URL, this); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.activity_menu, null); txt_card_management = (TextView) view .findViewById(R.id.txt_card_management); txt_card_management.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub dialog_card_management = new Dialog(context); dialog_card_management .requestWindowFeature(Window.FEATURE_NO_TITLE); LayoutInflater inflater = LayoutInflater .from(((SlidingActivity) getActivity())); final View dialogView = inflater.inflate( R.layout.dialog_card_management, null); dialog_card_management.setContentView(dialogView); InitCardManagementDialog(dialogView); dialog_card_management.show(); } }); txt_account_management = (TextView) view .findViewById(R.id.txt_account_management); txt_account_management.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub dialog_account_management = new Dialog(context); dialog_account_management .requestWindowFeature(Window.FEATURE_NO_TITLE); LayoutInflater inflater = LayoutInflater .from(((SlidingActivity) getActivity())); final View dialogView = inflater.inflate( R.layout.dialog_account_management, null); dialog_account_management.setContentView(dialogView); InitAccountManagementDialog(dialogView); dialog_account_management.show(); } }); txt_check_version = (TextView) view .findViewById(R.id.txt_check_version); txt_check_version.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub } }); txt_setting = (TextView) view.findViewById(R.id.txt_setting); txt_setting.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub dialog_synchronization = new Dialog(context); dialog_synchronization .requestWindowFeature(Window.FEATURE_NO_TITLE); LayoutInflater inflater = LayoutInflater .from(((SlidingActivity) getActivity())); final View dialogView = inflater.inflate( R.layout.dialog_synchronization, null); dialog_synchronization.setContentView(dialogView); InitSynchronizationDialog(dialogView); dialog_synchronization.show(); } }); txt_opinion = (TextView) view.findViewById(R.id.txt_opinion); txt_opinion.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub } }); txt_news = (TextView) view.findViewById(R.id.txt_news); txt_news.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub } }); txt_share = (TextView) view.findViewById(R.id.txt_share); txt_share.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub } }); txt_weibo = (TextView) view.findViewById(R.id.txt_weibo); txt_weibo.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub } }); txt_about_us = (TextView) view.findViewById(R.id.txt_about_us); txt_about_us.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub dialog_about_us = new Dialog(context); dialog_about_us.requestWindowFeature(Window.FEATURE_NO_TITLE); LayoutInflater inflater = LayoutInflater .from(((SlidingActivity) getActivity())); final View dialogView = inflater.inflate( R.layout.dialog_about_us, null); dialog_about_us.setContentView(dialogView); InitAboutUsDialog(dialogView); dialog_about_us.show(); } }); return view; } @Override public void onDestroy() { super.onDestroy(); } @Override public void onDetach() { super.onDetach(); } @Override public void onPause() { super.onPause(); } @Override public void onResume() { super.onResume(); } @Override public void onStart() { super.onStart(); } @Override public void onStop() { super.onStop(); } public byte[] getbyte() { byte[] tmp = new byte[1000]; byte[] db = null; ByteArrayOutputStream os = new ByteArrayOutputStream(1000); int n; try { File file = new File( "/data/data/com.businesscard.mobile/databases/" + get_userPhone + ".db3"); FileInputStream is = new FileInputStream(file); while ((n = is.read(tmp)) != -1) { os.write(tmp, 0, n); } is.close(); os.close(); db = os.toByteArray(); } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return db; } public void uploadDbFile() { byte[] db = getbyte(); HashMap args = new HashMap(); args.put("tel", get_userPhone); args.put("db", db); MyProgressDialog.show(getActivity(), "上传数据中,请稍后……", false, false); webService.callWebService("uploadCardDBFile", args, boolean.class); } protected void InitCardManagementDialog(View dialogView) { txt_card_holder = (TextView) dialogView .findViewById(R.id.txt_card_holder); txt_card_holder.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(((SlidingActivity) getActivity()), ViewPagerActivity.class); startActivity(intent); dialog_card_management.dismiss(); } }); Button btnCancel=(Button) dialogView.findViewById(R.id.dialogBtnCardManageCancel); btnCancel.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub dialog_card_management.cancel(); } }); } protected void InitAboutUsDialog(View dialogView) { text_version = (TextView) dialogView.findViewById(R.id.soft_current_version); text_user_warning = (TextView) dialogView.findViewById(R.id.user_warning); text_copyright = (TextView) dialogView.findViewById(R.id.copyright); text_version.setText(version); text_user_warning.setText(user_warning); text_copyright.setText(copyright); } protected void InitAccountManagementDialog(View dialogView) { txt_return = (TextView) dialogView.findViewById(R.id.txt_return); txt_return.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Editor edit = ((SlidingActivity) getActivity()).sp.edit(); edit.putBoolean("login_in", false); edit.commit(); Intent intent = new Intent(((SlidingActivity) getActivity()), LoginAndRegistActivity.class); startActivity(intent); dialog_account_management.dismiss(); ((SlidingActivity) getActivity()).finish(); } }); Button btnCancel=(Button) dialogView.findViewById(R.id.dialogAccountManageCancel); btnCancel.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub dialog_account_management.dismiss(); } }); txt_exit = (TextView) dialogView.findViewById(R.id.txt_exit); txt_exit.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub getActivity().finish(); } }); } protected void InitSynchronizationDialog(View dialogView) { tv_backup_cloud = (TextView) dialogView .findViewById(R.id.tv_backup_cloud); tv_backup_cloud.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub webflag = true; uploadDbFile(); } }); tv_synchronization = (TextView) dialogView .findViewById(R.id.tv_synchronization); tv_synchronization.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub webflag = false; HashMap args = new HashMap(); args.put("arg0", get_userPhone); MyProgressDialog.show(getActivity(), "下载数据中,请稍后……", false, false); webService.callWebService("downloadCardDBFile", args, byte[].class); } }); } @Override public void handleException(Object ex) { // TODO Auto-generated method stub MyProgressDialog.cancel(); Toast toast = Toast.makeText(getActivity(), "请检查网络连接", Toast.LENGTH_SHORT); toast.show(); } @Override public void handleResultOfWebService(String methodName, Object result) { // TODO Auto-generated method stub if (webflag == true) { boolean flag = (Boolean) result; if (flag == true) { MyProgressDialog.cancel(); Toast toast = Toast.makeText(getActivity(), "备份成功", Toast.LENGTH_SHORT); toast.show(); dialog_synchronization.dismiss(); } else { MyProgressDialog.cancel(); Toast toast = Toast.makeText(getActivity(), "备份失败", Toast.LENGTH_SHORT); toast.show(); } } else if (webflag == false) { String tmp = result.toString(); // 转化成byte数组 byte[] retByte = Base64.decode(tmp); createDatabase(retByte); ((SlidingActivity) getActivity()).getMainFragment().ResetData(); dialog_synchronization.dismiss(); MyProgressDialog.cancel(); Toast toast = Toast.makeText(getActivity(), "下载成功", Toast.LENGTH_SHORT); toast.show(); } } @SuppressLint("SdCardPath") public void createDatabase(byte[] db) { String path = "/data/data/com.businesscard.mobile/databases/"; File file = new File(path); file.mkdir(); path = path + get_userPhone + ".db3"; file = new File(path); try { file.createNewFile(); FileOutputStream os = new FileOutputStream(file); os.write(db); os.close(); System.out.println("success"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } srcalc/src/main/java/gov/va/med/srcalc/web/controller/DisplayResultsController.java package gov.va.med.srcalc.web.controller; import java.util.HashMap; import gov.va.med.srcalc.domain.calculation.*; import gov.va.med.srcalc.service.CalculationService; import gov.va.med.srcalc.web.view.ValueDisplayOrder; import gov.va.med.srcalc.web.view.Views; import javax.inject.Inject; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.DataAccessException; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.google.common.collect.ImmutableSortedSet; /** * Web MVC controller to display calculation results and allow the user to sign them. */ @Controller public class DisplayResultsController { private static final Logger LOGGER = LoggerFactory.getLogger(DisplayResultsController.class); private final CalculationService fCalculationService; /** * Constructs an instance. * @param calculationService the service to use for various operations when * performing a calculation */ @Inject public DisplayResultsController(final CalculationService calculationService) { fCalculationService = calculationService; } /** * Displays the results of the calculation that was performed. * @param session the current session * @param model the current model being used */ @RequestMapping(value = "/displayResults", method = RequestMethod.GET) public String displayResults( final HttpSession session, final Model model) { // Get the current CalculationSession. final CalculationSession cs = SrcalcSession.getCalculationSession(session); model.addAttribute("calculation", cs.getCalculation()); // And get the current CalculationResult from the session. final CalculationResult result = cs.getRequiredLastResult(); model.addAttribute("result", result); // Sort the input values in the desired display order and add to the // model. final ValueDisplayOrder displayOrder = new ValueDisplayOrder(); model.addAttribute("inputValues", ImmutableSortedSet.copyOf(displayOrder, result.getValues())); return Views.DISPLAY_RESULTS; } /** * Attempts to sign the current calculation and returns the status of that attempt in * a json format. * @param session the current session * @param electronicSignature the electronic signature to sign the calculation with * @param model the current model * @return a map that contains the result status message to be converted to json */ @RequestMapping( value="/signCalculation", method = RequestMethod.POST, produces = "application/json") @ResponseBody public HashMap signCalculation(final HttpSession session, @RequestParam(value = "eSig") final String electronicSignature, final Model model) { // Build the note body and submit the RPC String resultString; try { final CalculationResult lastResult = SrcalcSession.getCalculationSession(session).getRequiredLastResult(); resultString = fCalculationService.signRiskCalculation( lastResult, electronicSignature).getDescription(); } catch (final DataAccessException e) { final String msg = "There was a problem communicating to the database or VistA."; LOGGER.warn(msg, e); resultString = msg; } // The json could be expanded to return more information/fields final HashMap jsonStatus = new HashMap<>(); jsonStatus.put("status", resultString); // Return the result that will be translated to a json response return jsonStatus; } /** * Returns the page displaying to the user that the calculation signature was successful. * @param session the current session * @param model the current model */ @RequestMapping(value="/successfulSign", method = RequestMethod.GET) public String displaySuccess(final HttpSession session, final Model model) { return Views.SUCCESSFUL_SIGN; } } package org.robolectric.shadows; import android.webkit.JsPromptResult; import org.robolectric.Robolectric; import org.robolectric.annotation.Implements; @Implements(JsPromptResult.class) public class ShadowJsPromptResult extends ShadowJsResult{ public static JsPromptResult newInstance() { return Robolectric.newInstanceOf(JsPromptResult.class); } } 1-10 package com.jfinalshop.controller.admin; import java.util.Arrays; import com.jfinal.ext.route.ControllerBind; import com.jfinal.plugin.activerecord.Page; import com.jfinalshop.common.Message; import com.jfinalshop.common.Pageable; import com.jfinalshop.model.Attribute; import com.jfinalshop.model.Product; import com.jfinalshop.service.AttributeService; import com.jfinalshop.service.ProductCategoryService; /** * Controller - 属性 * * * */ @ControllerBind(controllerKey = "/admin/attribute") public class AttributeController extends BaseAdminController { private AttributeService attributeService = enhance(AttributeService.class); private ProductCategoryService productCategoryService = enhance(ProductCategoryService.class); private Attribute attribute; /** * 列表 */ public void list() { Pageable pageable = getBean(Pageable.class); Page page = attributeService.findPage(pageable); setAttr("page", page); setAttr("pageable", pageable); render("/admin/attribute/list.html"); } /** * 添加 */ public void add() { setAttr("productCategoryTree", productCategoryService.findTree()); setAttr("attributeValuePropertyCount", Product.ATTRIBUTE_VALUE_PROPERTY_COUNT); render("/admin/attribute/add.html"); } /** * 保存 */ public void save() { Long productCategoryId = getParaToLong("productCategoryId"); String[] options = getParaValues("options"); attribute = getModel(Attribute.class); attribute.setOptions(Arrays.asList(options)); attribute.setProductCategoryId(productCategoryId); if (attribute.getProductCategory().getAttributes().size() >= Product.ATTRIBUTE_VALUE_PROPERTY_COUNT) { addFlashMessage(Message.error("admin.attribute.addCountNotAllowed", Product.ATTRIBUTE_VALUE_PROPERTY_COUNT)); return; } else { attributeService.save(attribute); addFlashMessage(SUCCESS_MESSAGE); } list(); } /** * 编辑 */ public void edit() { Long id = getParaToLong("id"); setAttr("productCategoryTree", productCategoryService.findTree()); setAttr("attributeValuePropertyCount", Product.ATTRIBUTE_VALUE_PROPERTY_COUNT); setAttr("attribute", attributeService.find(id)); render("/admin/attribute/edit.html"); } /** * 更新 */ public void update() { String[] options = getParaValues("options"); attribute = getModel(Attribute.class); attribute.setOptions(Arrays.asList(options)); attributeService.update(attribute); addFlashMessage(SUCCESS_MESSAGE); list(); } /** * 删除 */ public void delete() { Long[] ids = getParaValuesToLong("ids"); if (ids.length > 0) { attributeService.delete(ids); renderJson(SUCCESS_MESSAGE); } else { renderJson(com.jfinalshop.common.Message.error("admin.common.deleteAllNotAllowed")); } } } import java.io.IOException; import java.util.HashMap; public class Demo { public static void main(String[] args)throws IOException, ClassNotFoundException { // String path = "/Users/jerry/Desktop/serializedobjects.ser"; // // Manager m = new Manager(path); // Company c = new Company(); // // c.pull("one"); // c.put("one"); // c.put("two"); // System.out.println(m.lst.size()); HashMap hm = new HashMap(); hm.put("lilei",1); System.out.println(hm.get("lilei")); // m.saveToFile(path); // System.out.println(m.getLst().size()); } } package gl8080.lifegame.logic.definition; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import gl8080.lifegame.logic.LifeGameCell; import gl8080.lifegame.logic.Position; import gl8080.lifegame.logic.exception.IllegalParameterException; public class GameDefinitionTest { @Rule public ExpectedException exception = ExpectedException.none(); private int size = 5; private GameDefinition gameDef; @Before public void setup() { gameDef = new GameDefinition(size); } @Test public void サイズに負数を指定したら例外がスローされること() throws Exception { // verify exception.expect(IllegalParameterException.class); // exercise new GameDefinition(-1); } @Test public void サイズに0を指定したら例外がスローされること() throws Exception { // verify exception.expect(IllegalParameterException.class); // exercise new GameDefinition(0); } @Test public void サイズに上限値を指定しても_例外はスローされないこと() throws Exception { // exercise new GameDefinition(GameDefinition.MAX_SIZE); } @Test public void サイズに上限値を越える値を指定したら_例外がスローされること() throws Exception { // verify exception.expect(IllegalParameterException.class); // exercise new GameDefinition(GameDefinition.MAX_SIZE + 1); } @Test public void インスタンスを生成すると_指定したサイズを二乗した数の死んだセル定義が作成される() { // verify Map matrix = gameDef.getCells(); Set uniqued = new HashSet<>(matrix.values()); assertThat(uniqued.size(), is(size * size)); assertThat(uniqued.stream().anyMatch(LifeGameCell::isAlive), is(false)); } @Test public void 位置を指定して_セル定義の状態を変更できる() { // setup Position position = new Position(2, 3); LifeGameCell targetCell = gameDef.getCells().get(position); assertThat(targetCell.isAlive(), is(false)); // exercise gameDef.setStatus(position, true); // verify assertThat(targetCell.isAlive(), is(true)); } @Test public void 指定した位置がnullの場合_例外がスローされる() { // verify exception.expect(NullPointerException.class); // exercise gameDef.setStatus(null, true); } @Test public void 座標が_サイズで指定した範囲より外の場合_例外がスローされる() { // verify exception.expect(IllegalParameterException.class); // exercise gameDef.setStatus(new Position(size, 0), true); } @Test public void 取得したセル定義一覧を変更しても_ゲーム定義が持っているセル定義には影響を与えない() { // setup Position position = new Position(1, 2); // exercise gameDef.getCells().remove(position); // verify assertThat(gameDef.getCells().containsKey(position), is(true)); } } package com.cy.tablayoutsimple_; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentStatePagerAdapter; import androidx.viewpager.widget.ViewPager; import android.graphics.Typeface; import android.os.Bundle; import android.view.View; import android.widget.TextView; import com.cy.tablayoutniubility.FragPageAdapterVp; import com.cy.tablayoutniubility.TabAdapter; import com.cy.tablayoutniubility.TabLayoutScroll; import com.cy.tablayoutniubility.TabMediatorVp; import com.cy.tablayoutniubility.TabViewHolder; import java.util.ArrayList; import java.util.List; public class TabLayoutVPActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tab_layout_v_p); final ViewPager viewPager = findViewById(R.id.view_pager); final TabLayoutScroll tabLayoutLine = findViewById(R.id.tablayout); // tabLayoutLine.setSpace_horizontal(dpAdapt(20)).setSpace_vertical(dpAdapt(8)); final FragPageAdapterVp fragmentPageAdapter = new FragPageAdapterVp(getSupportFragmentManager(), FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) { @Override public Fragment createFragment(String bean, int position) { LogUtils.log("createFragmenteeee",position); return FragmentTab2.newInstance(FragmentTab2.TAB_NAME2, getList_bean().get(position)); } @Override public void bindDataToTab(TabViewHolder holder, int position, String bean, boolean isSelected) { TextView textView = holder.getView(R.id.tv); if (isSelected) { textView.setTextColor(0xffe45540); textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD)); } else { textView.setTextColor(0xff444444); textView.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL)); } textView.setText(bean); } @Override public int getTabLayoutID(int position, String bean) { if (position == 0) { return R.layout.item_tab_msg; } return R.layout.item_tab; } }; final TabMediatorVp tabMediatorVp=new TabMediatorVp(tabLayoutLine, viewPager); final TabAdapter tabAdapter = tabMediatorVp.setAdapter(fragmentPageAdapter); List list = new ArrayList<>(); list.add("关注"); list.add("推荐"); list.add("视频"); list.add("抗疫"); list.add("深圳"); list.add("热榜"); list.add("小视频"); list.add("软件"); list.add("探索"); list.add("在家上课"); list.add("手机"); list.add("动漫"); list.add("通信"); list.add("影视"); list.add("互联网"); list.add("设计"); list.add("家电"); list.add("平板"); list.add("网球"); list.add("军事"); list.add("羽毛球"); list.add("奢侈品"); list.add("美食"); list.add("瘦身"); list.add("幸福里"); list.add("棋牌"); list.add("奇闻"); list.add("艺术"); list.add("减肥"); list.add("电玩"); list.add("台球"); list.add("八卦"); list.add("酷玩"); list.add("彩票"); list.add("漫画"); fragmentPageAdapter.add(list); tabAdapter.add(list); findViewById(R.id.btn_refresh).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TabAdapter tabAdapter = tabMediatorVp.setAdapter(fragmentPageAdapter); List list = new ArrayList<>(); list.add("关注"); list.add("推荐"); list.add("视频"); list.add("抗疫"); list.add("深圳"); list.add("热榜"); list.add("小视频"); list.add("软件"); list.add("探索"); list.add("在家上课"); list.add("手机"); list.add("动漫"); list.add("通信"); list.add("影视"); list.add("互联网"); list.add("设计"); list.add("家电"); list.add("平板"); list.add("网球"); list.add("军事"); list.add("羽毛球"); list.add("奢侈品"); list.add("美食"); list.add("瘦身"); list.add("幸福里"); list.add("棋牌"); list.add("奇闻"); list.add("艺术"); list.add("减肥"); list.add("电玩"); list.add("台球"); list.add("八卦"); list.add("酷玩"); list.add("彩票"); list.add("漫画"); fragmentPageAdapter.clearAdd(list); tabAdapter.clearAdd(list); } }); } } licket-framework/src/main/java/org/licket/core/view/ComponentChildLocator.java package org.licket.core.view; import org.licket.core.id.CompositeId; import java.util.Optional; import java.util.function.Predicate; import static java.util.Optional.ofNullable; /** * @author activey */ public class ComponentChildLocator { private LicketComponent startingComponent; public ComponentChildLocator(LicketComponent startingComponent) { this.startingComponent = startingComponent; } public final Optional> findByCompositeId(CompositeId compositeId) { ChildrenTraverse traverse = new ChildrenTraverse(compositeId); startingComponent.traverseDown(traverse); return traverse.getFound(); } private class ChildrenTraverse implements Predicate> { private CompositeId compositeId; private LicketComponent found; public ChildrenTraverse(CompositeId compositeId) { this.compositeId = compositeId; } public Optional> getFound() { return ofNullable(found); } @Override public boolean test(LicketComponent component) { if (compositeId.hasMore() && compositeId.current().equals(component.getId())) { compositeId.forward(); return true; } if (compositeId.current().equals(component.getId())) { this.found = component; } return false; } } } package org.gooru.nucleus.search.indexers.app.repositories.activejdbc; import org.gooru.nucleus.search.indexers.app.repositories.entities.Library; import org.gooru.nucleus.search.indexers.processors.repositories.activejdbc.formatter.JsonFormatterBuilder; import org.javalite.activejdbc.DB; import org.javalite.activejdbc.LazyList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.vertx.core.json.JsonObject; public class LibraryRepositoryImpl extends BaseIndexRepo implements LibraryRepository { private static final Logger LOGGER = LoggerFactory.getLogger(LibraryRepositoryImpl.class); @Override public JsonObject getLibraryContentById(String contentId) { JsonObject returnValue = null; DB db = getDefaultDataSourceDBConnection(); try { openDefaultDBConnection(db); LazyList result = Library.findBySQL(Library.FETCH_LIBRARY_CONTENT, contentId); if (result != null && result.size() > 0) { returnValue = new JsonObject(JsonFormatterBuilder.buildSimpleJsonFormatter(false, null).toJson(result.get(0))); } } catch (Exception e) { LOGGER.error("Not able to fetch library content : {} error : {}", contentId, e); } closeDefaultDBConn(db); return returnValue; } } kelvinnharris/main package seedu.ifridge.testutil; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import seedu.ifridge.logic.commands.EditCommand.EditFoodDescriptor; import seedu.ifridge.model.food.Amount; import seedu.ifridge.model.food.ExpiryDate; import seedu.ifridge.model.food.Food; import seedu.ifridge.model.food.Name; import seedu.ifridge.model.tag.Tag; /** * A utility class to help with building EditPersonDescriptor objects. */ public class EditFoodDescriptorBuilder { private EditFoodDescriptor descriptor; public EditFoodDescriptorBuilder() { descriptor = new EditFoodDescriptor(); } public EditFoodDescriptorBuilder(EditFoodDescriptor descriptor) { this.descriptor = new EditFoodDescriptor(descriptor); } /** * Returns an {@code EditPersonDescriptor} with fields containing {@code person}'s details */ public EditFoodDescriptorBuilder(Food food) { descriptor = new EditFoodDescriptor(); descriptor.setName(food.getName()); //descriptor.setTags(food.getTags()); } /** * Sets the {@code Name} of the {@code EditPersonDescriptor} that we are building. */ public EditFoodDescriptorBuilder withAmount(String name) { descriptor.setAmount(new Amount(name)); return this; } /** * Sets the {@code Name} of the {@code EditPersonDescriptor} that we are building. */ public EditFoodDescriptorBuilder withExpiryDate(String name) { descriptor.setExpiryDate(new ExpiryDate(name)); return this; } /** * Sets the {@code Name} of the {@code EditPersonDescriptor} that we are building. */ public EditFoodDescriptorBuilder withName(String name) { descriptor.setName(new Name(name)); return this; } /** * Parses the {@code tags} into a {@code Set} and set it to the {@code EditPersonDescriptor} * that we are building. */ public EditFoodDescriptorBuilder withTags(String... tags) { Set tagSet = Stream.of(tags).map(Tag::new).collect(Collectors.toSet()); descriptor.setTags(tagSet); return this; } public EditFoodDescriptor build() { return descriptor; } } package com.izzyacademy.sales.models; public class ProductDetail { } package com.espark.adarsh.bean; import java.io.Serializable; public class AddressBean implements Serializable { private int addressId; private String addressCountry; private String addressCity; private EmployeeBean employee; public EmployeeBean getEmployee() { return employee; } public void setEmployee(EmployeeBean employee) { this.employee = employee; } public int getAddressId() { return addressId; } public void setAddressId(int addressId) { this.addressId = addressId; } public String getAddressCountry() { return addressCountry; } public void setAddressCountry(String addressCountry) { this.addressCountry = addressCountry; } public String getAddressCity() { return addressCity; } public void setAddressCity(String addressCity) { this.addressCity = addressCity; } }/* * * Copyright 2016 Netflix, 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.netflix.genie.core.configs; import com.fasterxml.jackson.databind.ObjectMapper; import com.netflix.genie.common.exceptions.GenieException; import com.netflix.genie.core.jobs.workflow.WorkflowTask; import com.netflix.genie.core.jpa.repositories.JpaApplicationRepository; import com.netflix.genie.core.jpa.repositories.JpaClusterRepository; import com.netflix.genie.core.jpa.repositories.JpaCommandRepository; import com.netflix.genie.core.jpa.repositories.JpaJobExecutionRepository; import com.netflix.genie.core.jpa.repositories.JpaJobMetadataRepository; import com.netflix.genie.core.jpa.repositories.JpaJobRepository; import com.netflix.genie.core.jpa.repositories.JpaJobRequestRepository; import com.netflix.genie.core.jpa.services.JpaApplicationServiceImpl; import com.netflix.genie.core.jpa.services.JpaClusterServiceImpl; import com.netflix.genie.core.jpa.services.JpaCommandServiceImpl; import com.netflix.genie.core.jpa.services.JpaJobPersistenceServiceImpl; import com.netflix.genie.core.jpa.services.JpaJobSearchServiceImpl; import com.netflix.genie.core.properties.JobsProperties; import com.netflix.genie.core.services.ApplicationService; import com.netflix.genie.core.services.AttachmentService; import com.netflix.genie.core.services.ClusterLoadBalancer; import com.netflix.genie.core.services.ClusterService; import com.netflix.genie.core.services.CommandService; import com.netflix.genie.core.services.FileTransferFactory; import com.netflix.genie.core.services.JobCoordinatorService; import com.netflix.genie.core.services.JobKillService; import com.netflix.genie.core.services.JobMetricsService; import com.netflix.genie.core.services.JobPersistenceService; import com.netflix.genie.core.services.JobSearchService; import com.netflix.genie.core.services.JobStateService; import com.netflix.genie.core.services.JobSubmitterService; import com.netflix.genie.core.services.impl.FileSystemAttachmentService; import com.netflix.genie.core.services.impl.GenieFileTransferService; import com.netflix.genie.core.services.impl.JobCoordinatorServiceImpl; import com.netflix.genie.core.services.impl.JobMetricsServiceImpl; import com.netflix.genie.core.services.impl.JobStateServiceImpl; import com.netflix.genie.core.services.impl.LocalJobKillServiceImpl; import com.netflix.genie.core.services.impl.LocalJobRunner; import com.netflix.genie.core.services.impl.RandomizedClusterLoadBalancerImpl; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Registry; import org.apache.commons.exec.Executor; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.config.ServiceLocatorFactoryBean; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.event.ApplicationEventMulticaster; import org.springframework.context.event.SimpleApplicationEventMulticaster; import org.springframework.core.io.Resource; import org.springframework.core.task.AsyncTaskExecutor; import org.springframework.core.task.TaskExecutor; import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import java.util.List; /** * Configuration to create the Service beans for Genie Core Tests. * * @author amsharma * @since 3.0.0 */ @Configuration public class ServicesConfigTest { /** * Get JPA based implementation of the ApplicationService. * * @param applicationRepo The application repository to use. * @param commandRepo The command repository to use. * @return An application service instance. */ @Bean public ApplicationService applicationService( final JpaApplicationRepository applicationRepo, final JpaCommandRepository commandRepo ) { return new JpaApplicationServiceImpl(applicationRepo, commandRepo); } /** * Get JPA based implementation of the ClusterService. * * @param clusterRepo The cluster repository to use. * @param commandRepo The command repository to use. * @return A cluster service instance. */ @Bean public ClusterService clusterService( final JpaClusterRepository clusterRepo, final JpaCommandRepository commandRepo ) { return new JpaClusterServiceImpl(clusterRepo, commandRepo); } /** * Get JPA based implementation of the CommandService. * * @param commandRepo the command repository to use * @param appRepo the application repository to use * @param clusterRepo the cluster repository to use * @return A command service instance. */ @Bean public CommandService commandService( final JpaCommandRepository commandRepo, final JpaApplicationRepository appRepo, final JpaClusterRepository clusterRepo ) { return new JpaCommandServiceImpl(commandRepo, appRepo, clusterRepo); } /** * Get JPA based implementation of the JobSearchService. * * @param jobRepository The repository to use for job entities * @param jobRequestRepository The repository to use for job request entities * @param jobExecutionRepository The repository to use for job execution entities * @param clusterRepository The repository to use for cluster entities * @param commandRepository The repository to use for command entities * @return A job search service instance. */ @Bean public JobSearchService jobSearchService( final JpaJobRepository jobRepository, final JpaJobRequestRepository jobRequestRepository, final JpaJobExecutionRepository jobExecutionRepository, final JpaClusterRepository clusterRepository, final JpaCommandRepository commandRepository ) { return new JpaJobSearchServiceImpl( jobRepository, jobRequestRepository, jobExecutionRepository, clusterRepository, commandRepository ); } /** * Get JPA based implementation of the JobPersistenceService. * * @param jobRepo The job repository to use * @param jobRequestRepo The job request repository to use * @param jobMetadataRepository The job metadata repository to use * @param jobExecutionRepo The job execution repository to use * @param applicationRepo The application repository to use * @param clusterRepo The cluster repository to use * @param commandRepo The command repository to use * @return A job search service instance. */ @Bean public JobPersistenceService jobPersistenceService( final JpaJobRepository jobRepo, final JpaJobRequestRepository jobRequestRepo, final JpaJobMetadataRepository jobMetadataRepository, final JpaJobExecutionRepository jobExecutionRepo, final JpaApplicationRepository applicationRepo, final JpaClusterRepository clusterRepo, final JpaCommandRepository commandRepo ) { return new JpaJobPersistenceServiceImpl( jobRepo, jobRequestRepo, jobMetadataRepository, jobExecutionRepo, applicationRepo, clusterRepo, commandRepo ); } /** * Get an local implementation of the JobKillService. * * @param hostname The name of the host this Genie node is running on. * @param jobSearchService The job search service to use to locate job information. * @param executor The executor to use to run system processes. * @param eventPublisher The event publisher to use * @param genieWorkingDir Working directory for genie where it creates jobs directories. * @param objectMapper The Jackson ObjectMapper used to serialize from/to JSON * @return A job kill service instance. */ @Bean public JobKillService jobKillService( final String hostname, final JobSearchService jobSearchService, final Executor executor, final ApplicationEventPublisher eventPublisher, @Qualifier("jobsDir") final Resource genieWorkingDir, final ObjectMapper objectMapper ) { return new LocalJobKillServiceImpl( hostname, jobSearchService, executor, false, eventPublisher, genieWorkingDir, objectMapper ); } /** * Get a Randomized Cluster load balancer. * * @return A randomized cluster load balancer instance. */ @Bean public ClusterLoadBalancer clusterLoadBalancer() { return new RandomizedClusterLoadBalancerImpl(); } /** * Get an instance of the Genie File Transfer service. * * @param fileTransferFactory file transfer implementation factory * @return A singleton for GenieFileTransferService * @throws GenieException If there is any problem */ @Bean public GenieFileTransferService genieFileTransferService( final FileTransferFactory fileTransferFactory ) throws GenieException { return new GenieFileTransferService(fileTransferFactory); } /** * Get a implementation of the JobSubmitterService that runs jobs locally. * * @param jobPersistenceService Implementation of the job persistence service. * @param eventPublisher Instance of the synchronous event publisher. * @param eventMulticaster Instance of the asynchronous event publisher. * @param workflowTasks List of all the workflow tasks to be executed. * @param genieWorkingDir Working directory for genie where it creates jobs directories. * @param registry The metrics registry to use * @return An instance of the JobSubmitterService. */ @Bean public JobSubmitterService jobSubmitterService( final JobPersistenceService jobPersistenceService, final ApplicationEventPublisher eventPublisher, final ApplicationEventMulticaster eventMulticaster, final List workflowTasks, @Qualifier("jobsDir") final Resource genieWorkingDir, final Registry registry ) { return new LocalJobRunner( jobPersistenceService, eventPublisher, eventMulticaster, workflowTasks, genieWorkingDir, registry ); } /** * The job count service to use. * * @param jobSearchService The job search implementation to use * @param hostName The host name of this Genie node * @return The job count service bean */ @Bean public JobMetricsService jobCountService(final JobSearchService jobSearchService, final String hostName) { return new JobMetricsServiceImpl(jobSearchService, hostName); } /** * Default task scheduler. * @return task scheduler */ @Bean public TaskScheduler taskScheduler() { return new ThreadPoolTaskScheduler(); } /** * The job state service to use. * * @param jobSubmitterService The job submitter implementation to use * @param taskScheduler The task scheduler to use to register scheduling of job checkers * @param eventPublisher The application event publisher to use to publish synchronous events * @param registry The metrics registry * @return The job state service bean */ @Bean public JobStateService jobStateService(final JobSubmitterService jobSubmitterService, final TaskScheduler taskScheduler, final ApplicationEventPublisher eventPublisher, final Registry registry) { return new JobStateServiceImpl(jobSubmitterService, taskScheduler, eventPublisher, registry); } /** * The task executor to use. * * @return The task executor to for launching jobs */ @Bean public AsyncTaskExecutor taskExecutor() { return new ThreadPoolTaskExecutor(); } /** * A multicast (async) event publisher to replace the synchronous one used by Spring via the ApplicationContext. * * @param taskExecutor The task executor to use * @return The application event multicaster to use */ @Bean public ApplicationEventMulticaster applicationEventMulticaster(final TaskExecutor taskExecutor) { final SimpleApplicationEventMulticaster applicationEventMulticaster = new SimpleApplicationEventMulticaster(); applicationEventMulticaster.setTaskExecutor(taskExecutor); return applicationEventMulticaster; } /** * Registry bean. * * @return a default registry */ @Bean public Registry registry() { return new DefaultRegistry(); } /** * Get an instance of the JobCoordinatorService. * * @param jobPersistenceService implementation of job persistence service interface. * @param jobStateService implementation of job state service interface * @param jobKillService The job kill service to use. * @param jobsProperties The jobs properties to use * @param applicationService Implementation of application service interface * @param clusterService Implementation of cluster service interface * @param commandService Implementation of command service interface * @param clusterLoadBalancer Implementation of the cluster load balancer interface * @param registry The registry to use * @param hostName The host name to use * @return An instance of the JobCoordinatorService. */ @Bean public JobCoordinatorService jobCoordinatorService( final JobPersistenceService jobPersistenceService, final JobKillService jobKillService, final JobStateService jobStateService, final JobsProperties jobsProperties, final ApplicationService applicationService, final ClusterService clusterService, final CommandService commandService, final ClusterLoadBalancer clusterLoadBalancer, final Registry registry, final String hostName ) { return new JobCoordinatorServiceImpl( jobPersistenceService, jobKillService, jobStateService, jobsProperties, applicationService, clusterService, commandService, clusterLoadBalancer, registry, hostName ); } /** * The attachment service to use. * * @param jobsProperties The various jobs properties including the location of the attachments directory * @return The attachment service to use */ @Bean public AttachmentService attachmentService(final JobsProperties jobsProperties) { return new FileSystemAttachmentService(jobsProperties.getLocations().getAttachments()); } /** * FileTransfer factory. * * @return FileTransfer factory */ @Bean public FactoryBean fileTransferFactory() { final ServiceLocatorFactoryBean factoryBean = new ServiceLocatorFactoryBean(); factoryBean.setServiceLocatorInterface(FileTransferFactory.class); return factoryBean; } /** * Get the jobs properties to use for the services. * * @return The jobs properties to use */ @Bean @ConfigurationProperties("genie.jobs") public JobsProperties jobsProperties() { return new JobsProperties(); } } package com.jikexueyuan.dto; /** * FileName: IdEntity.java * desc: 所有实体类的父类,主键定义. * Date: 2015/01/21 * Copyright: www.jikexueyuan.com * MyBlog: blog.darkmi.com * @author darkmi * */ public abstract class IdEntity { protected Long id; public Long getId() { return id; } public void setId(Long id) { this.id = id; } } robwettach/webdiplomacy-poller package com.robwettach.webdiplomacy.notify; import static com.google.common.collect.ImmutableList.toImmutableList; import static java.util.stream.Collectors.toList; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableList; import com.robwettach.webdiplomacy.diff.Diff; import java.util.Arrays; import java.util.List; /** * {@link Notifier} that sends notifications to a collection of other {@link Notifier}s. */ @AutoValue public abstract class CompositeNotifier implements Notifier { @JsonIgnore public abstract ImmutableList getNotifiers(); @JsonProperty("notifiers") ImmutableList getUnionNotifiers() { return getNotifiers().stream().map(UnionNotifier::create).collect(toImmutableList()); } public static CompositeNotifier create(Notifier... notifiers) { return create(Arrays.asList(notifiers)); } public static CompositeNotifier create(List notifiers) { return new AutoValue_CompositeNotifier(ImmutableList.copyOf(notifiers)); } @JsonCreator static CompositeNotifier createJson(@JsonProperty("notifiers") List notifiers) { return create(notifiers.stream().map(UnionNotifier::getNotifier).collect(toList())); } @Override public void notify(List diffs) { getNotifiers().forEach(n -> n.notify(diffs)); } } package org.folio.repository.assigneduser; import java.util.Collection; import java.util.UUID; import java.util.concurrent.CompletableFuture; public interface AssignedUserRepository { CompletableFuture> findByCredentialsId(UUID credentialsId, String tenant); CompletableFuture count(UUID credentialsId, String tenant); CompletableFuture save(DbAssignedUser entity, String tenant); CompletableFuture delete(UUID credentialsId, UUID userId, String tenant); } package coffeemachine; import java.util.Arrays; /** * Class for returning the change after a payment for coffee using a coffee machine. * * @author () * @since 21.01.2019 * @version 1.0 */ public class CoffeeMachine { /** * Returns an array that contains change after the payment. The change represented as coins: 10, 5, 2, 1 and is * being returned in order starting with the most valuable (from 10 to 1). * * @param value - customer's value * @param price - price of coffee * @return an array containing change */ public int[] changes(int value, int price) { int change = value - price; int[] coins = {1, 2, 5, 10}; int index = 0; int[] result = new int[change]; int coinsIndex = coins.length - 1; while (change != 0) { while (change - coins[coinsIndex] < 0) { coinsIndex--; } change -= coins[coinsIndex]; result[index++] = coins[coinsIndex]; } return Arrays.copyOf(result, index); } }package com.utm.stanislav.parkingapp.web.dto; import com.utm.stanislav.parkingapp.model.enums.BookRequestStatus; import lombok.Data; import lombok.RequiredArgsConstructor; import java.util.UUID; @Data @RequiredArgsConstructor public class BookRequestDto { private final UUID id; private final String parking; private final String parkingLot; private final BookRequestStatus bookRequestStatus; } package uk.ac.ebi.subs.apisupport; import org.springframework.amqp.core.Binding; import org.springframework.amqp.core.BindingBuilder; import org.springframework.amqp.core.Queue; import org.springframework.amqp.core.TopicExchange; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import uk.ac.ebi.subs.messaging.Queues; /** * This configuration class responsible for the RabbitMQ configuration for the API support operations. */ @Configuration public class ApiSupportQueueConfig { /** * Queue for cleaning up contents of a submission if the user deletes it */ @Bean Queue onDeleteCleanupSubmissionContentsQueue(){return Queues.buildQueueWithDlx(Queues.SUBMISSION_DELETED_CLEANUP_CONTENTS);} @Bean Binding onDeleteCleanupSubmissionContentsBinding(Queue onDeleteCleanupSubmissionContentsQueue, TopicExchange submissionExchange) { return BindingBuilder.bind(onDeleteCleanupSubmissionContentsQueue).to(submissionExchange).with(Queues.SUBMISSION_DELETED_ROUTING_KEY); } /** * Queue for documents within a submission to have their status updated owhen the user submits the submission * @return */ @Bean Queue onSubmitMarkSubmittablesQueue() {return Queues.buildQueueWithDlx(Queues.SUBMISSION_SUBMITTED_MARK_SUBMITTABLES); } @Bean Binding onSubmitMarkSubmittablesBinding(Queue onSubmitMarkSubmittablesQueue, TopicExchange submissionExchange) { return BindingBuilder.bind(onSubmitMarkSubmittablesQueue).to(submissionExchange).with(Queues.SUBMISSION_SUBMITTED_ROUTING_KEY); } } public class Main { /** The method runs insertion sort for an example instance. **/ public static void main(String[] args) { int[] array = new int[] {7, 5, 3, 5, 2, 9}; MergeSort.sort(array); for (int i = 0; i < array.length; i++) { System.out.print(array[i]); System.out.print(" "); } System.out.println(); /** Integer[] a = new Integer[6]; a[0] = new Integer(7); a[1] = new Integer(5); a[2] = new Integer(3); a[3] = new Integer(5); a[4] = new Integer(2); a[5] = new Integer(9); InsertionSort.sort(a); for (int i = 0; i < a.length; i++) { System.out.print(a[i].toString()); System.out.print(" "); } **/ } } weicongs-amazon/sql-1 /* * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. * * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. */ /* * * Copyright 2020 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file 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.amazon.opendistroforelasticsearch.sql.opensearch.data.value; import static com.amazon.opendistroforelasticsearch.sql.opensearch.data.type.OpenSearchDataType.OPENSEARCH_IP; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; public class OpenSearchExprIpValueTest { private OpenSearchExprIpValue ipValue = new OpenSearchExprIpValue("192.168.0.1"); @Test void value() { assertEquals("192.168.0.1", ipValue.value()); } @Test void type() { assertEquals(OPENSEARCH_IP, ipValue.type()); } @Test void compare() { assertEquals(0, ipValue.compareTo(new OpenSearchExprIpValue("192.168.0.1"))); } @Test void equal() { assertTrue(ipValue.equal(new OpenSearchExprIpValue("192.168.0.1"))); } @Test void testHashCode() { assertNotNull(ipValue.hashCode()); } } 10-100 package org.jetbrains.dekaf.jdbc; /** * @author from JetBrains **/ public interface MysqlConsts { /** * Fetching whole result set at once when non-pack mode, * fetching row by row in pack mode. */ byte FETCH_STRATEGY_AUTO = 0; /** * Always fetch row by row. */ byte FETCH_STRATEGY_ROW = 1; /** * Always fetch all at once. */ byte FETCH_STRATEGY_WHOLE = 2; } 0 package com.ebrozon.controller; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.security.MessageDigest; import com.ebrozon.model.usuario; import com.ebrozon.model.usuarioverant; import com.ebrozon.repository.usuarioverantRepository; import io.swagger.annotations.Api; @RestController @Api(value="Historical user information Management System", description="Operations pertaining to historical user information in Historical user information Managament System ") public class usuarioverantController { @Autowired usuarioverantRepository repository; public void guardar(usuario u){ usuarioverant uv = new usuarioverant(u); repository.save(uv); } }/* * Copyright 2020 LTD. ŞTİ.. * * 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.sparrow.dnp; import com.automatak.dnp3.AnalogInput; import com.automatak.dnp3.AnalogOutputStatus; import com.automatak.dnp3.BinaryInput; import com.automatak.dnp3.BinaryOutputStatus; import com.automatak.dnp3.Counter; import com.automatak.dnp3.DNPTime; import com.automatak.dnp3.DoubleBitBinaryInput; import com.automatak.dnp3.FrozenCounter; import com.automatak.dnp3.HeaderInfo; import com.automatak.dnp3.IndexedValue; import com.automatak.dnp3.ResponseInfo; import com.automatak.dnp3.SOEHandler; import com.automatak.dnp3.mock.PrintingSOEHandler; import com.sparrow.dnp.config.MasterDeviceConfig; import com.sparrow.dnp.config.VariableConfig; import com.sparrow.dnp.config.VariableUnitConfig; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.util.HashMap; /** * @author ugurkara * */ public class MasterDevice extends BaseDevice implements SOEHandler { private final HashMap properties = new HashMap<>(); private final SOEHandler defaultHandler = PrintingSOEHandler.getInstance(); public MasterDevice(String name) { super(name); } @Override public void processBI(HeaderInfo hi, Iterable> itrbl) { defaultHandler.processBI(hi, itrbl); itrbl.forEach((IndexedValue v) -> { if (getDatabase().getDigitalInputs().getItems().containsKey(v.index)) { DnpVariable.DigitalInput oldValue = getDatabase().getDigitalInputs().getItems().get(v.index); oldValue.setObject(v.value); } else { getDatabase().getDigitalInputs().getItems().put(v.index, new DnpVariable.DigitalInput(v.index, v.value)); } }); } @Override public void processDBI(HeaderInfo hi, Iterable> itrbl) { defaultHandler.processDBI(hi, itrbl); itrbl.forEach((IndexedValue v) -> { if (getDatabase().getDoubleDigitals().getItems().containsKey(v.index)) { DnpVariable.DoubleDigital oldValue = getDatabase().getDoubleDigitals().getItems().get(v.index); oldValue.setObject(v.value); } else { getDatabase().getDoubleDigitals().getItems().put(v.index, new DnpVariable.DoubleDigital(v.index, v.value)); } }); } @Override public void processAI(HeaderInfo hi, Iterable> itrbl) { defaultHandler.processAI(hi, itrbl); itrbl.forEach((IndexedValue v) -> { if (getDatabase().getAnalogInputs().getItems().containsKey(v.index)) { DnpVariable.AnalogInput oldValue = getDatabase().getAnalogInputs().getItems().get(v.index); oldValue.setObject(v.value); } else { getDatabase().getAnalogInputs().getItems().put(v.index, new DnpVariable.AnalogInput(v.index, v.value)); } }); } @Override public void processC(HeaderInfo hi, Iterable> itrbl) { defaultHandler.processC(hi, itrbl); itrbl.forEach((IndexedValue v) -> { if (getDatabase().getCounters().getItems().containsKey(v.index)) { DnpVariable.Counter oldValue = getDatabase().getCounters().getItems().get(v.index); oldValue.setObject(v.value); } else { getDatabase().getCounters().getItems().put(v.index, new DnpVariable.Counter(v.index, v.value)); } }); } @Override public void processFC(HeaderInfo hi, Iterable> itrbl) { defaultHandler.processFC(hi, itrbl); itrbl.forEach((IndexedValue v) -> { if (getDatabase().getFrozenCounters().getItems().containsKey(v.index)) { DnpVariable.FrozenCounter oldValue = getDatabase().getFrozenCounters().getItems().get(v.index); oldValue.setObject(v.value); } else { getDatabase().getFrozenCounters().getItems().put(v.index, new DnpVariable.FrozenCounter(v.index, v.value)); } }); } @Override public void processBOS(HeaderInfo hi, Iterable> itrbl) { defaultHandler.processBOS(hi, itrbl); itrbl.forEach((IndexedValue v) -> { if (getDatabase().getDigitalOutputs().getItems().containsKey(v.index)) { DnpVariable.DigitalOutput oldValue = getDatabase().getDigitalOutputs().getItems().get(v.index); oldValue.setObject(v.value); } else { getDatabase().getDigitalOutputs().getItems().put(v.index, new DnpVariable.DigitalOutput(v.index, v.value)); } }); } @Override public void processAOS(HeaderInfo hi, Iterable> itrbl) { defaultHandler.processAOS(hi, itrbl); itrbl.forEach((IndexedValue v) -> { if (getDatabase().getAnalogOutputs().getItems().containsKey(v.index)) { DnpVariable.AnalogOutput oldValue = getDatabase().getAnalogOutputs().getItems().get(v.index); oldValue.setObject(v.value); } else { getDatabase().getAnalogOutputs().getItems().put(v.index, new DnpVariable.AnalogOutput(v.index, v.value)); } }); } @Override public void processDNPTime(HeaderInfo hi, Iterable itrbl) { itrbl.forEach((DNPTime dnpTime) -> { Object oldValue = properties.get("time"); properties.put("time", dnpTime.msSinceEpoch); this.pcs.firePropertyChange(new PropertyChangeEvent(dnpTime.msSinceEpoch, "properties", oldValue, dnpTime.msSinceEpoch)); }); } public HashMap getProperties() { return properties; } protected final PropertyChangeSupport pcs = new PropertyChangeSupport(this); public void addPropertyChangeListener(PropertyChangeListener listener) { pcs.addPropertyChangeListener(listener); } public void removePropertyChangeListener(PropertyChangeListener listener) { pcs.removePropertyChangeListener(listener); } public static MasterDevice newDevice(MasterDeviceConfig config) { //OutstationDevice monitor = new OutstationDevice(config.getName(), config.build()); MasterDevice masterDevice = new MasterDevice(config.getName()); config.getMemoryUnits().forEach((VariableUnitConfig pointUnitConfigBuilder) -> { switch (pointUnitConfigBuilder.getType()) { case AnalogInput: pointUnitConfigBuilder.getItems().forEach((Object t) -> { DnpVariable.AnalogInput analogInput = DnpVariable.AnalogInput.valueOf((VariableConfig.AnalogInputConfig) t); masterDevice.getDatabase().getAnalogInputs().getItems().put(analogInput.getIndex(), analogInput); }); break; case AnalogOutput: pointUnitConfigBuilder.getItems().forEach((Object t) -> { DnpVariable.AnalogOutput analogOutput = DnpVariable.AnalogOutput.valueOf((VariableConfig.AnalogOutputConfig) t); masterDevice.getDatabase().getAnalogOutputs().getItems().put(analogOutput.getIndex(), analogOutput); }); break; case Counter: pointUnitConfigBuilder.getItems().forEach((Object t) -> { DnpVariable.Counter counter = DnpVariable.Counter.valueOf((VariableConfig.CounterConfig) t); masterDevice.getDatabase().getCounters().getItems().put(counter.getIndex(), counter); }); break; case DigitalInput: pointUnitConfigBuilder.getItems().forEach((Object t) -> { DnpVariable.DigitalInput digitalInput = DnpVariable.DigitalInput.valueOf((VariableConfig.DigitalInputConfig) t); masterDevice.getDatabase().getDigitalInputs().getItems().put(digitalInput.getIndex(), digitalInput); }); break; case DigitalOutput: pointUnitConfigBuilder.getItems().forEach((Object t) -> { DnpVariable.DigitalOutput digitalOutput = DnpVariable.DigitalOutput.valueOf((VariableConfig.DigitalOutputConfig) t); masterDevice.getDatabase().getDigitalOutputs().getItems().put(digitalOutput.getIndex(), digitalOutput); }); break; case DoubleDigital: pointUnitConfigBuilder.getItems().forEach((Object t) -> { DnpVariable.DoubleDigital doubleDigital = DnpVariable.DoubleDigital.valueOf((VariableConfig.DoubleDigitalConfig) t); masterDevice.getDatabase().getDoubleDigitals().getItems().put(doubleDigital.getIndex(), doubleDigital); }); break; case FrozenCounter: pointUnitConfigBuilder.getItems().forEach((Object t) -> { DnpVariable.FrozenCounter frozenCounter = DnpVariable.FrozenCounter.valueOf((VariableConfig.FrozenCounterConfig) t); masterDevice.getDatabase().getFrozenCounters().getItems().put(frozenCounter.getIndex(), frozenCounter); }); break; } }); return masterDevice; } @Override public void beginFragment(ResponseInfo info) { } @Override public void endFragment(ResponseInfo info) { } }Cocoduf/json-schema-constraint-validator package com.cocoduf.jscv; import com.google.gson.*; import org.junit.Assert; import org.junit.Test; import java.io.*; import java.net.URL; import java.util.AbstractMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * Created by cocoduf on 17-05-11. */ public class TestLab { /* private File getFileResource(String fileName) throws FileNotFoundException { URL fileUrl = getClass().getClassLoader().getResource(fileName); if (fileUrl != null) { return new File(fileUrl.getFile()); } else { throw new FileNotFoundException("Resource "+fileName+" not found."); } } private JsonObject getJsonObjectFromFile(File file) throws FileNotFoundException, JsonParseException { InputStream inputStream = new FileInputStream(file); Reader reader = new InputStreamReader(inputStream); JsonParser parser = new JsonParser(); return parser.parse(reader).getAsJsonObject(); } private void handleException(Exception e) { System.out.println(e); } @Test public void testJsonSchemaValidator() { try { File schemaFile = getFileResource("invalid.json"); File jsonFile = getFileResource("data.json"); Assert.assertEquals(true, ValidationUtils.isJsonValid(schemaFile, jsonFile)); } catch (Exception e) { handleException(e); Assert.fail(); } } @Test public void testLoadJsonResources() { try { File dataFile = getFileResource("data.json"); JsonObject dataRootObject = getJsonObjectFromFile(dataFile); File constraintsFile = getFileResource("invalid.json"); JsonObject constraintsRootObject = getJsonObjectFromFile(constraintsFile); } catch (Exception e) { handleException(e); Assert.fail(); } } @Test public void testGetNullJsonResource() { try { File dataFile = getFileResource("null.json"); Assert.fail(); } catch (Exception e) { handleException(e); } } @Test public void testLoopOverDataEntrySet() { try { File dataFile = getFileResource("data.json"); JsonObject dataRootObject = getJsonObjectFromFile(dataFile); Set> entrySet = dataRootObject.entrySet(); for (Map.Entry entry : entrySet) { Assert.assertNotEquals(entry.getValue(), null); } } catch (Exception e) { handleException(e); Assert.fail(); } } private Set> getJsonObjects(JsonObject e) { Set> rawEntrySet = e.entrySet(); Set> jsonObjectsEntrySet = new HashSet<>(); for (Map.Entry entry : rawEntrySet) { if (entry.getValue().isJsonObject()) { jsonObjectsEntrySet.add(new AbstractMap.SimpleEntry<>(entry.getKey(), (JsonObject) entry.getValue())); } } return jsonObjectsEntrySet; } private void recursive(JsonObject o) { if (o.has("properties")) { JsonObject properties = o.get("properties").getAsJsonObject(); Set> entrySet = getJsonObjects(properties); for (Map.Entry entry : entrySet) { JsonObject prop = entry.getValue(); System.out.println(entry.getKey()); if (prop.has("constraints")) { System.out.println(prop.get("constraints").getAsJsonArray().toString()); } recursive(prop); } } } @Test public void testGatherConstraints() { try { File constraintsFile = getFileResource("invalid.json"); JsonObject cons_rootObject = getJsonObjectFromFile(constraintsFile); recursive(cons_rootObject); } catch (Exception e) { handleException(e); Assert.fail(); } } */ } package secretwriting; /** * A class for all SecretWriting objects that conceal the message instead of scrambling it. * @author VSpoe * */ public class Steganogram extends SecretWriting { } /** * {@link org.simpleflatmapper.jdbc.JdbcMapper} related classes. */ package org.simpleflatmapper.jdbc.impl;package net.daergoth.homewire; import com.vaadin.annotations.Theme; import com.vaadin.navigator.View; import com.vaadin.navigator.ViewDisplay; import com.vaadin.server.VaadinRequest; import com.vaadin.spring.annotation.SpringUI; import com.vaadin.spring.annotation.SpringViewDisplay; import com.vaadin.ui.Component; import com.vaadin.ui.UI; import com.vaadin.ui.VerticalLayout; import net.daergoth.homewire.controlpanel.ControlPanelView; import net.daergoth.homewire.flow.FlowView; import net.daergoth.homewire.home.HomeView; import net.daergoth.homewire.setup.SetupView; import net.daergoth.homewire.statistic.StatisticView; import org.vaadin.teemusa.sidemenu.SideMenu; import org.vaadin.teemusa.sidemenu.SideMenuUI; @Theme("homewire") @SpringUI @SideMenuUI @SpringViewDisplay public class BaseUI extends UI implements ViewDisplay { private VerticalLayout springViewDisplay; @Override protected void init(VaadinRequest request) { SideMenu menu = new SideMenu(); menu.setMenuCaption("HomeWire"); menu.addMenuItem("Home", () -> { getUI().getNavigator().navigateTo(HomeView.VIEW_NAME); }); menu.addMenuItem("Control Panel", () -> { getUI().getNavigator().navigateTo(ControlPanelView.VIEW_NAME); }); menu.addMenuItem("Flows", () -> { getUI().getNavigator().navigateTo(FlowView.VIEW_NAME); }); menu.addMenuItem("Statistics", () -> { getUI().getNavigator().navigateTo(StatisticView.VIEW_NAME); }); menu.addMenuItem("Setup", () -> { getUI().getNavigator().navigateTo(SetupView.VIEW_NAME); }); setContent(menu); springViewDisplay = new VerticalLayout(); springViewDisplay.setSizeFull(); springViewDisplay.setMargin(true); springViewDisplay.setSpacing(true); menu.setContent(springViewDisplay); } @Override public void showView(View view) { springViewDisplay.removeAllComponents(); springViewDisplay.addComponent((Component) view); } }/* * $RCSfile: ComponentSampleModelJAI.java,v $ * * Copyright (c) 2005 Sun Microsystems, Inc. All rights reserved. * * Use is subject to license terms. * * $Revision: 1.1 $ * $Date: 2005/02/11 04:57:07 $ * $State: Exp $ */ package com.lightcrafts.media.jai.codecimpl.util; import java.awt.image.ComponentSampleModel; import java.awt.image.DataBuffer; import java.awt.image.DataBufferByte; import java.awt.image.DataBufferShort; import java.awt.image.DataBufferInt; import java.awt.image.DataBufferUShort; import java.awt.image.SampleModel; /** * This class represents image data which is stored such that each sample * of a pixel occupies one data element of the DataBuffer. It stores the * N samples which make up a pixel in N separate data array elements. * Different bands may be in different banks of the DataBuffer. * Accessor methods are provided so that image data can be manipulated * directly. This class can support different kinds of interleaving, e.g. * band interleaving, scanline interleaving, and pixel interleaving. * Pixel stride is the number of data array elements between two samples * for the same band on the same scanline. Scanline stride is the number * of data array elements between a given sample and the corresponding sample * in the same column of the next scanline. Band offsets denote the number * of data array elements from the first data array element of the bank * of the DataBuffer holding each band to the first sample of the band. * The bands are numbered from 0 to N-1. This class can represent image * data for the dataTypes enumerated in java.awt.image.DataBuffer (all * samples of a given ComponentSampleModel are stored with the same precision) * . This class adds support for Double and Float data types in addition * to those supported by the ComponentSampleModel class in Java 2D. * All strides and offsets must be non-negative. * @see java.awt.image.ComponentSampleModel */ public class ComponentSampleModelJAI extends ComponentSampleModel { /** * Constructs a ComponentSampleModel with the specified * parameters. The number of bands will be given by the length of * the bandOffsets array. All bands will be stored in the first * bank of the DataBuffer. * * @param dataType The data type for storing samples. * @param w The width (in pixels) of the region of * image data described. * @param h The height (in pixels) of the region of * image data described. * @param pixelStride The pixel stride of the region of image * data described. * @param scanlineStride The line stride of the region of image * data described. * @param bandOffsets The offsets of all bands. */ public ComponentSampleModelJAI(int dataType, int w, int h, int pixelStride, int scanlineStride, int bandOffsets[]) { super(dataType, w, h, pixelStride, scanlineStride, bandOffsets); } /** * Constructs a ComponentSampleModel with the specified * parameters. The number of bands will be given by the length of * the bandOffsets array. Different bands may be stored in * different banks of the DataBuffer. * * @param dataType The data type for storing samples. * @param w The width (in pixels) of the region of * image data described. * @param h The height (in pixels) of the region of * image data described. * @param pixelStride The pixel stride of the region of image * data described. * @param scanlineStride The line stride of the region of image * data described. * @param bankIndices The bank indices of all bands. * @param bandOffsets The band offsets of all bands. */ public ComponentSampleModelJAI(int dataType, int w, int h, int pixelStride, int scanlineStride, int bankIndices[], int bandOffsets[]) { super(dataType, w, h, pixelStride, scanlineStride, bankIndices, bandOffsets); } /** * Returns the size of the data buffer (in data elements) needed * for a data buffer that matches this ComponentSampleModel. */ private long getBufferSize() { int maxBandOff=bandOffsets[0]; for (int i=1; i= 0) size += maxBandOff+1; if (pixelStride > 0) size += pixelStride * (width-1); if (scanlineStride > 0) size += scanlineStride*(height-1); return size; } /** * Preserves band ordering with new step factor... */ private int[] JAIorderBands(int orig[], int step) { int map[] = new int[orig.length]; int ret[] = new int[orig.length]; for (int i=0; i orig[map[j]]) { index = j; } } ret[map[index]] = i*step; map[index] = map[i]; } return ret; } /** * Creates a new ComponentSampleModel with the specified * width and height. The new SampleModel will have the same * number of bands, storage data type, interleaving scheme, and * pixel stride as this SampleModel. * * @param w The width in pixels. * @param h The height in pixels */ public SampleModel createCompatibleSampleModel(int w, int h) { SampleModel ret=null; long size; int minBandOff=bandOffsets[0]; int maxBandOff=bandOffsets[0]; for (int i=1; i lStride) { if (pStride > bStride) { if (lStride > bStride) { // pix > line > band bandOff = new int[bandOffsets.length]; for (int i=0; i band > line bandOff = JAIorderBands(bandOffsets,lStride*h); pStride = bands*lStride*h; } } else { // band > pix > line pStride = lStride*h; bandOff = JAIorderBands(bandOffsets,pStride*w); } } else { if (pStride > bStride) { // line > pix > band bandOff = new int[bandOffsets.length]; for (int i=0; i bStride) { // line > band > pix bandOff = JAIorderBands(bandOffsets,pStride*w); lStride = bands*pStride*w; } else { // band > line > pix lStride = pStride*w; bandOff = JAIorderBands(bandOffsets,lStride*h); } } } // make sure we make room for negative offsets... int base = 0; if (scanlineStride < 0) { base += lStride*h; lStride *= -1; } if (pixelStride < 0) { base += pStride*w; pStride *= -1; } for (int i=0; iComponentSampleModel with a subset of the bands * of this ComponentSampleModel. The new ComponentSampleModel can be * used with any DataBuffer that the existing ComponentSampleModel * can be used with. The new ComponentSampleModel/DataBuffer * combination will represent an image with a subset of the bands * of the original ComponentSampleModel/DataBuffer combination. * * @param bands subset of bands of this ComponentSampleModel */ public SampleModel createSubsetSampleModel(int bands[]) { int newBankIndices[] = new int[bands.length]; int newBandOffsets[] = new int[bands.length]; for (int i=0; iDataBuffer that corresponds to this ComponentSampleModel. * The DataBuffer's data type, number of banks, and size * will be consistent with this ComponentSampleModel. */ public DataBuffer createDataBuffer() { DataBuffer dataBuffer = null; int size = (int)getBufferSize(); switch (dataType) { case DataBuffer.TYPE_BYTE: dataBuffer = new DataBufferByte(size, numBanks); break; case DataBuffer.TYPE_USHORT: dataBuffer = new DataBufferUShort(size, numBanks); break; case DataBuffer.TYPE_INT: dataBuffer = new DataBufferInt(size, numBanks); break; case DataBuffer.TYPE_SHORT: dataBuffer = new DataBufferShort(size, numBanks); break; case DataBuffer.TYPE_FLOAT: dataBuffer = DataBufferUtils.createDataBufferFloat(size, numBanks); break; case DataBuffer.TYPE_DOUBLE: dataBuffer = DataBufferUtils.createDataBufferDouble(size, numBanks); break; default: throw new RuntimeException(JaiI18N.getString("RasterFactory3")); } return dataBuffer; } /** * Returns data for a single pixel in a primitive array of type * TransferType. For a ComponentSampleModel, this will be the same * as the data type, and samples will be returned one per array * element. Generally, obj * should be passed in as null, so that the Object will be created * automatically and will be of the right primitive data type. *

* The following code illustrates transferring data for one pixel from * DataBuffer db1, whose storage layout is described by * ComponentSampleModel csm1, to DataBuffer db2, * whose storage layout is described by * ComponentSampleModel csm2. * The transfer will generally be more efficient than using * getPixel/setPixel. *

     * 	     ComponentSampleModel csm1, csm2;
     *	     DataBufferInt db1, db2;
     * 	     csm2.setDataElements(x, y,
     *                            csm1.getDataElements(x, y, null, db1), db2);
     * 
* Using getDataElements/setDataElements to transfer between two * DataBuffer/SampleModel pairs is legitimate if the SampleModels have * the same number of bands, corresponding bands have the same number of * bits per sample, and the TransferTypes are the same. *

* @param x The X coordinate of the pixel location. * @param y The Y coordinate of the pixel location. * @param obj If non-null, a primitive array in which to return * the pixel data. * @param data The DataBuffer containing the image data. * @throws ClassCastException if obj is non-null and is not * a primitive array of type TransferType. * @throws ArrayIndexOutOfBoundsException if the coordinates * are not in bounds, or if obj is non-null and is not large * enough to hold the pixel data. */ public Object getDataElements(int x, int y, Object obj, DataBuffer data) { int type = getTransferType(); int numDataElems = getNumDataElements(); int pixelOffset = y*scanlineStride + x*pixelStride; switch(type) { case DataBuffer.TYPE_BYTE: byte[] bdata; if (obj == null) bdata = new byte[numDataElems]; else bdata = (byte[])obj; for (int i=0; iObject will be created automatically and will be of the right * primitive data type. *

* The following code illustrates transferring data for a rectangular * region of pixels from * DataBuffer db1, whose storage layout is described by * SampleModel sm1, to DataBuffer db2, whose * storage layout is described by SampleModel sm2. * The transfer will generally be more efficient than using * getPixels/setPixels. *

     *       SampleModel sm1, sm2;
     *       DataBuffer db1, db2;
     *       sm2.setDataElements(x, y, w, h, sm1.getDataElements(x, y, w,
     *                           h, null, db1), db2);
     * 
* Using getDataElements/setDataElements to transfer between two * DataBuffer/SampleModel pairs is legitimate if the SampleModels have * the same number of bands, corresponding bands have the same number of * bits per sample, and the TransferTypes are the same. *

* @param x The minimum X coordinate of the pixel rectangle. * @param y The minimum Y coordinate of the pixel rectangle. * @param w The width of the pixel rectangle. * @param h The height of the pixel rectangle. * @param obj If non-null, a primitive array in which to return * the pixel data. * @param data The DataBuffer containing the image data. * @see #getNumDataElements * @see #getTransferType * @see java.awt.image.DataBuffer * @throws ClassCastException if obj is non-null and is not * a primitive array of type TransferType. * @throws ArrayIndexOutOfBoundsException if the coordinates * are not in bounds, or if obj is non-null and is not large * enough to hold the pixel data. */ public Object getDataElements(int x, int y, int w, int h, Object obj, DataBuffer data) { int type = getTransferType(); int numDataElems = getNumDataElements(); int cnt = 0; Object o = null; switch(type) { case DataBuffer.TYPE_BYTE: { byte[] btemp; byte[] bdata; if (obj == null) bdata = new byte[numDataElems*w*h]; else bdata = (byte[])obj; for (int i=y; iDataBuffer from a * primitive array of type TransferType. For a ComponentSampleModel, * this will be the same as the data type, and samples are transferred * one per array element. *

* The following code illustrates transferring data for one pixel from * DataBuffer db1, whose storage layout is described by * ComponentSampleModel csm1, to DataBuffer db2, * whose storage layout is described by * ComponentSampleModel csm2. * The transfer will generally be more efficient than using * getPixel/setPixel. *

     * 	     ComponentSampleModel csm1, csm2;
     *	     DataBufferInt db1, db2;
     * 	     csm2.setDataElements(x, y, csm1.getDataElements(x, y, null, db1),
     *                            db2);
     * 
* Using getDataElements/setDataElements to transfer between two * DataBuffer/SampleModel pairs is legitimate if the SampleModels have * the same number of bands, corresponding bands have the same number of * bits per sample, and the TransferTypes are the same. *

* @param x The X coordinate of the pixel location. * @param y The Y coordinate of the pixel location. * @param obj A primitive array containing pixel data. * @param data The DataBuffer containing the image data. * @throws ClassCastException if obj is non-null and is not * a primitive array of type TransferType. * @throws ArrayIndexOutOfBoundsException if the coordinates * are not in bounds, or if obj is non-null and is not large * enough to hold the pixel data. */ public void setDataElements(int x, int y, Object obj, DataBuffer data) { int type = getTransferType(); int numDataElems = getNumDataElements(); int pixelOffset = y*scanlineStride + x*pixelStride; switch(type) { case DataBuffer.TYPE_BYTE: byte[] barray = (byte[])obj; for (int i=0; iDataBuffer * from a primitive array of type TransferType. For image data supported * by the Java 2D API, this will be one of the dataTypes supported by * java.awt.image.DataBuffer. Data in the array may be in a packed * format, thus increasing efficiency for data transfers. *

* The following code illustrates transferring data for a rectangular * region of pixels from * DataBuffer db1, whose storage layout is described by * SampleModel sm1, to DataBuffer db2, whose * storage layout is described by SampleModel sm2. * The transfer will generally be more efficient than using * getPixels/setPixels. *

     *       SampleModel sm1, sm2;
     *       DataBuffer db1, db2;
     *       sm2.setDataElements(x, y, w, h, sm1.getDataElements(x, y, w, h,
     *                           null, db1), db2);
     * 
* Using getDataElements/setDataElements to transfer between two * DataBuffer/SampleModel pairs is legitimate if the SampleModels have * the same number of bands, corresponding bands have the same number of * bits per sample, and the TransferTypes are the same. *

* @param x The minimum X coordinate of the pixel rectangle. * @param y The minimum Y coordinate of the pixel rectangle. * @param w The width of the pixel rectangle. * @param h The height of the pixel rectangle. * @param obj A primitive array containing pixel data. * @param data The DataBuffer containing the image data. * @throws ClassCastException if obj is non-null and is not * a primitive array of type TransferType. * @throws ArrayIndexOutOfBoundsException if the coordinates * are not in bounds, or if obj is non-null and is not large * enough to hold the pixel data. * @see #getNumDataElements * @see #getTransferType * @see java.awt.image.DataBuffer */ public void setDataElements(int x, int y, int w, int h, Object obj, DataBuffer data) { int cnt = 0; Object o = null; int type = getTransferType(); int numDataElems = getNumDataElements(); switch(type) { case DataBuffer.TYPE_BYTE: { byte[] barray = (byte[])obj; byte[] btemp = new byte[numDataElems]; for (int i=y; iDataBuffer using a float for input. * ArrayIndexOutOfBoundsException may be thrown if the coordinates are * not in bounds. * @param x The X coordinate of the pixel location. * @param y The Y coordinate of the pixel location. * @param b The band to set. * @param s The input sample as a float. * @param data The DataBuffer containing the image data. * * @throws ArrayIndexOutOfBoundsException if coordinates are not in bounds */ public void setSample(int x, int y, int b, float s, DataBuffer data) { data.setElemFloat(bankIndices[b], y*scanlineStride + x*pixelStride + bandOffsets[b], s); } /** * Returns the sample in a specified band * for the pixel located at (x,y) as a float. * ArrayIndexOutOfBoundsException may be thrown if the coordinates are * not in bounds. * @param x The X coordinate of the pixel location. * @param y The Y coordinate of the pixel location. * @param b The band to return. * @param data The DataBuffer containing the image data. * @return sample The floating point sample value * @throws ArrayIndexOutOfBoundsException if coordinates are not in bounds */ public float getSampleFloat(int x, int y, int b, DataBuffer data) { float sample = data.getElemFloat(bankIndices[b], y*scanlineStride + x*pixelStride + bandOffsets[b]); return sample; } /** * Sets a sample in the specified band for the pixel located at (x,y) * in the DataBuffer using a double for input. * ArrayIndexOutOfBoundsException may be thrown if the coordinates are * not in bounds. * @param x The X coordinate of the pixel location. * @param y The Y coordinate of the pixel location. * @param b The band to set. * @param s The input sample as a double. * @param data The DataBuffer containing the image data. * * @throws ArrayIndexOutOfBoundsException if coordinates are not in bounds */ public void setSample(int x, int y, int b, double s, DataBuffer data) { data.setElemDouble(bankIndices[b], y*scanlineStride + x*pixelStride + bandOffsets[b], s); } /** * Returns the sample in a specified band * for a pixel located at (x,y) as a double. * ArrayIndexOutOfBoundsException may be thrown if the coordinates are * not in bounds. * @param x The X coordinate of the pixel location. * @param y The Y coordinate of the pixel location. * @param b The band to return. * @param data The DataBuffer containing the image data. * @return sample The double sample value * @throws ArrayIndexOutOfBoundsException if coordinates are not in bounds */ public double getSampleDouble(int x, int y, int b, DataBuffer data) { double sample = data.getElemDouble(bankIndices[b], y*scanlineStride + x*pixelStride + bandOffsets[b]); return sample; } /** * Returns all samples for a rectangle of pixels in a double * array, one sample per array element. * ArrayIndexOutOfBoundsException may be thrown if the coordinates are * not in bounds. * @param x The X coordinate of the upper left pixel location. * @param y The Y coordinate of the upper left pixel location. * @param w The width of the pixel rectangle. * @param h The height of the pixel rectangle. * @param dArray If non-null, returns the samples in this array. * @param data The DataBuffer containing the image data. * @throws ArrayIndexOutOfBoundsException if coordinates are not in bounds */ public double[] getPixels(int x, int y, int w, int h, double dArray[], DataBuffer data) { double pixels[]; int Offset = 0; if (dArray != null) pixels = dArray; else pixels = new double[numBands * w * h]; for (int i=y; i<(h+y); i++) { for (int j=x; j<(w+x); j++) { for (int k=0; kString containing the values of all valid fields. */ public String toString() { String ret = "ComponentSampleModelJAI: " + " dataType=" + this.getDataType() + " numBands=" + this.getNumBands() + " width=" +this.getWidth() + " height=" +this.getHeight() + " bandOffsets=[ "; for (int i = 0; i < numBands; i++) { ret += this.getBandOffsets()[i] + " "; } ret += "]"; return ret; } } TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Util/PlaySound.java package org.firstinspires.ftc.teamcode.Util; import android.media.MediaPlayer; import com.qualcomm.robotcore.hardware.HardwareMap; import org.firstinspires.ftc.teamcode.R; public class PlaySound { private MediaPlayer mp; public PlaySound(HardwareMap hardwareMap, int soundId){ mp = MediaPlayer.create(hardwareMap.appContext, soundId); mp.setOnCompletionListener(MediaPlayer::release); } public void play(){ try { mp.start(); }catch (Exception e){ e.printStackTrace(); } } public void pause(){ try { mp.pause(); } catch (Exception e){ e.printStackTrace(); } } /** * Stop and release all the resources taken up by the media player */ public void stop(){ try { mp.stop(); mp.release(); } catch (Exception e){ e.printStackTrace(); } } } app/helper/Couchbase.java package helper; import com.couchbase.client.java.Bucket; import com.couchbase.client.java.Cluster; import com.couchbase.client.java.CouchbaseCluster; import com.couchbase.client.java.auth.Authenticator; import com.couchbase.client.java.auth.PasswordAuthenticator; import com.couchbase.client.java.document.JsonDocument; import com.couchbase.client.java.document.json.JsonObject; import com.couchbase.client.java.env.CouchbaseEnvironment; import com.couchbase.client.java.env.DefaultCouchbaseEnvironment; import com.couchbase.client.java.error.DocumentDoesNotExistException; import com.typesafe.config.Config; import play.Logger; import play.inject.ApplicationLifecycle; import javax.inject.Inject; import java.io.IOException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; public class Couchbase { private Cluster cluster; private static Bucket bucket; private static Config config; private static int TIMEOUT_CACHE_DOC = 200; public static final String CB_HOST = "127.0.0.1:8091"; public static final String CB_USERNAME="Administrator"; public static final String CB_PWD=""; public static final String DPS_BUCKET="dps"; @Inject public Couchbase(ApplicationLifecycle appLifecycle, Config config) { this.config = config; Logger.info("inside instance"); connect(); appLifecycle.addStopHook(() -> { Logger.info("Application stopped"); disconnect(); return CompletableFuture.completedFuture(null); }); } public Couchbase(){ connect(); } private Authenticator getCBAuthenticator() { PasswordAuthenticator auth = new PasswordAuthenticator(CB_USERNAME, CB_PWD); return auth; } public boolean connect() { connectToCluster(); connectToBucket(); return true; } private boolean connectToCluster() { if (cluster == null) { synchronized (Couchbase.class) { if (cluster == null) { CouchbaseEnvironment env = DefaultCouchbaseEnvironment.builder() .connectTimeout(30000) //10000ms = 10s, default is 5s .build(); cluster = CouchbaseCluster.create(env, CB_HOST); //Comment this for CB4. cluster.authenticate(getCBAuthenticator()); Logger.info("Initialized couchbase cluster."); return true; } } } return true; } private boolean connectToBucket() { this.bucket = cluster.openBucket(DPS_BUCKET); return true; } public boolean disconnect() { disconnectBucket(); disconnectCluster(); return true; } private boolean disconnectCluster() { return cluster.disconnect(5, TimeUnit.SECONDS); } private boolean disconnectBucket() { return this.bucket.close(5, TimeUnit.SECONDS) ; } public static JsonDocument get(String key) { Logger.debug("GET CB Key : " + key); JsonDocument obj = bucket.get(key); if (obj == null) { Logger.debug("Could not find the key"); //throw new DocumentDoesNotExistException("Could not find the key"); return null; } Logger.debug("Getting Key value : " + obj.content().toString()); return obj; } public static boolean exists(String key) { return bucket.exists(key); } public static boolean update(String key, String val) { Logger.debug("Setting Key "+key + " value " + val); try { JsonDocument result = bucket.upsert(toJsonDocument(key, val)); Logger.debug("Done setting : " + result); return true; }catch(Exception e){ Logger.error("Could not save the object " + e.getMessage()); return false; } } public static boolean delete(String key) { try { Logger.debug("Deleting Key : " + key); bucket.remove(key); JsonDocument jsonDocument = bucket.get(key); if (jsonDocument == null) { Logger.debug("Deleting Key Done : " + key); return true; } else { Logger.debug("Deleting Key Done not possible : " + key); return false; } }catch (DocumentDoesNotExistException e){ Logger.debug("Could not find key for delete :" + key); return false; } } //private methods private static JsonDocument toJsonDocument(String key, String val) throws IOException { return JsonDocument.create(key, JsonObject.fromJson(val)); } } package LeetCode; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; /** * @description: * @author: Desmand * @time: 2020/11/20 8:54 上午 */ public class LC3_2 { public static int lengthOfLongestSubstring(String s) { if (s.equals("") || s == null) return 0; if(s.length()==1)return 1; Set set = new HashSet<>(); set.add(s.charAt(0)); int left = 0, right = 0; int ans = 0; for (int i = 0; i < s.length(); i++) { while (right + 1 < s.length() && !set.contains(s.charAt(right + 1))) { set.add(s.charAt(++right)); } ans = Math.max(right - i + 1, ans); set.remove(s.charAt(i)); } return ans; } public static void main(String[] args) { System.out.println(lengthOfLongestSubstring("pwwkew")); } } package org.evomaster.dbconstraint; import java.util.Objects; /** * Represents the constraint table.column <= value */ public class UpperBoundConstraint extends TableConstraint { private final /*non-null*/ String columnName; private final long upperBound; public UpperBoundConstraint(String tableName, String columnName, long upperBound) { super(tableName); this.columnName = Objects.requireNonNull(columnName); this.upperBound = upperBound; } public String getColumnName() { return this.columnName; } public long getUpperBound() { return this.upperBound; } @Override public K accept(TableConstraintVisitor visitor, V argument) { return visitor.visit(this, argument); } } package com.adcolony.sdk; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import p017io.fabric.sdk.android.services.common.CommonUtils; /* renamed from: com.adcolony.sdk.n0 */ class C0765n0 { C0765n0() { } /* renamed from: a */ public static String m712a(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest instance = MessageDigest.getInstance(CommonUtils.SHA1_INSTANCE); instance.update(str.getBytes("iso-8859-1"), 0, str.length()); return m713a(instance.digest()); } /* renamed from: a */ private static String m713a(byte[] bArr) { StringBuilder sb = new StringBuilder(); for (byte b : bArr) { byte b2 = (b >>> 4) & 15; int i = 0; while (true) { sb.append((char) ((b2 < 0 || b2 > 9) ? (b2 - 10) + 97 : b2 + 48)); b2 = b & 15; int i2 = i + 1; if (i >= 1) { break; } i = i2; } } return sb.toString(); } } package org.montrealjug.meetups.model; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import java.time.Instant; import java.util.Objects; @JsonDeserialize(using = EventDeserializer.class) public class Event{ Instant instant; String name; String venueName; public Event() { } public Event(Instant instant, String name, String venueName) { this.instant = instant; this.name = name; this.venueName = venueName; } public Instant getInstant() { return instant; } public void setInstant(Instant instant) { this.instant = instant; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getVenueName() { return venueName; } public void setVenueName(String venueName) { this.venueName = venueName; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Event event = (Event) o; return Objects.equals(instant, event.instant) && Objects.equals(name, event.name) && Objects.equals(venueName, event.venueName); } @Override public int hashCode() { return Objects.hash(instant, name, venueName); } @Override public String toString() { return "Event{" + "instant=" + instant + ", name='" + name + '\'' + ", venueName='" + venueName + '\'' + '}'; } } /** * Copyright (c) 2018 Open Source Project * * 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 io.synoshy.zstu.presentation.menu; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.support.annotation.NonNull; import android.view.View; import com.annimon.stream.function.Function; public class MenuItem implements View.OnClickListener { public final String Name; private Function onClickHandler; private Drawable background; private String text; private int size; private int textColor; private final int DEFAULT_TEXT_COLOR = Color.WHITE; public MenuItem(@NonNull String name) { this.Name = name; } public Drawable getBackground() { return background; } public void setBackground(Drawable background) { this.background = background; } public String getText() { return text; } public void setText(String text) { this.text = text; } public int getSize() { return size; } public void setSize(int size) { this.size = size; } public int getSpacing() { return size / 6; } public int getTextColor() { return textColor == 0 ? DEFAULT_TEXT_COLOR : textColor; } public void setTextColor(int textColor) { this.textColor = textColor; } @Override public void onClick(View view) { if (onClickHandler != null) onClickHandler.apply(view); } public void setOnClickHandler(@NonNull Function onClickHandler) { this.onClickHandler = onClickHandler; } } /* * 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.metadata; import android.content.Context; import android.text.TextUtils; import com.google.android.apps.forscience.whistlepunk.R; import com.google.common.annotations.VisibleForTesting; /** * An Experiment is a grouping of data sources and labels. */ public class Experiment { private long mId; private String mExperimentId; private long mTimestamp; private String mTitle; private String mDescription; private boolean mArchived; private String mProjectId; private long mLastUsedTime; // TODO(justinkoh): add datasources when they get defined. @VisibleForTesting public Experiment(long id) { mId = id; mTimestamp = System.currentTimeMillis(); } /* package*/ long getId() { return mId; } @VisibleForTesting public void setExperimentId(String experimentId) { mExperimentId = experimentId; } @VisibleForTesting public void setTimestamp(long timestamp) { mTimestamp = timestamp; } public void setArchived(boolean archived) { this.mArchived = archived; } public void setTitle(String title) { this.mTitle = title; } public void setDescription(String description) { this.mDescription = description; } public void setProjectId(String projectId) { this.mProjectId = projectId; } public String getExperimentId() { return mExperimentId; } public long getTimestamp() { return mTimestamp; } public String getTitle() { return mTitle; } public String getDisplayTitle(Context context) { return !TextUtils.isEmpty(mTitle) ? mTitle : context.getString( R.string.default_experiment_name); } public String getDescription() { return mDescription; } public boolean isArchived() { return mArchived; } public String getProjectId() { return mProjectId; } public void setLastUsedTime(long lastUsedTime) { mLastUsedTime = lastUsedTime; } public long getLastUsedTime() { return mLastUsedTime; } // For testing purposes only @Override public String toString() { return "Experiment{" + "mId=" + mId + ", mTitle='" + mTitle + '\'' + '}'; } public static String getExperimentId(Experiment experiment) { return experiment == null ? null : experiment.getExperimentId(); } } package io.github.romangraef.jdacommandinterface.core.util; import io.github.romangraef.jdacommandinterface.core.Context; import io.github.romangraef.jdacommandinterface.core.ConversionException; import io.github.romangraef.jdacommandinterface.core.NoConverterFoundException; import io.github.romangraef.jdacommandinterface.core.NotEnoughArgumentsException; import io.github.romangraef.jdacommandinterface.core.converters.Converters; import java.lang.reflect.Array; import java.lang.reflect.Method; import java.lang.reflect.Parameter; public class ArgumentUtil { /** * For internal use. Converts a string list into a list of objects according to a method definition. * * if varargs is set to true the last element of the result will be an array of those converted varargs * * @param context the context of the command as passed to the {@link Converters} * @param args the arguments to convert * @param argCount the argument count of the method definition excluding {@link Context} and varargs * @param isVarArgs whether the method has varargs. * @param method the method definition to use * * @return the arguments converted to objects. * @throws NoConverterFoundException if the method asks for an object without a registered converter * @throws ConversionException this is reraised from the converters and indicated some kind of user error * @throws NotEnoughArgumentsException if the provided arguments aren't enough to fulfill the needs of the method. */ public static Object[] getArguments(Context context, String[] args, int argCount, boolean isVarArgs, Method method) throws NoConverterFoundException, ConversionException, NotEnoughArgumentsException { Object[] finalArgs = new Object[argCount + 1 + (isVarArgs ? 1 : 0)]; finalArgs[0] = context; Object[] normalArgs = getConvertedNormalArgs(args, argCount, method, context); System.arraycopy(normalArgs, 0, finalArgs, 1, normalArgs.length); if (isVarArgs) { Parameter p = null; for (Parameter pa : method.getParameters()) { if (pa.isVarArgs()) { p = pa; break; } } Class clazz = p.getType().getComponentType(); Object[] varArgs = (Object[]) Array.newInstance(clazz, args.length - argCount); for (int i = argCount, j = 0; j < args.length - argCount; i++, j++) { varArgs[j] = Converters.convert(clazz, context, args[i]); } finalArgs[argCount + 1] = varArgs; } return finalArgs; } private static Object[] getConvertedNormalArgs(String[] args, int argCount, Method method, Context context) throws NoConverterFoundException, ConversionException, NotEnoughArgumentsException { Object[] converted = new Object[argCount]; Parameter[] parameters = method.getParameters(); for (int i = 1; i < parameters.length; i++) { Parameter p = parameters[i]; if (p.isVarArgs()) continue; try { converted[i - 1] = Converters.convert(p.getType(), context, args[i - 1]); } catch (ArrayIndexOutOfBoundsException e) { throw new NotEnoughArgumentsException(e); } } return converted; } } package varadraj.product.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import varadraj.common.model.JsonResponse; import varadraj.common.model.ResponseMessage; import varadraj.product.model.ProductCreationRequest; import varadraj.product.service.ProductService; @RestController @CrossOrigin @PreAuthorize(value = "hasRole('ADMIN')") @RequestMapping("/auth/admin/product/products") public class ProductAdminProducts { @Autowired private ProductService productService; @PostMapping("/add") public JsonResponse addProduct(@RequestBody ProductCreationRequest request) { if(!productService.isValidRequest(request)) { return new JsonResponse(400 , ResponseMessage.INVALID_INPUT , null); } productService.addProduct(request); return new JsonResponse(201 , ResponseMessage.CREATED , null); } } 1-10 package io.thinkinglabs; /** * @author @tdpauw */ public class FeatureDecisions { private final Features features; public FeatureDecisions(final Features features) { this.features = features; } public boolean includeOrderCancellationInEmail() { return features.isEnabled("next-gen-ecomm"); } } package Storage; import PageGuest.AccomodationDataResultComposer; import PageGuest.AccomodationData_RESULT; import Util.StringHelper; import org.apache.log4j.Logger; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; /** * Created by Andras on 14/07/2017. */ public class SQLiteAgent_AccomodationData { private static org.apache.log4j.Logger mLogger = Logger.getLogger(SQLiteAgent_AccomodationData.class); private AccomodationData_RESULT mResult; private AccomodationDataResultComposer_SQLite mComposer; private int mBookingComCount = 0; private int mAirbnbComCount = 0; private Connection mConnection = null; private SQLiteAgent mSQLiteAgent; public SQLiteAgent_AccomodationData( Connection connection, SQLiteAgent sqliteAgent ) { mConnection = connection; mSQLiteAgent = sqliteAgent; } private int InsertNewSearch() { mLogger.trace( "begin" ); String lQuery = mComposer.insertNewSearchString(); mLogger.trace( lQuery ); mLogger.trace( "end" ); return mSQLiteAgent.ExecuteStatement( lQuery, Statement.RETURN_GENERATED_KEYS ); } private int GetAccomodationDataResultId( int aSearchId ) { mLogger.trace( "begin" ); String lQuery = mComposer.getAccomodationDataResultRecordIdString( aSearchId ); Statement lStmt = null; mLogger.trace( lQuery ); try { int lID = -1; lStmt = mConnection.createStatement(); ResultSet lResultSet = lStmt.executeQuery( lQuery ); while ( lResultSet.next() ) { lID = lResultSet.getInt("ID"); } lResultSet.close(); lStmt.close(); mLogger.trace( "return" ); return lID; } catch ( Exception e ) { //System.err.println( e.getClass().getName() + ": " + e.getMessage() ); mLogger.error( StringHelper.getTraceInformation( e ) ); System.exit( 0 ); } mLogger.trace( "end" ); return -1; } private int InsertAccomodationDataResult( int aSearchId ) { mLogger.trace( "begin" ); String lQuery = mComposer.insertAccomodationDataResultString( aSearchId ); mLogger.trace( lQuery ); mLogger.trace( "end" ); return mSQLiteAgent.ExecuteStatement( lQuery, Statement.RETURN_GENERATED_KEYS ); } private void InsertAccomodationDataResult_AvailableRooms( int aAccomodationDataResultId, String recordedDatetime ) { mLogger.trace( "begin" ); for( int i = 0; i < mResult.mAvailableRooms.size(); i++ ) { String lQuery = mComposer.insertAccomodationDataResult_AvailableRooms( mResult.mAvailableRooms.get( i ), aAccomodationDataResultId, recordedDatetime ); mLogger.trace( lQuery ); mSQLiteAgent.ExecuteStatement( lQuery ); } mLogger.trace( "end" ); } void WriteData( AccomodationData_RESULT aResult ) { mLogger.trace( "begin" ); mComposer = (AccomodationDataResultComposer_SQLite) AccomodationDataResultComposer.Create( aResult, "sqlite" ); mResult = aResult; int lSearchId = mSQLiteAgent.GetSearchId( mComposer.getSearchRecordIdString()); if( lSearchId == -1 ) { lSearchId = InsertNewSearch(); } if( aResult.mSite == 'B' ) mBookingComCount++; else if( aResult.mSite == 'A' ) mAirbnbComCount++; int lAccomodationDataResultId = GetAccomodationDataResultId( lSearchId ); if( lAccomodationDataResultId == -1 ) { lAccomodationDataResultId = InsertAccomodationDataResult( lSearchId ); } InsertAccomodationDataResult_AvailableRooms( lAccomodationDataResultId, aResult.mRecordedDatetime ); mLogger.trace( "end" ); } public int getBookingDotComAccomodationCount() { return mBookingComCount; } } sandrew1945/bury package com.sandrew.bury; import com.sandrew.bury.callback.POCallBack; import com.sandrew.bury.model.UORelExt; import org.junit.Test; import java.util.List; public class QueryByCustomCallbackTest { @Test public void test() { String configFile = "bury-config.xml"; SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); SqlSessionFactory factory = builder.build(configFile); Session session = factory.openSession(); try { StringBuilder sql = new StringBuilder("select *, 'abc' as `name` from nesc_uo_rel_tab"); List list = session.select(sql.toString(), null, new POCallBack(UORelExt.class)); for (UORelExt uoRelExt : list) { System.out.println(uoRelExt.getName()); System.out.println(uoRelExt.getId()); } } catch (Exception e) { e.printStackTrace(); } finally { session.close(); } } } src/api/java/logisticspipes/api/IRoutedPowerProvider.java package logisticspipes.api; import java.util.List; /** things implementing this interface are capable of providing power, but they draw from another sources * Implement ILogisticsPowerProvider if you wish to provide power to the LP network. * Losses of energy based on distance may be involved. * @author Andrew * */ public interface IRoutedPowerProvider { // typically calls useEnergy(amount,null); boolean useEnergy(int amount); // typically calls canUseEnergy(amount,null); boolean canUseEnergy(int amount); // for the case where 1 IRoutedPowerProvider has to check another // each IRoutedPowerProvider that can recurse should: // a) check that it is not already on the list // b) add itself to the list (creating it if the list is null), boolean useEnergy(int amount, List providersToIgnore); boolean canUseEnergy(int amount, List providersToIgnore); int getX(); // the coordinates of the associated tile (typically "this.xCoords"). needed for sending packets. int getY(); int getZ(); } admin/src/main/java/com/linln/admin/work/service/impl/WorkServiceImpl.java package com.linln.admin.work.service.impl; import com.linln.admin.work.domain.Work; import com.linln.admin.work.repository.WorkRepository; import com.linln.admin.work.service.WorkService; import com.linln.common.data.PageSort; import com.linln.common.enums.StatusEnum; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Example; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * @author 小王子 * @date 2020/01/17 */ @Service public class WorkServiceImpl implements WorkService { @Autowired private WorkRepository workRepository; /** * 根据ID查询数据 * @param id 主键ID */ @Override @Transactional public Work getById(Long id) { return workRepository.findById(id).orElse(null); } /** * 获取分页列表数据 * @param example 查询实例 * @return 返回分页数据 */ @Override public Page getPageList(Example example) { // 创建分页对象 PageRequest page = PageSort.pageRequest(); return workRepository.findAll(example, page); } /** * 保存数据 * @param work 实体对象 */ @Override public Work save(Work work) { return workRepository.save(work); } /** * 状态(启用,冻结,删除)/批量状态处理 */ @Override @Transactional public Boolean updateStatus(StatusEnum statusEnum, List idList) { return workRepository.updateStatus(statusEnum.getCode(), idList) > 0; } }/* * ReferenceIterator.java (Class: com.madphysicist.tools.util.ReferenceIterator) * * Mad Physicist JTools Project (General Purpose Utilities) * * The MIT License (MIT) * * Copyright (c) 2013 by * * 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.madphysicist.tools.util; import java.util.Iterator; /** * @brief A single-element iterator over a single object. * * This class is a much simpler version of doing something like * * Arrays.asList(new Object[] {object}).iterator()} * * This iterator also provides a `reset()` method that allows it to be run * multiple times without having to be re-created. * * This class does not support the `remove()` method for obvious reasons. * However, because it can be reset, this iterator is not thread safe. * * @param the element type of the iterator. This is just the class of the * object that it is initialized with. * @author * @version 1.0.0, 17 Jul 2014 - J. Fox-Rabinovitz - Initial coding * @since 1.3 */ public class ReferenceIterator implements Iterator { /** * @brief The object to iterate over. * * @since 1.0.0 */ private final E theObject; /** * @brief A flag indicating whether or not this iterator has a next element. * * This flag is set to `true` in the constructor and `reset()` method, and * `false` in the `next()` method. * * @since 1.0.0 */ private boolean theNextFlag; /** * @brief Constructs a new iterator over the specified object. * * @param anObject The object to iterate over. * @since 1.0.0 */ public ReferenceIterator(E anObject) { this.theObject = anObject; this.theNextFlag = true; } /** * @brief Checks if the object has been iterated over. * * @return `true` as long as `next()` has not been called. * @since 1.0.0 */ @Override public boolean hasNext() { return theNextFlag; } /** * @brief Returns the object being iterated over if it has not already been * returned. * * @return The object which this iterator encapsulates. * @throws IllegalStateException if this method was called a second time * before `reset()`. * @since 1.0.0 */ @Override public E next() { if(this.theNextFlag) { this.theNextFlag = false; return theObject; } throw new IllegalStateException("No more elements in " + getClass().getSimpleName()); } /** * @brief An unsupported operation required by the `Iterator` interface. * * This method always throws an exception. * * @throws UnsupportedOperationException always. * @since 1.0.0 */ @Override public void remove() { throw new UnsupportedOperationException("Deleting from SelfIterator"); } /** * @brief Resets this iterator. * * Further calls to `hasNext()` will return `true` and `next()` can be * invoked after this method without throwing an exception. If the iterator * is already active or has been reset, this method has no effect. * * @since 1.0.0 */ public void reset() { this.theNextFlag = true; } } /* * Copyright 2000-2014 JetBrains s.r.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 org.jetbrains.plugins.gradle.service.project; import com.intellij.ide.util.PsiNavigationSupport; import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId; import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListenerAdapter; import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType; import com.intellij.openapi.externalSystem.service.notification.ExternalSystemNotificationManager; import com.intellij.openapi.externalSystem.service.notification.NotificationCategory; import com.intellij.openapi.externalSystem.service.notification.NotificationData; import com.intellij.openapi.externalSystem.service.notification.NotificationSource; import com.intellij.openapi.externalSystem.util.ExternalSystemUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.pom.Navigatable; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.gradle.util.GradleConstants; import java.io.File; import static org.jetbrains.plugins.gradle.tooling.ErrorMessageBuilder.*; /** * @author Vladislav.Soroka * @since 5/13/2014 */ public class GradleProjectImportNotificationListener extends ExternalSystemTaskNotificationListenerAdapter { @Override public void onTaskOutput(@NotNull ExternalSystemTaskId id, @NotNull String text, boolean stdOut) { if (!stdOut && !StringUtil.isEmpty(text) && GradleConstants.SYSTEM_ID.getId().equals(id.getProjectSystemId().getId()) && id.getType() == ExternalSystemTaskType.RESOLVE_PROJECT) { final Project project = id.findProject(); if (project != null) { if (StringUtil.startsWith(text, GROUP_TAG)) { final String group = substringBetween(text, GROUP_TAG, GROUP_TAG); if (StringUtil.isEmpty(group)) return; int start = (GROUP_TAG.length() * 2) + group.length(); String path = null; String errorMessage = text.substring(start); if (StringUtil.startsWith(errorMessage, NAV_TAG)) { path = substringBetween(errorMessage, NAV_TAG, NAV_TAG); if (!StringUtil.isEmpty(path)) { start += (NAV_TAG.length() * 2) + path.length(); } } errorMessage = text.substring(start).replaceAll(EOL_TAG, "\n"); NotificationData notification = new NotificationData( group, errorMessage, StringUtil.equals("Performance statistics", group) ? NotificationCategory.INFO : NotificationCategory.WARNING, NotificationSource.PROJECT_SYNC); if (path != null) { notification.setNavigatable(new MyNavigatable(new File(path), project)); } ExternalSystemNotificationManager.getInstance(project).showNotification(id.getProjectSystemId(), notification); } } } } @Nullable private static String substringBetween(@NotNull String str, @NotNull String open, @NotNull String close) { int start = str.indexOf(open); if (start == -1) return null; int end = str.indexOf(close, start + open.length()); return end != -1 ? str.substring(start + open.length(), end) : null; } private static class MyNavigatable implements Navigatable { private final @NotNull File myFile; private final @NotNull Project myProject; private volatile Navigatable openFileDescriptor; public MyNavigatable(@NotNull File file, @NotNull Project project) { myFile = file; myProject = project; } @Override public void navigate(boolean requestFocus) { Navigatable fileDescriptor = openFileDescriptor; if (fileDescriptor == null) { final VirtualFile virtualFile = ExternalSystemUtil.findLocalFileByPath(myFile.getPath()); if (virtualFile != null) { openFileDescriptor = fileDescriptor = PsiNavigationSupport.getInstance().createNavigatable(myProject, virtualFile, -1); } } if (fileDescriptor != null && fileDescriptor.canNavigate()) { fileDescriptor.navigate(requestFocus); } } @Override public boolean canNavigate() { return myFile.exists(); } @Override public boolean canNavigateToSource() { return canNavigate(); } } } timboudreau/ANTLR4-Plugins-for-NetBeans /* * Copyright 2016-2020 , * * 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.nemesis.antlr.live.language; import java.awt.BasicStroke; import java.awt.Component; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.RenderingHints; import java.awt.geom.AffineTransform; import java.awt.geom.Line2D; import javax.swing.JComponent; import javax.swing.UIManager; import org.openide.util.NbBundle; /** * * @author */ @NbBundle.Messages(value = {"highlightParserErrors=Highlight Parse Errors", "highlightParserErrorsDesc=Highlight error nodes generated when parsing the document; " + "these are errors where the lexer recognized the tokens, but they did not " + "come in a sequence that made sense to the parser."}) final class ToggleHighlightParserErrorsAction extends AbstractPrefsKeyToggleAction { private final Line2D.Float line = new Line2D.Float(); ToggleHighlightParserErrorsAction(boolean icon) { super(icon, AdhocErrorHighlighter.PREFS_KEY_HIGHLIGHT_PARSER_ERRORS, Bundle.highlightParserErrors(), Bundle.highlightParserErrorsDesc()); } @Override protected boolean currentValue() { return AdhocErrorHighlighter.highlightParserErrors(); } @Override protected boolean updateValue(boolean val) { return AdhocErrorHighlighter.highlightParserErrors(val); } @Override public void paintIcon(Component c, Graphics g, int x, int y) { Graphics2D gg = (Graphics2D) g; Font f = c.getFont(); FontMetrics fm = gg.getFontMetrics(f); float ht = fm.getAscent(); Insets ins = ((JComponent) c).getInsets(); float availH = Math.max(4, (c.getHeight() - y) - ins.bottom); float availW = Math.max(4, ((c.getWidth() - x)) - ins.right); float w = (availW - 2) / 4F; gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); float top = availH / 4F; float sw = fm.stringWidth("x"); float sh = fm.getAscent(); float scale = top / sh; f = f.deriveFont(AffineTransform.getScaleInstance(scale, scale)); gg.setFont(f); if (AdhocErrorHighlighter.highlightParserErrors()) { g.setColor(c.getForeground()); } else { g.setColor(UIManager.getColor("ScrollBar.thumbHighlight")); } fm = gg.getFontMetrics(); float sl = (x + (availW / 2F)) - sw / 2F; gg.drawString("x", sl, y + top + fm.getAscent()); gg.setStroke(new BasicStroke(1.5F, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1)); float xoff = x + (availW / 2) - (w / 2); line.setLine(xoff, y + top, xoff + w, y + top); gg.draw(line); line.setLine(x + 1, y + top + top, x + w + 1, y + top + top); gg.draw(line); line.setLine((x + availW - 1) - w, y + top + top, x + availW - (w + 1), y + top + top); gg.draw(line); } @Override public int getIconWidth() { return 24; } @Override public int getIconHeight() { return 24; } } CM-Archive/android_packages_apps_FileManager package org.openintents.cmfilemanager; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.openintents.cmfilemanager.util.FileUtils; import org.openintents.cmfilemanager.util.ImageUtils; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Handler; import android.util.Log; import android.widget.ImageView; public class ThumbnailLoader { private static final String TAG = "OIFM_ThumbnailLoader"; // Both hard and soft caches are purged after 40 seconds idling. private static final int DELAY_BEFORE_PURGE = 40000; private static final int MAX_CACHE_CAPACITY = 40; // Maximum number of threads in the executor pool. // TODO: Tune POOL_SIZE for maximum performance gain private static final int POOL_SIZE = 5; private boolean cancel; private Context mContext; //private static int thumbnailWidth = 96; //private static int thumbnailHeight = 129; private static int thumbnailWidth = 32; private static int thumbnailHeight = 32; private Runnable purger; private Handler purgeHandler; private ExecutorService mExecutor; // Soft bitmap cache for thumbnails removed from the hard cache. // This gets cleared by the Garbage Collector everytime we get low on memory. private ConcurrentHashMap> mSoftBitmapCache; private LinkedHashMap mHardBitmapCache; private ArrayList mBlacklist; /** * Used for loading and decoding thumbnails from files. * * @author PhilipHayes * @param context Current application context. */ public ThumbnailLoader(Context context) { mContext = context; purger = new Runnable(){ @Override public void run() { Log.d(TAG, "Purge Timer hit; Clearing Caches."); clearCaches(); } }; purgeHandler = new Handler(); mExecutor = Executors.newFixedThreadPool(POOL_SIZE); mBlacklist = new ArrayList(); mSoftBitmapCache = new ConcurrentHashMap>(MAX_CACHE_CAPACITY / 2); mHardBitmapCache = new LinkedHashMap(MAX_CACHE_CAPACITY / 2, 0.75f, true){ /***/ private static final long serialVersionUID = 1347795807259717646L; @Override protected boolean removeEldestEntry(LinkedHashMap.Entry eldest){ // Moves the last used item in the hard cache to the soft cache. if(size() > MAX_CACHE_CAPACITY){ mSoftBitmapCache.put(eldest.getKey(), new SoftReference(eldest.getValue())); return true; } else { return false; } } }; } public static void setThumbnailHeight(int height) { thumbnailHeight = height; thumbnailWidth = height * 4 / 3; } /** * * @param parentFile The current directory. * @param text The IconifiedText container. * @param imageView The ImageView from the IconifiedTextView. */ public void loadImage(String parentFile, IconifiedText text, ImageView imageView) { if(!cancel && !mBlacklist.contains(text.getText())){ // We reset the caches after every 30 or so seconds of inactivity for memory efficiency. resetPurgeTimer(); Bitmap bitmap = getBitmapFromCache(text.getText()); if(bitmap != null){ // We're still in the UI thread so we just update the icons from here. imageView.setImageBitmap(bitmap); text.setIcon(bitmap); } else { if (!cancel) { // Submit the file for decoding. Thumbnail thumbnail = new Thumbnail(parentFile, imageView, text); WeakReference runner = new WeakReference(new ThumbnailRunner(thumbnail)); mExecutor.submit(runner.get()); } } } } /** * Cancels any downloads, shuts down the executor pool, * and then purges the caches. */ public void cancel(){ cancel = true; // We could also terminate it immediately, // but that may lead to synchronization issues. if(!mExecutor.isShutdown()){ mExecutor.shutdown(); } stopPurgeTimer(); mContext = null; clearCaches(); } /** * Stops the cache purger from running until it is reset again. */ public void stopPurgeTimer(){ purgeHandler.removeCallbacks(purger); } /** * Purges the cache every (DELAY_BEFORE_PURGE) milliseconds. * @see DELAY_BEFORE_PURGE */ private void resetPurgeTimer() { purgeHandler.removeCallbacks(purger); purgeHandler.postDelayed(purger, DELAY_BEFORE_PURGE); } private void clearCaches(){ mSoftBitmapCache.clear(); mHardBitmapCache.clear(); mBlacklist.clear(); } /** * @param key In this case the file name (used as the mapping id). * @return bitmap The cached bitmap or null if it could not be located. * * As the name suggests, this method attemps to obtain a bitmap stored * in one of the caches. First it checks the hard cache for the key. * If a key is found, it moves the cached bitmap to the head of the cache * so it gets moved to the soft cache last. * * If the hard cache doesn't contain the bitmap, it checks the soft cache * for the cached bitmap. If neither of the caches contain the bitmap, this * returns null. */ private Bitmap getBitmapFromCache(String key){ synchronized(mHardBitmapCache) { Bitmap bitmap = mHardBitmapCache.get(key); if(bitmap != null){ // Put bitmap on top of cache so it's purged last. mHardBitmapCache.remove(key); mHardBitmapCache.put(key, bitmap); return bitmap; } } SoftReference bitmapRef = mSoftBitmapCache.get(key); if(bitmapRef != null){ Bitmap bitmap = bitmapRef.get(); if(bitmap != null){ return bitmap; } else { // Must have been collected by the Garbage Collector // so we remove the bucket from the cache. mSoftBitmapCache.remove(key); } } // Could not locate the bitmap in any of the caches, so we return null. return null; } /** * @param parentFile The parentFile, so we can obtain the full path of the bitmap * @param fileName The name of the file, also the text in the list item. * @return The resized and resampled bitmap, if can not be decoded it returns null. */ private Bitmap decodeFile(String parentFile, String fileName) { if(!cancel){ try { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; options.outWidth = 0; options.outHeight = 0; options.inSampleSize = 1; String filePath = FileUtils.getFile(parentFile, fileName).getPath(); BitmapFactory.decodeFile(filePath, options); if(options.outWidth > 0 && options.outHeight > 0){ if (!cancel) { // Now see how much we need to scale it down. int widthFactor = (options.outWidth + thumbnailWidth - 1) / thumbnailWidth; int heightFactor = (options.outHeight + thumbnailHeight - 1) / thumbnailHeight; widthFactor = Math.max(widthFactor, heightFactor); widthFactor = Math.max(widthFactor, 1); // Now turn it into a power of two. if (widthFactor > 1) { if ((widthFactor & (widthFactor - 1)) != 0) { while ((widthFactor & (widthFactor - 1)) != 0) { widthFactor &= widthFactor - 1; } widthFactor <<= 1; } } options.inSampleSize = widthFactor; options.inJustDecodeBounds = false; Bitmap bitmap = ImageUtils.resizeBitmap( BitmapFactory.decodeFile(filePath, options), 72, 72); if (bitmap != null) { return bitmap; } } } else { // Must not be a bitmap, so we add it to the blacklist. if(!mBlacklist.contains(fileName)){ mBlacklist.add(fileName); } } } catch(Exception e) { } } return null; } /** * Holder object for thumbnail information. */ private class Thumbnail { public String parentFile; public ImageView imageView; public IconifiedText text; public Thumbnail(String parentFile, ImageView imageView, IconifiedText text) { this.parentFile = parentFile; this.imageView = imageView; this.text = text; } } /** * Decodes the bitmap and sends a ThumbnailUpdater on the UI Thread * to update the listitem and iconified text. * * @see ThumbnailUpdater */ private class ThumbnailRunner implements Runnable { Thumbnail thumb; ThumbnailRunner(Thumbnail thumb){ this.thumb = thumb; } @Override public void run() { if(!cancel){ Bitmap bitmap = decodeFile(thumb.parentFile, thumb.text.getText()); if(bitmap != null && !cancel){ // Bitmap was successfully decoded so we place it in the hard cache. mHardBitmapCache.put(thumb.text.getText(), bitmap); Activity activity = ((Activity) mContext); activity.runOnUiThread(new ThumbnailUpdater(bitmap, thumb)); thumb = null; } } } } /** * When run on the UI Thread, this updates the * thumbnail in the corresponding iconifiedtext and imageview. */ private class ThumbnailUpdater implements Runnable { private Bitmap bitmap; private Thumbnail thumb; public ThumbnailUpdater(Bitmap bitmap, Thumbnail thumb) { this.bitmap = bitmap; this.thumb = thumb; } @Override public void run() { if(bitmap != null && mContext != null && !cancel){ thumb.imageView.setImageBitmap(bitmap); thumb.text.setIcon(bitmap); } } } } sivanookala1979/getbike0 package utils; /** * Created by sivanookala on 24/11/16. */ public class ApplicationContext { static ApplicationContext context = new ApplicationContext(); IGcmUtils gcmUtils; private ApplicationContext() { gcmUtils = new GcmUtils(); } public static ApplicationContext defaultContext() { return context; } public IGcmUtils getGcmUtils() { return gcmUtils; } public void setGcmUtils(IGcmUtils gcmUtils) { this.gcmUtils = gcmUtils; } } /* * Generated by Robotoworks Mechanoid */ package com.robotoworks.example.movies.ops; import com.robotoworks.mechanoid.ops.OperationService; public class MoviesProcessor extends AbstractMoviesProcessor { public MoviesProcessor(OperationService service) { super(service, true); } } yacota/stagemonitor-issue127 package org.stagemonitor.core.metrics.annotations; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import org.junit.Assert; import org.junit.Test; import org.stagemonitor.core.metrics.aspects.SignatureUtils; public class SignatureUtilsTest { @Test public void testGetSignature() throws Exception { CtClass ctClass = ClassPool.getDefault().get("java.lang.String"); CtMethod toString = ctClass.getDeclaredMethod("toString"); Assert.assertEquals("toString", SignatureUtils.getSignature(toString, null, true)); Assert.assertEquals("String#toString", SignatureUtils.getSignature(toString, null, false)); Assert.assertEquals("stringify", SignatureUtils.getSignature(toString, "stringify", true)); Assert.assertEquals("String#stringify", SignatureUtils.getSignature(toString, "stringify", false)); } } package com.github.east196.rap.dict; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; import java.util.List; import com.github.east196.core.api.Result; public interface DictSelectApi { @GET("/sys/dict/getDictItems/{dictCode}") Call>> ajaxGetDictItems(@Path("dictCode") String dictCode); @GET("/sys/dict/getDictText/{dictCode}/{key}") Call> ajaxFilterDictText(@Path("dictCode") String dictCode, @Path("key") String key); } package leetcode.fourth; /** * 删除重复元素 * 返回移除后数组的新长度 * * @since 2020-6-15 Monday 16:16 */ public class Code_026_RemoveDuplicates { static int removeDuplicates(int[] nums) { int len = nums.length; if (len < 2) return len; int res = 0, cur = 1; while (cur < len) { if (nums[cur] == nums[res]) { cur++; } else { nums[++res] = nums[cur]; } } return res + 1; } public static void main(String[] args) { int[] arr = new int[]{1, 1, 1, 2, 2, 2, 3}; // int[] arr = new int[]{1, 2, 2, 2}; int res = removeDuplicates(arr); for (int i = 0; i < res; i++) { System.out.println(arr[i]); } } } /* * Copyright 2017 The Embulk project * * 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.embulk.base.restclient.record; import java.util.List; public class RecordExporter { public RecordExporter(final List valueExporters, final ServiceRecord.Builder serviceRecordBuilder) { this.valueExporters = valueExporters; this.serviceRecordBuilder = serviceRecordBuilder; } public ServiceRecord exportRecord(final SinglePageRecordReader singlePageRecordReader) { this.serviceRecordBuilder.reset(); for (final ValueExporter valueExporter : this.valueExporters) { // |EmbulkValueScope| and |ValueLocator| are contained in |ValueExporter|. valueExporter.exportValueToBuildRecord(singlePageRecordReader, this.serviceRecordBuilder); } return this.serviceRecordBuilder.build(); } private final List valueExporters; private final ServiceRecord.Builder serviceRecordBuilder; } blog-web/src/main/java/com/finn/entity/Menu.java package com.finn.entity; import com.baomidou.mybatisplus.annotation.*; import java.io.Serializable; import java.time.LocalDateTime; import java.util.List; import com.finn.dto.MenuDTO; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.*; import lombok.experimental.Accessors; /** *

* *

* * @author finn * @since 2022-01-20 */ @Data @Builder @AllArgsConstructor @NoArgsConstructor @TableName("tb_menu") @ApiModel(value = "Menu", description = "后台管理左侧菜单") public class Menu implements Serializable { private static final long serialVersionUID = 1L; @ApiModelProperty(value = "后台菜单id") @TableId(value = "id", type = IdType.AUTO) private Integer id; @ApiModelProperty(value = "菜单列表名字") private String name; @ApiModelProperty(value = "菜单的path") private String path; @ApiModelProperty(value = "菜单的component") private String component; @ApiModelProperty(value = "菜单图标") private String icon; @ApiModelProperty(value = "创建时间") @TableField(fill = FieldFill.INSERT) private LocalDateTime createTime; @ApiModelProperty(value = "更新时间") @TableField(fill = FieldFill.UPDATE) private LocalDateTime updateTime; @ApiModelProperty(value = "排序") private Integer orderNum; @ApiModelProperty(value = "父菜单") private Integer parentId; @ApiModelProperty(value = "是否隐藏") private Integer isHidden; } Exareme-Docker/src/exareme/exareme-worker/src/main/java/madgik/exareme/worker/art/container/event/closeSession/CloseSessionEventHandler.java /** * Copyright MaDgIK Group 2010 - 2015. */ package madgik.exareme.worker.art.container.event.closeSession; import madgik.exareme.utils.eventProcessor.EventHandler; import madgik.exareme.utils.eventProcessor.EventProcessor; import org.apache.log4j.Logger; import java.rmi.RemoteException; /** * @author heraldkllapi */ public class CloseSessionEventHandler implements EventHandler { public static CloseSessionEventHandler instance = new CloseSessionEventHandler(); private static Logger log = Logger.getLogger(CloseSessionEventHandler.class); @Override public void handle(CloseSessionEvent event, EventProcessor proc) throws RemoteException { if (event.cSID != null) { log.debug("Destroying container session : " + event.sID.getLongId()); int count = event.session.destroySession(event.cSID); //// event.bufferPool.destroyContainerSession(event.cSID, event.sID, true); event.status.getOperatorMeasurement().changeActiveValue(-count); } else { log.debug("Destroying plan session : " + event.sID.getLongId()); int count = event.session.destroySession(); // event.bufferPool.destroySessions(event.sID, true); event.status.getOperatorMeasurement().changeActiveValue(-count); } } } /* * Copyright 2021-2021 VMware, Inc. * SPDX-License-Identifier: BSD-2-Clause */ package com.vmware.devops.pebble.filters.cloudassembly; import java.util.List; import java.util.Map; import java.util.TreeMap; import com.mitchellbosecke.pebble.error.PebbleException; import com.mitchellbosecke.pebble.extension.Filter; import com.mitchellbosecke.pebble.template.EvaluationContext; import com.mitchellbosecke.pebble.template.PebbleTemplate; import com.vmware.devops.model.cloudassembly.design.CloudTemplate.BlueprintContent.Input; import com.vmware.devops.model.cloudassembly.design.CloudTemplate.BlueprintContent.StringInput; public class CloudTemplateInputFilter implements Filter { private static String TYPE_INPUT_ARG_NAME = "type"; @Override public Object apply(Object input, Map args, PebbleTemplate self, EvaluationContext context, int lineNumber) throws PebbleException { Map result = new TreeMap<>(); String type = (String) args.get(TYPE_INPUT_ARG_NAME); if (type.equalsIgnoreCase("string")) { ((Map) input).entrySet().stream() .filter(e -> e.getValue() instanceof StringInput) .forEach(e -> result.put(e.getKey(), e.getValue())); return result; } throw new UnsupportedOperationException("Unknown type: " + type); } @Override public List getArgumentNames() { return List.of( TYPE_INPUT_ARG_NAME ); } } package cn.cqray.android.editor.ui; import android.graphics.Color; import android.graphics.drawable.GradientDrawable; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.core.view.ViewCompat; import androidx.lifecycle.LifecycleOwner; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.Observer; import androidx.recyclerview.widget.RecyclerView; import java.util.List; /** * 富文本调色板文字颜色适配器 * @author Cqray */ class EditorColorsAdapter extends RecyclerView.Adapter { /** 是否可以取消选择 **/ private boolean mCancelEnable; /** 单项大小 **/ private int mItemSize; /** 数据 **/ private List mData; /** 选择的颜色 **/ private final MutableLiveData mSelectColor = new MutableLiveData<>(); public EditorColorsAdapter(List data, String color, int itemSize) { mData = data; mItemSize = itemSize; mSelectColor.setValue(color); } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = new View(parent.getContext()); view.setLayoutParams(new ViewGroup.LayoutParams(mItemSize, mItemSize)); return new RecyclerView.ViewHolder(view) {}; } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) { final String color = mData.get(position); GradientDrawable background = new GradientDrawable(); background.setColor(Color.parseColor(color)); if (color.equalsIgnoreCase(mSelectColor.getValue())) { background.setStroke(mItemSize / 20, ColorUtils.reverseColor(color)); } ViewCompat.setBackground(holder.itemView, background); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean equal = color.equals(mSelectColor.getValue()); mSelectColor.setValue(mCancelEnable && equal ? null :color); notifyDataSetChanged(); } }); } @Override public int getItemCount() { return mData == null ? 0 : mData.size(); } public void setCancelEnable(boolean enable) { mCancelEnable = enable; } public void observeSelectColor(LifecycleOwner owner, Observer observer) { mSelectColor.observe(owner, observer); } public void setSelectColor(String color) { mSelectColor.setValue(color); notifyDataSetChanged(); } } /** * 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.camel.component.xmlsecurity.processor; import java.io.IOException; import java.io.InputStream; import java.security.NoSuchProviderException; import java.util.ArrayList; import java.util.List; import javax.xml.crypto.KeySelector; import javax.xml.crypto.XMLStructure; import javax.xml.crypto.dsig.Manifest; import javax.xml.crypto.dsig.Reference; import javax.xml.crypto.dsig.SignedInfo; import javax.xml.crypto.dsig.XMLObject; import javax.xml.crypto.dsig.XMLSignature; import javax.xml.crypto.dsig.XMLSignature.SignatureValue; import javax.xml.crypto.dsig.XMLSignatureException; import javax.xml.crypto.dsig.XMLSignatureFactory; import javax.xml.crypto.dsig.dom.DOMValidateContext; import javax.xml.crypto.dsig.keyinfo.KeyInfo; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.ParserConfigurationException; import javax.xml.validation.Schema; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.component.xmlsecurity.api.ValidationFailedHandler; import org.apache.camel.component.xmlsecurity.api.XmlSignature2Message; import org.apache.camel.component.xmlsecurity.api.XmlSignatureChecker; import org.apache.camel.component.xmlsecurity.api.XmlSignatureFormatException; import org.apache.camel.component.xmlsecurity.api.XmlSignatureHelper; import org.apache.camel.component.xmlsecurity.api.XmlSignatureInvalidException; import org.apache.camel.processor.validation.DefaultValidationErrorHandler; import org.apache.camel.processor.validation.ValidatorErrorHandler; import org.apache.camel.util.IOHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * XML signature verifier. Assumes that the input XML contains exactly one * Signature element. */ public class XmlVerifierProcessor extends XmlSignatureProcessor { private static final Logger LOG = LoggerFactory.getLogger(XmlVerifierProcessor.class); private final XmlVerifierConfiguration config; public XmlVerifierProcessor(XmlVerifierConfiguration config) { this.config = config; } @Override public XmlVerifierConfiguration getConfiguration() { return config; } @Override public void process(Exchange exchange) throws Exception { //NOPMD InputStream stream = exchange.getIn().getMandatoryBody(InputStream.class); try { // lets setup the out message before we invoke the signing // so that it can mutate it if necessary Message out = exchange.getOut(); out.copyFrom(exchange.getIn()); verify(stream, out); clearMessageHeaders(out); } catch (Exception e) { // remove OUT message, as an exception occurred exchange.setOut(null); throw e; } finally { IOHelper.close(stream, "input stream"); } } @SuppressWarnings("unchecked") protected void verify(InputStream input, final Message out) throws Exception { //NOPMD LOG.debug("Verification of XML signature document started"); final Document doc = parseInput(input, out); XMLSignatureFactory fac; // Try to install the Santuario Provider - fall back to the JDK provider if this does // not work try { fac = XMLSignatureFactory.getInstance("DOM", "ApacheXMLDSig"); } catch (NoSuchProviderException ex) { fac = XMLSignatureFactory.getInstance("DOM"); } KeySelector selector = getConfiguration().getKeySelector(); if (selector == null) { throw new IllegalStateException("Wrong configuration. Key selector is missing."); } DOMValidateContext valContext = new DOMValidateContext(selector, doc); valContext.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE); valContext.setProperty("org.jcp.xml.dsig.validateManifests", Boolean.TRUE); if (getConfiguration().getSecureValidation() == Boolean.TRUE) { valContext.setProperty("org.apache.jcp.xml.dsig.secureValidation", Boolean.TRUE); valContext.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.TRUE); } setUriDereferencerAndBaseUri(valContext); setCryptoContextProperties(valContext); NodeList signatureNodes = getSignatureNodes(doc); List collectedObjects = new ArrayList<>(3); List collectedReferences = new ArrayList<>(3); int totalCount = signatureNodes.getLength(); for (int i = 0; i < totalCount; i++) { Element signatureNode = (Element) signatureNodes.item(i); valContext.setNode(signatureNode); final XMLSignature signature = fac.unmarshalXMLSignature(valContext); if (getConfiguration().getXmlSignatureChecker() != null) { XmlSignatureChecker.Input checkerInput = new CheckerInputBuilder().message(out).messageBodyDocument(doc) .keyInfo(signature.getKeyInfo()).currentCountOfSignatures(i + 1).currentSignatureElement(signatureNode) .objects(signature.getObjects()).signatureValue(signature.getSignatureValue()) .signedInfo(signature.getSignedInfo()).totalCountOfSignatures(totalCount) .xmlSchemaValidationExecuted(getSchemaResourceUri(out) != null).build(); getConfiguration().getXmlSignatureChecker().checkBeforeCoreValidation(checkerInput); } boolean coreValidity; try { coreValidity = signature.validate(valContext); } catch (XMLSignatureException se) { throw getConfiguration().getValidationFailedHandler().onXMLSignatureException(se); } // Check core validation status boolean goon = coreValidity; if (!coreValidity) { goon = handleSignatureValidationFailed(valContext, signature); } if (goon) { LOG.debug("XML signature {} verified", i + 1); } else { throw new XmlSignatureInvalidException("XML signature validation failed"); } collectedObjects.addAll(signature.getObjects()); collectedReferences.addAll(signature.getSignedInfo().getReferences()); } map2Message(collectedReferences, collectedObjects, out, doc); } private void map2Message(final List refs, final List objs, Message out, final Document messageBodyDocument) throws Exception { //NOPMD XmlSignature2Message.Input refsAndObjects = new XmlSignature2Message.Input() { @Override public List getReferences() { return refs; } @Override public List getObjects() { return objs; } @Override public Document getMessageBodyDocument() { return messageBodyDocument; } @Override public Boolean omitXmlDeclaration() { return getConfiguration().getOmitXmlDeclaration(); } @Override public Object getOutputNodeSearch() { return getConfiguration().getOutputNodeSearch(); } @Override public String getOutputNodeSearchType() { return getConfiguration().getOutputNodeSearchType(); } @Override public Boolean getRemoveSignatureElements() { return getConfiguration().getRemoveSignatureElements(); } @Override public String getOutputXmlEncoding() { return getConfiguration().getOutputXmlEncoding(); } }; getConfiguration().getXmlSignature2Message().mapToMessage(refsAndObjects, out); } private NodeList getSignatureNodes(Document doc) throws IOException, ParserConfigurationException, XmlSignatureFormatException { // Find Signature element NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (nl.getLength() == 0) { throw new XmlSignatureFormatException( "Message is not a correct XML signature document: 'Signature' element is missing. Check the sent message."); } LOG.debug("{} signature elements found", nl.getLength()); return nl; } @SuppressWarnings("unchecked") protected boolean handleSignatureValidationFailed(DOMValidateContext valContext, XMLSignature signature) throws Exception { //NOPMD ValidationFailedHandler handler = getConfiguration().getValidationFailedHandler(); LOG.debug("handleSignatureValidationFailed called"); try { handler.start(); // first check signature value, see // https://www.isecpartners.com/media/12012/XMLDSIG_Command_Injection.pdf SignatureValue sigValue = signature.getSignatureValue(); boolean sv = sigValue.validate(valContext); if (!sv) { handler.signatureValueValidationFailed(sigValue); } // then the references! // check the validation status of each Reference for (Reference ref : (List) signature.getSignedInfo().getReferences()) { boolean refValid = ref.validate(valContext); if (!refValid) { handler.referenceValidationFailed(ref); } } // validate Manifests, if property set if (Boolean.TRUE.equals(valContext.getProperty("org.jcp.xml.dsig.validateManifests"))) { for (XMLObject xo : (List) signature.getObjects()) { List content = xo.getContent(); for (XMLStructure xs : content) { if (xs instanceof Manifest) { Manifest man = (Manifest) xs; for (Reference ref : (List) man.getReferences()) { boolean refValid = ref.validate(valContext); if (!refValid) { handler.manifestReferenceValidationFailed(ref); } } } } } } boolean goon = handler.ignoreCoreValidationFailure(); LOG.debug("Ignore Core Validation failure: {}", goon); return goon; } finally { handler.end(); } } protected Document parseInput(InputStream is, Message message) throws Exception { //NOPMD try { ValidatorErrorHandler errorHandler = new DefaultValidationErrorHandler(); Schema schema = getSchema(message); DocumentBuilder db = XmlSignatureHelper.newDocumentBuilder(getConfiguration().getDisallowDoctypeDecl(), schema); db.setErrorHandler(errorHandler); Document doc = db.parse(is); errorHandler.handleErrors(message.getExchange(), schema, null); // throws ValidationException return doc; } catch (SAXException e) { throw new XmlSignatureFormatException("Message has wrong format, it is not a XML signature document. Check the sent message.", e); } } static class CheckerInputBuilder { private boolean xmlSchemaValidationExecuted; private int totalCountOfSignatures; private SignedInfo signedInfo; private SignatureValue signatureValue; private List objects; private Document messageBodyDocument; private Message message; private KeyInfo keyInfo; private Element currentSignatureElement; private int currentCountOfSignatures; CheckerInputBuilder xmlSchemaValidationExecuted(boolean xmlSchemaValidationExecuted) { this.xmlSchemaValidationExecuted = xmlSchemaValidationExecuted; return this; } CheckerInputBuilder totalCountOfSignatures(int totalCountOfSignatures) { this.totalCountOfSignatures = totalCountOfSignatures; return this; } CheckerInputBuilder signedInfo(SignedInfo signedInfo) { this.signedInfo = signedInfo; return this; } CheckerInputBuilder signatureValue(SignatureValue signatureValue) { this.signatureValue = signatureValue; return this; } CheckerInputBuilder objects(List objects) { this.objects = objects; return this; } CheckerInputBuilder messageBodyDocument(Document messageBodyDocument) { this.messageBodyDocument = messageBodyDocument; return this; } CheckerInputBuilder message(Message message) { this.message = message; return this; } CheckerInputBuilder keyInfo(KeyInfo keyInfo) { this.keyInfo = keyInfo; return this; } CheckerInputBuilder currentSignatureElement(Element currentSignatureElement) { this.currentSignatureElement = currentSignatureElement; return this; } CheckerInputBuilder currentCountOfSignatures(int currentCountOfSignatures) { this.currentCountOfSignatures = currentCountOfSignatures; return this; } XmlSignatureChecker.Input build() { return new XmlSignatureChecker.Input() { @Override public boolean isXmlSchemaValidationExecuted() { return xmlSchemaValidationExecuted; } @Override public int getTotalCountOfSignatures() { return totalCountOfSignatures; } @Override public SignedInfo getSignedInfo() { return signedInfo; } @Override public SignatureValue getSignatureValue() { return signatureValue; } @Override public List getObjects() { return objects; } @Override public Document getMessageBodyDocument() { return messageBodyDocument; } @Override public Message getMessage() { return message; } @Override public KeyInfo getKeyInfo() { return keyInfo; } @Override public Element getCurrentSignatureElement() { return currentSignatureElement; } @Override public int getCurrentCountOfSignatures() { return currentCountOfSignatures; } }; } } } barrakovsky/lambdaj // Modified or written by Lambdascale SRL for inclusion with lambdaj. // Copyright (c) 2009-2010 . // Licensed under the Apache License, Version 2.0 (the "License") package ch.lambdaj.group; import static ch.lambdaj.Lambda.*; import static ch.lambdaj.mock.ExposureBy.*; import static java.util.Arrays.*; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import java.util.*; import org.junit.*; import ch.lambdaj.mock.*; /** * @author * @author */ public class GroupsTest { @Before public void setUp() { FexFrance1 = new Exposure() { { setCountryName("France"); setInsuredName("Fex France 1"); } }; FexFrance2 = new Exposure() { { setCountryName("France"); setInsuredName("Fex France 2"); } }; FexCanada1 = new Exposure() { { setCountryName("Canada"); setInsuredName("Fex Canada 1"); } }; FexCanada2 = new Exposure() { { setCountryName("Canada"); setInsuredName("Fex Canada 2"); } }; exposures = asList(FexFrance1, FexFrance2, FexCanada1, FexCanada2); } private Exposure FexFrance1, FexFrance2, FexCanada1, FexCanada2; private List exposures; @Test public void testByCriteria() { byExposure().countryName().insuredName(); } @Test public void testGroupByCountry() { Group group = group(exposures, "countryName"); assertThat(group.keySet(), hasItems("France", "Canada")); Iterable groupFrance = group.find("France"); assertThat(groupFrance, hasItems(FexFrance1, FexFrance2)); Iterable groupCanada = group.find("Canada"); assertThat(groupCanada, hasItems(FexCanada1, FexCanada2)); } @Test public void testGroupByInsuredName() { Group group = group(exposures, "insuredName"); assertThat(group.keySet(), hasItems("Fex France 1", "Fex France 2", "Fex Canada 1", "Fex Canada 2")); Iterable groupFrance = group.find("Fex France 2"); assertThat(groupFrance, hasItems(FexFrance2)); Iterable groupCanada = group.find("Fex Canada 1"); assertThat(groupCanada, hasItems(FexCanada1)); } @Test public void testGroupByCountryAndInsuredName() { Group group = group(exposures, "countryName", "insuredName"); assertThat(group.keySet(), hasItems("France", "Canada")); Group groupFrance = group.findGroup("France"); assertThat(groupFrance.findAll(), hasItems(FexFrance1, FexFrance2)); Iterable groupFexFrance = groupFrance.find("Fex France 1"); assertThat(groupFexFrance, hasItems(FexFrance1)); Group groupCanada = group.findGroup("Canada"); assertThat(groupCanada.findAll(), hasItems(FexCanada1, FexCanada2)); Iterable groupFexCanada = groupCanada.find("Fex Canada 2"); assertThat(groupFexCanada, hasItems(FexCanada2)); } @Test public void testGroupTypedByCountryAndInsuredName() { Group group = group(exposures, byExposure().countryName().insuredName()); assertThat(group.keySet(), hasItems("France", "Canada")); Group groupFrance = group.findGroup("France"); assertThat(groupFrance.findAll(), hasItems(FexFrance1, FexFrance2)); Iterable groupFexFrance = groupFrance.find("Fex France 1"); assertThat(groupFexFrance, hasItems(FexFrance1)); Group groupCanada = group.findGroup("Canada"); assertThat(groupCanada.findAll(), hasItems(FexCanada1, FexCanada2)); Iterable groupFexCanada = groupCanada.find("Fex Canada 2"); assertThat(groupFexCanada, hasItems(FexCanada2)); } } package handy.cards; import java.util.HashSet; import java.util.Set; import handy.cards.Card.VALUE; public class SpanishShoe extends Shoe { public SpanishShoe(int deckCount) { super(deckCount); Set popSet = new HashSet(); for(Card card : shoeList){ if(card.value == VALUE.TEN){ popSet.add(card); } } for(Card card : popSet){ shoeList.remove(card); } deckSize = 48; } } 1-10 package org.apereo.cas.authentication.principal; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apereo.cas.CasProtocolConstants; import org.springframework.util.StringUtils; import java.util.HashMap; import java.util.Map; /** * Default response builder that passes back the ticket * id to the original url of the service based on the response type. * * @author * @since 4.2 */ public class WebApplicationServiceResponseBuilder extends AbstractWebApplicationServiceResponseBuilder { private static final long serialVersionUID = -851233878780818494L; public WebApplicationServiceResponseBuilder() { } @Override public Response build(final WebApplicationService service, final String serviceTicketId) { final Map parameters = new HashMap<>(); if (StringUtils.hasText(serviceTicketId)) { parameters.put(CasProtocolConstants.PARAMETER_TICKET, serviceTicketId); } final WebApplicationService finalService = buildInternal(service, parameters); final Response.ResponseType responseType = getWebApplicationServiceResponseType(); if (responseType == Response.ResponseType.POST) { return buildPost(finalService, parameters); } if (responseType == Response.ResponseType.REDIRECT) { return buildRedirect(finalService, parameters); } if (responseType == Response.ResponseType.HEADER) { return buildHeader(finalService, parameters); } throw new IllegalArgumentException("Response type is valid. Only POST/REDIRECT are supported"); } /** * Build internal service. * * @param service the service * @param parameters the parameters * @return the service */ protected WebApplicationService buildInternal(final WebApplicationService service, final Map parameters) { return service; } @Override public boolean equals(final Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (obj.getClass() != getClass()) { return false; } final WebApplicationServiceResponseBuilder rhs = (WebApplicationServiceResponseBuilder) obj; return new EqualsBuilder() .appendSuper(super.equals(obj)) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder() .appendSuper(super.hashCode()) .toHashCode(); } @Override public boolean supports(final WebApplicationService service) { return true; } @Override public int getOrder() { return Integer.MAX_VALUE; } } Debabrata-Giri-2001/JAVA-all-in-ONE package OOP; public class student { private int age; private String Name; public int getAge(int i) { return age; } public void setAge(int age) { if (age>20){ System.out.println("You are not allowed"); }else { this.age = age; } } } src/cn/year2018/chy/design/proxy/jdkdynamic/MyInvocationHandler.java package cn.year2018.chy.design.proxy.jdkdynamic; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Arrays; public class MyInvocationHandler implements InvocationHandler { //invocationHandler持有的被代理对象 Object target; public MyInvocationHandler(Object target) { this.target = target; } /** * proxy:代表动态代理对象 * method:代表正在执行的方法 * args:代表调用目标方法时传入的实参 */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("代理执行" + method.getName() + "方法"); System.out.println("参数" + Arrays.toString(args)); //代理过程中插入监测方法,计算该方法耗时 Object result = method.invoke(target, args); return result; } //创建一个代理对象stuProxy来代理zhangsan,代理对象的每个执行方法都会替换执行Invocation中的invoke方法 public Object getProxy() { Object o = Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this); return o; } } package com.atlwj.protocol.dubbo; import com.atlwj.framework.AbstractProtocol; import com.atlwj.framework.Invocation; import com.atlwj.framework.Url; import com.atlwj.protocol.http.HttpClient; public class DubboProtocol extends AbstractProtocol { @Override public void start(Url url) { new NettyServer().start(url.getHostname(),url.getPort()); } @Override public String send(Url url, Invocation invocation) { return new HttpClient().send(url.getHostname(),url.getPort(),invocation); } } package com.lcg.rabbitstable.scopeoperations; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.core.*; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; import org.springframework.amqp.rabbit.core.RabbitAdmin; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Profile; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import java.util.ArrayList; import java.util.List; import java.util.UUID; /** * 使用场景: *

基于同一个channel发送所有的消息

*

只需要简单的确认信息返回

*

*/ @Slf4j @Profile("scoped-operations") @Configuration @EnableScheduling public class ScopedOperationConfig { protected static final String queue_name = "so.queue.0"; protected static final String exchange_name = "so.exchange.0"; @Lazy @Autowired private RabbitTemplate rabbitTemplate; @Bean public CachingConnectionFactory factory() { CachingConnectionFactory factory = new CachingConnectionFactory(); factory.setPublisherConfirmType(CachingConnectionFactory.ConfirmType.SIMPLE); factory.setUri("amqp://localhost:5672"); factory.setUsername("guest"); factory.setPassword(""); factory.addChannelListener((ch, transaction) -> log.info("channel connected:{}, tx:{}", ch.getChannelNumber(), transaction)); return factory; } @Bean public AmqpAdmin admin() { RabbitAdmin admin = new RabbitAdmin(factory()); Queue queue = QueueBuilder.durable(queue_name).build(); admin.declareQueue(queue); TopicExchange exchange = new TopicExchange(exchange_name); admin.declareExchange(exchange); admin.declareBinding(BindingBuilder.bind(queue).to(exchange).with("")); return admin; } @RabbitListener(queues = queue_name) public void handler(String message) { log.info("handle massage: {}", message); } @Scheduled(cron = "0/4 * * * * ?") public void sendMsgWithoutCallback() { List list = new ArrayList<>(); list.add("a_" + UUID.randomUUID().toString()); list.add("b_" + UUID.randomUUID().toString()); list.add("c_" + UUID.randomUUID().toString()); Boolean result = this.rabbitTemplate.invoke(t -> { list.forEach(str -> t.convertAndSend(exchange_name, "", str)); t.waitForConfirmsOrDie(5000); return true; }); log.info("non-callback result: {}", result); } @Scheduled(cron = "0/5 * * * * ?") public void sendMsgWithCallback() { List list = new ArrayList<>(); list.add("1_" + UUID.randomUUID().toString()); list.add("2_" + UUID.randomUUID().toString()); list.add("3_" + UUID.randomUUID().toString()); list.add("4_" + UUID.randomUUID().toString()); Boolean result = this.rabbitTemplate.invoke(t -> { list.forEach(str -> t.convertAndSend(exchange_name, "", str)); t.waitForConfirmsOrDie(5000); return true; }, (tag, multiple) -> { log.info("callback Ack: " + tag + ":" + multiple); }, (tag, multiple) -> { log.info("callback Nack: " + tag + ":" + multiple); } ); log.info("callback result: {}", result); } } src/main/java/run/halo/app/security/support/UserDetail.java0 package run.halo.app.security.support; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.ToString; import org.springframework.lang.NonNull; import run.halo.app.exception.AuthenticationException; import run.halo.app.model.entity.User; /** * User detail. * * @author johnniang */ @ToString @EqualsAndHashCode @AllArgsConstructor @NoArgsConstructor public class UserDetail { private User user; /** * Gets user info. * * @return user info * @throws AuthenticationException throws if the user is null */ @NonNull public User getUser() { return user; } /** * Sets user info. * * @param user user info */ public void setUser(User user) { this.user = user; } } package com.commercetools.sunrise.ctp.graphql; import io.sphere.sdk.http.HttpResponse; public class GraphQLException extends RuntimeException { private static final long serialVersionUID = 0L; public GraphQLException(final String message, final Throwable cause) { super(message, cause); } public GraphQLException(final String message, final HttpResponse httpResponse) { super(message + "\n" + httpResponse.toString()); } } 0 package com.youcruit.onfido.api.checks; import java.net.URI; import java.util.Date; import java.util.List; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Check { @Expose @SerializedName("id") private CheckId id; @Expose @SerializedName("created_at") private Date createdAt; @Expose @SerializedName("href") private String pathToThis; @Expose @SerializedName("type") private CheckType type; @Expose @SerializedName("status") private ResultStatus status; @Expose @SerializedName("result") private Result result; @Expose @SerializedName("redirect_uri") private URI redirectUri; @Expose @SerializedName("download_uri") private URI downloadUri; @Expose @SerializedName("results_uri") private URI resultsUri; @Expose @SerializedName("form_uri") private URI formUri; @Expose @SerializedName("reports") private List reports; public CheckId getId() { return id; } public void setId(final CheckId id) { this.id = id; } public Date getCreatedAt() { return createdAt; } public void setCreatedAt(final Date createdAt) { this.createdAt = createdAt; } public String getPathToThis() { return pathToThis; } public void setPathToThis(final String pathToThis) { this.pathToThis = pathToThis; } public CheckType getType() { return type; } public void setType(final CheckType type) { this.type = type; } public ResultStatus getStatus() { return status; } public void setStatus(final ResultStatus status) { this.status = status; } public Result getResult() { return result; } public void setResult(final Result result) { this.result = result; } public URI getRedirectUri() { return redirectUri; } public void setRedirectUri(final URI redirectUri) { this.redirectUri = redirectUri; } public URI getDownloadUri() { return downloadUri; } public void setDownloadUri(final URI downloadUri) { this.downloadUri = downloadUri; } public URI getResultsUri() { return resultsUri; } public void setResultsUri(final URI resultsUri) { this.resultsUri = resultsUri; } public URI getFormUri() { return formUri; } public void setFormUri(final URI formUri) { this.formUri = formUri; } public List getReports() { return reports; } public void setReports(final List reports) { this.reports = reports; } @Override public String toString() { return "Check{" + "id=" + id + ", createdAt=" + createdAt + ", pathToThis='" + pathToThis + '\'' + ", type=" + type + ", status=" + status + ", result=" + result + ", redirectUri=" + redirectUri + ", downloadUri=" + downloadUri + ", resultsUri=" + resultsUri + ", reports=" + reports + '}'; } } OnlineBankUtility/src/main/java/com/neu/edu/controller/TransactionController.java package com.neu.edu.controller; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import com.neu.edu.dao.TransactionDao; import com.neu.edu.pojo.Customer; import com.neu.edu.pojo.TransactionDetails; @Controller public class TransactionController { @RequestMapping(value = "/downloadPDF", method = RequestMethod.GET) public ModelAndView downloadExcel(HttpServletRequest request) { // create some sample data HttpSession session = request.getSession(); List transactions = (List) session.getAttribute("transactionlist"); // return a view which will be resolved by an excel view resolver return new ModelAndView("pdfView", "transactions", transactions); } @RequestMapping(value = "/retrieveTransactions.htm", method = RequestMethod.GET) public ModelAndView createTransactionView(ModelMap model, HttpServletRequest request) { HttpSession session = request.getSession(); Customer customer = (Customer) session.getAttribute("customer"); return new ModelAndView("Customer/account-transaction", "customer", customer); } @RequestMapping(value = "/getTransactions.htm", method = RequestMethod.POST) public ModelAndView getTransactionView(@RequestParam("FromAccNum") int fromAccNum, HttpServletRequest request, TransactionDao transactionDao) { HttpSession session = request.getSession(); List results = transactionDao.getCustomerTransactions(fromAccNum); if (results != null) { session.setAttribute("transactionlist", results); return new ModelAndView("Customer/get-transaction", "results", results); } Customer customer = (Customer) session.getAttribute("customer"); return new ModelAndView("Customer/account-transaction", "customer", customer); } } package binary_search; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; /** * * @author exponential-e * 백준 14786번: Ax+Bsin(x)=C * * @see https://www.acmicpc.net/problem/14786/ * */ public class Boj14786 { private static final int INF = 1_000_000_000; public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); int C = Integer.parseInt(st.nextToken()); System.out.println(triangularFunction(A, B, C)); } private static double triangularFunction(double a, double b, double c){ double left = (c - b) / a; double right = (c + b) / a; double result = 0; for(; left <= right; left++){ int start = 0, end = INF; while(start <= end){ int mid = (start + end) / 2; double x = (mid / (double) INF) + left; // make x with decimal point double temp = makeValue(a, b, x); if(temp > c) { end = mid - 1; } else { start = mid + 1; result = x; } } } return result; } private static double makeValue(double a, double b, double x){ return a * x + b * Math.sin(x); } } package vdsMain.transaction; import bitcoin.script.CScript; public class SignatureData { //f12370a public CScript cScript = new CScript(); //f12371b public CScriptWitness cScriptWitness = new CScriptWitness(); /* renamed from: c */ public CScript f12372c = new CScript(); /* renamed from: d */ public boolean f12373d = true; }/* * Copyright 2017 The OpenDSP Project * * The OpenDSP Project 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 mobi.f2time.dorado.rest.annotation; import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * * @author wangwp */ @Documented @Retention(RUNTIME) @Target({ METHOD, ANNOTATION_TYPE }) public @interface HttpMethod { /** * HTTP GET method */ public static final String GET = "GET"; /** * HTTP POST method */ public static final String POST = "POST"; /** * HTTP PUT method */ public static final String PUT = "PUT"; /** * HTTP DELETE method */ public static final String DELETE = "DELETE"; /** * HTTP HEAD method */ public static final String HEAD = "HEAD"; /** * HTTP OPTIONS method */ public static final String OPTIONS = "OPTIONS"; /** * Specifies the name of a HTTP method. E.g. "GET". */ String value(); } src/main/java/org/jorge/lolin1dp/io/net/HTTPRequestsSingleton.java package org.jorge.lolin1dp.io.net; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import java.io.IOException; public final class HTTPRequestsSingleton { private static final Object LOCK = new Object(); public static final Integer IN_PLACE_ERROR_STATUS_CODE = 666; private static volatile HTTPRequestsSingleton mInstance; private final OkHttpClient mClient; private HTTPRequestsSingleton() { mClient = new OkHttpClient(); } public static HTTPRequestsSingleton getInstance() { HTTPRequestsSingleton ret = mInstance; if (ret == null) { synchronized (LOCK) { ret = mInstance; if (ret == null) { ret = new HTTPRequestsSingleton(); mInstance = ret; } } } return ret; } public Response performRequest(Request request) { try { return mClient.newCall(request).execute(); } catch (IOException e) { e.printStackTrace(System.err); return new Response.Builder().code(IN_PLACE_ERROR_STATUS_CODE).build(); } } } /* (c) https://github.com/MontiCore/monticore */ package de.monticore.generating.templateengine.reporting.reporter; import de.monticore.ast.ASTNode; import de.monticore.generating.templateengine.reporting.commons.AReporter; import de.monticore.generating.templateengine.reporting.commons.ReportingConstants; import java.io.File; public class SuccessfulReporter extends AReporter { static final String SIMPLE_FILE_NAME = "19_Successful"; public SuccessfulReporter(String outputDir, String modelName) { super(outputDir + File.separator + modelName, SIMPLE_FILE_NAME, ReportingConstants.REPORT_FILE_EXTENSION); } /** * @see de.monticore.generating.templateengine.reporting.commons.DefaultReportEventHandler#reportModelStart(de.monticore.ast.ASTNode, java.lang.String, java.lang.String) */ @Override public void reportModelStart(ASTNode ast, String modelName, String fileName) { reportingHelper.deleteFile(SIMPLE_FILE_NAME, ReportingConstants.REPORT_FILE_EXTENSION); } /** * @see de.monticore.generating.templateengine.reporting.commons.DefaultReportEventHandler#reportModelEnd(java.lang.String, java.lang.String) */ @Override public void reportModelEnd(String modelname, String filename) { writeLine("#Successful generation"); } /** * @see de.monticore.generating.templateengine.reporting.commons.AReporter#writeHeader() */ @Override protected void writeHeader() { } } package org.solovyev.android.drag; import android.support.annotation.NonNull; public final class Intervals { private Intervals() { throw new AssertionError(); } @NonNull public static > Interval newPoint(@NonNull T point) { return newInstance(IntervalLimit.create(point, true), IntervalLimit.create(point, true)); } @NonNull public static > Interval newInterval(@NonNull T left, boolean leftClosed, @NonNull T right, boolean rightClosed) { return newInstance(newLimit(left, leftClosed), newLimit(right, rightClosed)); } @NonNull public static > Interval newClosedInterval(@NonNull T left, @NonNull T right) { return newInstance(newClosedLimit(left), newClosedLimit(right)); } @NonNull public static > IntervalLimit newClosedLimit(@NonNull T value) { return newLimit(value, true); } @NonNull public static > IntervalLimit newLimit(@NonNull T value, boolean closed) { return IntervalLimit.create(value, closed); } @NonNull public static > IntervalLimit newOpenedLimit(@NonNull T value) { return newLimit(value, false); } @NonNull public static > Interval newInstance(@NonNull IntervalLimit left, @NonNull IntervalLimit right) { return Interval.create(left, right); } @NonNull public static > IntervalLimit newLowestLimit() { return IntervalLimit.newLowest(); } @NonNull public static > IntervalLimit newHighestLimit() { return IntervalLimit.newHighest(); } } package com.sj.time; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; /* * Utilities for Time, such as Date, Calendar. * */ public class DateTimeUtils { private static final int HOURS_PER_DAY = 24; private static final int MINUTES_PER_HOUR = 60; private static final int SECONDS_PER_MINUTE = 60; private static final int MILLISECONDS_PER_SECOND = 1000; public static final long SECOND = MILLISECONDS_PER_SECOND; public static final long MINUTE = SECOND * SECONDS_PER_MINUTE; public static final long HOUR = MINUTE * MINUTES_PER_HOUR; public static final long DAY = HOUR * HOURS_PER_DAY; public static final long AM_09 = HOUR * 9; public static final long PM_05 = HOUR * 17; public static long compoundTime(long hour, long min) { return hour * HOUR + min * MINUTE; } static long compoundTime(long hour, long min, long sec) { return hour * HOUR + min * MINUTE + sec * SECOND; } static long[] getTime(long time) { long hour = time / HOUR; long min = (time - hour * HOUR) / MINUTE; return new long[]{hour, min}; } public static String formatRefTime(long time) { long hour = time / HOUR; long min = (time - hour * HOUR) / MINUTE; return String.format(Locale.getDefault(), "%02d:%02d", hour, min); } public static String formatTime(Date date) { return String.format(Locale.getDefault(), "%02d:%02d", date.getHours(), date.getMinutes()); } public static String formatTime(long time) { Date date = new Date(); date.setTime(time); return String.format(Locale.getDefault(), "%02d:%02d", date.getHours(), date.getMinutes()); } public static String formatDate(long time) { Date date = new Date(); date.setTime(time); return formatDate(date); } public static String formatDate(Date date) { String str; if (date == null) { date = new Date(); } SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd", Locale.getDefault()); str = sdf.format(date); return str; } public static long compoundTime(long offset) { Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); int day = calendar.get(Calendar.DAY_OF_MONTH); calendar.clear(); calendar.set(year, month, day); return calendar.getTimeInMillis() + offset; } public static long timeInMillisByDate(Date date) { return date.getHours() * DateTimeUtils.HOUR + date.getMinutes() * DateTimeUtils.MINUTE + date.getSeconds() * DateTimeUtils.SECOND; } public static String formatTime(int hour, int minute) { return String.format(Locale.getDefault(), "%02d:%02d", hour, minute); } static public long getDayDate(Date date) { long timeInMillis = 0; Calendar calendar = Calendar.getInstance(); calendar.setTime(date); { int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); int day = calendar.get(Calendar.DAY_OF_MONTH); Calendar cal = (Calendar) calendar.clone(); cal.clear(); cal.set(year, month, day); timeInMillis = cal.getTimeInMillis(); } return timeInMillis; } public static long getDayTime(Date date) { long tmp = getDayDate(date); return date.getTime() - tmp; } public static int getHour(long refTime) { return (int) (refTime / HOUR); } public static int getMinute(long refTime) { return (int) (refTime % HOUR); } } /******************************************************************************* * Copyright C 2012, The Pistoia Alliance * * 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 org.helm.editor.componentPanel.sequenceviewpanel; import java.util.List; import java.util.Map; import y.base.Node; import y.view.Graph2D; import org.helm.editor.mapping.GraphMapper; public interface SequenceViewModel extends GraphMapper { // public static final String EDGETYPE_REGULAR = "Regular"; // public static final String EDGETYPE_PNODE = "modified phosphate"; // public static final String EDGETYPE_PAIR = "Pair"; public static final Object MODIFICATION_COUNT = "ModificationCount"; public static final Object COMPLEMENTARY_VIEW_NODE = "ComplementaryViewNode"; public static final Object IS_FLIPPED = "IsFlipped"; public static final String LABELS_MAP = "edeg-label map"; public List getStartingViewNodeList(); public void addStrartingViewNode(Node viewNode); public Node getViewNode(Node src); public void putViewNode(Node srcNode, Node viewNode); public Map getEditorViewMap(); public Node getComplementaryViewNode(Node viewNode); public void addComplentaryViewNodes(Node srcViewNode, Node tgtViewNode); public Graph2D getGraph(); public List transform(Node srcNode); } craping/jeeves package com.cherry.jeeves.service; import java.io.IOException; import java.net.URISyntaxException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.stream.Collectors; import javax.annotation.PostConstruct; import org.apache.commons.lang3.StringEscapeUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import com.cherry.jeeves.domain.response.BatchGetContactResponse; import com.cherry.jeeves.domain.response.SyncCheckResponse; import com.cherry.jeeves.domain.response.SyncResponse; import com.cherry.jeeves.domain.response.VerifyUserResponse; import com.cherry.jeeves.domain.shared.ChatRoomDescription; import com.cherry.jeeves.domain.shared.Contact; import com.cherry.jeeves.domain.shared.Message; import com.cherry.jeeves.domain.shared.RecommendInfo; import com.cherry.jeeves.domain.shared.VerifyUser; import com.cherry.jeeves.enums.AppMessageType; import com.cherry.jeeves.enums.MessageType; import com.cherry.jeeves.enums.RetCode; import com.cherry.jeeves.enums.Selector; import com.cherry.jeeves.enums.StatusNotifyCode; import com.cherry.jeeves.service.disruptor.MsgEvent; import com.cherry.jeeves.utils.WechatUtils; import com.lmax.disruptor.BlockingWaitStrategy; import com.lmax.disruptor.dsl.Disruptor; import com.lmax.disruptor.dsl.ProducerType; import com.lmax.disruptor.util.DaemonThreadFactory; @Component public class SyncServie { private static final Logger logger = LoggerFactory.getLogger(SyncServie.class); @Autowired private CacheService cacheService; @Autowired private WechatHttpServiceInternal wechatHttpService; @Autowired(required = false) private MessageHandler messageHandler; @Value("${wechat.url.get_msg_img}") private String WECHAT_URL_GET_MSG_IMG; @Value("${wechat.url.get_voice}") private String WECHAT_URL_GET_VOICE; @Value("${wechat.url.get_video}") private String WECHAT_URL_GET_VIDEO; @Value("${wechat.url.get_media}") private String WECHAT_URL_GET_MEDIA; // private final static String RED_PACKET_CONTENT = "收到红包,请在手机上查看"; //Disruptor环形数组队列大小 private static final int BUFFER_SIZE = 128; private static final Map EVENTS = new HashMap<>(); public static final Disruptor DISRUPTOR = new Disruptor<>(MsgEvent::new, BUFFER_SIZE, DaemonThreadFactory.INSTANCE, ProducerType.SINGLE, new BlockingWaitStrategy()); @PostConstruct public void setMessageHandler() { if (messageHandler == null) { this.messageHandler = new DefaultMessageHandler(); } } public void listen() throws IOException, URISyntaxException { SyncCheckResponse syncCheckResponse = wechatHttpService.syncCheck(); if(syncCheckResponse == null) return; int retCode = syncCheckResponse.getRetcode(); int selector = syncCheckResponse.getSelector(); logger.info(String.format("[SYNCCHECK] retcode = %s, selector = %s", retCode, selector)); if (retCode == RetCode.NORMAL.getCode()) { //有新消息 if (selector == Selector.NORMAL.getCode()) { return; } else { sync(); } } else if(retCode == RetCode.LOGOUT1.getCode() || retCode == RetCode.LOGOUT2.getCode() || retCode == RetCode.LOGOUT3.getCode()) { this.messageHandler.onLogout(cacheService.getOwner()); cacheService.setAlive(false); logger.info(String.format("[Logout] syncCheckResponse ret = %s", retCode)); // throw new WechatException("syncCheckResponse ret = " + retCode); } } private void sync() { SyncResponse syncResponse = wechatHttpService.sync(null); logger.debug(String.format("[SYNC DONE] syncResponse msg count=%s; mod count=%s; del count=%s;", syncResponse.getAddMsgCount(), syncResponse.getModContactCount(), syncResponse.getDelContactCount())); logger.debug(String.format("[SYNC DONE] syncResponse ret=%s; errMsg=%s;", syncResponse.getBaseResponse().getRet(), syncResponse.getBaseResponse().getErrMsg())); // WechatUtils.checkBaseResponse(syncResponse); logger.debug("[SYNC CHECK]"); cacheService.setSyncKey(syncResponse.getSyncKey()); cacheService.setSyncCheckKey(syncResponse.getSyncCheckKey()); EVENTS.clear(); logger.debug(String.format("[EVENTS CLEAR] events size= %s", EVENTS.size())); if (syncResponse.getModContactCount() > 0) { syncResponse.getModContactList().forEach(c -> { int hashCode = c.getUserName().hashCode() & Integer.MAX_VALUE; MsgEvent msg = EVENTS.get(hashCode); if (msg == null) { msg = new MsgEvent(hashCode); EVENTS.put(hashCode, msg); } msg.getModContactList().add(c); }); logger.debug(String.format("[MOD DONE] events size= %s", EVENTS.size())); } if (syncResponse.getDelContactCount() > 0) { syncResponse.getDelContactList().forEach(c -> { int hashCode = c.getUserName().hashCode() & Integer.MAX_VALUE; MsgEvent msg = EVENTS.get(hashCode); if (msg == null) { msg = new MsgEvent(hashCode); EVENTS.put(hashCode, msg); } msg.getDelContactList().add(c); }); logger.debug(String.format("[DEL DONE] events size= %s", EVENTS.size())); } for (Message message : syncResponse.getAddMsgList()){ int hashCode = message.getFromUserName().hashCode() & Integer.MAX_VALUE; MsgEvent msg = EVENTS.get(hashCode); if (msg == null) { msg = new MsgEvent(hashCode); EVENTS.put(hashCode, msg); } msg.getAddMsgList().add(message); logger.debug(String.format("[MSG DONE] events size= %s", EVENTS.size())); } EVENTS.forEach((k, v) -> { logger.debug(String.format("[PUT EVENTS] event hash = %s", k)); DISRUPTOR.getRingBuffer().publishEvent((event, sequence, data) -> { event.setHash(data.getHash()); event.setAddMsgList(data.getAddMsgList()); event.setModContactList(data.getModContactList()); event.setDelContactList(data.getDelContactList()); }, v); }); logger.debug(String.format("[PUT EVENTS DONE] DISRUPTOR range = %s", (DISRUPTOR.getRingBuffer().getMinimumGatingSequence() + "-" + DISRUPTOR.getRingBuffer().getCursor()))); } private void acceptFriendInvitation(RecommendInfo info) throws IOException, URISyntaxException { VerifyUser user = new VerifyUser(); user.setValue(info.getUserName()); user.setVerifyUserTicket(info.getTicket()); VerifyUserResponse verifyUserResponse = wechatHttpService.acceptFriend(new VerifyUser[]{user} ); WechatUtils.checkBaseResponse(verifyUserResponse); } private boolean isMessageFromIndividual(Message message) { return message.getFromUserName() != null && message.getFromUserName().startsWith("@") && !message.getFromUserName().startsWith("@@"); } private boolean isMessageFromChatRoom(Message message) { return (message.getFromUserName() != null && message.getFromUserName().startsWith("@@")) || (message.getToUserName() != null && message.getToUserName().startsWith("@@")); } public void onNewMessage(Collection msgs) throws IOException, URISyntaxException { if (messageHandler == null) { return; } msgs.forEach(message -> { try { //如果群列表不在最近聊天中则拉取 if (isMessageFromChatRoom(message)) { String chatRoomUserName = message.getFromUserName().contains("@@")?message.getFromUserName():message.getToUserName(); if(cacheService.getChatRoom(chatRoomUserName) == null){ ChatRoomDescription description = new ChatRoomDescription(); description.setUserName(chatRoomUserName); ChatRoomDescription[] descriptions = new ChatRoomDescription[]{description}; BatchGetContactResponse response = wechatHttpService.batchGetContact(descriptions); for (Contact c : response.getContactList()) { cacheService.getChatRooms().add(c); } messageHandler.onStatusNotifySyncConv(message); } } //文本消息 if (message.getMsgType() == MessageType.TEXT.getCode()) { //群 if (isMessageFromChatRoom(message)) { messageHandler.onReceivingChatRoomTextMessage(message); } //个人 else if (isMessageFromIndividual(message)) { messageHandler.onReceivingPrivateTextMessage(message); } } //图片 else if (message.getMsgType() == MessageType.IMAGE.getCode() || message.getAppMsgType() == AppMessageType.IMG.getCode()) { String fullImageUrl = String.format(WECHAT_URL_GET_MSG_IMG, cacheService.getHostUrl(), message.getMsgId(), cacheService.getsKey()); String thumbImageUrl = fullImageUrl + "&type=slave"; //群 if (isMessageFromChatRoom(message)) { messageHandler.onReceivingChatRoomImageMessage(message, thumbImageUrl, fullImageUrl); } //个人 else if (isMessageFromIndividual(message)) { messageHandler.onReceivingPrivateImageMessage(message, thumbImageUrl, fullImageUrl); } } //表情 else if (message.getMsgType() == MessageType.EMOTICON.getCode() || message.getAppMsgType() == AppMessageType.EMOJI.getCode()) { String emoticonUrl = String.format(WECHAT_URL_GET_MSG_IMG, cacheService.getHostUrl(), message.getMsgId(), cacheService.getsKey()); emoticonUrl = emoticonUrl + "&type=big"; //群 if (isMessageFromChatRoom(message)) { messageHandler.onReceivingChatRoomEmoticonMessage(message, emoticonUrl); } //个人 else if (isMessageFromIndividual(message)) { messageHandler.onReceivingPrivateEmoticonMessage(message, emoticonUrl); } } //语音消息 else if (message.getMsgType() == MessageType.VOICE.getCode()) { String voiceUrl = String.format(WECHAT_URL_GET_VOICE, cacheService.getHostUrl(), message.getMsgId(), cacheService.getsKey()); //群 if (isMessageFromChatRoom(message)) { messageHandler.onReceivingChatRoomVoiceMessage(message, voiceUrl); } //个人 else if (isMessageFromIndividual(message)) { messageHandler.onReceivingPrivateVoiceMessage(message, voiceUrl); } } //视频消息 else if (message.getMsgType() == MessageType.VIDEO.getCode() || message.getMsgType() == MessageType.MICROVIDEO.getCode()) { String videoUrl = String.format(WECHAT_URL_GET_VIDEO, cacheService.getHostUrl(), message.getMsgId(), cacheService.getsKey()); String thumbImageUrl = String.format(WECHAT_URL_GET_MSG_IMG, cacheService.getHostUrl(), message.getMsgId(), cacheService.getsKey()) + "&type=slave"; //群 if (isMessageFromChatRoom(message)) { messageHandler.onReceivingChatRoomVideoMessage(message, thumbImageUrl, videoUrl); } //个人 else if (isMessageFromIndividual(message)) { messageHandler.onReceivingPrivateVideoMessage(message, thumbImageUrl, videoUrl); } } //多媒体(文件)消息 else if (message.getMsgType() == MessageType.APP.getCode()) { String thumbImageUrl = String.format(WECHAT_URL_GET_MSG_IMG, cacheService.getHostUrl(), message.getMsgId(), cacheService.getsKey()) + "&type=slave"; String mediaUrl; if(message.getAppMsgType() == AppMessageType.URL.getCode()) mediaUrl = StringEscapeUtils.unescapeHtml4(message.getUrl()); else mediaUrl = String.format(WECHAT_URL_GET_MEDIA, cacheService.getFileUrl(), message.getFromUserName(), message.getMediaId(), escape(message.getFileName()), cacheService.getPassTicket()); //群 if (isMessageFromChatRoom(message)) { messageHandler.onReceivingChatRoomMediaMessage(message, thumbImageUrl, mediaUrl); } //个人 else if (isMessageFromIndividual(message)) { messageHandler.onReceivingPrivateMediaMessage(message, thumbImageUrl, mediaUrl); } } //好友邀请 else if (message.getMsgType() == MessageType.VERIFYMSG.getCode() && cacheService.getOwner().getUserName().equals(message.getToUserName())) { if (messageHandler.onReceivingFriendInvitation(message.getRecommendInfo())) { acceptFriendInvitation(message.getRecommendInfo()); logger.info("[*] you've accepted the invitation"); messageHandler.postAcceptFriendInvitation(message); } else { logger.info("[*] you've declined the invitation"); } } //状态同步消息 else if (message.getMsgType() == MessageType.STATUSNOTIFY.getCode()) { // 消息已读 if (message.getStatusNotifyCode() == StatusNotifyCode.READED.getCode()) { messageHandler.onStatusNotifyReaded(message); } // 发起会话 else if (message.getStatusNotifyCode() == StatusNotifyCode.ENTER_SESSION.getCode()) { messageHandler.onStatusNotifyEnterSession(message); } //正在输入 else if (message.getStatusNotifyCode() == StatusNotifyCode.INITED.getCode()) { messageHandler.onStatusNotifyInited(message); } // 同步通讯录 else if (message.getStatusNotifyCode() == StatusNotifyCode.SYNC_CONV.getCode()) { Set chatRooms = Arrays.stream(message.getStatusNotifyUserName().split(",")) .filter(x -> x != null && x.startsWith("@@")).map(x -> { Contact contact = new Contact(); contact.setUserName(x); return contact; }).collect(Collectors.toSet()); while (true) { ChatRoomDescription[] chatRoomDescriptions = chatRooms.stream() .filter(x -> x.getEncryChatRoomId() == null || x.getEncryChatRoomId().isEmpty()) .limit(50) .map(x -> { ChatRoomDescription description = new ChatRoomDescription(); description.setUserName(x.getUserName()); return description; }).toArray(ChatRoomDescription[]::new); if (chatRoomDescriptions.length > 0) { BatchGetContactResponse response = wechatHttpService.batchGetContact(chatRoomDescriptions); if(response == null || response.getCount() == 0 || response.getContactList().stream().filter(m -> m.getHeadImgUrl() == null || m.getHeadImgUrl().isEmpty()).count() > 0) break; WechatUtils.checkBaseResponse(response); response.getContactList().forEach(x -> { chatRooms.remove(x); cacheService.getChatRooms().remove(x); cacheService.getChatRooms().add(x); }); } else { break; } } messageHandler.onStatusNotifySyncConv(message); } //关闭会话 else if (message.getStatusNotifyCode() == StatusNotifyCode.QUIT_SESSION.getCode()) { messageHandler.onStatusNotifyQuitSession(message); } } //系统消息 else if (message.getMsgType() == MessageType.SYS.getCode()) { //红包 if (message.getAppMsgType() == AppMessageType.RED_ENVELOPES.getCode()) { logger.info("[*] you've received a red packet"); String from = message.getFromUserName(); ConcurrentLinkedQueue contacts = null; //群 if (isMessageFromChatRoom(message)) { contacts = cacheService.getChatRooms(); } //个人 else if (isMessageFromIndividual(message)) { contacts = cacheService.getIndividuals(); } if (contacts != null) { Contact contact = contacts.stream().filter(x -> Objects.equals(x.getUserName(), from)).findAny().orElse(null); messageHandler.onRedPacketReceived(contact); } } //被对方删除 else if(message.getContent() != null && message.getContent().contains("开启了朋友验证")){ String from = message.getFromUserName(); ConcurrentLinkedQueue contacts = null; //群 if (isMessageFromChatRoom(message)) { contacts = cacheService.getChatRooms(); } //个人 else if (isMessageFromIndividual(message)) { contacts = cacheService.getIndividuals(); } if (contacts != null) { Contact contact = contacts.stream().filter(x -> Objects.equals(x.getUserName(), from)).findAny().orElse(null); messageHandler.onFriendVerify(contact); } } //被对方拉黑 else if(message.getContent() != null && message.getContent().contains("但被对方拒收了")){ String from = message.getFromUserName(); ConcurrentLinkedQueue contacts = null; //群 if (isMessageFromChatRoom(message)) { contacts = cacheService.getChatRooms(); } //个人 else if (isMessageFromIndividual(message)) { contacts = cacheService.getIndividuals(); } if (contacts != null) { Contact contact = contacts.stream().filter(x -> Objects.equals(x.getUserName(), from)).findAny().orElse(null); messageHandler.onFriendBlacklist(contact); } } } } catch (Exception e) { logger.error("onNewMessage exception", e); } }); } public void onContactsModified(Collection contacts) { Set individuals = new HashSet<>(); Set chatRooms = new HashSet<>(); Set mediaPlatforms = new HashSet<>(); for (Contact contact : contacts) { if (WechatUtils.isIndividual(contact)) { individuals.add(contact); } else if (WechatUtils.isMediaPlatform(contact)) { mediaPlatforms.add(contact); } else if (WechatUtils.isChatRoom(contact)) { chatRooms.add(contact); } } Map seqMap = new HashMap<>(); //individual if (individuals.size() > 0) { ConcurrentLinkedQueue existingIndividuals = cacheService.getIndividuals(); Set newIndividuals = individuals.stream().filter(x -> !existingIndividuals.contains(x)).collect(Collectors.toSet()); Set modifiedIndividuals = individuals.stream().filter(x -> existingIndividuals.contains(x)).collect(Collectors.toSet()); individuals.forEach(x -> { //更新seq唯一值 for (Contact c : existingIndividuals) { if(x.equals(c) && x.getSeq() != null && !x.getSeq().equals("0") && !x.getSeq().equals(c.getSeq())){ seqMap.put(c.getSeq(), x.getSeq()); break; } } existingIndividuals.remove(x); existingIndividuals.add(x); }); if (messageHandler != null && newIndividuals.size() > 0) { messageHandler.onNewFriendsFound(newIndividuals); } if (messageHandler != null && modifiedIndividuals.size() > 0) { messageHandler.onFriendsModify(modifiedIndividuals); } } //chatroom if (chatRooms.size() > 0) { ConcurrentLinkedQueue existingChatRooms = cacheService.getChatRooms(); Set newChatRooms = new HashSet<>(); Set modifiedChatRooms = new HashSet<>(); chatRooms.forEach(x -> { Contact existChatRoom = existingChatRooms.stream().filter(c -> c.equals(x)).findFirst().orElse(null); if(existChatRoom != null){ //更新seq唯一值 if(x.getSeq() != null && !x.getSeq().equals("0") && !x.getSeq().equals(existChatRoom.getSeq())){ seqMap.put(existChatRoom.getSeq(), x.getSeq()); } modifiedChatRooms.add(x); }else{ newChatRooms.add(x); } }); //获取新群EncryChatRoomId while (true) { ChatRoomDescription[] chatRoomDescriptions = newChatRooms.stream() .filter(x -> x.getEncryChatRoomId() == null || x.getEncryChatRoomId().isEmpty()) .limit(50) .map(x -> { ChatRoomDescription description = new ChatRoomDescription(); description.setUserName(x.getUserName()); return description; }).toArray(ChatRoomDescription[]::new); if (chatRoomDescriptions.length > 0) { BatchGetContactResponse response = wechatHttpService.batchGetContact(chatRoomDescriptions); if(response == null || response.getCount() == 0 || response.getContactList().stream().filter(m -> m.getHeadImgUrl() == null || m.getHeadImgUrl().isEmpty()).count() > 0) break; response.getContactList().forEach(x -> { newChatRooms.remove(x); newChatRooms.add(x); existingChatRooms.add(x); }); } else { break; } } // //添加新群 // if(newChatRooms.size() > 0) // existingChatRooms.addAll(newChatRooms); if (messageHandler != null && newChatRooms.size() > 0) { messageHandler.onNewChatRoomsFound(newChatRooms); } for (Contact chatRoom : modifiedChatRooms) { Contact existingChatRoom = existingChatRooms.stream().filter(x -> x.getUserName().equals(chatRoom.getUserName())).findFirst().orElse(null); if (existingChatRoom == null) { continue; } chatRoom.setEncryChatRoomId(existingChatRoom.getEncryChatRoomId()); if(chatRoom.getSeq() == null || "0".equals(chatRoom.getSeq())) chatRoom.setHeadImgUrl(existingChatRoom.getHeadImgUrl()); ConcurrentLinkedQueue oldMembers = existingChatRoom.getMemberList(); ConcurrentLinkedQueue newMembers = chatRoom.getMemberList(); Set joined = newMembers.stream().filter(x -> !oldMembers.contains(x)).collect(Collectors.toSet()); Set left = oldMembers.stream().filter(x -> !newMembers.contains(x)).collect(Collectors.toSet()); oldMembers.removeAll(left); oldMembers.addAll(joined); chatRoom.setMemberList(oldMembers); existingChatRooms.remove(existingChatRoom); existingChatRooms.add(chatRoom); if (messageHandler != null) { if (joined.size() > 0 || left.size() > 0) { messageHandler.onChatRoomMembersChanged(chatRoom, joined, left); } } } if (messageHandler != null && modifiedChatRooms.size() > 0) { messageHandler.onChatRoomsModify(modifiedChatRooms); } // for (Contact chatRoom : modifiedChatRooms) { // Contact existingChatRoom = existingChatRooms.stream().filter(x -> x.getUserName().equals(chatRoom.getUserName())).findFirst().orElse(null); // if (existingChatRoom == null) { // continue; // } // //获取变动消息中的群主信息 // existingChatRoom.setChatRoomOwner(chatRoom.getChatRoomOwner()); // existingChatRoom.setNickName(chatRoom.getNickName()); // // ConcurrentLinkedQueue oldMembers = existingChatRoom.getMemberList(); // ConcurrentLinkedQueue newMembers = chatRoom.getMemberList(); // Set joined = newMembers.stream().filter(x -> !oldMembers.contains(x)).collect(Collectors.toSet()); // Set left = oldMembers.stream().filter(x -> !newMembers.contains(x)).collect(Collectors.toSet()); // oldMembers.removeAll(left); // // //获取新加入成员头像信息 // if(joined.size() > 0){ // while (true) { // ChatRoomDescription[] chatRoomDescriptions = joined.stream().filter(x -> x.getHeadImgUrl() == null || x.getHeadImgUrl().isEmpty()) // .limit(50) // .map(x -> { // ChatRoomDescription description = new ChatRoomDescription(); // description.setEncryChatRoomId(existingChatRoom.getEncryChatRoomId()); // description.setUserName(x.getUserName()); // return description; // }).toArray(ChatRoomDescription[]::new); // if (chatRoomDescriptions.length > 0) { // BatchGetContactResponse batchGetContactResponse = wechatHttpService.batchGetContact(chatRoomDescriptions); // if(batchGetContactResponse.getCount() == 0) // break; // WechatUtils.checkBaseResponse(batchGetContactResponse); // logger.info("[joined] batchGetContactResponse count = " + batchGetContactResponse.getCount()); // batchGetContactResponse.getContactList().forEach(x -> { // joined.remove(x); // joined.add(x); // oldMembers.add(x); // }); // } else { // break; // } // } // } // // if (messageHandler != null) { // if (joined.size() > 0 || left.size() > 0) { // messageHandler.onChatRoomMembersChanged(chatRoom, joined, left); // } // } // } } if (mediaPlatforms.size() > 0) { //media platform ConcurrentLinkedQueue existingPlatforms = cacheService.getMediaPlatforms(); Set newMediaPlatforms = existingPlatforms.stream().filter(x -> !existingPlatforms.contains(x)).collect(Collectors.toSet()); mediaPlatforms.forEach(x -> { existingPlatforms.remove(x); existingPlatforms.add(x); }); if (messageHandler != null && newMediaPlatforms.size() > 0) { messageHandler.onNewMediaPlatformsFound(newMediaPlatforms); } } if (messageHandler != null && seqMap.size() > 0) { messageHandler.onMembersSeqChanged(seqMap); } } public void onContactsDeleted(Collection contacts) { Set individuals = new HashSet<>(); Set chatRooms = new HashSet<>(); Set mediaPlatforms = new HashSet<>(); for (Contact contact : contacts) { if (WechatUtils.isIndividual(contact)) { individuals.add(contact); cacheService.getIndividuals().remove(contact); } else if (WechatUtils.isChatRoom(contact)) { chatRooms.add(contact); cacheService.getChatRooms().remove(contact); } else if (WechatUtils.isMediaPlatform(contact)) { mediaPlatforms.add(contact); cacheService.getMediaPlatforms().remove(contact); } } if (messageHandler != null) { if (individuals.size() > 0) { messageHandler.onFriendsDeleted(individuals); } if (chatRooms.size() > 0) { messageHandler.onChatRoomsDeleted(chatRooms); } if (mediaPlatforms.size() > 0) { messageHandler.onMediaPlatformsDeleted(mediaPlatforms); } } } private String escape(String str) throws IOException { return URLEncoder.encode(str, StandardCharsets.UTF_8.toString()); } public MessageHandler getMessageHandler() { return messageHandler; } public void setMessageHandler(MessageHandler messageHandler) { this.messageHandler = messageHandler; } } /* * MIT License * * Copyright (c) 2016. * * 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.adkdevelopment.earthquakesurvival.ui; import android.Manifest; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.util.Pair; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.adkdevelopment.earthquakesurvival.R; import com.adkdevelopment.earthquakesurvival.data.objects.earthquake.Feature; import com.adkdevelopment.earthquakesurvival.data.provider.earthquake.EarthquakeColumns; import com.adkdevelopment.earthquakesurvival.utils.LocationUtils; import com.adkdevelopment.earthquakesurvival.utils.Utilities; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapView; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.UiSettings; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.maps.android.kml.KmlLayer; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import butterknife.BindDrawable; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.Unbinder; import rx.Observable; import rx.Subscriber; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; /** * Fragment with a map which monitors location changes and updates the view */ public class MapviewFragment extends Fragment implements OnMapReadyCallback, LoaderManager.LoaderCallbacks, SharedPreferences.OnSharedPreferenceChangeListener { /** * The fragment argument representing the section number for this * fragment. */ private static final String TAG = MapviewFragment.class.getSimpleName(); private static final String ARG_SECTION_NUMBER = "section_number"; public static final String CAMERA_POSITION = "camera"; public static final int LOCATION_PERMISSION = 12223; private GoogleMap mGoogleMap; private CameraPosition mCameraPosition; private Cursor mCursor; private static final int CURSOR_LOADER_ID = 20; @BindView(R.id.map) MapView mMapView; @BindDrawable(R.drawable.marker) Drawable mOval; private Unbinder mUnbinder; // data to start detail activity on info window click private HashMap mMarkersIntents = new HashMap<>(); private List mMarkers; private KmlLayer mFaults; private Subscription mSubscription; public MapviewFragment() { } /** * Returns a new instance of this fragment for the given section * number. */ public static MapviewFragment newInstance(int sectionNumber) { MapviewFragment fragment = new MapviewFragment(); Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, sectionNumber); fragment.setArguments(args); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.map_fragment, container, false); mUnbinder = ButterKnife.bind(this, rootView); mMarkers = new ArrayList<>(); if (Utilities.checkPlayServices(getActivity())) { mMapView.onCreate(savedInstanceState); mMapView.getMapAsync(this); } if (savedInstanceState != null) { mCameraPosition = savedInstanceState.getParcelable(CAMERA_POSITION); } else { mCameraPosition = CameraPosition.builder() .target(LocationUtils.getLocation(getContext())) .zoom(LocationUtils.CAMERA_DEFAULT_ZOOM) .build(); } return rootView; } @Override public void onMapReady(GoogleMap googleMap) { mGoogleMap = googleMap; UiSettings uiSettings = mGoogleMap.getUiSettings(); uiSettings.setZoomControlsEnabled(true); addMyLocation(); uiSettings.setMyLocationButtonEnabled(true); if (mCameraPosition != null) { mGoogleMap.moveCamera(CameraUpdateFactory.newCameraPosition(mCameraPosition)); } addMarkersObservable(); showFaultlines(); } /** * Adds my location button to the MapView. */ private void addMyLocation() { if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_PERMISSION); } else { mGoogleMap.setMyLocationEnabled(true); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { switch (requestCode) { case LOCATION_PERMISSION: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { addMyLocation(); } } } } @Override public void onResume() { super.onResume(); mMapView.onResume(); PreferenceManager.getDefaultSharedPreferences(getContext()) .registerOnSharedPreferenceChangeListener(this); } @Override public void onPause() { super.onPause(); mMapView.onPause(); } @Override public void onLowMemory() { super.onLowMemory(); mMapView.onLowMemory(); } @Override public void onDestroy() { super.onDestroy(); if (mSubscription != null && !mSubscription.isUnsubscribed()) { mSubscription.unsubscribe(); } mMapView.onDestroy(); mUnbinder.unbind(); PreferenceManager.getDefaultSharedPreferences(getContext()) .unregisterOnSharedPreferenceChangeListener(this); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mGoogleMap != null) { CameraPosition save = mGoogleMap.getCameraPosition(); outState.putParcelable(CAMERA_POSITION, save); } } @Override public void onActivityCreated(Bundle savedInstanceState) { getLoaderManager().initLoader(CURSOR_LOADER_ID, null, this); super.onActivityCreated(savedInstanceState); } @Override public Loader onCreateLoader(int id, Bundle args) { return new CursorLoader(getActivity(), EarthquakeColumns.CONTENT_URI, null, EarthquakeColumns.MAG + " >= ?", new String[]{String.valueOf(Utilities.getMagnitudePrefs(getContext()))}, null); } @Override public void onLoadFinished(Loader loader, Cursor data) { mCursor = data; addMarkersObservable(); } /** * Loads markers from the IO thread. */ private void addMarkersObservable() { mSubscription = Observable.fromCallable(this::getMarkers) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new Subscriber, List>>() { @Override public void onCompleted() { Log.d(TAG, "onCompleted: "); } @Override public void onError(Throwable e) { e.printStackTrace(); } @Override public void onNext(Pair, List> pair) { addMarkers(pair); } }); } /** * Adds markers to the GoogleMap if it's available. * * @param pair a Pair of Lists with MarkerOptions and Intents fot InfoWindows. */ public void addMarkers(Pair, List> pair) { if (mGoogleMap != null) { //noinspection Convert2streamapi for (Marker each : mMarkers) { each.remove(); } mMarkers.clear(); List first = pair.first; for (int i = 0; i < first.size(); i++) { MarkerOptions each = first.get(i); Marker marker = mGoogleMap.addMarker(each); mMarkers.add(marker); mMarkersIntents.put(marker.getId(), pair.second.get(i)); mGoogleMap.setOnInfoWindowClickListener(l -> startActivity(mMarkersIntents.get(l.getId()))); } } } /** * Creates MarkerOptions and Intents for InfoWindows. * * @return a Pair of Lists with MarkerOptions and corresponding Intents. */ @NonNull private Pair, List> getMarkers() { List markers = new ArrayList<>(); List intents = new ArrayList<>(); if (mCursor != null) { mCursor.moveToFirst(); int lat = mCursor.getColumnIndex(EarthquakeColumns.LATITUDE); int lng = mCursor.getColumnIndex(EarthquakeColumns.LONGITUDE); int desc = mCursor.getColumnIndex(EarthquakeColumns.PLACE); int magn = mCursor.getColumnIndex(EarthquakeColumns.MAG); int date = mCursor.getColumnIndex(EarthquakeColumns.TIME); int link = mCursor.getColumnIndex(EarthquakeColumns.URL); int depth = mCursor.getColumnIndex(EarthquakeColumns.DEPTH); while (mCursor.moveToNext()) { Double latitude = mCursor.getDouble(lat); Double longitude = mCursor.getDouble(lng); String description = mCursor.getString(desc); description = Utilities.formatEarthquakePlace(description); Long dateMillis = mCursor.getLong(date); String linkDetails = mCursor.getString(link); Double magnitude = mCursor.getDouble(magn); double depthEarthquake = mCursor.getDouble(depth) / 1.6; LatLng latLng = new LatLng(latitude, longitude); String distance = getContext().getString(R.string.earthquake_distance, LocationUtils.getDistance(latLng, LocationUtils.getLocation(getContext()))); MarkerOptions markerOptions = new MarkerOptions() .position(latLng) .title(getString(R.string.earthquake_magnitude, magnitude) + ", " + Utilities.getRelativeDate(dateMillis)) .snippet(description) .icon(BitmapDescriptorFactory.fromBitmap(Utilities.getEarthquakeMarker(getContext(), magnitude))); Intent intent = new Intent(getContext(), DetailActivity.class); intent.putExtra(Feature.MAGNITUDE, magnitude); intent.putExtra(Feature.PLACE, description); intent.putExtra(Feature.DATE, Utilities.getRelativeDate(dateMillis)); intent.putExtra(Feature.LINK, linkDetails); intent.putExtra(Feature.LATLNG, latLng); intent.putExtra(Feature.DISTANCE, distance); intent.putExtra(Feature.DEPTH, depthEarthquake); markers.add(markerOptions); intents.add(intent); } } return new Pair<>(markers, intents); } @Override public void onLoaderReset(Loader loader) { mCursor = null; } /** * Shows or hides fault lines on the map. */ private void showFaultlines() { // if fault lines are enabled - show them on the map if (Utilities.getFaultlinesPrefs(getContext())) { try { mFaults = new KmlLayer(mGoogleMap, R.raw.tectonics, getContext()); mFaults.addLayerToMap(); } catch (IOException | XmlPullParserException e) { Log.e(TAG, "e:" + e); } } else if (mGoogleMap != null && mFaults != null) { mFaults.removeLayerFromMap(); } } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(getString(R.string.sharedprefs_key_magnitude))) { getLoaderManager().restartLoader(CURSOR_LOADER_ID, null, this); } else if (key.equals(getString(R.string.sharedprefs_key_latitude)) || key.equals(getString(R.string.sharedprefs_key_longitude))) { if (mGoogleMap != null) { mCameraPosition = CameraPosition.builder() .target(LocationUtils.getLocation(getContext())) .zoom(LocationUtils.CAMERA_DEFAULT_ZOOM) .build(); mGoogleMap.moveCamera(CameraUpdateFactory.newCameraPosition(mCameraPosition)); } } else if (key.equals(getString(R.string.sharedprefs_key_faultlines))) { showFaultlines(); } } } package syntaxTree.statOp; import java_cup.runtime.ComplexSymbolFactory.Location; import syntaxTree.Expr; import syntaxTree.Stat; import syntaxTree.leaf.IdConst; import visitor.Visitable; import visitor.Visitor; public class DecPostOp extends Stat implements Visitable{ private String op; private IdConst id; public DecPostOp(Location left, Location right, String op, IdConst id) { super(left,right,op,id); this.op = op; this.id = id; } public String getOp() { return op; } public void setOp(String op) { this.op = op; } public IdConst getId() { return id; } public void setId(IdConst id) { this.id = id; } @Override public Object accept(Visitor visitor) throws RuntimeException { return visitor.visit(this); } } package com.lhx.springcloud.security.dto; import com.lhx.springcloud.security.domain.JWT; import com.lhx.springcloud.security.domain.User; /** * @author lihongxu * @desc @link(https://github.com/bjlhx15/spring-cloud-base) * @since 2018/10/31 下午5:32 */ public class UserLoginDTO { private JWT jwt; private User user; public JWT getJwt() { return jwt; } public void setJwt(JWT jwt) { this.jwt = jwt; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } } skkuse-adv/2019Fall_team2 package kr.co.popone.fitts.feature.post.upload.create; import android.widget.LinearLayout; import androidx.recyclerview.widget.RecyclerView; import io.reactivex.functions.Consumer; import kotlin.jvm.internal.Intrinsics; import kr.co.popone.fitts.C0010R$id; final class CreatePostActivity$onCreate$61 implements Consumer { final /* synthetic */ CreatePostActivity this$0; CreatePostActivity$onCreate$61(CreatePostActivity createPostActivity) { this.this$0 = createPostActivity; } public final void accept(Boolean bool) { LinearLayout linearLayout = (LinearLayout) this.this$0._$_findCachedViewById(C0010R$id.post_image_insert_button); Intrinsics.checkExpressionValueIsNotNull(linearLayout, "post_image_insert_button"); Intrinsics.checkExpressionValueIsNotNull(bool, "it"); int i = 8; linearLayout.setVisibility(bool.booleanValue() ? 8 : 0); RecyclerView recyclerView = (RecyclerView) this.this$0._$_findCachedViewById(C0010R$id.post_image_list); Intrinsics.checkExpressionValueIsNotNull(recyclerView, "post_image_list"); if (bool.booleanValue()) { i = 0; } recyclerView.setVisibility(i); } } /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Aula_09_ADO_03; import Aula_08_Remocao.*; import Aula_07_insercao_busco.*; import Aula_06_ADO_02.*; /** * * @author Gabriel */ public class ListaEncadeada { private No ini; //Criar uma lista vazia public ListaEncadeada(){ this.ini=null; } //Verifica se a lista está vazia public boolean vazia(){ return this.ini == null; } @Override public String toString() { String strLista = ""; No temp = ini; while (temp != null){ strLista = strLista + temp.getElemento() + " "; temp = temp.getProx(); } return strLista; } public void insereInicio(int elemento){ No novo = new No(elemento, ini); ini = novo; } public void insereFinal(int elemento){ No novo = new No(elemento, null); No temp = ini; //Lista vazia if(temp == null){ ini = novo; } else { //Lista 1 ou mais nós while (temp.getProx() != null){ temp = temp.getProx(); } temp.setProx(novo); } } public void insereFinalR(int elemento){ insereFinalR(ini, elemento); } public void insereFinalR(No temp, int elemento){ //Lista vazia if(temp == null){ No novo = new No(elemento, null); ini = novo; return; } //Último nó if(temp.getProx() == null){ No novo = new No(elemento, null); temp.setProx(novo); return; } insereFinalR(temp.getProx(),elemento); } public void insereOrdenado(int elemento){ No novo = new No(elemento, ini); No temp = ini; No anterior = null; while(temp != null && temp.getElemento() < novo.getElemento()){ anterior = temp; temp = temp.getProx(); } //Inserção no inicio if(anterior == null){ ini = novo; } //Inserir entre 2 nós ou no final else{ novo.setProx(temp); anterior.setProx(novo); } } public void insereOrdenadaR(int elemento){ insereOrdenadaR(null,ini,elemento); } public void insereOrdenadaR(No anterior, No temp, int elemento) { //Lista Vazia if(temp == null && anterior == null){ No novo = new No(elemento, ini); ini = novo; return; } //inserção no inicio if(anterior == null && temp.getElemento() > elemento){ No novo = new No(elemento, ini); ini = novo; return; } //Inserção no final if(temp == null && anterior.getProx() == null){ No novo = new No(elemento, null); anterior.setProx(novo); return; } //Inserção entre 2 nós if(anterior != null && temp.getElemento() > elemento){ No novo = new No(elemento, ini); novo.setProx(temp); anterior.setProx(novo); return; } insereOrdenadaR(temp, temp.getProx(), elemento); } public boolean buscaLinearIT(int x){ No temp = ini; while(temp != null){ if(x == temp.getElemento()) return true; temp = temp.getProx(); } return false; } public boolean buscaLinearR(int x){ return buscarLinearR(ini,x); } public boolean buscarLinearR(No temp, int x) { if(temp.getElemento() == x){ return true; } if(temp == null){ return false; } return buscarLinearR(temp.getProx(),x); } public No buscaLinearIT2(int x){ No temp = ini; while(temp != null){ if(x == temp.getElemento()) return temp; temp = temp.getProx(); } return null; } public No buscaLinearR2(int x){ return buscarLinearR2(ini,x); } public No buscarLinearR2(No temp, int x) { if(temp == null){ return null; } if(temp.getElemento() == x){ return temp; } return buscarLinearR2(temp.getProx(),x); } public void removeInicio(){ if(vazia()){ System.out.println("Lista Vazia"); return; } ini = ini.getProx(); } public void removeFinal(){ if(vazia()){ System.out.println("Lista Vazia"); return; } No temp = ini; No anterior = null; while(temp.getProx() != null){ anterior = temp; temp = temp.getProx(); } // Alista com somente 1 nó if(anterior == null){ ini = null; return; } // A lista com 2 ou mais nós anterior.setProx(null); } public void removeFinalR(){ removeFinalR(null,ini); } public void removeFinalv2(){ if(vazia()){ System.out.println("Lista Vazia"); return; } No temp = ini; while(temp.getProx().getProx() != null){ temp = temp.getProx(); } // Alista com somente 1 nó if(temp.getProx() == null){ ini = null; return; } // A lista com 2 ou mais nós temp.setProx(null); } public void removeFinalR(No anterior, No temp) { if(vazia()){ System.out.println("Lista Vazia"); return; } if(anterior == null && temp.getProx() == null){ ini = null; return; } if(temp.getProx() == null){ anterior.setProx(null); return; } removeFinalR(temp, temp.getProx()); } public void removeFinalR2(){ removeFinalR2(ini); } public void removeFinalR2(No temp) { if(vazia()){ System.out.println("Lista Vazia"); return; } if(temp.getProx() == null ){ ini = null; return; } if(temp.getProx().getProx() == null){ temp.setProx(null); return; } removeFinalR(temp, temp.getProx()); } public void removeOrdenado(int elemento){ if(vazia()){ System.out.println("Lista Vazia"); return; } No temp = ini; No anterior = null; while(temp != null && temp.getElemento() != elemento){ anterior = temp; temp = temp.getProx(); } //Remove no inicio if(anterior == null){ ini = ini.getProx(); return; } if(temp != null && temp.getElemento() == elemento){ anterior.setProx(temp.getProx()); return; } System.out.println(elemento + " não encontrado"); } public int contaNos(){ No temp = ini; int i =0; while(temp != null){ i++; temp = temp.getProx(); } return i; } public int contaNos2(){ int count =0; for(No temp = ini;temp != null;temp = temp.getProx()){ count ++; } return count ++; } public No menorNo(){ No temp = ini; No menor =temp; while(temp != null){ if(temp.getElemento() < menor.getElemento()){ menor = temp; } temp = temp.getProx(); } return menor; } public void inverteNos(){ No temp = ini; No anterior = null; No posterior = null; while(temp.getProx() != null){ posterior = anterior; anterior = temp; temp = temp.getProx(); anterior.setProx(posterior); } //ajustar o No temp ini = temp; temp.setProx(anterior); } } /* Copyright 2018 Ryos.io. 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.ryos.rhino.sdk.users.repositories; import io.ryos.rhino.sdk.data.UserSession; import io.ryos.rhino.sdk.data.UserSessionImpl; import io.ryos.rhino.sdk.users.data.User; import io.ryos.rhino.sdk.users.source.UserSource; import java.util.List; import java.util.Objects; import java.util.Queue; import java.util.concurrent.LinkedBlockingQueue; import java.util.stream.Collectors; public class DefaultUserRepositoryImpl implements UserRepository { private final Queue users; DefaultUserRepositoryImpl(UserSource userSource) { Objects.requireNonNull(userSource); this.users = new LinkedBlockingQueue<>(userSource.getUsers()); } @Override public List leaseUsers(int numberOfUsers, String region) { return users.stream().map(UserSessionImpl::new).collect(Collectors.toList()); } } package org.visallo.opennlpDictionary.model; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.google.inject.Inject; import com.v5analytics.simpleorm.SimpleOrmContext; import com.v5analytics.simpleorm.SimpleOrmSession; import org.visallo.core.user.User; public class DictionaryEntryRepository { private static final String VISIBILITY_STRING = ""; private final SimpleOrmSession simpleOrmSession; @Inject public DictionaryEntryRepository(SimpleOrmSession simpleOrmSession) { this.simpleOrmSession = simpleOrmSession; } public Iterable findAll(SimpleOrmContext simpleOrmContext) { return this.simpleOrmSession.findAll(DictionaryEntry.class, simpleOrmContext); } public Iterable findByConcept(final String concept, User user) { Iterable rows = findAll(user.getSimpleOrmContext()); return Iterables.filter(rows, new Predicate() { @Override public boolean apply(DictionaryEntry dictionaryEntry) { return dictionaryEntry.getConcept().equals(concept); } }); } public void delete(String id, User user) { this.simpleOrmSession.delete(DictionaryEntry.class, id, user.getSimpleOrmContext()); } public DictionaryEntry createNew(String tokens, String concept) { return createNew(tokens, concept, null); } public DictionaryEntry createNew(String tokens, String concept, String resolvedName) { return new DictionaryEntry( tokens, concept, resolvedName ); } public DictionaryEntry saveNew(String tokens, String concept, String resolvedName, User user) { DictionaryEntry entry = createNew(tokens, concept, resolvedName); this.simpleOrmSession.save(entry, VISIBILITY_STRING, user.getSimpleOrmContext()); return entry; } public DictionaryEntry saveNew(String tokens, String concept, User user) { DictionaryEntry entry = createNew(tokens, concept); this.simpleOrmSession.save(entry, VISIBILITY_STRING, user.getSimpleOrmContext()); return entry; } } package org.folio.rest.service.action; import java.util.Date; import java.util.Map; import java.util.UUID; import org.folio.rest.domain.Action; import org.folio.rest.domain.MonetaryValue; import org.folio.rest.jaxrs.model.Account; import org.folio.rest.jaxrs.model.CancelActionRequest; import org.folio.rest.jaxrs.model.Feefineaction; import org.folio.rest.service.action.context.ActionContext; import org.folio.rest.service.action.validation.CancelActionValidationService; import io.vertx.core.Context; import io.vertx.core.Future; public class CancelActionService extends ActionService { public CancelActionService(Map headers, Context context) { super(Action.CANCEL, new CancelActionValidationService(headers, context), headers, context); } @Override protected Future createFeeFineActions(ActionContext context) { final CancelActionRequest request = (CancelActionRequest) context.getRequest(); final Account account = context.getAccount(); MonetaryValue remainingAmountAfterAction = new MonetaryValue(account.getRemaining()); Feefineaction feeFineAction = new Feefineaction() .withComments(request.getComments()) .withNotify(request.getNotifyPatron()) .withCreatedAt(request.getServicePointId()) .withSource(request.getUserName()) .withAccountId(context.getAccountId()) .withUserId(account.getUserId()) .withBalance(remainingAmountAfterAction.toDouble()) .withTypeAction(action.getFullResult()) .withId(UUID.randomUUID().toString()) .withDateAction(new Date()) .withAccountId(context.getAccountId()); return feeFineActionRepository.save(feeFineAction) .map(context.withFeeFineAction(feeFineAction) .withShouldCloseAccount(true)); } @Override protected Future validateAction(ActionContext context) { return validationService.validate(context.getAccountId(), context.getAccount(), null) .map(result -> context.withRequestedAmount(null)); } } wangxy518/BackgroundHealthMonitorMngHealthMonitorMng/util/MailUtil.java0 package HealthMonitorMng.util; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.Address; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; /** * @ClassName: MailUtil * @Description: 发送邮件工具库 * @author DingMingliang * @date 2014年10月31日 下午6:52:25 */ public class MailUtil { private MimeMessage mimeMsg; private Session session; private Properties props; /** * @Fields needAuth : 是否需要认证stmp */ private boolean needAuth = false; private String username; private String password; private Multipart mp; /** * Constructor * * @param smtp * 邮件发送服务器 */ public MailUtil(String smtp) { setSmtpHost(smtp); createMimeMessage(); } /** * 设置邮件发送服务器 * * @param hostName * String */ public void setSmtpHost(String hostName) { if (props == null) props = System.getProperties(); props.put("mail.smtp.host", hostName); } /** * 创建MIME邮件对象 * * @return */ public boolean createMimeMessage() { try { session = Session.getDefaultInstance(props, null); } catch (Exception e) { return false; } try { mimeMsg = new MimeMessage(session); mp = new MimeMultipart(); return true; } catch (Exception e) { return false; } } /** * 设置SMTP是否需要验证 * * @param need */ public void setNeedAuth(boolean need) { if (props == null) props = System.getProperties(); if (need) { props.put("mail.smtp.auth", "true"); } else { props.put("mail.smtp.auth", "false"); } } /** * 设置用户名和密码 * * @param name * @param pass */ public void setNamePass(String name, String pass) { username = name; password = ; } /** * 设置邮件主题 * * @param mailSubject * @return */ public boolean setSubject(String mailSubject) { try { mimeMsg.setSubject(mailSubject); return true; } catch (Exception e) { return false; } } /** * 设置邮件正文 * * @param mailBody * String */ public boolean setBody(String mailBody) { try { BodyPart bp = new MimeBodyPart(); // 设置编码格式 bp.setContent("" + mailBody, "text/html;charset=GBK"); mp.addBodyPart(bp); return true; } catch (Exception e) { return false; } } /** * 添加附件 * * @param filename * String */ public boolean addFileAffix(String filename) { try { BodyPart bp = new MimeBodyPart(); FileDataSource fileds = new FileDataSource(filename); bp.setDataHandler(new DataHandler(fileds)); // 设置编码格式 bp.setFileName("=?UTF-8?B?" + new sun.misc.BASE64Encoder().encode(fileds.getName().getBytes()) + "?="); mp.addBodyPart(bp); return true; } catch (Exception e) { return false; } } /** * 设置发信人 * * @param from * String */ public boolean setFrom(String from) { try { mimeMsg.setFrom(new InternetAddress(from)); return true; } catch (Exception e) { return false; } } /** * 设置收信人 * * @param to * String */ public boolean setTo(String to) { if (to == null) return false; try { mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); return true; } catch (Exception e) { return false; } } /** * 设置抄送人 * * @param copyto * String */ public boolean setCopyTo(String copyto) { if (copyto == null) return false; try { mimeMsg.setRecipients(Message.RecipientType.CC, (Address[]) InternetAddress.parse(copyto)); return true; } catch (Exception e) { return false; } } /** * 发送邮件 */ public boolean sendOut() { try { mimeMsg.setContent(mp); mimeMsg.saveChanges(); Session mailSession = Session.getInstance(props, null); Transport transport = mailSession.getTransport("smtp"); transport.connect((String) props.get("mail.smtp.host"), username, password); transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO)); transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.CC)); transport.close(); return true; } catch (Exception e) { return false; } } /** * 调用sendOut方法完成邮件发送 * * @param smtp * @param from * @param to * @param subject * @param content * @param username * @param password * @return boolean */ public static boolean send(String smtp, String from, String to, String subject, String content, String username, String password) { MailUtil theMail = new MailUtil(smtp); theMail.setNeedAuth(true); if (!theMail.setSubject(subject)) return false; if (!theMail.setBody(content)) return false; if (!theMail.setTo(to)) return false; if (!theMail.setFrom(from)) return false; theMail.setNamePass(username, password); if (!theMail.sendOut()) return false; return true; } /** * 调用sendOut方法完成邮件发送,带抄送 * * @param smtp * @param from * @param to * @param copyto * @param subject * @param content * @param username * @param password * @return boolean */ public static boolean sendAndCc(String smtp, String from, String to, String copyto, String subject, String content, String username, String password) { MailUtil theMail = new MailUtil(smtp); theMail.setNeedAuth(true); if (!theMail.setSubject(subject)) return false; if (!theMail.setBody(content)) return false; if (!theMail.setTo(to)) return false; if (!theMail.setCopyTo(copyto)) return false; if (!theMail.setFrom(from)) return false; theMail.setNamePass(username, password); if (!theMail.sendOut()) return false; return true; } /** * 调用sendOut方法完成邮件发送,带附件 * * @param smtp * @param from * @param to * @param subject * @param content * @param username * @param password * @param filename * 附件路径 * @return */ public static boolean send(String smtp, String from, String to, String subject, String content, String username, String password, String filename) { MailUtil theMail = new MailUtil(smtp); theMail.setNeedAuth(true); if (!theMail.setSubject(subject)) return false; if (!theMail.setBody(content)) return false; if (!theMail.addFileAffix(filename)) return false; if (!theMail.setTo(to)) return false; if (!theMail.setFrom(from)) return false; theMail.setNamePass(username, password); if (!theMail.sendOut()) return false; return true; } /** * 调用sendOut方法完成邮件发送,带附件和抄送 * * @param smtp * @param from * @param to * @param copyto * @param subject * @param content * @param username * @param password * @param filename * @return */ public static boolean sendAndCc(String smtp, String from, String to, String copyto, String subject, String content, String username, String password, String filename) { MailUtil theMail = new MailUtil(smtp); theMail.setNeedAuth(true); if (!theMail.setSubject(subject)) return false; if (!theMail.setBody(content)) return false; if (!theMail.addFileAffix(filename)) return false; if (!theMail.setTo(to)) return false; if (!theMail.setCopyTo(copyto)) return false; if (!theMail.setFrom(from)) return false; theMail.setNamePass(username, password); if (!theMail.sendOut()) return false; return true; } public static void main(String[] args) { String smtp = "smtp.qq.com"; String from = ""; String to = ""; String copyto = ""; String subject = "邮件主题"; String content = "邮件内容"; String username = "290035317"; String password = ""; String filename = "C:\\code\\测试.txt"; MailUtil.send(smtp, from, to, subject, content, username, password); } } /* ### * IP: GHIDRA * * 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 ghidra.file.formats.android.vdex.android12; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.ArrayUtils; import ghidra.app.util.bin.BinaryReader; import ghidra.app.util.bin.ByteProviderWrapper; import ghidra.file.formats.android.dex.DexHeaderFactory; import ghidra.file.formats.android.dex.format.DexHeader; import ghidra.file.formats.android.vdex.*; import ghidra.program.model.data.*; import ghidra.util.exception.CancelledException; import ghidra.util.exception.DuplicateNameException; import ghidra.util.task.TaskMonitor; /** * https://android.googlesource.com/platform/art/+/refs/heads/android-s-beta-5/runtime/vdex_file.h#129 * * https://android.googlesource.com/platform/art/+/refs/heads/android12-release/runtime/vdex_file.h#129 * */ public class VdexHeader_12 extends VdexHeader { private String vdex_version_; private int number_of_sections_; private List sections = new ArrayList<>(); private List checksums = new ArrayList<>(); public VdexHeader_12(BinaryReader reader) throws IOException, UnsupportedVdexVersionException { super(reader); vdex_version_ = reader.readNextAsciiString(4); number_of_sections_ = reader.readNextInt(); } @Override public void parse(BinaryReader reader, TaskMonitor monitor) throws IOException, CancelledException { for (int i = 0; i < number_of_sections_; ++i) { monitor.checkCanceled(); sections.add(new VdexSectionHeader_12(reader)); } parseChecksums(reader, monitor); parseDexFiles(reader, monitor); parseVerifierDeps(reader, monitor); parseTypeLookupTable(reader, monitor); } private void parseChecksums(BinaryReader reader, TaskMonitor monitor) throws CancelledException, IOException { VdexSectionHeader_12 checksumSection = sections.get(VdexSection_12.kChecksumSection.ordinal()); if (checksumSection.getSectionSize() > 0) { reader.setPointerIndex(checksumSection.getSectionOffset()); for (int i = 0; i < checksumSection.getSectionSize() / 4; ++i) { monitor.checkCanceled(); checksums.add(reader.readNextInt()); } } } private void parseDexFiles(BinaryReader reader, TaskMonitor monitor) throws CancelledException, IOException { VdexSectionHeader_12 dexFileSection = sections.get(VdexSection_12.kDexFileSection.ordinal()); if (dexFileSection.getSectionSize() > 0) { reader.setPointerIndex(dexFileSection.getSectionOffset()); dexHeaderStartsList.add(Integer.toUnsignedLong(dexFileSection.getSectionOffset())); ByteProviderWrapper wrappedProvider = new ByteProviderWrapper( reader.getByteProvider(), dexFileSection.getSectionOffset(), dexFileSection.getSectionSize()); BinaryReader wrappedReader = new BinaryReader(wrappedProvider, reader.isLittleEndian()); DexHeader cdexHeader = DexHeaderFactory.getDexHeader(wrappedReader); dexHeaderList.add(cdexHeader); } } private void parseVerifierDeps(BinaryReader reader, TaskMonitor monitor) throws CancelledException, IOException { VdexSectionHeader_12 verifierDepsSection = sections.get(VdexSection_12.kVerifierDepsSection.ordinal()); if (verifierDepsSection.getSectionSize() > 0) { reader.setPointerIndex(verifierDepsSection.getSectionOffset()); //TODO } } private void parseTypeLookupTable(BinaryReader reader, TaskMonitor monitor) throws CancelledException, IOException { VdexSectionHeader_12 typeLookupTableSection = sections.get(VdexSection_12.kTypeLookupTableSection.ordinal()); if (typeLookupTableSection.getSectionSize() > 0) { reader.setPointerIndex(typeLookupTableSection.getSectionOffset()); //TODO } } @Override public int getVerifierDepsSize() { return 0;//not used in this VDEX version } @Override public int getQuickeningInfoSize() { return 0;//not used in this VDEX version } @Override public int[] getDexChecksums() { return ArrayUtils.toPrimitive(checksums.toArray(new Integer[checksums.size()])); } @Override public boolean isDexHeaderEmbeddedInDataType() { return true; } @Override public DexSectionHeader_002 getDexSectionHeader_002() { return null;//not used in this VDEX version } public String getVdexVersion() { return vdex_version_; } @Override public DataType toDataType() throws DuplicateNameException, IOException { Structure structure = new StructureDataType(VdexHeader_12.class.getSimpleName(), 0); structure.add(STRING, 4, "magic_", null); structure.add(STRING, 4, "vdex_version_", null); structure.add(DWORD, "number_of_sections_", null); for (int i = 0; i < sections.size(); ++i) { structure.add(sections.get(i).toDataType(), "section_" + i, null); } for (int i = 0; i < checksums.size(); ++i) { structure.add(DWORD, "checksum_" + i, null); } toDataTypeDexFile(structure); toDataTypeVerifierDeps(structure); toDataTypeTypeLookupTable(structure); return structure; } private void toDataTypeDexFile(Structure structure) { VdexSectionHeader_12 dexFileSection = sections.get(VdexSection_12.kDexFileSection.ordinal()); if (dexFileSection.getSectionSize() > 0) { DataType array = new ArrayDataType(BYTE, dexFileSection.getSectionSize(), BYTE.getLength()); structure.add(array, "cdex", null); } } private void toDataTypeVerifierDeps(Structure structure) { VdexSectionHeader_12 verifierDepsSection = sections.get(VdexSection_12.kVerifierDepsSection.ordinal()); if (verifierDepsSection.getSectionSize() > 0) { DataType array = new ArrayDataType(BYTE, verifierDepsSection.getSectionSize(), BYTE.getLength()); structure.add(array, "verifier_deps", null); } } private void toDataTypeTypeLookupTable(Structure structure) { VdexSectionHeader_12 typeLookupTableSection = sections.get(VdexSection_12.kTypeLookupTableSection.ordinal()); if (typeLookupTableSection.getSectionSize() > 0) { DataType array = new ArrayDataType(BYTE, typeLookupTableSection.getSectionSize(), BYTE.getLength()); structure.add(array, "type_lookup_table", null); } } } BaoBaoJianqiang/That1.2Plugin1/src/main/java/jianqiang/com/plugin1/MainActivity.java0 package jianqiang.com.plugin1; import android.content.ComponentName; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import com.example.jianqiang.mypluginlibrary.AppConstants; public class MainActivity extends BasePluginActivity { private static final String TAG = "Client-MainActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //startActivity,插件内跳转 Button button1 = (Button) findViewById(R.id.button1); button1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(AppConstants.PROXY_VIEW_ACTION); intent.putExtra(AppConstants.EXTRA_DEX_PATH, dexPath); intent.putExtra(AppConstants.EXTRA_CLASS, "jianqiang.com.plugin1.SecondActivity"); startActivity(intent); } }); } }/** * Copyright © 2018 spring-data-dynamodb (https://github.com/boostchicken/spring-data-dynamodb) * * 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.socialsignin.spring.data.dynamodb.mapping; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBIgnore; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import org.socialsignin.spring.data.dynamodb.repository.DynamoDBHashAndRangeKey; import org.springframework.data.annotation.Id; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; /** * Unit tests for {@link DynamoDBMappingContext}. * * @author * @author */ @RunWith(MockitoJUnitRunner.class) public class DynamoDBMappingContextTest { @DynamoDBTable(tableName = "a") static class DynamoDBMappingContextTestFieldEntity { @DynamoDBHashKey private String hashKey; @DynamoDBRangeKey private String rangeKey; @SuppressWarnings("unused") private String someProperty; } @DynamoDBTable(tableName = "b") static class DynamoDBMappingContextTestMethodEntity { @DynamoDBHashKey public String getHashKey() { return null; } @DynamoDBRangeKey public String getRangeKey() { return null; } public String getSomeProperty() { return null; } } @DynamoDBTable(tableName = "c") static class DynamoDBMappingContextTestIdEntity { @Id private DynamoDBHashAndRangeKey hashRangeKey; @DynamoDBIgnore public String getSomething() { return null; } } private DynamoDBMappingContext underTest; @Before public void setUp() { underTest = new DynamoDBMappingContext(); } @Test public void detectsPropertyAnnotation() { DynamoDBPersistentEntityImpl entity = underTest .getPersistentEntity(DynamoDBMappingContextTestFieldEntity.class); assertNotNull(entity); assertThat(entity.getIdProperty(), is(notNullValue())); } @Test @Ignore public void detectdMethodsAnnotation() { DynamoDBPersistentEntityImpl entity = underTest .getPersistentEntity(DynamoDBMappingContextTestMethodEntity.class); assertNotNull(entity); assertThat(entity.getIdProperty(), is(notNullValue())); } @Test public void detectdMethodsId() { DynamoDBPersistentEntityImpl entity = underTest .getPersistentEntity(DynamoDBMappingContextTestIdEntity.class); assertNotNull(entity); assertThat(entity.getIdProperty(), is(notNullValue())); } } package com.softserveinc.tender.repo; import com.softserveinc.tender.entity.Comment; import com.softserveinc.tender.entity.Tender; import com.softserveinc.tender.entity.User; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface CommentRepository extends JpaRepository { List findByTender(Tender tender); List findByUser(User user); } /** Copyright 2014-2015 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file 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.amazon.speech.speechlet; import java.util.Date; import org.apache.commons.lang3.Validate; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeName; /** * The request object used to notify a {@code Speechlet} that a new session has launched. * * @see Speechlet#onLaunch(LaunchRequest, Session) */ @JsonTypeName("SessionStartedRequest") public final class SessionStartedRequest extends SpeechletRequest { /** * Returns a new builder instance used to construct a new {@code SessionStartedRequest}. * * @return the builder */ public static Builder builder() { return new Builder(); } /** * Private constructor to return a new {@code SessionStartedRequest} from a {@code Builder}. * * @param builder * the builder used to construct the {@code SessionStartedRequest} */ private SessionStartedRequest(final Builder builder) { super(builder.requestId, builder.timestamp); } /** * Private constructor a new {@code SessionStartedRequest}. * * @param requestId * the unique identifier associated with the request * @param timestamp * the request timestamp */ private SessionStartedRequest(@JsonProperty("requestId") final String requestId, @JsonProperty("timestamp") final Date timestamp) { super(requestId, timestamp); } /** * Builder used to construct a new {@code SessionStartedRequest}. */ public static final class Builder { private String requestId; private Date timestamp = new Date(); private Builder() { } public Builder withRequestId(final String requestId) { this.requestId = requestId; return this; } public Builder withTimestamp(final Date timestamp) { this.timestamp = (timestamp != null) ? new Date(timestamp.getTime()) : null; return this; } public SessionStartedRequest build() { Validate.notBlank(requestId, "RequestId must be defined"); return new SessionStartedRequest(this); } } } binxuankong/sts-chronomancer-mod package chronoMod.cards; import chronoMod.ChronoMod; import chronoMod.actions.PrecognitionAction; import chronoMod.characters.Chronomancer; import com.megacrit.cardcrawl.actions.common.DrawCardAction; import com.megacrit.cardcrawl.cards.AbstractCard; import com.megacrit.cardcrawl.characters.AbstractPlayer; import com.megacrit.cardcrawl.core.CardCrawlGame; import com.megacrit.cardcrawl.localization.CardStrings; import com.megacrit.cardcrawl.monsters.AbstractMonster; import static chronoMod.ChronoMod.makeCardPath; public class Precognition extends AbstractXCostCard { private static final String CARD_ID = Precognition.class.getSimpleName(); public static final String ID = ChronoMod.makeID(CARD_ID); public static final String IMG = makeCardPath("skill/" + CARD_ID + ".png"); private static final CardStrings cardStrings = CardCrawlGame.languagePack.getCardStrings(ID); public static final String UPGRADE_DESCRIPTION = cardStrings.UPGRADE_DESCRIPTION; private static final CardRarity RARITY = CardRarity.RARE; private static final CardTarget TARGET = CardTarget.SELF; private static final CardType TYPE = CardType.SKILL; public static final CardColor COLOR = Chronomancer.Enums.COLOR_BLUE; public Precognition() { super(ID, IMG, TYPE, COLOR, RARITY, TARGET); this.exhaust = true; } @Override public void use(AbstractPlayer p, AbstractMonster m) { int effect = this.getEffectNum(p); if (effect > 0) { this.addToBot(new DrawCardAction(effect, new PrecognitionAction())); } } @Override public void upgrade() { if (!upgraded) { upgradeName(); this.exhaust = false; rawDescription = UPGRADE_DESCRIPTION; initializeDescription(); } } @Override public AbstractCard makeCopy() { return new Precognition(); } } package com.antisocial.system; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; import javax.servlet.ServletRegistration; public class SpringMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { /** * This class is needed for no web.xml configuration. * Customize Registration registers unknown URL exceptions. * We then catch those exceptions in Exception Controller. * * @author - Github/Exercon * */ @Override protected Class[] getRootConfigClasses() { return new Class[] {SpringConfiguration.class} ; } @Override protected Class[] getServletConfigClasses() { return null; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } @Override public void customizeRegistration(ServletRegistration.Dynamic registration) { registration.setInitParameter("throwExceptionIfNoHandlerFound", "true"); } } package com.hardelele.ct.dto; import java.util.Objects; public class TripDto { private long id; private String departure; private String destination; private int driverId; private int carId; private double driverPrice; private String startDate; private String endDate; public TripDto() { } public TripDto(long id, String departure, String destination, int driverId, int carId, double driverPrice, String startDate, String endDate) { this.id = id; this.departure = departure; this.destination = destination; this.driverId = driverId; this.carId = carId; this.driverPrice = driverPrice; this.startDate = startDate; this.endDate = endDate; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getDeparture() { return departure; } public void setDeparture(String departure) { this.departure = departure; } public String getDestination() { return destination; } public void setDestination(String destination) { this.destination = destination; } public int getDriverId() { return driverId; } public void setDriverId(int driverId) { this.driverId = driverId; } public int getCarId() { return carId; } public void setCarId(int carId) { this.carId = carId; } public double getDriverPrice() { return driverPrice; } public void setDriverPrice(double driverPrice) { this.driverPrice = driverPrice; } public String getStartDate() { return startDate; } public void setStartDate(String startDate) { this.startDate = startDate; } public String getEndDate() { return endDate; } public void setEndDate(String endDate) { this.endDate = endDate; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TripDto tripDto = (TripDto) o; return id == tripDto.id && driverId == tripDto.driverId && carId == tripDto.carId && Double.compare(tripDto.driverPrice, driverPrice) == 0 && Objects.equals(departure, tripDto.departure) && Objects.equals(destination, tripDto.destination) && Objects.equals(startDate, tripDto.startDate) && Objects.equals(endDate, tripDto.endDate); } @Override public int hashCode() { return Objects.hash(id, departure, destination, driverId, carId, driverPrice, startDate, endDate); } @Override public String toString() { return "TripDto{" + "id=" + id + ", departure='" + departure + '\'' + ", destination='" + destination + '\'' + ", driverId=" + driverId + ", carId=" + carId + ", driverPrice=" + driverPrice + ", startDate='" + startDate + '\'' + ", endDate='" + endDate + '\'' + '}'; } } OSADP/P-ODE /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.leidos.ode.emulator; /** * * @author cassadyja */ public class RITISZoneDirectionData { private int[] eastZones = new int[]{910,912,913,914,1168,1365,1371,1392}; private int[] westZones = new int[]{911,917,935,938,939,1175,1372,1399}; public int[] getZonesForDirection(String direction){ if("W".equalsIgnoreCase(direction)){ return westZones; }else if("E".equalsIgnoreCase(direction)){ return eastZones; } return new int[0]; } public int[] getZonesForOppositeDirection(String direction){ if("W".equalsIgnoreCase(direction)){ return eastZones; }else if("E".equalsIgnoreCase(direction)){ return westZones; } return new int[0]; } public int isInDirectionOfTravelRITIS(int zone, String direction){ int ret = 0; int[] directionZones = getZonesForDirection(direction); int[] oppDirZones = getZonesForOppositeDirection(direction); for(int i=0;i */ package org.nuxeo.launcher; import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.GeneralSecurityException; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.FileUtils; import org.junit.AssumptionViolatedException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.nuxeo.common.Environment; import org.nuxeo.connect.identity.LogicalInstanceIdentifier; import org.nuxeo.launcher.config.AbstractConfigurationTest; import org.nuxeo.launcher.config.ConfigurationGenerator; import org.nuxeo.launcher.config.TomcatConfigurator; import org.nuxeo.launcher.info.InstanceInfo; import org.nuxeo.launcher.process.SolarisProcessManager; public class TestNuxeoLauncher extends AbstractConfigurationTest { private static final String TEST_INSTANCE_CLID = "/opt/build/hudson/instance.clid"; private static final String NUXEO_PATH = "/opt/nuxeo"; private static final String STARTUP_CLASS = "org.apache.catalina.startup.Bootstrap"; // USER PID %CPU %MEM SZ RSS TT S START TIME COMMAND private static final String SOL_PS1_CMD = "fsflush"; private static final String SOL_PS1 = "root 3 0.2 0.0 0 0 ? S 16:02:16 0:00 " + SOL_PS1_CMD; private static final String SOL_PS2_CMD = "/usr/lib/rad/rad -m /usr/lib/rad/transport -m /usr/lib/rad/protocol -m /usr/lib/rad/module -m /usr/lib/rad/site-modules -t pipe:fd=3,exit -e 180"; private static final String SOL_PS2 = "fguillau 1786 0.0 0.219136 3908 ? S 16:05:41 0:00 " + SOL_PS2_CMD; private static final String SOL_PS3_CMD = "gnome-terminal"; private static final String SOL_PS3 = "fguillau 1921 2.2 0.913130018836 ? S 16:08:28 0:00 " + SOL_PS3_CMD; private static final String SOL_PS4_CMD = "/usr/jdk/instances/jdk1.7.0/jre/bin/java -server -Xms512m -Xmx1024m -XX:MaxPermSize=512m -Dsun.rmi.dgc.client.gcInterval=3600000 -Dsun.rmi.dgc.server.gcInterval=3600000 -Dfile.encoding=UTF-8 -Dmail.mime.decodeparameters=true -Xdebug -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n -Djava.net.preferIPv4Stack=true -Djava.awt.headless=true -cp .:/opt/nuxeo/nxserver/lib:/opt/nuxeo/bin/bootstrap.jar:/opt/nuxeo/bin/tomcat-juli.jar -Dnuxeo.home=/opt/nuxeo -Dnuxeo.conf=/opt/nuxeo/bin/nuxeo.conf -Dnuxeo.log.dir=/opt/nuxeo/log -Dnuxeo.data.dir=/opt/nuxeo/nxserver/data -Dnuxeo.tmp.dir=/opt/nuxeo/tmp -Djava.io.tmpdir=/opt/nuxeo/tmp -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Dcatalina.base=/opt/nuxeo -Dcatalina.home=/opt/nuxeo -Djava.endorsed.dirs=/opt/nuxeo/endorsed org.apache.catalina.startup.Bootstrap start"; private static final String SOL_PS4 = "fguillau 2788 1.2 19.5699008405296 pts/2 S 18:54:51 1:26 " + SOL_PS4_CMD; @Rule public final ExpectedException thrown = ExpectedException.none(); protected class MockSolarisProcessManager extends SolarisProcessManager { protected Map> commands = new HashMap<>(); public void setLines(String command, List lines) { commands.put(command, lines); } @Override protected List execute(String... command) { for (Entry> es : commands.entrySet()) { String c = es.getKey(); if (command[0].contains(c)) { return es.getValue(); } } fail("Bad command: " + Arrays.toString(command)); return null; } } /** Code from {@link NuxeoLauncher#init} */ protected String getRegex() { return "^(?!/bin/sh).*" + Pattern.quote(NUXEO_PATH) + ".*" + Pattern.quote(STARTUP_CLASS) + ".*$"; } protected static void assertSolarisMatch(MockSolarisProcessManager pm, String expectedPid, String expectedCommand, String line) { Matcher lineMatcher = pm.getLineMatcher(line); assertTrue(lineMatcher.matches()); String pid = lineMatcher.group(1); String command = lineMatcher.group(2); assertEquals(expectedPid, pid); assertEquals(expectedCommand, command); } @Test public void testSolarisProcessManagerParsing() throws Exception { MockSolarisProcessManager pm = new MockSolarisProcessManager(); pm.setLines("uname", Collections.singletonList("5.11")); assertEquals("5.11", pm.getSolarisVersion()); assertSolarisMatch(pm, "3", SOL_PS1_CMD, SOL_PS1); assertSolarisMatch(pm, "1786", SOL_PS2_CMD, SOL_PS2); assertSolarisMatch(pm, "1921", SOL_PS3_CMD, SOL_PS3); assertSolarisMatch(pm, "2788", SOL_PS4_CMD, SOL_PS4); pm.setLines("ps", Arrays.asList(SOL_PS1, SOL_PS2, SOL_PS3, SOL_PS4)); assertEquals("2788", pm.findPid(getRegex())); } @Override @Before public void setUp() throws Exception { Environment.setDefault(null); nuxeoHome = new File("target/launcher"); FileUtils.deleteQuietly(nuxeoHome); Files.createDirectories(nuxeoHome.toPath()); File nuxeoConf = getResourceFile("config/nuxeo.conf"); FileUtils.copyFileToDirectory(nuxeoConf, nuxeoHome); FileUtils.copyDirectory(getResourceFile("templates"), new File(nuxeoHome, "templates")); setSystemProperty(Environment.NUXEO_HOME, nuxeoHome.getPath()); setSystemProperty(ConfigurationGenerator.NUXEO_CONF, new File(nuxeoHome, nuxeoConf.getName()).getPath()); setSystemProperty(TomcatConfigurator.TOMCAT_HOME, Environment.getDefault().getServerHome().getPath()); configGenerator = new ConfigurationGenerator(); assertTrue(configGenerator.init()); } @Test public void testClidOption() throws Exception { Path instanceClid = Paths.get(TEST_INSTANCE_CLID); if (!Files.exists(instanceClid)) { throw new AssumptionViolatedException("No test CLID available"); } String[] args = new String[] { "--clid", instanceClid.toString(), "showconf" }; final NuxeoLauncher launcher = NuxeoLauncher.createLauncher(args); InstanceInfo info = launcher.getInfo(); assertNotNull("Failed to get instance info", info); List clidLines = Files.readAllLines(instanceClid, UTF_8); LogicalInstanceIdentifier expectedClid = new LogicalInstanceIdentifier( clidLines.get(0) + LogicalInstanceIdentifier.ID_SEP + clidLines.get(1), "expected clid"); assertEquals("Not the right instance.clid file: ", expectedClid.getCLID(), info.clid); } @Test public void testRegisterTrialIsValidCommand() throws Exception { String[] args = { "register-trial" }; NuxeoLauncher launcher = NuxeoLauncher.createLauncher(args); assertTrue(launcher.commandIs("register-trial")); assertTrue(launcher.commandRequiresNoGUI()); } /** * Command "register-trial" is deprecated since 9.3. * * @deprecated since 9.3 */ @Test @Deprecated public void testRegisterTrialIsDeprecated() throws Exception { thrown.expect(UnsupportedOperationException.class); thrown.expectMessage("deprecated"); thrown.expectMessage("https://connect.nuxeo.com/register"); NuxeoLauncher.createLauncher(new String[] { "register-trial" }).registerTrial(); } /** * NXP-19071: avoid confusion with the command parameters when passing an argument to an option, or when calling * without argument an option which accepts optional arguments. * * @since 8.2 */ @Test public void testParamSeparator() throws Exception { // failing syntax: "value1" is parsed as an argument to "--encrypt" option NuxeoLauncher launcher = NuxeoLauncher.createLauncher( new String[] { "encrypt", "--encrypt", "value1", "value2" }); assertTrue(launcher.commandIs("encrypt")); assertTrue(launcher.cmdLine.hasOption(NuxeoLauncher.OPTION_ENCRYPT)); assertEquals("value1", launcher.cmdLine.getOptionValue(NuxeoLauncher.OPTION_ENCRYPT)); assertArrayEquals(new String[] { "value2" }, launcher.params); try { launcher.encrypt(); fail("Expected 'java.security.NoSuchAlgorithmException: Cannot find any provider supporting value1'"); } catch (NoSuchAlgorithmException e) { assertEquals("Cannot find any provider supporting value1", e.getMessage()); } // working syntax: "value1" is a parsed as a parameter to "encrypt" command // 1) option without argument placed at the end launcher = NuxeoLauncher.createLauncher(new String[] { "encrypt", "value1", "value2", "--encrypt" }); checkParsing(launcher); // 2) option with an argument launcher = NuxeoLauncher.createLauncher( new String[] { "encrypt", "--encrypt", "AES/ECB/PKCS5Padding", "value1", "value2" }); checkParsing(launcher); // 3) option without argument separated with "--" launcher = NuxeoLauncher.createLauncher(new String[] { "encrypt", "--encrypt", "--", "value1", "value2" }); checkParsing(launcher); // Check specific case of the "--set" option launcher = NuxeoLauncher.createLauncher(new String[] { "config", "--set", "someTemplate", "someKey" }); assertTrue(launcher.commandIs("config")); assertTrue(launcher.cmdLine.hasOption(NuxeoLauncher.OPTION_SET)); assertEquals("someTemplate", launcher.cmdLine.getOptionValue(NuxeoLauncher.OPTION_SET)); assertArrayEquals(new String[] { "someKey" }, launcher.params); launcher = NuxeoLauncher.createLauncher(new String[] { "config", "--set", "--", "someKey" }); assertTrue(launcher.commandIs("config")); assertTrue(launcher.cmdLine.hasOption(NuxeoLauncher.OPTION_SET)); assertNull(launcher.cmdLine.getOptionValue(NuxeoLauncher.OPTION_SET)); assertArrayEquals(new String[] { "someKey" }, launcher.params); launcher = NuxeoLauncher.createLauncher(new String[] { "config", "someKey", "--set" }); assertTrue(launcher.commandIs("config")); assertTrue(launcher.cmdLine.hasOption(NuxeoLauncher.OPTION_SET)); assertNull(launcher.cmdLine.getOptionValue(NuxeoLauncher.OPTION_SET)); assertArrayEquals(new String[] { "someKey" }, launcher.params); } private void checkParsing(NuxeoLauncher launcher) throws GeneralSecurityException { assertTrue(launcher.commandIs("encrypt")); assertTrue(launcher.cmdLine.hasOption(NuxeoLauncher.OPTION_ENCRYPT)); assertEquals("AES/ECB/PKCS5Padding", launcher.cmdLine.getOptionValue(NuxeoLauncher.OPTION_ENCRYPT, "AES/ECB/PKCS5Padding")); assertArrayEquals(new String[] { "value1", "value2" }, launcher.params); launcher.encrypt(); } } midorlo/pumpernickelsrc/main/java/com/pump/plaf/AquaColorWellUI.java /** * This software is released as part of the Pumpernickel project. * All com.pump resources in the Pumpernickel project are distributed under the * MIT License: * https://raw.githubusercontent.com/mickleness/pumpernickel/master/License.txt * More information about the Pumpernickel project is available here: * https://mickleness.github.io/pumpernickel/ */ package com.pump.plaf; import javax.swing.*; import javax.swing.border.Border; import javax.swing.plaf.ComponentUI; import java.awt.*; import java.awt.geom.GeneralPath; import java.awt.geom.Path2D; public class AquaColorWellUI extends ColorWellUI { @Override public Dimension getMaximumSize(JComponent c) { Border border = c.getBorder(); Insets i = border.getBorderInsets(c); return new Dimension(40 + i.left + i.right, 40 + i.top + i.bottom); } @Override public Dimension getMinimumSize(JComponent c) { Border border = c.getBorder(); Insets i = border.getBorderInsets(c); return new Dimension(11 + i.left + i.right, 11 + i.top + i.bottom); } @Override public Dimension getPreferredSize(JComponent c) { Border border = c.getBorder(); Insets i = border.getBorderInsets(c); return new Dimension(49 + i.left + i.right, 11 + i.top + i.bottom); } @Override public void installUI(JComponent c) { super.installUI(c); c.setBorder(new AquaColorWellBorder()); } public static ComponentUI createUI(JComponent jc) { return new AquaColorWellUI(); } static class AquaColorWellBorder implements Border { static final Color fill = new Color(0xF3F3F3); static final Color border = new Color(0xB0B0B0); static final Color borderSelected = new Color(0x575757); static final Color[] normalGradient = new Color[]{ new Color(0x00000000, true), new Color(0x03000000, true)}; static final Color[] selectedGradient = new Color[]{ new Color(0x00000000, true), new Color(0x00000000, true)}; static final Color[] selectedFillGradient = new Color[]{ new Color(0xB0B0B0), new Color(0xC4C4C4)}; public Insets getBorderInsets(Component c) { return new Insets(6, 6, 6, 6); } public boolean isBorderOpaque() { return true; } public void paintBorder(Component c, Graphics g0, int x, int y, int width, int height) { Graphics2D g = (Graphics2D) g0; boolean selected = c.hasFocus(); if (c instanceof JComponent) { JComponent jc = (JComponent) c; Boolean pressed = (Boolean) jc .getClientProperty("mousePressed"); if (pressed == null) {pressed = Boolean.FALSE;} if (pressed) {selected = true;} } GeneralPath body = new GeneralPath(Path2D.WIND_EVEN_ODD); body.moveTo(x, y); body.lineTo(x + width, y); body.lineTo(x + width, y + height); body.lineTo(x, y + height); body.closePath(); body.moveTo(x + 5, y + 5); body.lineTo(x + width - 5, y + 5); body.lineTo(x + width - 5, y + height - 5); body.lineTo(x + 5, y + height - 5); body.closePath(); if (!selected) { g.setColor(fill); } else { Paint paint = PlafPaintUtils.getVerticalGradient( "aquaSelectedColorWellFill", height, y, new float[]{ 0, 1}, selectedFillGradient); g.setPaint(paint); } g.fill(body); if (!selected) { g.setColor(border); } else { g.setColor(borderSelected); } g.drawLine(x, y, x + width - 1, y); g.drawLine(x, y + height - 1, x + width - 1, y + height - 1); g.drawLine(x, y, x, y + height - 1); g.drawLine(x + width - 1, y, x + width - 1, y + height - 1); g.drawLine(x + 5, y + 5, x + width - 1 - 5, y + 5); g.drawLine(x + 5, y + height - 1 - 5, x + width - 1 - 5, y + height - 1 - 5); g.drawLine(x + 5, y + 5, x + 5, y + height - 1 - 5); g.drawLine(x + width - 1 - 5, y + 5, x + width - 1 - 5, y + height - 1 - 5); // side shades: if (!selected) { g.setPaint(PlafPaintUtils.getVerticalGradient("aquaColorWell", height, y, new float[]{0, 1}, normalGradient)); } else { g.setPaint(PlafPaintUtils.getVerticalGradient( "aquaSelectedColorWell", height, y, new float[]{0, 1}, selectedGradient)); } g.drawLine(x + 1, y + 1, x + 1, y + height - 2); g.drawLine(x + width - 2, y + 1, x + width - 2, y + height - 2); } } }package com.tencent.msdk.dns.core; public interface ISorter { interface IFactory { ISorter create(int curNetStack); } // NOTE: ips可能为空数组 void put(IDns dns, String[] ips); IpSet sort(); } /* * Copyright 2015 JSourceMap contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hibnet.jsourcemap; import java.util.List; class BinarySearch { enum Bias { GREATEST_LOWER_BOUND, LEAST_UPPER_BOUND } static interface Comparator { int compare(T needle, T element); } private static int recursiveSearch(int aLow, int aHigh, T aNeedle, List aHaystack, Comparator aCompare, Bias aBias) { // This function terminates when one of the following is true: // // 1. We find the exact element we are looking for. // // 2. We did not find the exact element, but we can return the index of // the next-closest element. // // 3. We did not find the exact element, and there is no next-closest // element than the one we are searching for, so we return -1. int mid = (int) (Math.floor((aHigh - aLow) / 2) + aLow); int cmp = aCompare.compare(aNeedle, aHaystack.get(mid)); if (cmp == 0) { // Found the element we are looking for. return mid; } else if (cmp > 0) { // Our needle is greater than aHaystack[mid]. if (aHigh - mid > 1) { // The element is in the upper half. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); } // The exact needle element was not found in this haystack. Determine if // we are in termination case (3) or (2) and return the appropriate thing. if (aBias == Bias.LEAST_UPPER_BOUND) { return aHigh < aHaystack.size() ? aHigh : -1; } else { return mid; } } else { // Our needle is less than aHaystack[mid]. if (mid - aLow > 1) { // The element is in the lower half. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); } // we are in termination case (3) or (2) and return the appropriate thing. if (aBias == Bias.LEAST_UPPER_BOUND) { return mid; } else { return aLow < 0 ? -1 : aLow; } } } static int search(T aNeedle, List aHaystack, Comparator aCompare, Bias aBias) { if (aHaystack.size() == 0) { return -1; } if (aBias == null) { aBias = Bias.GREATEST_LOWER_BOUND; } int index = recursiveSearch(-1, aHaystack.size(), aNeedle, aHaystack, aCompare, aBias); if (index < 0) { return -1; } // We have found either the exact element, or the next-closest element than // the one we are searching for. However, there may be more than one such // element. Make sure we always return the smallest of these. while (index - 1 >= 0) { if (aCompare.compare(aHaystack.get(index), aHaystack.get(index - 1)) != 0) { break; } --index; } return index; } } package com.kanbagoly.guice.cached; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.concurrent.TimeUnit; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Cached { /** * Define for how long the value in the cache is valid. */ int duration(); TimeUnit timeUnit(); /** * Maximum size of the cache. * * Same or similar behaviour can be expected as the LRU * algorithm if the size of the cache reach this value. */ int maxSize(); } package com.jamesg.forecastr.cards; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.graphics.drawable.TransitionDrawable; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.animation.RotateAnimation; import android.view.animation.TranslateAnimation; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextSwitcher; import android.widget.TextView; import android.widget.ViewSwitcher; import com.jamesg.forecastr.R; import com.jamesg.forecastr.base.CardBase; import com.jamesg.forecastr.data.Spot; import com.jamesg.forecastr.data.TimestampData; import java.text.SimpleDateFormat; import java.util.Calendar; /** * Created by James on 17/10/2014. */ public class WindCard extends CardBase { private TextView titleTextView; private boolean favouritesList; public WindCard(Context context, Spot spot, int dateTab){ this.context = context; this.spot = spot; this.dateTab = dateTab; } public WindCard(Context context, Spot spot, int dateTab, boolean favouritesList){ this.context = context; this.spot = spot; this.dateTab = dateTab; this.favouritesList = favouritesList; } @Override public String getTitle() { if(favouritesList){ return spot.getName(); }else { return "Wind"; } } public View getView(LayoutInflater inflater){ return getView(inflater, true); } public View getView(LayoutInflater inflater, boolean animate){ View view = inflater.inflate(R.layout.card_layout_overview, null); view.setTag(getTag()); titleTextView = (TextView) view.findViewById(android.R.id.title); titleTextView.setText(getTitle()); Calendar c = null; SimpleDateFormat df = new SimpleDateFormat("EEE"); if(dateTab == 2) c = Calendar.getInstance(); int timeSteps = 7; if(dateTab == 2){ timeSteps = spot.getSevenDayDayCount(); } for(int i=0; i < 7; i++){ boolean windColorChange = true; boolean gustColorChange = true; int timeStamp = (i+1)*3; TimestampData intervalData = null; if(dateTab == 0){ intervalData = spot.getTodayTimestamp(timeStamp); }else if(dateTab == 1){ intervalData = spot.getTomorrowTimestamp(timeStamp); }else { if(i < timeSteps)intervalData = spot.getSevenDayDay(i); else intervalData = null; } //Log.d("WINDFINDER APP", "Column-" + i); int colID = context.getResources().getIdentifier("column"+(i+1), "id", context.getPackageName()); View column = view.findViewById(colID); TextView time = (TextView) column.findViewById(R.id.valueText); if(dateTab == 0 || dateTab == 1){ int timeID = context.getResources().getIdentifier("time"+(i+1), "string", context.getPackageName()); time.setText(timeID); }else{ time.setText(df.format(c.getTime())); c.add(c.DAY_OF_MONTH, 1); } int windVal = 0; String windString = ""; int gustVal = 0; String gustString = ""; int windDirection = 0; if(intervalData != null){ windVal = intervalData.windSpeed; windString = Integer.toString(windVal); gustVal = intervalData.windGust; gustString = Integer.toString(gustVal); windDirection = intervalData.windDirection; //Log.d("WINDFINDER APP", "WindVal " + windVal); }else{ //Log.d("WINDFINDER APP", "intervalData null"); } String oldWindString; String oldGustString; TextSwitcher wind = (TextSwitcher) column.findViewById(R.id.windSpeedSwitcher); TextView windTextView = (TextView) wind.getCurrentView(); if(windTextView == null){ wind.setFactory(new ViewSwitcher.ViewFactory() { public View makeView() { TextView myText = new TextView(context); myText.setGravity(Gravity.CENTER); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.CENTER); myText.setLayoutParams(params); myText.setTextSize(18); myText.setTextColor(Color.WHITE); return myText; } }); oldWindString = ""; }else{ oldWindString = windTextView.getText().toString(); } if(animate){ wind.setInAnimation(AnimationUtils.loadAnimation(context, R.anim.fade_in)); wind.setOutAnimation(context, R.anim.fade_out); }else{ wind.setInAnimation(AnimationUtils.loadAnimation(context, R.anim.no_anim_in)); wind.setOutAnimation(context, R.anim.no_anim_out); } TextSwitcher gust = (TextSwitcher) column.findViewById(R.id.gustSpeedSwitcher); TextView gustTextView = (TextView) gust.getCurrentView(); if(gustTextView == null){ gust.setFactory(new ViewSwitcher.ViewFactory() { public View makeView() { TextView myText = new TextView(context); myText.setGravity(Gravity.CENTER); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.CENTER); myText.setLayoutParams(params); myText.setTextSize(18); myText.setTextColor(Color.WHITE); return myText; } }); oldGustString = ""; }else{ oldGustString = gustTextView.getText().toString(); } if(animate){ gust.setInAnimation(AnimationUtils.loadAnimation(context, R.anim.fade_in)); gust.setOutAnimation(context, R.anim.fade_out); }else{ gust.setInAnimation(AnimationUtils.loadAnimation(context, R.anim.no_anim_in)); gust.setOutAnimation(context, R.anim.no_anim_out); } if(oldWindString == "") oldWindString = "0"; if(oldGustString == "") oldGustString = "0"; final int oldWindVal = Integer.parseInt(oldWindString); final int oldGustVal = Integer.parseInt(oldGustString); wind.setText(windString); gust.setText(gustString); final ImageView gustImage = (ImageView)column.findViewById(R.id.gustImage); final ImageView windImage = (ImageView)column.findViewById(R.id.windImage); int windToDrawable; int gustToDrawable; if(windVal >= 45){ windToDrawable = R.drawable.wind_icon_12; if(oldWindVal >= 45) windColorChange = false;} else if(windVal >= 40){windToDrawable = R.drawable.wind_icon_11;if(oldWindVal >= 40 && oldWindVal < 45) windColorChange = false;} else if(windVal >= 35){windToDrawable = R.drawable.wind_icon_10;if(oldWindVal >= 35 && oldWindVal < 40) windColorChange = false;} else if(windVal >= 30){windToDrawable = R.drawable.wind_icon_9;if(oldWindVal >= 30 && oldWindVal < 35) windColorChange = false;} else if(windVal >= 25){windToDrawable = R.drawable.wind_icon_8;if(oldWindVal >= 25 && oldWindVal < 30) windColorChange = false;} else if(windVal >= 22){windToDrawable = R.drawable.wind_icon_7;if(oldWindVal >= 22 && oldWindVal < 25) windColorChange = false;} else if(windVal >= 18){windToDrawable = R.drawable.wind_icon_6;if(oldWindVal >= 18 && oldWindVal < 22) windColorChange = false;} else if(windVal >= 14){windToDrawable = R.drawable.wind_icon_5;if(oldWindVal >= 14 && oldWindVal < 18) windColorChange = false;} else if(windVal >= 10){windToDrawable = R.drawable.wind_icon_4;if(oldWindVal >= 10 && oldWindVal < 14) windColorChange = false;} else if(windVal >= 6){windToDrawable = R.drawable.wind_icon_3;if(oldWindVal >= 6 && oldWindVal < 10) windColorChange = false;} else if(windVal >= 3){windToDrawable = R.drawable.wind_icon_2;if(oldWindVal >= 3 && oldWindVal < 6) windColorChange = false;} else if(windVal >= 1){windToDrawable = R.drawable.wind_icon_1;if(oldWindVal >= 1 && oldWindVal < 3) windColorChange = false;} else {windToDrawable = R.drawable.wind_icon_0;if(oldWindVal == 0) windColorChange = false;} if(gustVal >= 45){ gustToDrawable = R.drawable.wind_icon_12; if(oldGustVal >= 45) gustColorChange = false;} else if(gustVal >= 40){gustToDrawable = R.drawable.wind_icon_11;if(oldGustVal >= 40 && oldGustVal < 45) gustColorChange = false;} else if(gustVal >= 35){gustToDrawable = R.drawable.wind_icon_10;if(oldGustVal >= 35 && oldGustVal < 40) gustColorChange = false;} else if(gustVal >= 30){gustToDrawable = R.drawable.wind_icon_9;if(oldGustVal >= 30 && oldGustVal < 35) gustColorChange = false;} else if(gustVal >= 25){gustToDrawable = R.drawable.wind_icon_8;if(oldGustVal >= 25 && oldGustVal < 30) gustColorChange = false;} else if(gustVal >= 22){gustToDrawable = R.drawable.wind_icon_7;if(oldGustVal >= 22 && oldGustVal < 25) gustColorChange = false;} else if(gustVal >= 18){gustToDrawable = R.drawable.wind_icon_6;if(oldGustVal >= 18 && oldGustVal < 22) gustColorChange = false;} else if(gustVal >= 14){gustToDrawable = R.drawable.wind_icon_5;if(oldGustVal >= 14 && oldGustVal < 18) gustColorChange = false;} else if(gustVal >= 10){gustToDrawable = R.drawable.wind_icon_4;if(oldGustVal >= 10 && oldGustVal < 14) gustColorChange = false;} else if(gustVal >= 6){gustToDrawable = R.drawable.wind_icon_3;if(oldGustVal >= 6 && oldGustVal < 10) gustColorChange = false;} else if(gustVal >= 3){gustToDrawable = R.drawable.wind_icon_2;if(oldGustVal >= 3 && oldGustVal < 6) gustColorChange = false;} else if(gustVal >= 1){gustToDrawable = R.drawable.wind_icon_1;if(oldGustVal >= 1 && oldGustVal < 3) gustColorChange = false;} else {gustToDrawable = R.drawable.wind_icon_0;if(oldGustVal == 0) gustColorChange = false;} if(windColorChange){ final TransitionDrawable windTransitionDrawable = new TransitionDrawable(new Drawable[] { windImage.getDrawable(), context.getResources().getDrawable(windToDrawable) }); windImage.setImageDrawable(windTransitionDrawable); windTransitionDrawable.setCrossFadeEnabled(true); if(animate)windTransitionDrawable.startTransition(400); else windTransitionDrawable.startTransition(0); }else{ windImage.setImageDrawable(context.getResources().getDrawable(windToDrawable)); } if(gustColorChange){ final TransitionDrawable gustTransitionDrawable = new TransitionDrawable(new Drawable[] { gustImage.getDrawable(), context.getResources().getDrawable(gustToDrawable) }); gustImage.setImageDrawable(gustTransitionDrawable); gustTransitionDrawable.setCrossFadeEnabled(true); if(animate)gustTransitionDrawable.startTransition(400); else gustTransitionDrawable.startTransition(0); }else{ gustImage.setImageDrawable(context.getResources().getDrawable(gustToDrawable)); } TextView currentDirection = (TextView)column.findViewById(R.id.direction); int currentDirectionVal = Integer.parseInt(currentDirection.getText().toString()); //Log.d("WINDFINDER APP", "rotation FROM - " + currentDirectionVal); currentDirection.setText(windDirection+""); float rotateAmount = windDirection - currentDirectionVal; //Log.d("WINDFINDER APP", "rotation TO - " + windDirection); final int windDirectionFinal = windDirection; if(currentDirectionVal != windDirection){ if(rotateAmount > 180) rotateAmount = rotateAmount - 360; else if(rotateAmount < -180) rotateAmount = rotateAmount + 360; final RotateAnimation rotateAnim = new RotateAnimation(0f, rotateAmount, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f); rotateAnim.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { //windImage.setRotation(windDirectionFinal); //gustImage.setRotation(windDirectionFinal); } @Override public void onAnimationEnd(Animation animation) { animation = new TranslateAnimation(0.0f, 0.0f, 0.0f, 0.0f); animation.setDuration(1); windImage.startAnimation(animation); gustImage.startAnimation(animation); windImage.setRotation(windDirectionFinal); gustImage.setRotation(windDirectionFinal); windImage.clearAnimation(); gustImage.clearAnimation(); } @Override public void onAnimationRepeat(Animation animation) { } }); if(animate) rotateAnim.setDuration(400); else rotateAnim.setDuration(0); rotateAnim.setFillAfter(true); rotateAnim.setFillBefore(false); gustImage.startAnimation(rotateAnim); windImage.startAnimation(rotateAnim); } } return view; } public void updateView(int newDateTab){ super.updateView(newDateTab); View view = ((Activity)context).findViewById(R.id.content_body).findViewWithTag(getTitle()); boolean animate = true; Calendar c = null; SimpleDateFormat df = new SimpleDateFormat("EEE"); if(dateTab == 2) c = Calendar.getInstance(); int timeSteps = 7; if(dateTab == 2){ timeSteps = spot.getSevenDayDayCount(); } for(int i=0; i < 7; i++){ boolean windColorChange = true; boolean gustColorChange = true; int timeStamp = (i+1)*3; TimestampData intervalData = null; if(dateTab == 0){ intervalData = spot.getTodayTimestamp(timeStamp); }else if(dateTab == 1){ intervalData = spot.getTomorrowTimestamp(timeStamp); }else { if(i < timeSteps)intervalData = spot.getSevenDayDay(i); else intervalData = null; } //Log.d("WINDFINDER APP", "Column-" + i); int colID = context.getResources().getIdentifier("column"+(i+1), "id", context.getPackageName()); View column = view.findViewById(colID); TextView time = (TextView) column.findViewById(R.id.valueText); if(dateTab == 0 || dateTab == 1){ int timeID = context.getResources().getIdentifier("time"+(i+1), "string", context.getPackageName()); time.setText(timeID); }else{ time.setText(df.format(c.getTime())); c.add(c.DAY_OF_MONTH, 1); } int windVal = 0; String windString = ""; int gustVal = 0; String gustString = ""; int windDirection = 0; if(intervalData != null){ windVal = intervalData.windSpeed; windString = Integer.toString(windVal); gustVal = intervalData.windGust; gustString = Integer.toString(gustVal); windDirection = intervalData.windDirection; //Log.d("WINDFINDER APP", "WindVal " + windVal); }else{ //Log.d("WINDFINDER APP", "intervalData null"); } String oldWindString; String oldGustString; TextSwitcher wind = (TextSwitcher) column.findViewById(R.id.windSpeedSwitcher); TextView windTextView = (TextView) wind.getCurrentView(); if(windTextView == null){ wind.setFactory(new ViewSwitcher.ViewFactory() { public View makeView() { TextView myText = new TextView(context); myText.setGravity(Gravity.CENTER); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.CENTER); myText.setLayoutParams(params); myText.setTextSize(18); myText.setTextColor(Color.WHITE); return myText; } }); oldWindString = ""; }else{ oldWindString = windTextView.getText().toString(); } if(animate){ wind.setInAnimation(AnimationUtils.loadAnimation(context, R.anim.fade_in)); wind.setOutAnimation(context, R.anim.fade_out); }else{ wind.setInAnimation(AnimationUtils.loadAnimation(context, R.anim.no_anim_in)); wind.setOutAnimation(context, R.anim.no_anim_out); } TextSwitcher gust = (TextSwitcher) column.findViewById(R.id.gustSpeedSwitcher); TextView gustTextView = (TextView) gust.getCurrentView(); if(gustTextView == null){ gust.setFactory(new ViewSwitcher.ViewFactory() { public View makeView() { TextView myText = new TextView(context); myText.setGravity(Gravity.CENTER); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.CENTER); myText.setLayoutParams(params); myText.setTextSize(18); myText.setTextColor(Color.WHITE); return myText; } }); oldGustString = ""; }else{ oldGustString = gustTextView.getText().toString(); } if(animate){ gust.setInAnimation(AnimationUtils.loadAnimation(context, R.anim.fade_in)); gust.setOutAnimation(context, R.anim.fade_out); }else{ gust.setInAnimation(AnimationUtils.loadAnimation(context, R.anim.no_anim_in)); gust.setOutAnimation(context, R.anim.no_anim_out); } if(oldWindString == "") oldWindString = "0"; if(oldGustString == "") oldGustString = "0"; final int oldWindVal = Integer.parseInt(oldWindString); final int oldGustVal = Integer.parseInt(oldGustString); wind.setText(windString); gust.setText(gustString); final ImageView gustImage = (ImageView)column.findViewById(R.id.gustImage); final ImageView windImage = (ImageView)column.findViewById(R.id.windImage); int windToDrawable; int gustToDrawable; if(windVal >= 45){ windToDrawable = R.drawable.wind_icon_12; if(oldWindVal >= 45) windColorChange = false;} else if(windVal >= 40){windToDrawable = R.drawable.wind_icon_11;if(oldWindVal >= 40 && oldWindVal < 45) windColorChange = false;} else if(windVal >= 35){windToDrawable = R.drawable.wind_icon_10;if(oldWindVal >= 35 && oldWindVal < 40) windColorChange = false;} else if(windVal >= 30){windToDrawable = R.drawable.wind_icon_9;if(oldWindVal >= 30 && oldWindVal < 35) windColorChange = false;} else if(windVal >= 25){windToDrawable = R.drawable.wind_icon_8;if(oldWindVal >= 25 && oldWindVal < 30) windColorChange = false;} else if(windVal >= 22){windToDrawable = R.drawable.wind_icon_7;if(oldWindVal >= 22 && oldWindVal < 25) windColorChange = false;} else if(windVal >= 18){windToDrawable = R.drawable.wind_icon_6;if(oldWindVal >= 18 && oldWindVal < 22) windColorChange = false;} else if(windVal >= 14){windToDrawable = R.drawable.wind_icon_5;if(oldWindVal >= 14 && oldWindVal < 18) windColorChange = false;} else if(windVal >= 10){windToDrawable = R.drawable.wind_icon_4;if(oldWindVal >= 10 && oldWindVal < 14) windColorChange = false;} else if(windVal >= 6){windToDrawable = R.drawable.wind_icon_3;if(oldWindVal >= 6 && oldWindVal < 10) windColorChange = false;} else if(windVal >= 3){windToDrawable = R.drawable.wind_icon_2;if(oldWindVal >= 3 && oldWindVal < 6) windColorChange = false;} else if(windVal >= 1){windToDrawable = R.drawable.wind_icon_1;if(oldWindVal >= 1 && oldWindVal < 3) windColorChange = false;} else {windToDrawable = R.drawable.wind_icon_0;if(oldWindVal == 0) windColorChange = false;} if(gustVal >= 45){ gustToDrawable = R.drawable.wind_icon_12; if(oldGustVal >= 45) gustColorChange = false;} else if(gustVal >= 40){gustToDrawable = R.drawable.wind_icon_11;if(oldGustVal >= 40 && oldGustVal < 45) gustColorChange = false;} else if(gustVal >= 35){gustToDrawable = R.drawable.wind_icon_10;if(oldGustVal >= 35 && oldGustVal < 40) gustColorChange = false;} else if(gustVal >= 30){gustToDrawable = R.drawable.wind_icon_9;if(oldGustVal >= 30 && oldGustVal < 35) gustColorChange = false;} else if(gustVal >= 25){gustToDrawable = R.drawable.wind_icon_8;if(oldGustVal >= 25 && oldGustVal < 30) gustColorChange = false;} else if(gustVal >= 22){gustToDrawable = R.drawable.wind_icon_7;if(oldGustVal >= 22 && oldGustVal < 25) gustColorChange = false;} else if(gustVal >= 18){gustToDrawable = R.drawable.wind_icon_6;if(oldGustVal >= 18 && oldGustVal < 22) gustColorChange = false;} else if(gustVal >= 14){gustToDrawable = R.drawable.wind_icon_5;if(oldGustVal >= 14 && oldGustVal < 18) gustColorChange = false;} else if(gustVal >= 10){gustToDrawable = R.drawable.wind_icon_4;if(oldGustVal >= 10 && oldGustVal < 14) gustColorChange = false;} else if(gustVal >= 6){gustToDrawable = R.drawable.wind_icon_3;if(oldGustVal >= 6 && oldGustVal < 10) gustColorChange = false;} else if(gustVal >= 3){gustToDrawable = R.drawable.wind_icon_2;if(oldGustVal >= 3 && oldGustVal < 6) gustColorChange = false;} else if(gustVal >= 1){gustToDrawable = R.drawable.wind_icon_1;if(oldGustVal >= 1 && oldGustVal < 3) gustColorChange = false;} else {gustToDrawable = R.drawable.wind_icon_0;if(oldGustVal == 0) gustColorChange = false;} if(windColorChange){ final TransitionDrawable windTransitionDrawable = new TransitionDrawable(new Drawable[] { windImage.getDrawable(), context.getResources().getDrawable(windToDrawable) }); windImage.setImageDrawable(windTransitionDrawable); windTransitionDrawable.setCrossFadeEnabled(true); if(animate)windTransitionDrawable.startTransition(400); else windTransitionDrawable.startTransition(0); }else{ windImage.setImageDrawable(context.getResources().getDrawable(windToDrawable)); } if(gustColorChange){ final TransitionDrawable gustTransitionDrawable = new TransitionDrawable(new Drawable[] { gustImage.getDrawable(), context.getResources().getDrawable(gustToDrawable) }); gustImage.setImageDrawable(gustTransitionDrawable); gustTransitionDrawable.setCrossFadeEnabled(true); if(animate)gustTransitionDrawable.startTransition(400); else gustTransitionDrawable.startTransition(0); }else{ gustImage.setImageDrawable(context.getResources().getDrawable(gustToDrawable)); } TextView currentDirection = (TextView)column.findViewById(R.id.direction); int currentDirectionVal = Integer.parseInt(currentDirection.getText().toString()); //Log.d("WINDFINDER APP", "rotation FROM - " + currentDirectionVal); currentDirection.setText(windDirection+""); float rotateAmount = windDirection - currentDirectionVal; //Log.d("WINDFINDER APP", "rotation TO - " + windDirection); final int windDirectionFinal = windDirection; if(currentDirectionVal != windDirection){ if(rotateAmount > 180) rotateAmount = rotateAmount - 360; else if(rotateAmount < -180) rotateAmount = rotateAmount + 360; final RotateAnimation rotateAnim = new RotateAnimation(0f, rotateAmount, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f); rotateAnim.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { //windImage.setRotation(windDirectionFinal); //gustImage.setRotation(windDirectionFinal); } @Override public void onAnimationEnd(Animation animation) { animation = new TranslateAnimation(0.0f, 0.0f, 0.0f, 0.0f); animation.setDuration(1); windImage.startAnimation(animation); gustImage.startAnimation(animation); windImage.setRotation(windDirectionFinal); gustImage.setRotation(windDirectionFinal); windImage.clearAnimation(); gustImage.clearAnimation(); } @Override public void onAnimationRepeat(Animation animation) { } }); if(animate) rotateAnim.setDuration(400); else rotateAnim.setDuration(0); rotateAnim.setFillAfter(true); rotateAnim.setFillBefore(false); gustImage.startAnimation(rotateAnim); windImage.startAnimation(rotateAnim); } } } } 0 package com.fangbian365.kuaidi.mod.asynctask.download.http; public abstract interface HttpProviderListener { public abstract boolean onStart(long contentLen); public abstract boolean onAdvance(byte[] paramArrayOfByte, int start, int len); public abstract void onFinished(); public abstract void onFail(NetworkResult paramSimpleNetworkResult, Throwable paramThrowable); public abstract long getFileSize(); } package course.hibernate.spring.entity; import lombok.Data; import javax.persistence.Embeddable; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.Id; import java.net.URL; @Entity(name = "Contact") @Data public class Contact { @Id private Integer id; @Embedded private Name name; private String notes; private URL website; private boolean starred; public Name getName() { return name; } } package com.nt.factory; import com.nt.dao.FinanceEmployeeDAOImpl; import com.nt.dao.HREmployeeDAOImpl; public class EmployeeMgmtDAOFactory { public static Object createDAO(String type){ if(type.equals("HR")) return new HREmployeeDAOImpl(); else if(type.equals("FINANCE")) return new FinanceEmployeeDAOImpl(); else throw new IllegalArgumentException("InValid option"); } } src/jsip/javax2/sip/address/SipURI.java100-1000 package javax2.sip.address; import java.text.ParseException; import java.util.Iterator; import javax2.sip.InvalidArgumentException; import javax2.sip.header.Parameters; public interface SipURI extends URI, Parameters { boolean isSecure(); void setSecure(boolean secure); String getHeader(String name); void setHeader(String name, String value); Iterator getHeaderNames(); String getHost(); void setHost(String host) throws ParseException; String getLrParam(); void setLrParam(); boolean hasLrParam(); String getMAddrParam(); void setMAddrParam(String mAddrParam) throws ParseException; int getPort(); void setPort(int port) throws InvalidArgumentException; int getTTLParam(); void setTTLParam(int ttlParam); String getTransportParam(); void setTransportParam(String transportParam) throws ParseException; boolean hasTransport(); String getUser(); void setUser(String user); String getUserParam(); void setUserParam(String userParam); String getUserType(); void removeUserType(); String getUserPassword(); void setUserPassword(String userPassword); String getUserAtHost(); String getUserAtHostPort(); String getMethodParam(); void setMethodParam(String methodParam) throws ParseException; } package org.jroute.util.json; import static org.hamcrest.Matchers.is; import static org.jroute.util.json.JsonUtil.o; import static org.jroute.util.json.JsonUtil.p; import static org.junit.Assert.assertThat; import org.junit.Test; public class JsonObjectTest { public static class A { public String data; } public static class B { public int data; public Integer data2; } public static class C { public A data; private String name; public String getName() { return name; } } @Test public void loadLoadsAllStringData() { // given JsonObject object = new JsonObject(new JsonPair("data", "value")); // when A a = object.load(A.class); // then assertThat(a.data, is("value")); } @Test public void loadLoadsAllIntegerData() { // given JsonObject object = o(p("data", 1), p("data2", 3)); // when B b = object.load(B.class); // then assertThat(b.data, is(1)); assertThat(b.data2, is(3)); } @Test public void loadConvertsNumericData() { // given JsonObject object = o(p("data", 1L), p("data2", (short) 3)); // when B b = object.load(B.class); // then assertThat(b.data, is(1)); assertThat(b.data2, is(3)); } @Test public void loadLoadsObjectsToo() throws Exception { // given JsonObject object = o(p("data", o(p("data", "hello"))), p("name", "hoho")); // when C c = object.load(C.class); // then assertThat(c.data.data, is("hello")); assertThat(c.getName(), is("hoho")); } @Test public void numericValuesConverte() throws Exception { // given // when // then } } package com.ani.captain.interfaces.web.controller.dto.function; /** * Created by huangbin on 7/7/16. */ public class ArgumentData { public ArgumentType argumentType; public Object instance; public ArgumentData() { argumentType = null; instance = null; } public ArgumentData(ArgumentType argumentType, Object instance) { this.argumentType = argumentType; this.instance = instance; } public Object get() { return instance; } } package com.tabnine.eclipse.module.impl; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.io.UnsupportedEncodingException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import com.tabnine.eclipse.constant.TabNineConstants; import com.tabnine.eclipse.data.TabNineCore; import com.tabnine.eclipse.enums.TabNinePlatformInfo; import com.tabnine.eclipse.exception.TabNineApplicationException; import com.tabnine.eclipse.module.TabNineCoreDownloader; import com.tabnine.eclipse.module.TabNineCoreManager; import com.tabnine.eclipse.util.TabNineIOUtils; import com.tabnine.eclipse.util.TabNineLangUtils; import com.tabnine.eclipse.util.TabNineLoggingUtils; /** * The basic implementation of {@link TabNineCoreManager} * @author ZhouYi * @version version * @date 2019-10-30 10:35:11 * @description description */ public class TabNineCoreManagerBasicImpl implements TabNineCoreManager { // ===== ===== ===== ===== [Constants] ===== ===== ===== ===== // // ===== ===== ===== ===== [Static Variables] ===== ===== ===== ===== // /** The folder path to storage TabNine core : {String} tabNineCoreRootFolderPath */ private static String tabNineCoreRootFolderPath = null; // ===== ===== ===== ===== [Static Block] ===== ===== ===== ===== // // ===== ===== ===== ===== [Entry Method (For test only)] ===== ===== ===== ===== // public static void main(String[] args) { System.out.println(getLocalTabNineCoreList(getTabNineCoreRootFolderPath(), TabNinePlatformInfo.getTabNinePlatformInfoMatchedCurrentOS())); } // ===== ===== ===== ===== [Test Methods] ===== ===== ===== ===== // // ===== ===== ===== ===== [Instance Variables] ===== ===== ===== ===== // /** The tabNineCore kept by this manager : {TabNineCore} tabNinecore */ protected TabNineCore tabNineCore = null; /** The downloader to get latest TabNine core from remote : {tabNineCoreDownloaderBasicImpl} tabNineCoreDownloader */ protected TabNineCoreDownloader tabNineCoreDownloader = new TabNineCoreDownloaderBasicImpl(); /** If this core manager is in a update operation: boolean inUpdateOperation */ protected boolean inUpdateOperation = false; // ===== ===== ===== ===== [Instance Methods] ===== ===== ===== ===== // /* (non-Javadoc) * @see com.tabnine.eclipse.module.impl.TabNineCoreManager#loadTabNineCore() * @return * @writer ZhouYi * @date 2019-11-07 17:00:43 * @description description */ @Override public TabNineCore loadTabNineCore() { // STEP Number Check if the {@link #tabNineCore} was initialized if (this.tabNineCore == null) { initializeTabNineCore(false); } // STEP Number Return the {@link #tabNineCore} return this.tabNineCore; } // ===== ===== ===== ===== [Instance Utility Methods - Utility] ===== ===== ===== ===== // /** * Initialize the {@link #tabNineCore} of this manager * @param forcibly If the {@link #tabNineCore} already existed, should this function init and cover it * @author ZhouYi * @since version * @date 2019-11-01 10:23:33 * @description description */ protected void initializeTabNineCore(boolean forcibly) { // STEP Number Declare variables about log String logTitle = "Try to initialize TabNine core"; // Log message title String logMessage = null; // Log message text // STEP Number Check if the {@link #tabNineCore} was initialized if ((this.tabNineCore != null) && !forcibly) { return; } // STEP Number Get core from local storage TabNinePlatformInfo platformInfo = TabNinePlatformInfo.getTabNinePlatformInfoMatchedCurrentOS(); List localTabNineCoreList = getLocalTabNineCoreList( getTabNineCoreRootFolderPath() , platformInfo ); // STEP Number Check local core list // BRANCH Number If the local core list is empty if (localTabNineCoreList.isEmpty()) { // SUBSTEP Number Print log TabNineLoggingUtils.error(logTitle + " - Cannot find any TabNine core in local storage, try to download a latest one from remote"); // SUBSTEP Number Check if the downloader function is available if (!TabNineConstants.IS_TABNINE_CORE_DOWNLOADER_AVAILABLE) { logMessage = logTitle + " - Failed: The local TabNine core dose not exist, and downloader function is unavailable"; TabNineLoggingUtils.error(logMessage); throw new TabNineApplicationException(logMessage); } // SUBSTEP Number Make up the information of latest TabNine Core String latestVersion = this.tabNineCoreDownloader.getLatestTabNineVersion(); String downloadUrlPath = this.tabNineCoreDownloader.getDownloadUrlPath(latestVersion); String destFilePath = generateLocalTabNineCoreFilePath( getTabNineCoreRootFolderPath() , latestVersion , platformInfo.toPlatformTypeText() , TABNINE_CORE_FILE_NAME_LOCAL + platformInfo.getSuffixNameOfExecutableFile() ); // SUBSTEP Number Download File (blocking operation) File downloadedCoreFile = this.tabNineCoreDownloader.downloadTabNineCode(downloadUrlPath, destFilePath); // SUBSTEP Number Check File and init if (isTabNineCoreAvailable(downloadedCoreFile)) { this.tabNineCore = new TabNineCore(downloadedCoreFile, latestVersion, platformInfo, false, null); return; } else { logMessage = logTitle + " - Failed: The local TabNine core dose not exist, and downloading operation is failed neither"; TabNineLoggingUtils.error(logMessage); throw new TabNineApplicationException(logMessage); } // BRANCH Number If the local core list is not empty } else { // SUBSTEP Number Get the newest core among local core list sortTabNineCoreByVersion(localTabNineCoreList, true); TabNineCore newestCore = localTabNineCoreList.get(0); // SUBSTEP Number Check if the downloader function is available if (!TabNineConstants.IS_TABNINE_CORE_DOWNLOADER_AVAILABLE) { this.tabNineCore = newestCore; return; } // SUBSTEP Number Start a new thread to find available update for TabNine Core if (!this.inUpdateOperation) { this.inUpdateOperation = true; // Change the operation mark new Thread(new Runnable() { @Override public void run() { // PART Number Get the latest version from remote String latestVersion = tabNineCoreDownloader.getLatestTabNineVersion(); // PART Number Compare the two versions, check if there is a newer version int compareResult = safelyCompareTabNineVersion(newestCore.getVersion(), latestVersion); // PART Number Print log TabNineLoggingUtils.info(logTitle + " - Version Check: A latest version is [" + latestVersion + "], the newest version in local storage is [" + newestCore.getVersion() + "]"); // SUBSTEP Number If a update was found, download it if (compareResult < 0) { // INNER-PART Number Print log TabNineLoggingUtils.info(logTitle + " - Try to download the latest version [" + latestVersion + "] core asynchronously"); // INNER-PART Number Make up the information of latest TabNine Core String downloadUrlPath = tabNineCoreDownloader.getDownloadUrlPath(latestVersion); String destFilePath = generateLocalTabNineCoreFilePath( getTabNineCoreRootFolderPath() , latestVersion , platformInfo.toPlatformTypeText() , TABNINE_CORE_FILE_NAME_LOCAL + platformInfo.getSuffixNameOfExecutableFile() ); // INNER-PART Number Download File (blocking operation) tabNineCoreDownloader.downloadTabNineCode(downloadUrlPath, destFilePath); // INNER-PART Number Get core from local storage List localTabNineCoreList = getLocalTabNineCoreList( getTabNineCoreRootFolderPath() , platformInfo ); // INNER-PART Number Check the amount of core file if (localTabNineCoreList.size() > LOCAL_TABNINE_CORE_FILE_LIMIT) { sortTabNineCoreByVersion(localTabNineCoreList, false); localTabNineCoreList.get(0).getCoreFile().deleteOnExit(); } } } }).start(); } // SUBSTEP Number Set the newest core in local storage as current core this.tabNineCore = newestCore; } } // ===== ===== ===== ===== [Static Utility Methods - Utility] ===== ===== ===== ===== // /** * Get the root folder path which saved primary TabNine core file * @return path The path got * @author ZhouYi * @date 2019-12-01 22:03:43 * @description description * @note note */ protected static String getTabNineCoreRootFolderPath() { // STEP Number Declare variables about log String logTitle = "Try to get the root path of folder hold TabNine core"; // Log message title String logMessage = null; // Log message text // BRANCH Number If the path cache is available, return it if (tabNineCoreRootFolderPath != null) { return tabNineCoreRootFolderPath; // BRANCH Number Or we will load the path } else { // SUBSTEP Number Declare returned variable String path = null; // SUBSTEP Number Try to get path related to the plug-in bundle try { // PART Number Get the root folder of current plug-in File projectRootFolder = TabNineIOUtils.getPluginRootFolder(); // PART Number Circularly check the available core folder until get a correct one File tabNineCoreRootFolder = null; for (int i = 0, length = TABNINE_CORE_FILE_FOLDER_NAMES.size(); i < length; i++) { tabNineCoreRootFolder = new File(projectRootFolder, TABNINE_CORE_FILE_FOLDER_NAMES.get(i)); if (tabNineCoreRootFolder.isDirectory()) { break; } } // PART Number Check the result we got, it nothing exists, try to create a default one if (!tabNineCoreRootFolder.exists()) { logMessage = logTitle + " - Warning: No core file folder exists, try to create a default folder to contain the tabnine core."; TabNineLoggingUtils.warning(logMessage); tabNineCoreRootFolder.mkdirs(); if (!tabNineCoreRootFolder.isDirectory()) { throw new IOException(logTitle + " - Failed: No core file folder exists ande the defatul folder cannot be created"); } } // PART Number Get path text of the folder path = tabNineCoreRootFolder.getAbsolutePath(); } catch (IOException e) { logMessage = logTitle + " - Failed: Unknown IOException hanppend."; TabNineLoggingUtils.error(logMessage, e); throw new TabNineApplicationException(logMessage, e); } catch (URISyntaxException e) { logMessage = logTitle + " - Failed: Unknown URISyntaxException hanppend."; TabNineLoggingUtils.error(logMessage, e); throw new TabNineApplicationException(logMessage, e); } // SUBSTEP Number Save the path got tabNineCoreRootFolderPath = path; // SUBSTEP Number Return the path return tabNineCoreRootFolderPath; } } /** * Get local TabNine core list from specified folder * @param rootFolderPath The root folder of TabNine core storage * @param tabNinePlatformInfo The platform which TabNine core is corresponding to * @return coreList The TabNine core list got * @author ZhouYi * @since version * @date 2019-11-01 10:48:20 * @description description */ protected static List getLocalTabNineCoreList(String rootFolderPath, TabNinePlatformInfo tabNinePlatformInfo) { // STEP Number Declare variables about log String logTitle = "Try to get local TabNine core list"; // Log message title String logMessage = null; // Log message text // STEP Number Validate incoming parameters if (TabNineLangUtils.isBlank(rootFolderPath) || (tabNinePlatformInfo == null)) { logMessage = logTitle + " - Failed: the folder information is not complete"; TabNineLoggingUtils.error(logMessage); throw new TabNineApplicationException(logMessage); } // STEP Number Check if the container folder existed File folder = new File(rootFolderPath); if (!folder.isDirectory()) { logMessage = logTitle + " - Failed: the folder [" + rootFolderPath + "] dose not exist or was not a directory"; TabNineLoggingUtils.error(logMessage); throw new TabNineApplicationException(logMessage); } // STEP Number Declare relative variables List coreList = new ArrayList(); // The core list got from local File[] versionFolderArray = folder.listFiles(); // The version folders in platform folder String platformTypeText = tabNinePlatformInfo.toPlatformTypeText(); String coreFileName = TABNINE_CORE_FILE_NAME_LOCAL + tabNinePlatformInfo.getSuffixNameOfExecutableFile(); // The name of core file in target platform // STEP Number Traverse all the core file inside each version folder for (File versionFolder : versionFolderArray) { // SUBSTEP Number Check the version folder if (!versionFolder.isDirectory()) { continue; } // SUBSTEP Number Concatenate core file path String coreFilePath = generateLocalTabNineCoreFilePath( getTabNineCoreRootFolderPath() , versionFolder.getName() , platformTypeText , coreFileName ); // SUBSTEP Number Try to get the core file File coreFile = new File(coreFilePath); if (coreFile.isFile() && isTabNineCoreAvailable(coreFile)) { coreList.add(new TabNineCore(coreFile, versionFolder.getName(), tabNinePlatformInfo, false, null)); continue; // CONDITION Number If the core file is not available, delete it } else { coreFile.delete(); } } // STEP Number Return the core file got return coreList; } /** * Generate path text for local TabNine core file * @param rootFolderPath The path of root folder contains TabNine core * @param version The version of target TabNine core * @param platformTypeText The platform type of target TabNine core * @param coreFileName The name of target TabNine core * @return localTabNineCoreFilePath The path generated * @author ZhouYi * @date 2019-11-01 12:31:10 * @description description * @note note */ protected static String generateLocalTabNineCoreFilePath(String rootFolderPath, String version, String platformTypeText, String coreFileName) { // STEP Number Concatenate and return result return rootFolderPath + File.separator + version + File.separator + platformTypeText + File.separator + coreFileName; } /** * Is target TabNine core file complete and available * @param coreFile The core file to judge * @return isAvailalle The judgment result * @author ZhouYi * @date 2019-11-01 12:19:27 * @description description * @note note */ protected static boolean isTabNineCoreAvailable(File coreFile) { // STEP Number Declare variables about log String logTitle = "Try to check if the TabNine core file is available"; // Log message title // STEP Number Validate incoming parameters if ((coreFile == null) || !coreFile.isFile()) { TabNineLoggingUtils.error(logTitle + " - Failed: the core file [" + coreFile.getPath() + "] dose not exist or is not a available file"); return false; } // STEP Number Try to get the information file of this core file File infoFile = new File(coreFile.getAbsolutePath() + TabNineConstants.INFO_FILE_SUFFIX_NAME); if (!infoFile.isFile()) { TabNineLoggingUtils.error(logTitle + " - Failed: the concomitant inforamtion file of [" + coreFile.getPath() + "] dose not exist or is not a available file"); return false; } // STEP Number Read the information from file and check it String line = null; // The line text read from information file try { // SUBSTEP Number Create reader LineNumberReader reader = new LineNumberReader( new InputStreamReader( new FileInputStream(infoFile), TabNineConstants.INFO_FILE_CHARSET_NAME ) ); // SUBSTEP Number Read lines until get the key information while ((line = reader.readLine()) != null) { if (line.startsWith(TabNineConstants.INFO_CONTENT_LEGNTH_PREFIX)) { TabNineIOUtils.safelyClose(reader); break; } } // SUBSTEP Number Handle the text, parse content length // NOTE Number The content length come from the downloading HTTP response header, // so it is not so stable to ensure that the TabNine core file is available, // but it is also the only we can check the core file until we found way to get standard MD5 code of file line = line.replace(TabNineConstants.INFO_CONTENT_LEGNTH_PREFIX, "").trim(); long contentLength = Long.parseLong(line); // SUBSTEP Number Compare length information and return result return (contentLength == coreFile.length()); } catch (NumberFormatException e) { TabNineLoggingUtils.error(logTitle + " - Failed: The number text of content length [" + line + "] is not available", e); } catch (UnsupportedEncodingException e) { TabNineLoggingUtils.error(logTitle + " - Failed: Unsupported character set type [" + TabNineConstants.INFO_FILE_CHARSET_NAME + "]", e); } catch (FileNotFoundException e) { TabNineLoggingUtils.error(logTitle + " - Failed: Unknown FileNotFoundException happended", e); } catch (IOException e) { TabNineLoggingUtils.error(logTitle + " - Failed: Unknown IOException happended", e); } // STEP Number If no judgment got, return false return false; } /** * Sort the TabNine core object in list by their version * @param coreList The TabNine core list * @param desc Is the sort order descend * @author ZhouYi * @date 2019-11-01 12:59:27 * @description description * @note note */ protected static void sortTabNineCoreByVersion(List coreList, boolean desc) { // STEP Number Create new comparator and do sort coreList.sort(new Comparator() { @Override public int compare(TabNineCore core1, TabNineCore core2) { // STEP Number Make comparison int comparisonResult = safelyCompareTabNineVersion(core1.getVersion(), core2.getVersion()); // STEP Number Return comparing result return desc ? - comparisonResult : comparisonResult; } }); } /** * Safely parse and compare two version text of TabNine core * @param version1 The version text 1 * @param version2 The version text 2 * @return comparisonRestul {@link Integer#compare(int, int)} * @author ZhouYi * @date 2019-11-01 13:12:48 * @description description * @note This method suit only the simple version format like "2.1.17", if there were any hyphen or modifier, it will not be recognized * @note note */ protected static int safelyCompareTabNineVersion(String version1, String version2) { // STEP Number Check if the version text is blank boolean isVersion1Blank = TabNineLangUtils.isBlank(version1); boolean isVersion2Blank = TabNineLangUtils.isBlank(version2); // STEP Number Make judgment if there was at least one blank version if (isVersion1Blank && isVersion2Blank) { return 0; } else if (isVersion1Blank) { return -1; } else if (isVersion2Blank) { return 1; } // STEP Number Make judgment when the two version text were both available String[] versionPart1 = version1.split("\\."); String[] versionPart2 = version2.split("\\."); int comparisonResult = 0; int versionLength = (versionPart1.length < versionPart2.length) ? versionPart1.length : versionPart2.length; for (int i = 0; i < versionLength; i++) { comparisonResult = safelyCompareIntegerText(versionPart1[i], versionPart2[i]); if (comparisonResult != 0) { return comparisonResult; } } // STEP Number Return 0 (for safety) return comparisonResult; } /** * Safely parse and compare two integer text * @param intText1 The integer text 1 * @param intText2 The integer text 2 * @return comparisonRestul {@link Integer#compare(int, int)} * @author ZhouYi * @date 2019-11-01 12:54:34 * @description description * @note note */ protected static int safelyCompareIntegerText(String intText1, String intText2) { // STEP Number Declare variables and set default value Integer int1 = Integer.MIN_VALUE; Integer int2 = Integer.MIN_VALUE; // STEP Number Try to parse integer numbers, if failed, it remains default value try { int1 = Integer.parseInt(intText1); } catch (NumberFormatException e) { TabNineLoggingUtils.error("Error happened while parsing text [" + intText1 + "] to int.", e); } try { int2 = Integer.parseInt(intText2); } catch (NumberFormatException e) { TabNineLoggingUtils.error("Error happened while parsing text [" + intText2 + "] to int.", e); } // STEP Number Return comparison result return Integer.compare(int1, int2); } // ===== ===== ===== ===== [Constructors] ===== ===== ===== ===== // // ===== ===== ===== ===== [Static Factory Methods] ===== ===== ===== ===== // } /* * Java * * Copyright 2014 IS2T. All rights reserved. * Use of this source code is governed by a BSD-style license that can be found at http://www.is2t.com/open-source-bsd-license/. */ package com.is2t.demo.settings.page; import java.util.List; import com.is2t.demo.settings.widget.LeftIconLabelButton; import com.is2t.demo.settings.widget.LinedToggleButton; import com.is2t.mwt.composites.BorderComposite; import com.is2t.mwt.widgets.ListComposite; import com.is2t.mwt.widgets.LookExtension; import com.is2t.mwt.widgets.Picto; import com.is2t.mwt.widgets.Picto.PictoSize; import com.is2t.mwt.widgets.label.HeadlineLabel; import com.is2t.mwt.widgets.label.LeftIconLabel; import com.is2t.mwt.widgets.scroll.ScrollComposite; import com.is2t.mwt.widgets.tiny.CheckBox; import ej.microui.Listener; import ej.mwt.Composite; import ej.mwt.MWT; import ej.mwt.Widget; public abstract class ListSettingsPage extends SettingsPage { private ScrollComposite scrollComposite; @Override protected Composite createMainContent() { boolean horizontal = false; Composite listComposite = new ListComposite(horizontal); List listContent = getListElements(); for (Widget widget : listContent) { listComposite.add(widget); } scrollComposite = new ScrollComposite(listComposite, horizontal, false); return scrollComposite; } @Override public void showNotify() { scrollComposite.showNotify(); super.showNotify(); } @Override public void hideNotify() { scrollComposite.hideNotify(); super.hideNotify(); } /** * Gets the elements printed in the list. * * @return the elements printed in the list. */ protected abstract List getListElements(); protected HeadlineLabel createHeadlineLabel(String text) { HeadlineLabel headlineLabel = new HeadlineLabel(text, "", 2); headlineLabel.setHeadlineFontSize(LookExtension.GET_MEDIUM_FONT_INDEX); headlineLabel.setUnderlined(true); return headlineLabel; } protected LeftIconLabel createItem(String text, char picto, boolean overlined) { LeftIconLabel item = new LeftIconLabel(text, new Picto(picto, PictoSize.Small)); item.setFontSize(LookExtension.GET_MEDIUM_FONT_INDEX); item.setOverlined(overlined); return item; } protected LeftIconLabelButton createSelectableItem(String text, char picto, boolean overlined, Listener listener) { LeftIconLabelButton item = new LeftIconLabelButton(text, new Picto(picto, PictoSize.Small)); item.setFontSize(LookExtension.GET_MEDIUM_FONT_INDEX); item.setOverlined(overlined); item.setListener(listener); return item; } protected LeftIconLabel createItem(String text, boolean overlined) { LeftIconLabel item = new LeftIconLabel(text, null); item.setFontSize(LookExtension.GET_MEDIUM_FONT_INDEX); item.setOverlined(overlined); return item; } protected Widget createItemWithToggleButton(String text, char picto, boolean overlined, boolean initial) { BorderComposite layout = new BorderComposite(); LeftIconLabel item = createItem(text, picto, overlined); layout.add(item); LinedToggleButton toggleButton = new LinedToggleButton(); toggleButton.setOverlined(overlined); if (initial) { toggleButton.toggleSelection(); } layout.addAt(toggleButton, MWT.EAST); return layout; } protected Widget createItemWithCheckbox(String text, char picto, boolean overlined, boolean initial) { BorderComposite layout = new BorderComposite(); LeftIconLabel item = createItem(text, picto, overlined); layout.add(item); CheckBox checkbox = new CheckBox(); // checkbox.setOverlined(overlined); if (initial) { checkbox.toggleSelection(); } layout.addAt(checkbox, MWT.EAST); return layout; } } // // Connect SDK Sample App by LG Electronics // // To the extent possible under law, the person who associated CC0 with // this sample app has waived all copyright and related or neighboring rights // to the sample app. // // You should have received a copy of the CC0 legalcode along with this // work. If not, see http://creativecommons.org/publicdomain/zero/1.0/. // package com.connectsdk.sampler; import java.util.ArrayList; import java.util.List; import tv.matchstick.flint.Flint; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.text.InputType; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.EditText; import android.widget.Toast; import com.connectsdk.device.ConnectableDevice; import com.connectsdk.device.ConnectableDeviceListener; import com.connectsdk.device.DevicePicker; import com.connectsdk.discovery.DiscoveryManager; import com.connectsdk.discovery.DiscoveryManager.PairingLevel; import com.connectsdk.sampler.fragments.BaseFragment; import com.connectsdk.service.DeviceService; import com.connectsdk.service.DeviceService.PairingType; import com.connectsdk.service.capability.MediaPlayer; import com.connectsdk.service.command.ServiceCommandError; public class MainActivity extends ActionBarActivity implements ActionBar.TabListener { private String APPLICATION_ID = "~flintplayer"; private ConnectableDevice mTV; private AlertDialog dialog; private AlertDialog pairingAlertDialog; private AlertDialog pairingCodeDialog; private DevicePicker dp; private MenuItem connectItem; SectionsPagerAdapter mSectionsPagerAdapter; ViewPager mViewPager; private ConnectableDeviceListener deviceListener = new ConnectableDeviceListener() { @Override public void onPairingRequired(ConnectableDevice device, DeviceService service, PairingType pairingType) { Log.d("2ndScreenAPP", "Connected to " + mTV.getIpAddress()); switch (pairingType) { case FIRST_SCREEN: Log.d("2ndScreenAPP", "First Screen"); pairingAlertDialog.show(); break; case PIN_CODE: Log.d("2ndScreenAPP", "Pin Code"); pairingCodeDialog.show(); break; case NONE: default: break; } } @Override public void onConnectionFailed(ConnectableDevice device, ServiceCommandError error) { Log.d("2ndScreenAPP", "onConnectFailed"); connectFailed(mTV); } @Override public void onDeviceReady(ConnectableDevice device) { if (pairingAlertDialog.isShowing()) { Log.d("2ndScreenAPP", "onPairingSuccess"); pairingAlertDialog.dismiss(); } registerSuccess(mTV); } @Override public void onDeviceDisconnected(ConnectableDevice device) { Log.d("2ndScreenAPP", "Device Disconnected"); connectEnded(mTV); connectItem.setTitle("Connect"); BaseFragment frag = mSectionsPagerAdapter.getFragment(mViewPager .getCurrentItem()); if (frag != null) { Toast.makeText(getApplicationContext(), "Device Disconnected", Toast.LENGTH_SHORT).show(); frag.disableButtons(); } } @Override public void onCapabilityUpdated(ConnectableDevice device, List added, List removed) { } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); mSectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager()); mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mSectionsPagerAdapter); mViewPager .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { actionBar.setSelectedNavigationItem(position); } }); for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) { actionBar.addTab(actionBar.newTab() .setIcon(mSectionsPagerAdapter.getIcon(i)) .setTabListener(this)); } setupPicker(); DiscoveryManager.getInstance().setPairingLevel(PairingLevel.ON); DiscoveryManager.getInstance().start(); Flint.FlintApi.setApplicationId(APPLICATION_ID); } public List getImageDevices() { List imageDevices = new ArrayList(); for (ConnectableDevice device : DiscoveryManager.getInstance() .getCompatibleDevices().values()) { if (device.hasCapability(MediaPlayer.Display_Image)) imageDevices.add(device); } return imageDevices; } @Override protected void onDestroy() { super.onDestroy(); if (dialog != null) { dialog.dismiss(); } if (mTV != null) { mTV.disconnect(); } } public void hConnectToggle() { if (!this.isFinishing()) { if (mTV != null) { if (mTV.isConnected()) mTV.disconnect(); connectItem.setTitle("Connect"); mTV.removeListener(deviceListener); mTV = null; for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) { if (mSectionsPagerAdapter.getFragment(i) != null) { mSectionsPagerAdapter.getFragment(i).setTv(null); } } } else { dialog.show(); } } } private void setupPicker() { DiscoveryManager.getInstance().registerDefaultDeviceTypes(); dp = new DevicePicker(this); dialog = dp.getPickerDialog("Device List", new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) { // DiscoveryManager.getInstance().stop(); mTV = (ConnectableDevice) arg0.getItemAtPosition(arg2); mTV.addListener(deviceListener); mTV.connect(); connectItem.setTitle(mTV.getFriendlyName()); dp.pickDevice(mTV); } }); pairingAlertDialog = new AlertDialog.Builder(this) .setTitle("Pairing with TV") .setMessage("Please confirm the connection on your TV") .setPositiveButton("Okay", null) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dp.cancelPicker(); hConnectToggle(); } }).create(); final EditText input = new EditText(this); input.setInputType(InputType.TYPE_CLASS_NUMBER); pairingCodeDialog = new AlertDialog.Builder(this) .setTitle("Enter Pairing Code on TV") .setView(input) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { if (mTV != null) { String value = input.getText().toString() .trim(); mTV.sendPairingKey(value); } } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { dp.cancelPicker(); hConnectToggle(); } }).create(); } @Override protected void onResume() { super.onResume(); } void registerSuccess(ConnectableDevice device) { Log.d("2ndScreenAPP", "successful register"); BaseFragment frag = mSectionsPagerAdapter.getFragment(mViewPager .getCurrentItem()); if (frag != null) frag.setTv(mTV); } void connectFailed(ConnectableDevice device) { if (device != null) Log.d("2ndScreenAPP", "Failed to connect to " + device.getIpAddress()); if (mTV != null) { mTV.removeListener(deviceListener); mTV.disconnect(); mTV = null; } } void connectEnded(ConnectableDevice device) { if (pairingAlertDialog.isShowing()) { pairingAlertDialog.dismiss(); } mTV.removeListener(deviceListener); mTV = null; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); connectItem = menu.getItem(0); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_connect: hConnectToggle(); return true; } return super.onOptionsItemSelected(item); } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { mViewPager.setCurrentItem(tab.getPosition()); getSupportActionBar().setTitle( mSectionsPagerAdapter.getTitle(tab.getPosition())); BaseFragment frag = mSectionsPagerAdapter .getFragment(tab.getPosition()); if (frag != null) frag.setTv(mTV); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } } KaluNight/riot-api-java package net.rithms.riot.api.endpoints.match.v5.dto; import java.io.Serializable; import net.rithms.riot.api.Dto; public class RuneSelection extends Dto implements Serializable { private static final long serialVersionUID = -4743950572043921229L; private int perk; private int var1; private int var2; private int var3; public int getPerk() { return perk; } public int getVar1() { return var1; } public int getVar2() { return var2; } public int getVar3() { return var3; } } LazaroMakarioFelipe/FLMaterialSpinner1-10 package com.lazaro.makario.flmaterialspinner; /* //// (O O) --------oOO----(_)------------------------------ Created by Làzaro, on 18/09/2017. Email: Complaint Received, 10 year later... ----------------------oOO-----------------------*/ public class FLMaterialSpinnerItem { private String itemCode; private String itemValue; FLMaterialSpinnerItem(String code, String value){ this.itemCode = code; this.itemValue = value; } public String getItemCode() { return itemCode; } public void setItemCode(String itemCode) { this.itemCode = itemCode; } public String getItemValue() { return itemValue; } public void setItemValue(String itemValue) { this.itemValue = itemValue; } } package designPattern.other.test; import org.springframework.util.StringUtils; /** * 描述: * * @author WuYanchang * @date 2021/7/9 16:39 */ class DanLi { /** * Class String is special cased within the Serialization Stream Protocol. * * A String instance is written into an ObjectOutputStream according to * * Object Serialization Specification, Section 6.2, "Stream Elements" */ //编写用来解题的方法 /** * Class String is special cased within the Serialization Stream Protocol. * * A String instance is written into an ObjectOutputStream according to * * Object Serialization Specification, Section 6.2, "Stream Elements" */ public static String compress(String s){ String result = ""; if (StringUtils.isEmpty(s)){ result ="你输入为空!"; }else if (s.contains(" ")){ result ="请不要输入空格!"; }else { int length = s.length(); System.out.println("length: "+length); int count = 0; for (int i= 1;i<=length;i++){ String[] strings1 = s.split(s.substring(0,i)); if (strings1.length==0){ System.out.println("切分到"+i); count = i; break; } } result = length/count + s.substring(0,count); } return result; } } class Test1 { public static void main(String[] args) { String s = "aaaaaa"; String result = ""; System.out.println(result); } } /* * Copyright (c) 2016, * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of this project 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 * OWNER 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.jtconnors.socketfx; import com.jtconnors.socket.Constants; import com.jtconnors.socket.DebugFlags; import com.jtconnors.socket.GenericSocket; import com.jtconnors.socket.SocketListener; import java.io.IOException; import java.lang.invoke.MethodHandles; import java.net.*; import java.util.logging.Level; import java.util.logging.Logger; public class FxSocketServer extends GenericSocket implements SocketListener { private final static Logger LOGGER = Logger.getLogger(MethodHandles.lookup().lookupClass().getName()); private SocketListener fxListener; private ServerSocket serverSocket; /** * Called whenever a message is read from the socket. In * JavaFX, this method must be run on the main thread and is * accomplished by the Platform.runLater() call. Failure to do so * *will* result in strange errors and exceptions. * @param line Line of text read from the socket. */ @Override public void onMessage(final String line) { javafx.application.Platform.runLater(() -> { fxListener.onMessage(line); }); } /** * Called whenever the open/closed status of the Socket * changes. In JavaFX, this method must be run on the main thread and is * accomplished by the Platform.runLater() call. Failure to do so * *will* result in strange errors and exceptions. * @param isClosed true if the socket is closed */ @Override public void onClosedStatus(final boolean isClosed) { javafx.application.Platform.runLater(() -> { fxListener.onClosedStatus(isClosed); }); } /** * Initialize the FxSocketServer up to and including issuing the * accept() method on its socketConnection. * @throws java.net.SocketException */ @Override protected void initSocketConnection() throws SocketException { try { /* * Create server socket */ serverSocket = new ServerSocket(getPort()); /* * Allows the socket to be bound even though a previous * connection is in a timeout state. */ serverSocket.setReuseAddress(true); /* * Wait for connection */ if (debugFlagIsSet(DebugFlags.instance().DEBUG_STATUS)) { LOGGER.info("Waiting for connection"); } socketConnection = serverSocket.accept(); if (debugFlagIsSet(DebugFlags.instance().DEBUG_STATUS)) { LOGGER.log(Level.INFO, "Connection received from {0}", socketConnection.getInetAddress().getHostName()); } } catch (IOException e) { if (debugFlagIsSet(DebugFlags.instance().DEBUG_EXCEPTIONS)) { LOGGER.log(Level.SEVERE, ExceptionStackTraceAsString(e)); } throw new SocketException(); } } /** * For FxSocketServer class, additional ServerSocket instance has * to be closed. */ @Override protected void closeAdditionalSockets() { try { if (serverSocket != null && !serverSocket.isClosed()) { serverSocket.close(); } } catch (IOException e) { LOGGER.log(Level.INFO, ExceptionStackTraceAsString(e)); } } public FxSocketServer(SocketListener fxListener, int port, int debugFlags) { super(port, debugFlags); this.fxListener = fxListener; } public FxSocketServer(SocketListener fxListener) { this(fxListener, Constants.instance().DEFAULT_PORT, DebugFlags.instance().DEBUG_NONE); } public FxSocketServer(SocketListener fxListener, int port) { this(fxListener, port, DebugFlags.instance().DEBUG_NONE); } } package com.aziz.listener; import android.animation.ValueAnimator; import android.content.Context; import android.support.v4.view.ViewPager; import android.view.animation.DecelerateInterpolator; import android.widget.TextView; import com.aziz.sleektablayout.SleekTabLayout; public class PageListener implements ViewPager.OnPageChangeListener { private Context context; private SleekTabLayout sleekTabLayout; private int lastTitle = 0; private float startSize; private float endSize; private final long animationDuration = 150; public PageListener(SleekTabLayout sleekTabLayout) { this.sleekTabLayout = sleekTabLayout; startSize = sleekTabLayout.getMinTextSize(); endSize = sleekTabLayout.getMaxTextSize(); lastTitle = sleekTabLayout.getStartAt(); } @Override public void onPageScrolled(int i, float v, int i1) { } private void resetTitle(int i) { ((TextView) sleekTabLayout.getChildAt(lastTitle)).setTextSize(startSize); ((TextView) sleekTabLayout.getChildAt(lastTitle)).setTextColor(sleekTabLayout.getTextColor()); lastTitle = i; } @Override public void onPageSelected(int i) { pageChanged(i); } @Override public void onPageScrollStateChanged(int i) { } private void pageChanged(final int i) { resetTitle(i); animateTitle(i); } private void animateTitle(final int i) { ValueAnimator animator = ValueAnimator.ofFloat(startSize, endSize); animator.setDuration(animationDuration); animator.setInterpolator(new DecelerateInterpolator()); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { float animatedValue = (float) valueAnimator.getAnimatedValue(); ((TextView) sleekTabLayout.getChildAt(i)).setTextSize(animatedValue); (sleekTabLayout.getChildAt(i)).setAlpha((animatedValue / 100) + 0.68f); if (animatedValue == endSize) { ((TextView) sleekTabLayout.getChildAt(i)).setTextColor(sleekTabLayout.getSelectedColor()); } } }); animator.start(); } } package dev.emi.trinkets.mixin; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.At.Shift; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; import dev.emi.trinkets.TrinketSlot; import dev.emi.trinkets.api.SlotAttributes; import dev.emi.trinkets.api.SlotReference; import dev.emi.trinkets.api.SlotType; import dev.emi.trinkets.api.Trinket; import dev.emi.trinkets.api.TrinketInventory; import dev.emi.trinkets.api.TrinketsApi; import net.minecraft.client.item.TooltipContext; import net.minecraft.entity.attribute.EntityAttribute; import net.minecraft.entity.attribute.EntityAttributeModifier; import net.minecraft.entity.attribute.EntityAttributes; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.text.Text; import net.minecraft.text.TranslatableText; import net.minecraft.util.Formatting; /** * Adds a tooltip for trinkets describing slots and attributes * * @author Emi */ @Mixin(ItemStack.class) public abstract class ItemStackMixin { @Inject(at = @At(value = "INVOKE", target = "Lnet/minecraft/item/ItemStack;isSectionVisible(ILnet/minecraft/item/ItemStack$TooltipSection;)Z", ordinal = 3, shift = Shift.BEFORE), method = "getTooltip", locals = LocalCapture.CAPTURE_FAILHARD) private void getTooltip(PlayerEntity player, TooltipContext context, CallbackInfoReturnable> info, List list) { TrinketsApi.getTrinketComponent(player).ifPresent(comp -> { ItemStack self = (ItemStack) (Object) this; Set slots = Sets.newHashSet(); Map> modifiers = Maps.newHashMap(); Multimap defaultModifier = null; boolean allModifiersSame = true; int slotCount = 0; for (Map.Entry> group : comp.getInventory().entrySet()) { for (Map.Entry inventory : group.getValue().entrySet()) { TrinketInventory trinketInventory = inventory.getValue(); SlotType slotType = trinketInventory.getSlotType(); for (int i = 0; i < trinketInventory.size(); i++) { SlotReference ref = new SlotReference(trinketInventory, i); boolean res = TrinketsApi.evaluatePredicateSet(slotType.getTooltipPredicates(), self, ref, player); if (res && TrinketSlot.canInsert(self, ref, player)) { boolean sameTranslationExists = false; for (SlotType t : slots) { if (t.getTranslation().getString().equals(slotType.getTranslation().getString())) { sameTranslationExists = true; break; } } if (!sameTranslationExists) { slots.add(slotType); } Trinket trinket = TrinketsApi.getTrinket((self).getItem()); Multimap map = trinket.getModifiers(self, ref, player, SlotAttributes.getUuid(ref)); if (defaultModifier == null) { defaultModifier = map; } else if (allModifiersSame) { allModifiersSame = areMapsEqual(defaultModifier, map); } boolean duplicate = false; for (var entry : modifiers.entrySet()) { if (entry.getKey().getTranslation().getString().equals(slotType.getTranslation().getString())) { if (areMapsEqual(entry.getValue(), map)) { duplicate = true; break; } } } if (!duplicate) { modifiers.put(slotType, map); } } } slotCount++; } } if (slots.size() == slotCount && slotCount > 1) { list.add(new TranslatableText("trinkets.tooltip.slots.any").formatted(Formatting.GRAY)); } else if (slots.size() > 1) { list.add(new TranslatableText("trinkets.tooltip.slots.list").formatted(Formatting.GRAY)); for (SlotType type : slots) { list.add(type.getTranslation().formatted(Formatting.BLUE)); } } else if (slots.size() == 1) { // Should only run once for (SlotType type : slots) { list.add(new TranslatableText("trinkets.tooltip.slots.single", type.getTranslation().formatted(Formatting.BLUE)).formatted(Formatting.GRAY)); } } if (modifiers.size() > 0) { if (allModifiersSame) { if (defaultModifier != null && !defaultModifier.isEmpty()) { list.add(new TranslatableText("trinkets.tooltip.attributes.all").formatted(Formatting.GRAY)); addAttributes(list, defaultModifier); } } else { for (SlotType type : modifiers.keySet()) { list.add(new TranslatableText("trinkets.tooltip.attributes.single", type.getTranslation().formatted(Formatting.BLUE)).formatted(Formatting.GRAY)); addAttributes(list, modifiers.get(type)); } } } }); } @Unique private void addAttributes(List list, Multimap map) { if (!map.isEmpty()) { for (Map.Entry entry : map.entries()) { EntityAttribute attribute = entry.getKey(); EntityAttributeModifier modifier = entry.getValue(); double g = modifier.getValue(); if (modifier.getOperation() != EntityAttributeModifier.Operation.MULTIPLY_BASE && modifier.getOperation() != EntityAttributeModifier.Operation.MULTIPLY_TOTAL) { if (entry.getKey().equals(EntityAttributes.GENERIC_KNOCKBACK_RESISTANCE)) { g *= 10.0D; } } else { g *= 100.0D; } Text text = new TranslatableText(attribute.getTranslationKey()); if (attribute instanceof SlotAttributes.SlotEntityAttribute) { text = new TranslatableText("trinkets.tooltip.attributes.slots", text); } if (g > 0.0D) { list.add(new TranslatableText("attribute.modifier.plus." + modifier.getOperation().getId(), ItemStack.MODIFIER_FORMAT.format(g), text).formatted(Formatting.BLUE)); } else if (g < 0.0D) { g *= -1.0D; list.add(new TranslatableText("attribute.modifier.take." + modifier.getOperation().getId(), ItemStack.MODIFIER_FORMAT.format(g), text).formatted(Formatting.RED)); } } } } // `equals` doesn't test thoroughly @Unique private boolean areMapsEqual(Multimap map1, Multimap map2) { if (map1.size() != map2.size()) { return false; } else { for (EntityAttribute attribute : map1.keySet()) { if (!map2.containsKey(attribute)) { return false; } Collection col1 = map1.get(attribute); Collection col2 = map2.get(attribute); if (col1.size() != col2.size()) { return false; } else { Iterator iter = col2.iterator(); for (EntityAttributeModifier modifier : col1) { EntityAttributeModifier eam = iter.next(); if (!modifier.toNbt().equals(eam.toNbt())) { return false; } } } } } return true; } } package edu.gatech.chai.VRDR.model; import org.hl7.fhir.r4.model.CodeableConcept; import org.hl7.fhir.r4.model.Identifier; import org.hl7.fhir.r4.model.Practitioner; import ca.uhn.fhir.model.api.annotation.ResourceDef; import edu.gatech.chai.VRDR.model.util.CommonUtil; @ResourceDef(name = "Practitioner", profile = "http://hl7.org/fhir/us/vrdr/StructureDefinition/VRDR-Certifier") public class Certifier extends Practitioner { public Certifier() { super(); CommonUtil.initResource(this); } public PractitionerQualificationComponent addQualification(String identifier, String type) { CodeableConcept identifierTypeCodeableConcept = CommonUtil.findConceptFromCollectionUsingSimpleString(type, CommonUtil.certifierTypeSet); PractitionerQualificationComponent component = new PractitionerQualificationComponent(identifierTypeCodeableConcept); component.addIdentifier(new Identifier().setValue(identifier)); addQualification(component); return component; } }1-10 /** * Copyright 2013 Canada Health Infoway, 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. * * Author: $LastChangedBy$ * Last modified: $LastChangedDate$ * Revision: $LastChangedRevision$ */ package ca.infoway.messagebuilder.xml; /** *

A tool that can locate message parts. * * @author Intelliware Development */ public interface MessagePartResolver { /** *

Find a message part by name. * * @param type - the name of message type to retrieve. * @return - the message part */ public MessagePart getMessagePart(String type); /** *

Find the root type of a package location. * @param packageLocationName - the name of the package location. * @return - the root type of the package location. */ public String getPackageLocationRootType(String packageLocationName); } autoconfigure/src/main/java/com/cmpl/web/configuration/manager/privileges/NewsPrivilegeConfiguration.java package com.cmpl.web.configuration.manager.privileges; import com.cmpl.web.core.common.user.Privilege; import com.cmpl.web.core.common.user.SimplePrivilege; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class NewsPrivilegeConfiguration { @Bean public Privilege newsReadPrivilege() { return new SimplePrivilege("webmastering", "news", "read"); } @Bean public Privilege newsWritePrivilege() { return new SimplePrivilege("webmastering", "news", "write"); } @Bean public Privilege newsCreatePrivilege() { return new SimplePrivilege("webmastering", "news", "create"); } @Bean public Privilege newsDeletePrivilege() { return new SimplePrivilege("webmastering", "news", "delete"); } } /* * Copyright (C) 2015 Synchronoss Technologies * * 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.synchronoss.cloud.nio.multipart.example.model; /** *

File metadata: path, size, checksum * * @author . */ public class FileMetadata { private String file; private long size; private String checksum; public String getFile() { return file; } public void setFile(String file) { this.file = file; } public long getSize() { return size; } public void setSize(long size) { this.size = size; } public String getChecksum() { return checksum; } public void setChecksum(String checksum) { this.checksum = checksum; } @Override public String toString() { return "FileMetadata{" + "file='" + file + '\'' + ", size=" + size + ", checksum='" + checksum + '\'' + '}'; } } /*Modified 9.2 (The Stock class) Following the example of the * Circle class in Section 9.2, * design a class named Stock that contains: * A string data field named symbol for the stock’s symbol. * A string data field named name for the stock’s * name.; * A double data field named previousClosingPrice * that stores the stock price for the previous day.; * A double data field named currentPrice that stores the * stock price * for the current time.; * A constructor that creates a stock * with the specified symbol and name; * A method named getChangePercent() that returns the * percentage changed * from previousClosingPrice to currentPrice. Make a UML * diagram for the class in the comments in the top of the * class, and then implement the class. Write a test program * that creates a Stock object with the stock symbol ORCL, the * name Oracle Corporation, and the previous closing price of * 34.5. Set a new current price to 34.35 and display the * price-change percentage. */ public class Ex_9_2 { /** Main method */ public static void main(String[] args) { // Create a Stock object with the stock // symbol ORCL, the name Oracle Corporation Stock stock = new Stock("ORCL", "Oracle Corporation"); stock.previousClosingPrice = 34.5; stock.currentPrice = 34.35; // Display the price-change percentage System.out.println("\nStock name: " + stock.name); System.out.println("Stock symbol: " + stock.symbol); System.out.printf("Price-change percentage: %.2f%%\n", stock.getChangePercent()); } }szemyxz/Filmbox package pl.filmbox.validators; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; import pl.filmbox.models.User; import pl.filmbox.services.UserService; @Component public class UserValidation implements Validator { private static final String EMAIL_PATTERN = "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$"; private final UserService userService; @Autowired public UserValidation(UserService userService) { this.userService = userService; } @Override public boolean supports(Class clazz) { return User.class.isAssignableFrom(clazz); } @Override public void validate(Object target, Errors errors) { User user = (User) target; ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "username.notEmpty"); if (user.getUsername().length() < 6 || user.getUsername().length() > 32) { errors.rejectValue("username", "username.size"); } if (userService.getUserByUsername(user.getUsername()) != null) { errors.rejectValue("username", "username.duplicate"); } ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "password.notEmpty"); if (user.getPassword().length() < 8) { errors.rejectValue("password", "password.size"); } ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "email.notEmpty"); if (user.getEmail().matches(EMAIL_PATTERN)) { errors.rejectValue("email", "email.regex"); } if (userService.getUserByEmail(user.getEmail()) != null) { errors.rejectValue("email", "email.duplicate"); } } } omp-user-center/src/main/java/com/ahdms/user/center/bean/bo/CompanyInfoBo.java0 package com.ahdms.user.center.bean.bo; /** * @author qinxiang * @date 2020-07-23 17:58 */ public class CompanyInfoBo { } /* * Copyright 2017-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.glowroot.common2.repo.util; import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; import java.text.NumberFormat; import java.util.Locale; import com.google.common.annotations.VisibleForTesting; public class Formatting { private Formatting() {} public static String displaySixDigitsOfPrecision(double value) { return displaySixDigitsOfPrecision(value, Locale.getDefault()); } static String formatBytes(long bytes) { return formatBytes(bytes, Locale.getDefault()); } // this mimics the javascript function of same name in gauge-values.js @VisibleForTesting static String displaySixDigitsOfPrecision(double value, Locale locale) { NumberFormat format = NumberFormat.getInstance(locale); format.setMaximumFractionDigits(20); if (value < 1000000) { return format.format( BigDecimal.valueOf(value).round(new MathContext(6, RoundingMode.HALF_UP))); } else { return format.format(Math.round(value)); } } // this mimics the javascript function of same name in handlebars-rendering.js @VisibleForTesting static String formatBytes(long bytes, Locale locale) { if (bytes == 0) { // no unit needed return "0"; } if (bytes == 1) { // special case for singular return "1 byte"; } String[] units = new String[] {"bytes", "KB", "MB", "GB", "TB", "PB"}; int number = (int) Math.floor(Math.log(bytes) / Math.log(1024)); double num = bytes / Math.pow(1024, number); if (number == 0) { return Math.round(num) + " bytes"; } else { NumberFormat format = NumberFormat.getInstance(locale); format.setGroupingUsed(false); format.setRoundingMode(RoundingMode.HALF_UP); format.setMinimumFractionDigits(1); format.setMaximumFractionDigits(1); return format.format(num) + ' ' + units[number]; } } } /* GtkMouseDragGestureRecognizer.java -- Copyright (C) 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package gnu.java.awt.dnd; import java.awt.Component; import java.awt.Point; import java.awt.dnd.DnDConstants; import java.awt.dnd.DragGestureListener; import java.awt.dnd.DragSource; import java.awt.dnd.MouseDragGestureRecognizer; import java.awt.event.MouseEvent; public class GtkMouseDragGestureRecognizer extends MouseDragGestureRecognizer { public GtkMouseDragGestureRecognizer (DragSource ds) { this(ds, null, 0, null); } public GtkMouseDragGestureRecognizer (DragSource ds, Component c) { this (ds, c, 0, null); } public GtkMouseDragGestureRecognizer (DragSource ds, Component c, int act) { this(ds, c, act, null); } public GtkMouseDragGestureRecognizer (DragSource ds, Component c, int act, DragGestureListener dgl) { super(ds, c, act, dgl); } public void registerListeners () { super.registerListeners(); } public void unregisterListeners () { super.unregisterListeners(); } public void mouseClicked (MouseEvent e) { // Nothing to do here. } public void mousePressed (MouseEvent e) { events.clear(); if (getDropActionFromEvent(e) != DnDConstants.ACTION_NONE) appendEvent(e); } public void mouseReleased (MouseEvent e) { events.clear(); } public void mouseEntered (MouseEvent e) { events.clear(); } public void mouseExited(MouseEvent e) { if (!events.isEmpty()) if (getDropActionFromEvent(e) == DnDConstants.ACTION_NONE) events.clear(); } public void mouseDragged(MouseEvent e) { if (!events.isEmpty()) { int act = getDropActionFromEvent(e); if (act == DnDConstants.ACTION_NONE) return; Point origin = ((MouseEvent) events.get(0)).getPoint(); Point current = e.getPoint(); int dx = Math.abs(origin.x - current.x); int dy = Math.abs(origin.y - current.y); int threshold = DragSource.getDragThreshold(); if (dx > threshold || dy > threshold) fireDragGestureRecognized(act, origin); else appendEvent(e); } } public void mouseMoved (MouseEvent e) { // Nothing to do here. } private int getDropActionFromEvent(MouseEvent e) { int modEx = e.getModifiersEx(); int buttons = modEx & (MouseEvent.BUTTON1_DOWN_MASK | MouseEvent.BUTTON2_DOWN_MASK | MouseEvent.BUTTON3_DOWN_MASK); if (!(buttons == MouseEvent.BUTTON1_DOWN_MASK || buttons == MouseEvent.BUTTON2_DOWN_MASK)) return DnDConstants.ACTION_NONE; // Convert modifier to a drop action int sourceActions = getSourceActions(); int mod = modEx & (MouseEvent.SHIFT_DOWN_MASK | MouseEvent.CTRL_DOWN_MASK); switch (mod) { case MouseEvent.SHIFT_DOWN_MASK | MouseEvent.CTRL_DOWN_MASK: return DnDConstants.ACTION_LINK & sourceActions; case MouseEvent.CTRL_DOWN_MASK: return DnDConstants.ACTION_COPY & sourceActions; case MouseEvent.SHIFT_DOWN_MASK: return DnDConstants.ACTION_MOVE & sourceActions; default: if ((sourceActions & DnDConstants.ACTION_MOVE) != 0) return DnDConstants.ACTION_MOVE & sourceActions; else if ((sourceActions & DnDConstants.ACTION_COPY) != 0) return DnDConstants.ACTION_COPY & sourceActions; else if ((sourceActions & DnDConstants.ACTION_LINK) != 0) return DnDConstants.ACTION_LINK & sourceActions; } return DnDConstants.ACTION_NONE & sourceActions; } } begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/** * 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. */ end_comment begin_package DECL|package|org.apache.hadoop.yarn.server.resourcemanager.security package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|server operator|. name|resourcemanager operator|. name|security package|; end_package begin_import import|import name|com operator|. name|google operator|. name|protobuf operator|. name|BlockingService import|; end_import begin_import import|import name|com operator|. name|google operator|. name|protobuf operator|. name|RpcController import|; end_import begin_import import|import name|com operator|. name|google operator|. name|protobuf operator|. name|ServiceException import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|conf operator|. name|Configuration import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|fs operator|. name|CommonConfigurationKeysPublic import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|ipc operator|. name|ProtobufRpcEngine import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|ipc operator|. name|ProtocolInfo import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|ipc operator|. name|RPC import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|ipc operator|. name|RemoteException import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|ipc operator|. name|Server import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|ipc operator|. name|TestRpcBase import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|ipc operator|. name|protobuf operator|. name|TestProtos import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|ipc operator|. name|protobuf operator|. name|TestRpcServiceProtos import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|net operator|. name|NetUtils import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|security operator|. name|KerberosInfo import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|security operator|. name|SecurityInfo import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|security operator|. name|SecurityUtil import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|security operator|. name|UserGroupInformation import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|security operator|. name|token operator|. name|Token import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|security operator|. name|token operator|. name|TokenIdentifier import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|security operator|. name|token operator|. name|TokenInfo import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|security operator|. name|token operator|. name|TokenSelector import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|service operator|. name|AbstractService import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|ContainerManagementProtocol import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|protocolrecords operator|. name|GetApplicationReportRequest import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|protocolrecords operator|. name|GetApplicationReportResponse import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|protocolrecords operator|. name|RegisterApplicationMasterResponse import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|protocolrecords operator|. name|StartContainersRequest import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|protocolrecords operator|. name|StartContainersResponse import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|records operator|. name|ApplicationAttemptId import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|records operator|. name|ApplicationReport import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|conf operator|. name|YarnConfiguration import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|exceptions operator|. name|YarnRuntimeException import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|security operator|. name|client operator|. name|ClientToAMTokenIdentifier import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|security operator|. name|client operator|. name|ClientToAMTokenSecretManager import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|security operator|. name|client operator|. name|ClientToAMTokenSelector import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|server operator|. name|resourcemanager operator|. name|ClientRMService import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|server operator|. name|resourcemanager operator|. name|MockAM import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|server operator|. name|resourcemanager operator|. name|MockNM import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|server operator|. name|resourcemanager operator|. name|MockRM import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|server operator|. name|resourcemanager operator|. name|MockRMAppSubmitter import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|server operator|. name|resourcemanager operator|. name|MockRMWithCustomAMLauncher import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|server operator|. name|resourcemanager operator|. name|ParameterizedSchedulerTestBase import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|server operator|. name|resourcemanager operator|. name|rmapp operator|. name|RMApp import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|server operator|. name|utils operator|. name|BuilderUtils import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|util operator|. name|ConverterUtils import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|util operator|. name|Records import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Assert import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Before import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Test import|; end_import begin_import import|import name|javax operator|. name|security operator|. name|sasl operator|. name|SaslException import|; end_import begin_import import|import name|java operator|. name|io operator|. name|IOException import|; end_import begin_import import|import name|java operator|. name|lang operator|. name|annotation operator|. name|Annotation import|; end_import begin_import import|import name|java operator|. name|net operator|. name|InetSocketAddress import|; end_import begin_import import|import name|java operator|. name|nio operator|. name|ByteBuffer import|; end_import begin_import import|import name|java operator|. name|security operator|. name|PrivilegedAction import|; end_import begin_import import|import name|java operator|. name|security operator|. name|PrivilegedExceptionAction import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Timer import|; end_import begin_import import|import name|java operator|. name|util operator|. name|TimerTask import|; end_import begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|fail import|; end_import begin_import import|import static name|org operator|. name|mockito operator|. name|ArgumentMatchers operator|. name|any import|; end_import begin_import import|import static name|org operator|. name|mockito operator|. name|Mockito operator|. name|mock import|; end_import begin_import import|import static name|org operator|. name|mockito operator|. name|Mockito operator|. name|when import|; end_import begin_class DECL|class|TestClientToAMTokens specifier|public class|class name|TestClientToAMTokens extends|extends name|ParameterizedSchedulerTestBase block|{ DECL|field|conf specifier|private name|YarnConfiguration name|conf decl_stmt|; DECL|method|TestClientToAMTokens (SchedulerType type) specifier|public name|TestClientToAMTokens parameter_list|( name|SchedulerType name|type parameter_list|) throws|throws name|IOException block|{ name|super argument_list|( name|type argument_list|) expr_stmt|; block|} annotation|@ name|Before DECL|method|setup () specifier|public name|void name|setup parameter_list|() block|{ name|conf operator|= name|getConf argument_list|() expr_stmt|; block|} annotation|@ name|TokenInfo argument_list|( name|ClientToAMTokenSelector operator|. name|class argument_list|) annotation|@ name|ProtocolInfo argument_list|( name|protocolName operator|= literal|"org.apache.hadoop.yarn.server.resourcemanager.security$CustomProtocol" argument_list|, name|protocolVersion operator|= literal|1 argument_list|) DECL|interface|CustomProtocol specifier|public interface|interface name|CustomProtocol extends|extends name|TestRpcServiceProtos operator|. name|CustomProto operator|. name|BlockingInterface block|{ } DECL|class|CustomSecurityInfo specifier|private specifier|static class|class name|CustomSecurityInfo extends|extends name|SecurityInfo block|{ annotation|@ name|Override DECL|method|getTokenInfo (Class protocol, Configuration conf) specifier|public name|TokenInfo name|getTokenInfo parameter_list|( name|Class argument_list|< name|? argument_list|> name|protocol parameter_list|, name|Configuration name|conf parameter_list|) block|{ return|return operator|new name|TokenInfo argument_list|() block|{ annotation|@ name|Override specifier|public name|Class argument_list|< name|? extends|extends name|Annotation argument_list|> name|annotationType parameter_list|() block|{ return|return literal|null return|; block|} annotation|@ name|Override specifier|public name|Class argument_list|< name|? extends|extends name|TokenSelector argument_list|< name|? extends|extends name|TokenIdentifier argument_list|> argument_list|> name|value parameter_list|() block|{ return|return name|ClientToAMTokenSelector operator|. name|class return|; block|} block|} return|; block|} annotation|@ name|Override DECL|method|getKerberosInfo (Class protocol, Configuration conf) specifier|public name|KerberosInfo name|getKerberosInfo parameter_list|( name|Class argument_list|< name|? argument_list|> name|protocol parameter_list|, name|Configuration name|conf parameter_list|) block|{ return|return literal|null return|; block|} block|} empty_stmt|; DECL|class|CustomAM specifier|private specifier|static class|class name|CustomAM extends|extends name|AbstractService implements|implements name|CustomProtocol block|{ DECL|field|appAttemptId specifier|private specifier|final name|ApplicationAttemptId name|appAttemptId decl_stmt|; DECL|field|secretKey specifier|private specifier|final name|byte index|[] name|secretKey decl_stmt|; DECL|field|address specifier|private name|InetSocketAddress name|address decl_stmt|; DECL|field|pinged specifier|private name|boolean name|pinged init|= literal|false decl_stmt|; DECL|field|secretMgr specifier|private name|ClientToAMTokenSecretManager name|secretMgr decl_stmt|; DECL|method|CustomAM (ApplicationAttemptId appId, byte[] secretKey) specifier|public name|CustomAM parameter_list|( name|ApplicationAttemptId name|appId parameter_list|, name|byte index|[] name|secretKey parameter_list|) block|{ name|super argument_list|( literal|"CustomAM" argument_list|) expr_stmt|; name|this operator|. name|appAttemptId operator|= name|appId expr_stmt|; name|this operator|. name|secretKey operator|= name|secretKey expr_stmt|; block|} annotation|@ name|Override DECL|method|ping (RpcController unused, TestProtos.EmptyRequestProto request) specifier|public name|TestProtos operator|. name|EmptyResponseProto name|ping parameter_list|( name|RpcController name|unused parameter_list|, name|TestProtos operator|. name|EmptyRequestProto name|request parameter_list|) throws|throws name|ServiceException block|{ name|this operator|. name|pinged operator|= literal|true expr_stmt|; return|return name|TestProtos operator|. name|EmptyResponseProto operator|. name|newBuilder argument_list|() operator|. name|build argument_list|() return|; block|} DECL|method|getClientToAMTokenSecretManager () specifier|public name|ClientToAMTokenSecretManager name|getClientToAMTokenSecretManager parameter_list|() block|{ return|return name|secretMgr return|; block|} annotation|@ name|Override DECL|method|serviceStart () specifier|protected name|void name|serviceStart parameter_list|() throws|throws name|Exception block|{ name|Configuration name|conf init|= name|getConfig argument_list|() decl_stmt|; comment|// Set RPC engine to protobuf RPC engine name|RPC operator|. name|setProtocolEngine argument_list|( name|conf argument_list|, name|CustomProtocol operator|. name|class argument_list|, name|ProtobufRpcEngine operator|. name|class argument_list|) expr_stmt|; name|UserGroupInformation operator|. name|setConfiguration argument_list|( name|conf argument_list|) expr_stmt|; name|BlockingService name|service init|= name|TestRpcServiceProtos operator|. name|CustomProto operator|. name|newReflectiveBlockingService argument_list|( name|this argument_list|) decl_stmt|; name|Server name|server decl_stmt|; try|try block|{ name|secretMgr operator|= operator|new name|ClientToAMTokenSecretManager argument_list|( name|this operator|. name|appAttemptId argument_list|, name|secretKey argument_list|) expr_stmt|; name|server operator|= operator|new name|RPC operator|. name|Builder argument_list|( name|conf argument_list|) operator|. name|setProtocol argument_list|( name|CustomProtocol operator|. name|class argument_list|) operator|. name|setNumHandlers argument_list|( literal|1 argument_list|) operator|. name|setSecretManager argument_list|( name|secretMgr argument_list|) operator|. name|setInstance argument_list|( name|service argument_list|) operator|. name|build argument_list|() expr_stmt|; block|} catch|catch parameter_list|( name|Exception name|e parameter_list|) block|{ throw|throw operator|new name|YarnRuntimeException argument_list|( name|e argument_list|) throw|; block|} name|server operator|. name|start argument_list|() expr_stmt|; name|this operator|. name|address operator|= name|NetUtils operator|. name|getConnectAddress argument_list|( name|server argument_list|) expr_stmt|; name|super operator|. name|serviceStart argument_list|() expr_stmt|; block|} DECL|method|setClientSecretKey (byte[] key) specifier|public name|void name|setClientSecretKey parameter_list|( name|byte index|[] name|key parameter_list|) block|{ name|secretMgr operator|. name|setMasterKey argument_list|( name|key argument_list|) expr_stmt|; block|} block|} annotation|@ name|Test DECL|method|testClientToAMTokens () specifier|public name|void name|testClientToAMTokens parameter_list|() throws|throws name|Exception block|{ name|conf operator|. name|set argument_list|( name|CommonConfigurationKeysPublic operator|. name|HADOOP_SECURITY_AUTHENTICATION argument_list|, literal|"kerberos" argument_list|) expr_stmt|; comment|// Set RPC engine to protobuf RPC engine name|RPC operator|. name|setProtocolEngine argument_list|( name|conf argument_list|, name|CustomProtocol operator|. name|class argument_list|, name|ProtobufRpcEngine operator|. name|class argument_list|) expr_stmt|; name|UserGroupInformation operator|. name|setConfiguration argument_list|( name|conf argument_list|) expr_stmt|; name|ContainerManagementProtocol name|containerManager init|= name|mock argument_list|( name|ContainerManagementProtocol operator|. name|class argument_list|) decl_stmt|; name|StartContainersResponse name|mockResponse init|= name|mock argument_list|( name|StartContainersResponse operator|. name|class argument_list|) decl_stmt|; name|when argument_list|( name|containerManager operator|. name|startContainers argument_list|( operator|( name|StartContainersRequest operator|) name|any argument_list|() argument_list|) argument_list|) operator|. name|thenReturn argument_list|( name|mockResponse argument_list|) expr_stmt|; name|MockRM name|rm init|= operator|new name|MockRMWithCustomAMLauncher argument_list|( name|conf argument_list|, name|containerManager argument_list|) block|{ specifier|protected name|ClientRMService name|createClientRMService parameter_list|() block|{ return|return operator|new name|ClientRMService argument_list|( name|this operator|. name|rmContext argument_list|, name|scheduler argument_list|, name|this operator|. name|rmAppManager argument_list|, name|this operator|. name|applicationACLsManager argument_list|, name|this operator|. name|queueACLsManager argument_list|, name|getRMContext argument_list|() operator|. name|getRMDelegationTokenSecretManager argument_list|() argument_list|) return|; block|} empty_stmt|; annotation|@ name|Override specifier|protected name|void name|doSecureLogin parameter_list|() throws|throws name|IOException block|{ } block|} decl_stmt|; name|rm operator|. name|start argument_list|() expr_stmt|; comment|// Submit an app name|RMApp name|app init|= name|MockRMAppSubmitter operator|. name|submitWithMemory argument_list|( literal|1024 argument_list|, name|rm argument_list|) decl_stmt|; comment|// Set up a node. name|MockNM name|nm1 init|= name|rm operator|. name|registerNode argument_list|( literal|"localhost:1234" argument_list|, literal|3072 argument_list|) decl_stmt|; name|nm1 operator|. name|nodeHeartbeat argument_list|( literal|true argument_list|) expr_stmt|; name|rm operator|. name|drainEvents argument_list|() expr_stmt|; name|nm1 operator|. name|nodeHeartbeat argument_list|( literal|true argument_list|) expr_stmt|; name|rm operator|. name|drainEvents argument_list|() expr_stmt|; name|ApplicationAttemptId name|appAttempt init|= name|app operator|. name|getCurrentAppAttempt argument_list|() operator|. name|getAppAttemptId argument_list|() decl_stmt|; specifier|final name|MockAM name|mockAM init|= operator|new name|MockAM argument_list|( name|rm operator|. name|getRMContext argument_list|() argument_list|, name|rm operator|. name|getApplicationMasterService argument_list|() argument_list|, name|app operator|. name|getCurrentAppAttempt argument_list|() operator|. name|getAppAttemptId argument_list|() argument_list|) decl_stmt|; name|UserGroupInformation name|appUgi init|= name|UserGroupInformation operator|. name|createRemoteUser argument_list|( name|appAttempt operator|. name|toString argument_list|() argument_list|) decl_stmt|; name|RegisterApplicationMasterResponse name|response init|= name|appUgi operator|. name|doAs argument_list|( operator|new name|PrivilegedAction argument_list|< name|RegisterApplicationMasterResponse argument_list|> argument_list|() block|{ annotation|@ name|Override specifier|public name|RegisterApplicationMasterResponse name|run parameter_list|() block|{ name|RegisterApplicationMasterResponse name|response init|= literal|null decl_stmt|; try|try block|{ name|response operator|= name|mockAM operator|. name|registerAppAttempt argument_list|() expr_stmt|; block|} catch|catch parameter_list|( name|Exception name|e parameter_list|) block|{ name|Assert operator|. name|fail argument_list|( literal|"Exception was not expected" argument_list|) expr_stmt|; block|} return|return name|response return|; block|} block|} argument_list|) decl_stmt|; comment|// Get the app-report. name|GetApplicationReportRequest name|request init|= name|Records operator|. name|newRecord argument_list|( name|GetApplicationReportRequest operator|. name|class argument_list|) decl_stmt|; name|request operator|. name|setApplicationId argument_list|( name|app operator|. name|getApplicationId argument_list|() argument_list|) expr_stmt|; name|GetApplicationReportResponse name|reportResponse init|= name|rm operator|. name|getClientRMService argument_list|() operator|. name|getApplicationReport argument_list|( name|request argument_list|) decl_stmt|; name|ApplicationReport name|appReport init|= name|reportResponse operator|. name|getApplicationReport argument_list|() decl_stmt|; name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|records operator|. name|Token name|originalClientToAMToken init|= name|appReport operator|. name|getClientToAMToken argument_list|() decl_stmt|; comment|// ClientToAMToken master key should have been received on register comment|// application master response. name|Assert operator|. name|assertNotNull argument_list|( name|response operator|. name|getClientToAMTokenMasterKey argument_list|() argument_list|) expr_stmt|; name|Assert operator|. name|assertTrue argument_list|( name|response operator|. name|getClientToAMTokenMasterKey argument_list|() operator|. name|array argument_list|() operator|. name|length operator|> literal|0 argument_list|) expr_stmt|; comment|// Start the AM with the correct shared-secret. name|ApplicationAttemptId name|appAttemptId init|= name|app operator|. name|getAppAttempts argument_list|() operator|. name|keySet argument_list|() operator|. name|iterator argument_list|() operator|. name|next argument_list|() decl_stmt|; name|Assert operator|. name|assertNotNull argument_list|( name|appAttemptId argument_list|) expr_stmt|; specifier|final name|CustomAM name|am init|= operator|new name|CustomAM argument_list|( name|appAttemptId argument_list|, name|response operator|. name|getClientToAMTokenMasterKey argument_list|() operator|. name|array argument_list|() argument_list|) decl_stmt|; name|am operator|. name|init argument_list|( name|conf argument_list|) expr_stmt|; name|am operator|. name|start argument_list|() expr_stmt|; comment|// Now the real test! comment|// Set up clients to be able to pick up correct tokens. name|SecurityUtil operator|. name|setSecurityInfoProviders argument_list|( operator|new name|CustomSecurityInfo argument_list|() argument_list|) expr_stmt|; comment|// Verify denial for unauthenticated user try|try block|{ name|CustomProtocol name|client init|= name|RPC operator|. name|getProxy argument_list|( name|CustomProtocol operator|. name|class argument_list|, literal|1L argument_list|, name|am operator|. name|address argument_list|, name|conf argument_list|) decl_stmt|; name|client operator|. name|ping argument_list|( literal|null argument_list|, name|TestRpcBase operator|. name|newEmptyRequest argument_list|() argument_list|) expr_stmt|; name|fail argument_list|( literal|"Access by unauthenticated user should fail!!" argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|Exception name|e parameter_list|) block|{ name|Assert operator|. name|assertFalse argument_list|( name|am operator|. name|pinged argument_list|) expr_stmt|; block|} name|Token argument_list|< name|ClientToAMTokenIdentifier argument_list|> name|token init|= name|ConverterUtils operator|. name|convertFromYarn argument_list|( name|originalClientToAMToken argument_list|, name|am operator|. name|address argument_list|) decl_stmt|; comment|// Verify denial for a malicious user with tampered ID name|verifyTokenWithTamperedID argument_list|( name|conf argument_list|, name|am argument_list|, name|token argument_list|) expr_stmt|; comment|// Verify denial for a malicious user with tampered user-name name|verifyTokenWithTamperedUserName argument_list|( name|conf argument_list|, name|am argument_list|, name|token argument_list|) expr_stmt|; comment|// Now for an authenticated user name|verifyValidToken argument_list|( name|conf argument_list|, name|am argument_list|, name|token argument_list|) expr_stmt|; comment|// Verify for a new version token name|verifyNewVersionToken argument_list|( name|conf argument_list|, name|am argument_list|, name|token argument_list|, name|rm argument_list|) expr_stmt|; name|am operator|. name|stop argument_list|() expr_stmt|; name|rm operator|. name|stop argument_list|() expr_stmt|; block|} DECL|method|verifyTokenWithTamperedID (final Configuration conf, final CustomAM am, Token token) specifier|private name|void name|verifyTokenWithTamperedID parameter_list|( specifier|final name|Configuration name|conf parameter_list|, specifier|final name|CustomAM name|am parameter_list|, name|Token argument_list|< name|ClientToAMTokenIdentifier argument_list|> name|token parameter_list|) throws|throws name|IOException block|{ comment|// Malicious user, messes with appId name|UserGroupInformation name|ugi init|= name|UserGroupInformation operator|. name|createRemoteUser argument_list|( literal|"me" argument_list|) decl_stmt|; name|ClientToAMTokenIdentifier name|maliciousID init|= operator|new name|ClientToAMTokenIdentifier argument_list|( name|BuilderUtils operator|. name|newApplicationAttemptId argument_list|( name|BuilderUtils operator|. name|newApplicationId argument_list|( name|am operator|. name|appAttemptId operator|. name|getApplicationId argument_list|() operator|. name|getClusterTimestamp argument_list|() argument_list|, literal|42 argument_list|) argument_list|, literal|43 argument_list|) argument_list|, name|UserGroupInformation operator|. name|getCurrentUser argument_list|() operator|. name|getShortUserName argument_list|() argument_list|) decl_stmt|; name|verifyTamperedToken argument_list|( name|conf argument_list|, name|am argument_list|, name|token argument_list|, name|ugi argument_list|, name|maliciousID argument_list|) expr_stmt|; block|} DECL|method|verifyTokenWithTamperedUserName (final Configuration conf, final CustomAM am, Token token) specifier|private name|void name|verifyTokenWithTamperedUserName parameter_list|( specifier|final name|Configuration name|conf parameter_list|, specifier|final name|CustomAM name|am parameter_list|, name|Token argument_list|< name|ClientToAMTokenIdentifier argument_list|> name|token parameter_list|) throws|throws name|IOException block|{ comment|// Malicious user, messes with appId name|UserGroupInformation name|ugi init|= name|UserGroupInformation operator|. name|createRemoteUser argument_list|( literal|"me" argument_list|) decl_stmt|; name|ClientToAMTokenIdentifier name|maliciousID init|= operator|new name|ClientToAMTokenIdentifier argument_list|( name|am operator|. name|appAttemptId argument_list|, literal|"evilOrc" argument_list|) decl_stmt|; name|verifyTamperedToken argument_list|( name|conf argument_list|, name|am argument_list|, name|token argument_list|, name|ugi argument_list|, name|maliciousID argument_list|) expr_stmt|; block|} DECL|method|verifyTamperedToken (final Configuration conf, final CustomAM am, Token token, UserGroupInformation ugi, ClientToAMTokenIdentifier maliciousID) specifier|private name|void name|verifyTamperedToken parameter_list|( specifier|final name|Configuration name|conf parameter_list|, specifier|final name|CustomAM name|am parameter_list|, name|Token argument_list|< name|ClientToAMTokenIdentifier argument_list|> name|token parameter_list|, name|UserGroupInformation name|ugi parameter_list|, name|ClientToAMTokenIdentifier name|maliciousID parameter_list|) block|{ name|Token argument_list|< name|ClientToAMTokenIdentifier argument_list|> name|maliciousToken init|= operator|new name|Token argument_list|< name|ClientToAMTokenIdentifier argument_list|> argument_list|( name|maliciousID operator|. name|getBytes argument_list|() argument_list|, name|token operator|. name|getPassword argument_list|() argument_list|, name|token operator|. name|getKind argument_list|() argument_list|, name|token operator|. name|getService argument_list|() argument_list|) decl_stmt|; name|ugi operator|. name|addToken argument_list|( name|maliciousToken argument_list|) expr_stmt|; try|try block|{ name|ugi operator|. name|doAs argument_list|( operator|new name|PrivilegedExceptionAction argument_list|< name|Void argument_list|> argument_list|() block|{ annotation|@ name|Override specifier|public name|Void name|run parameter_list|() throws|throws name|Exception block|{ try|try block|{ name|CustomProtocol name|client init|= name|RPC operator|. name|getProxy argument_list|( name|CustomProtocol operator|. name|class argument_list|, literal|1L argument_list|, name|am operator|. name|address argument_list|, name|conf argument_list|) decl_stmt|; name|client operator|. name|ping argument_list|( literal|null argument_list|, name|TestRpcBase operator|. name|newEmptyRequest argument_list|() argument_list|) expr_stmt|; name|fail argument_list|( literal|"Connection initiation with illegally modified " operator|+ literal|"tokens is expected to fail." argument_list|) expr_stmt|; return|return literal|null return|; block|} catch|catch parameter_list|( name|ServiceException name|ex parameter_list|) block|{ comment|//fail("Cannot get a YARN remote exception as " comment|// + "it indicates RPC success"); throw|throw operator|( name|Exception operator|) name|ex operator|. name|getCause argument_list|() throw|; block|} block|} block|} argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|Exception name|e parameter_list|) block|{ name|Assert operator|. name|assertEquals argument_list|( name|RemoteException operator|. name|class operator|. name|getName argument_list|() argument_list|, name|e operator|. name|getClass argument_list|() operator|. name|getName argument_list|() argument_list|) expr_stmt|; name|e operator|= operator|( operator|( name|RemoteException operator|) name|e operator|) operator|. name|unwrapRemoteException argument_list|() expr_stmt|; name|Assert operator|. name|assertEquals argument_list|( name|SaslException operator|. name|class operator|. name|getCanonicalName argument_list|() argument_list|, name|e operator|. name|getClass argument_list|() operator|. name|getCanonicalName argument_list|() argument_list|) expr_stmt|; name|Assert operator|. name|assertTrue argument_list|( name|e operator|. name|getMessage argument_list|() operator|. name|contains argument_list|( literal|"DIGEST-MD5: digest response format violation. " operator|+ literal|"Mismatched response." argument_list|) argument_list|) expr_stmt|; name|Assert operator|. name|assertFalse argument_list|( name|am operator|. name|pinged argument_list|) expr_stmt|; block|} block|} DECL|method|verifyNewVersionToken (final Configuration conf, final CustomAM am, Token token, MockRM rm) specifier|private name|void name|verifyNewVersionToken parameter_list|( specifier|final name|Configuration name|conf parameter_list|, specifier|final name|CustomAM name|am parameter_list|, name|Token argument_list|< name|ClientToAMTokenIdentifier argument_list|> name|token parameter_list|, name|MockRM name|rm parameter_list|) throws|throws name|IOException throws|, name|InterruptedException block|{ name|UserGroupInformation name|ugi decl_stmt|; name|ugi operator|= name|UserGroupInformation operator|. name|createRemoteUser argument_list|( literal|"me" argument_list|) expr_stmt|; name|Token argument_list|< name|ClientToAMTokenIdentifier argument_list|> name|newToken init|= operator|new name|Token argument_list|< name|ClientToAMTokenIdentifier argument_list|> argument_list|( operator|new name|ClientToAMTokenIdentifierForTest argument_list|( name|token operator|. name|decodeIdentifier argument_list|() argument_list|, literal|"message" argument_list|) argument_list|, name|am operator|. name|getClientToAMTokenSecretManager argument_list|() argument_list|) decl_stmt|; name|newToken operator|. name|setService argument_list|( name|token operator|. name|getService argument_list|() argument_list|) expr_stmt|; name|ugi operator|. name|addToken argument_list|( name|newToken argument_list|) expr_stmt|; name|ugi operator|. name|doAs argument_list|( operator|new name|PrivilegedExceptionAction argument_list|< name|Void argument_list|> argument_list|() block|{ annotation|@ name|Override specifier|public name|Void name|run parameter_list|() throws|throws name|Exception block|{ name|CustomProtocol name|client init|= name|RPC operator|. name|getProxy argument_list|( name|CustomProtocol operator|. name|class argument_list|, literal|1L argument_list|, name|am operator|. name|address argument_list|, name|conf argument_list|) decl_stmt|; name|client operator|. name|ping argument_list|( literal|null argument_list|, name|TestRpcBase operator|. name|newEmptyRequest argument_list|() argument_list|) expr_stmt|; name|Assert operator|. name|assertTrue argument_list|( name|am operator|. name|pinged argument_list|) expr_stmt|; return|return literal|null return|; block|} block|} argument_list|) expr_stmt|; block|} DECL|method|verifyValidToken (final Configuration conf, final CustomAM am, Token token) specifier|private name|void name|verifyValidToken parameter_list|( specifier|final name|Configuration name|conf parameter_list|, specifier|final name|CustomAM name|am parameter_list|, name|Token argument_list|< name|ClientToAMTokenIdentifier argument_list|> name|token parameter_list|) throws|throws name|IOException throws|, name|InterruptedException block|{ name|UserGroupInformation name|ugi decl_stmt|; name|ugi operator|= name|UserGroupInformation operator|. name|createRemoteUser argument_list|( literal|"me" argument_list|) expr_stmt|; name|ugi operator|. name|addToken argument_list|( name|token argument_list|) expr_stmt|; name|ugi operator|. name|doAs argument_list|( operator|new name|PrivilegedExceptionAction argument_list|< name|Void argument_list|> argument_list|() block|{ annotation|@ name|Override specifier|public name|Void name|run parameter_list|() throws|throws name|Exception block|{ name|CustomProtocol name|client init|= name|RPC operator|. name|getProxy argument_list|( name|CustomProtocol operator|. name|class argument_list|, literal|1L argument_list|, name|am operator|. name|address argument_list|, name|conf argument_list|) decl_stmt|; name|client operator|. name|ping argument_list|( literal|null argument_list|, name|TestRpcBase operator|. name|newEmptyRequest argument_list|() argument_list|) expr_stmt|; name|Assert operator|. name|assertTrue argument_list|( name|am operator|. name|pinged argument_list|) expr_stmt|; return|return literal|null return|; block|} block|} argument_list|) expr_stmt|; block|} annotation|@ name|Test argument_list|( name|timeout operator|= literal|20000 argument_list|) DECL|method|testClientTokenRace () specifier|public name|void name|testClientTokenRace parameter_list|() throws|throws name|Exception block|{ name|conf operator|. name|set argument_list|( name|CommonConfigurationKeysPublic operator|. name|HADOOP_SECURITY_AUTHENTICATION argument_list|, literal|"kerberos" argument_list|) expr_stmt|; name|UserGroupInformation operator|. name|setConfiguration argument_list|( name|conf argument_list|) expr_stmt|; name|ContainerManagementProtocol name|containerManager init|= name|mock argument_list|( name|ContainerManagementProtocol operator|. name|class argument_list|) decl_stmt|; name|StartContainersResponse name|mockResponse init|= name|mock argument_list|( name|StartContainersResponse operator|. name|class argument_list|) decl_stmt|; name|when argument_list|( name|containerManager operator|. name|startContainers argument_list|( operator|( name|StartContainersRequest operator|) name|any argument_list|() argument_list|) argument_list|) operator|. name|thenReturn argument_list|( name|mockResponse argument_list|) expr_stmt|; name|MockRM name|rm init|= operator|new name|MockRMWithCustomAMLauncher argument_list|( name|conf argument_list|, name|containerManager argument_list|) block|{ specifier|protected name|ClientRMService name|createClientRMService parameter_list|() block|{ return|return operator|new name|ClientRMService argument_list|( name|this operator|. name|rmContext argument_list|, name|scheduler argument_list|, name|this operator|. name|rmAppManager argument_list|, name|this operator|. name|applicationACLsManager argument_list|, name|this operator|. name|queueACLsManager argument_list|, name|getRMContext argument_list|() operator|. name|getRMDelegationTokenSecretManager argument_list|() argument_list|) return|; block|} empty_stmt|; annotation|@ name|Override specifier|protected name|void name|doSecureLogin parameter_list|() throws|throws name|IOException block|{ } block|} decl_stmt|; name|rm operator|. name|start argument_list|() expr_stmt|; comment|// Submit an app name|RMApp name|app init|= name|MockRMAppSubmitter operator|. name|submitWithMemory argument_list|( literal|1024 argument_list|, name|rm argument_list|) decl_stmt|; comment|// Set up a node. name|MockNM name|nm1 init|= name|rm operator|. name|registerNode argument_list|( literal|"localhost:1234" argument_list|, literal|3072 argument_list|) decl_stmt|; name|nm1 operator|. name|nodeHeartbeat argument_list|( literal|true argument_list|) expr_stmt|; name|rm operator|. name|drainEvents argument_list|() expr_stmt|; name|nm1 operator|. name|nodeHeartbeat argument_list|( literal|true argument_list|) expr_stmt|; name|rm operator|. name|drainEvents argument_list|() expr_stmt|; name|ApplicationAttemptId name|appAttempt init|= name|app operator|. name|getCurrentAppAttempt argument_list|() operator|. name|getAppAttemptId argument_list|() decl_stmt|; specifier|final name|MockAM name|mockAM init|= operator|new name|MockAM argument_list|( name|rm operator|. name|getRMContext argument_list|() argument_list|, name|rm operator|. name|getApplicationMasterService argument_list|() argument_list|, name|app operator|. name|getCurrentAppAttempt argument_list|() operator|. name|getAppAttemptId argument_list|() argument_list|) decl_stmt|; name|UserGroupInformation name|appUgi init|= name|UserGroupInformation operator|. name|createRemoteUser argument_list|( name|appAttempt operator|. name|toString argument_list|() argument_list|) decl_stmt|; name|RegisterApplicationMasterResponse name|response init|= name|appUgi operator|. name|doAs argument_list|( operator|new name|PrivilegedAction argument_list|< name|RegisterApplicationMasterResponse argument_list|> argument_list|() block|{ annotation|@ name|Override specifier|public name|RegisterApplicationMasterResponse name|run parameter_list|() block|{ name|RegisterApplicationMasterResponse name|response init|= literal|null decl_stmt|; try|try block|{ name|response operator|= name|mockAM operator|. name|registerAppAttempt argument_list|() expr_stmt|; block|} catch|catch parameter_list|( name|Exception name|e parameter_list|) block|{ name|Assert operator|. name|fail argument_list|( literal|"Exception was not expected" argument_list|) expr_stmt|; block|} return|return name|response return|; block|} block|} argument_list|) decl_stmt|; comment|// Get the app-report. name|GetApplicationReportRequest name|request init|= name|Records operator|. name|newRecord argument_list|( name|GetApplicationReportRequest operator|. name|class argument_list|) decl_stmt|; name|request operator|. name|setApplicationId argument_list|( name|app operator|. name|getApplicationId argument_list|() argument_list|) expr_stmt|; name|GetApplicationReportResponse name|reportResponse init|= name|rm operator|. name|getClientRMService argument_list|() operator|. name|getApplicationReport argument_list|( name|request argument_list|) decl_stmt|; name|ApplicationReport name|appReport init|= name|reportResponse operator|. name|getApplicationReport argument_list|() decl_stmt|; name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|records operator|. name|Token name|originalClientToAMToken init|= name|appReport operator|. name|getClientToAMToken argument_list|() decl_stmt|; comment|// ClientToAMToken master key should have been received on register comment|// application master response. specifier|final name|ByteBuffer name|clientMasterKey init|= name|response operator|. name|getClientToAMTokenMasterKey argument_list|() decl_stmt|; name|Assert operator|. name|assertNotNull argument_list|( name|clientMasterKey argument_list|) expr_stmt|; name|Assert operator|. name|assertTrue argument_list|( name|clientMasterKey operator|. name|array argument_list|() operator|. name|length operator|> literal|0 argument_list|) expr_stmt|; comment|// Start the AM with the correct shared-secret. name|ApplicationAttemptId name|appAttemptId init|= name|app operator|. name|getAppAttempts argument_list|() operator|. name|keySet argument_list|() operator|. name|iterator argument_list|() operator|. name|next argument_list|() decl_stmt|; name|Assert operator|. name|assertNotNull argument_list|( name|appAttemptId argument_list|) expr_stmt|; specifier|final name|CustomAM name|am init|= operator|new name|CustomAM argument_list|( name|appAttemptId argument_list|, literal|null argument_list|) decl_stmt|; name|am operator|. name|init argument_list|( name|conf argument_list|) expr_stmt|; name|am operator|. name|start argument_list|() expr_stmt|; comment|// Now the real test! comment|// Set up clients to be able to pick up correct tokens. name|SecurityUtil operator|. name|setSecurityInfoProviders argument_list|( operator|new name|CustomSecurityInfo argument_list|() argument_list|) expr_stmt|; name|Token argument_list|< name|ClientToAMTokenIdentifier argument_list|> name|token init|= name|ConverterUtils operator|. name|convertFromYarn argument_list|( name|originalClientToAMToken argument_list|, name|am operator|. name|address argument_list|) decl_stmt|; comment|// Schedule the key to be set after a significant delay name|Timer name|timer init|= operator|new name|Timer argument_list|() decl_stmt|; name|TimerTask name|timerTask init|= operator|new name|TimerTask argument_list|() block|{ annotation|@ name|Override specifier|public name|void name|run parameter_list|() block|{ name|am operator|. name|setClientSecretKey argument_list|( name|clientMasterKey operator|. name|array argument_list|() argument_list|) expr_stmt|; block|} block|} decl_stmt|; name|timer operator|. name|schedule argument_list|( name|timerTask argument_list|, literal|250 argument_list|) expr_stmt|; comment|// connect should pause waiting for the master key to arrive name|verifyValidToken argument_list|( name|conf argument_list|, name|am argument_list|, name|token argument_list|) expr_stmt|; name|am operator|. name|stop argument_list|() expr_stmt|; name|rm operator|. name|stop argument_list|() expr_stmt|; block|} block|} end_class end_unit // Copyright 2020 Mavenir // // 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.xgvela.model; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyDescription; import com.fasterxml.jackson.annotation.JsonPropertyOrder; /** * Mavenir Event Format *

* * */ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "event" }) public class MEF implements Serializable { /** * the root level of the common event format * */ @JsonProperty("event") @JsonPropertyDescription("the root level of the common event format") private Event event; @JsonIgnore private Map additionalProperties = new HashMap(); private final static long serialVersionUID = 8176205186062925124L; /** * No args constructor for use in serialization * */ public MEF() { } /** * * @param event */ public MEF(Event event) { super(); this.event = event; } /** * the root level of the common event format * */ @JsonProperty("event") public Event getEvent() { return event; } /** * the root level of the common event format * */ @JsonProperty("event") public void setEvent(Event event) { this.event = event; } public MEF withEvent(Event event) { this.event = event; return this; } @JsonAnyGetter public Map getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } public MEF withAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); return this; } } package com.hccake.extend.kafka; import cn.hutool.core.collection.ListUtil; import cn.hutool.core.util.StrUtil; import lombok.extern.slf4j.Slf4j; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.serialization.Serializer; import java.util.*; import java.util.function.Function; import static com.hccake.extend.kafka.KafkaConstants.BOOTSTRAP_SERVERS_DELIMITER; /** * 生产者 具体的配置请参考 {@link ProducerConfig} 这里只提供一些常用配置 * * @author lingting 2020/5/19 20:56 */ @Slf4j public class KafkaProducerBuilder { private final Properties properties = new Properties(); private final Set bootstrapServers = new HashSet<>(); public KafkaProducerBuilder keySerializer(Class> c) { return keySerializer(c.getName()); } public KafkaProducerBuilder keySerializer(String className) { return put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, className); } public KafkaProducerBuilder valueSerializer(Class> c) { return valueSerializer(c.getName()); } public KafkaProducerBuilder valueSerializer(String className) { return put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, className); } /** * 添加 kafka 路径 host:port * * @author lingting 2020-06-19 16:30:03 */ public KafkaProducerBuilder addBootstrapServers(String uri) { bootstrapServers.add(uri); return this; } public KafkaProducerBuilder addAllBootstrapServers(Collection uris) { bootstrapServers.addAll(uris); return this; } /** * 添加配置 * * @author lingting 2020-06-19 16:30:50 */ public KafkaProducerBuilder put(Object key, Object val) { properties.put(key, val); return this; } /** * 添加配置 * * @author lingting 2020-06-19 16:30:50 */ public KafkaProducerBuilder putAll(Properties properties) { this.properties.putAll(properties); return this; } public KafkaProducerBuilder putAll(Map map) { this.properties.putAll(map); return this; } public KafkaExtendProducer build(Function> function) { return function.apply(getProperties()); } public KafkaExtendProducer build(Properties properties) { return putAll(properties).build(); } public KafkaExtendProducer build() { return build(p -> new KafkaExtendProducer<>(new org.apache.kafka.clients.producer.KafkaProducer<>(p))); } public Set getBootstrapServers() { getProperties(); return bootstrapServers; } public Properties getProperties() { bootstrapServers .addAll(ListUtil.toList(properties.getProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, StrUtil.EMPTY) .split(BOOTSTRAP_SERVERS_DELIMITER))); properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, String.join(BOOTSTRAP_SERVERS_DELIMITER, bootstrapServers)); return properties; } } // 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.v4.content; import android.content.Context; import android.support.v4.util.DebugUtils; import java.io.FileDescriptor; import java.io.PrintWriter; public class Loader { public static interface OnLoadCanceledListener { public abstract void onLoadCanceled(Loader loader); } public static interface OnLoadCompleteListener { public abstract void onLoadComplete(Loader loader, Object obj); } public Loader(Context context) { // 0 0:aload_0 // 1 1:invokespecial #33 mStarted = false; // 2 4:aload_0 // 3 5:iconst_0 // 4 6:putfield #35 mAbandoned = false; // 5 9:aload_0 // 6 10:iconst_0 // 7 11:putfield #37 mReset = true; // 8 14:aload_0 // 9 15:iconst_1 // 10 16:putfield #39 mContentChanged = false; // 11 19:aload_0 // 12 20:iconst_0 // 13 21:putfield #41 mProcessingChange = false; // 14 24:aload_0 // 15 25:iconst_0 // 16 26:putfield #43 mContext = context.getApplicationContext(); // 17 29:aload_0 // 18 30:aload_1 // 19 31:invokevirtual #49 // 20 34:putfield #51 // 21 37:return } public void abandon() { mAbandoned = true; // 0 0:aload_0 // 1 1:iconst_1 // 2 2:putfield #37 onAbandon(); // 3 5:aload_0 // 4 6:invokevirtual #58 // 5 9:return } public boolean cancelLoad() { return onCancelLoad(); // 0 0:aload_0 // 1 1:invokevirtual #64 // 2 4:ireturn } public void commitContentChanged() { mProcessingChange = false; // 0 0:aload_0 // 1 1:iconst_0 // 2 2:putfield #43 // 3 5:return } public String dataToString(Object obj) { StringBuilder stringbuilder = new StringBuilder(64); // 0 0:new #70 // 1 3:dup // 2 4:bipush 64 // 3 6:invokespecial #73 // 4 9:astore_2 DebugUtils.buildShortClassTag(obj, stringbuilder); // 5 10:aload_1 // 6 11:aload_2 // 7 12:invokestatic #79 stringbuilder.append("}"); // 8 15:aload_2 // 9 16:ldc1 #81 // 10 18:invokevirtual #85 // 11 21:pop return stringbuilder.toString(); // 12 22:aload_2 // 13 23:invokevirtual #89 // 14 26:areturn } public void deliverCancellation() { OnLoadCanceledListener onloadcanceledlistener = mOnLoadCanceledListener; // 0 0:aload_0 // 1 1:getfield #94 // 2 4:astore_1 if(onloadcanceledlistener != null) //* 3 5:aload_1 //* 4 6:ifnull 16 onloadcanceledlistener.onLoadCanceled(this); // 5 9:aload_1 // 6 10:aload_0 // 7 11:invokeinterface #98 // 8 16:return } public void deliverResult(Object obj) { OnLoadCompleteListener onloadcompletelistener = mListener; // 0 0:aload_0 // 1 1:getfield #102 // 2 4:astore_2 if(onloadcompletelistener != null) //* 3 5:aload_2 //* 4 6:ifnull 17 onloadcompletelistener.onLoadComplete(this, obj); // 5 9:aload_2 // 6 10:aload_0 // 7 11:aload_1 // 8 12:invokeinterface #106 // 9 17:return } public void dump(String s, FileDescriptor filedescriptor, PrintWriter printwriter, String as[]) { printwriter.print(s); // 0 0:aload_3 // 1 1:aload_1 // 2 2:invokevirtual #116 printwriter.print("mId="); // 3 5:aload_3 // 4 6:ldc1 #118 // 11 21:dup // 12 22:ldc1 #165 // 13 24:invokespecial #167 // 14 27:athrow } } public void registerOnLoadCanceledListener(OnLoadCanceledListener onloadcanceledlistener) { if(mOnLoadCanceledListener == null) //* 0 0:aload_0 //* 1 1:getfield #94 //* 2 4:ifnonnull 13 { mOnLoadCanceledListener = onloadcanceledlistener; // 3 7:aload_0 // 4 8:aload_1 // 5 9:putfield #94 return; // 6 12:return } else { throw new IllegalStateException("There is already a listener registered"); // 7 13:new #163 // 8 16:dup // 9 17:ldc1 #165 // 10 19:invokespecial #167 // 11 22:athrow } } public void reset() { onReset(); // 0 0:aload_0 // 1 1:invokevirtual #174 mReset = true; // 2 4:aload_0 // 3 5:iconst_1 // 4 6:putfield #39 mStarted = false; // 5 9:aload_0 // 6 10:iconst_0 // 7 11:putfield #35 mAbandoned = false; // 8 14:aload_0 // 9 15:iconst_0 // 10 16:putfield #37 mContentChanged = false; // 11 19:aload_0 // 12 20:iconst_0 // 13 21:putfield #41 mProcessingChange = false; // 14 24:aload_0 // 15 25:iconst_0 // 16 26:putfield #43 // 17 29:return } public void rollbackContentChanged() { if(mProcessingChange) //* 0 0:aload_0 //* 1 1:getfield #43 //* 2 4:ifeq 11 onContentChanged(); // 3 7:aload_0 // 4 8:invokevirtual #177 // 5 11:return } public final void startLoading() { mStarted = true; // 0 0:aload_0 // 1 1:iconst_1 // 2 2:putfield #35 mReset = false; // 3 5:aload_0 // 4 6:iconst_0 // 5 7:putfield #39 mAbandoned = false; // 6 10:aload_0 // 7 11:iconst_0 // 8 12:putfield #37 onStartLoading(); // 9 15:aload_0 // 10 16:invokevirtual #180 // 11 19:return } public void stopLoading() { mStarted = false; // 0 0:aload_0 // 1 1:iconst_0 // 2 2:putfield #35 onStopLoading(); // 3 5:aload_0 // 4 6:invokevirtual #183 // 5 9:return } public boolean takeContentChanged() { boolean flag = mContentChanged; // 0 0:aload_0 // 1 1:getfield #41 // 2 4:istore_1 mContentChanged = false; // 3 5:aload_0 // 4 6:iconst_0 // 5 7:putfield #41 mProcessingChange = mProcessingChange | flag; // 6 10:aload_0 // 7 11:aload_0 // 8 12:getfield #43 // 9 15:iload_1 // 10 16:ior // 11 17:putfield #43 return flag; // 12 20:iload_1 // 13 21:ireturn } public String toString() { StringBuilder stringbuilder = new StringBuilder(64); // 0 0:new #70 // 1 3:dup // 2 4:bipush 64 // 3 6:invokespecial #73 // 4 9:astore_1 DebugUtils.buildShortClassTag(((Object) (this)), stringbuilder); // 5 10:aload_0 // 6 11:aload_1 // 7 12:invokestatic #79 stringbuilder.append(" id="); // 8 15:aload_1 // 9 16:ldc1 #186 // 19 34:invokevirtual #85 // 20 37:pop return stringbuilder.toString(); // 21 38:aload_1 // 22 39:invokevirtual #89 // 23 42:areturn } public void unregisterListener(OnLoadCompleteListener onloadcompletelistener) { OnLoadCompleteListener onloadcompletelistener1 = mListener; // 0 0:aload_0 // 1 1:getfield #102 // 2 4:astore_2 if(onloadcompletelistener1 != null) //* 3 5:aload_2 //* 4 6:ifnull 30 { if(onloadcompletelistener1 == onloadcompletelistener) //* 5 9:aload_2 //* 6 10:aload_1 //* 7 11:if_acmpne 20 { mListener = null; // 8 14:aload_0 // 9 15:aconst_null // 10 16:putfield #102 return; // 11 19:return } else { throw new IllegalArgumentException("Attempting to unregister the wrong listener"); // 12 20:new #193 // 13 23:dup // 14 24:ldc1 #195 // 15 26:invokespecial #196 // 16 29:athrow } } else { throw new IllegalStateException("No listener register"); // 17 30:new #163 // 18 33:dup // 19 34:ldc1 #198 // 20 36:invokespecial #167 // 21 39:athrow } } public void unregisterOnLoadCanceledListener(OnLoadCanceledListener onloadcanceledlistener) { OnLoadCanceledListener onloadcanceledlistener1 = mOnLoadCanceledListener; // 0 0:aload_0 // 1 1:getfield #94 // 2 4:astore_2 if(onloadcanceledlistener1 != null) //* 3 5:aload_2 //* 4 6:ifnull 30 { if(onloadcanceledlistener1 == onloadcanceledlistener) //* 5 9:aload_2 //* 6 10:aload_1 //* 7 11:if_acmpne 20 { mOnLoadCanceledListener = null; // 8 14:aload_0 // 9 15:aconst_null // 10 16:putfield #94 return; // 11 19:return } else { throw new IllegalArgumentException("Attempting to unregister the wrong listener"); // 12 20:new #193 // 13 23:dup // 14 24:ldc1 #195 // 15 26:invokespecial #196 // 16 29:athrow } } else { throw new IllegalStateException("No listener register"); // 17 30:new #163 // 18 33:dup // 19 34:ldc1 #198 // 20 36:invokespecial #167 // 21 39:athrow } } boolean mAbandoned; boolean mContentChanged; Context mContext; int mId; OnLoadCompleteListener mListener; OnLoadCanceledListener mOnLoadCanceledListener; boolean mProcessingChange; boolean mReset; boolean mStarted; } App/src/main/java/cc/softwarefactory/lokki/android/fragments/ContactsFragment.java /* Copyright (c) 2014-2015 F-Secure See LICENSE for details */ package cc.softwarefactory.lokki.android.fragments; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.app.AlertDialog; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.ContextMenu; import android.view.LayoutInflater; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.androidquery.AQuery; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import cc.softwarefactory.lokki.android.MainApplication; import cc.softwarefactory.lokki.android.R; import cc.softwarefactory.lokki.android.avatar.AvatarLoader; import cc.softwarefactory.lokki.android.models.Contact; import cc.softwarefactory.lokki.android.services.ContactService; import cc.softwarefactory.lokki.android.utilities.AnalyticsUtils; import cc.softwarefactory.lokki.android.utilities.Utils; import static cc.softwarefactory.lokki.android.R.string.analytics_label_confirm_rename_contact_dialog; public class ContactsFragment extends Fragment { private static final String TAG = "Contacts"; private ArrayList peopleList; private AQuery aq; private static Boolean cancelAsynTasks = false; private Context context; private AvatarLoader avatarLoader; private ContactService contactService; private EditText inputSearch; private Button clearFilter; private ArrayAdapter adapter; public ContactsFragment() { peopleList = new ArrayList<>(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.activity_contacts, container, false); aq = new AQuery(getActivity(), rootView); cancelAsynTasks = false; context = getActivity().getApplicationContext(); contactService = new ContactService(context); avatarLoader = new AvatarLoader(); inputSearch = (EditText) rootView.findViewById(R.id.contact_search); inputSearch.setEnabled(false); inputSearch.setAlpha(0); clearFilter = (Button) rootView.findViewById(R.id.clear_contact_filter); new GetPeopleThatCanSeeMe().execute(); ListView listView = aq.id(R.id.contacts_list_view).getListView(); this.registerForContextMenu(listView); return rootView; } @Override public void onResume() { Log.d(TAG, "onResume"); super.onResume(); //Register a receiver to update the contents of the contact list whenever we load contacts from server LocalBroadcastManager.getInstance(context).registerReceiver(mMessageReceiver, new IntentFilter("CONTACTS-UPDATE")); AnalyticsUtils.screenHit(getString(R.string.analytics_screen_contacts)); enableSearchFilter(); } @Override public void onPause() { super.onPause(); //Deregister the receiver LocalBroadcastManager.getInstance(context).unregisterReceiver(mMessageReceiver); } private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { //Update contact list Log.d(TAG, "BroadcastReceiver onReceive"); refresh(); } }; @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); // Create the contact context menu (remove contact) MenuInflater inflater = getActivity().getMenuInflater(); inflater.inflate(R.menu.contacts_context, menu); Log.d(TAG, "opened contact context menu"); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo(); int position = info.position; Contact contact = peopleList.get(position); switch(item.getItemId()) { // Remove contact case R.id.contacts_context_menu_delete: AnalyticsUtils.eventHit(getString(R.string.analytics_category_ux), getString(R.string.analytics_action_click), getString(R.string.analytics_label_delete_contact)); deleteContactDialog(contact); return true; //Rename contact case R.id.contacts_context_menu_rename: showRenameDialog(contact); return true; } return super.onContextItemSelected(item); } /** Ask the user to confirm contact deletion * * @param contact The contact to be removed */ private void deleteContactDialog(final Contact contact){ new AlertDialog.Builder(getActivity()) .setMessage(getString(R.string.delete_contact)) .setMessage(contact.toString() + " " + getString(R.string.will_be_deleted_from_contacts)) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { AnalyticsUtils.eventHit(getString(R.string.analytics_category_ux), getString(R.string.analytics_action_click), getString(R.string.analytics_label_confirm_delete_contact_dialog)); deleteContact(contact); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { AnalyticsUtils.eventHit(getString(R.string.analytics_category_ux), getString(R.string.analytics_action_click), getString(R.string.analytics_label_cancel_delete_contact_dialog)); } }) .show(); } /**Deletes a contact from the user's contacts * * @param contact The contact to be deleted */ private void deleteContact(Contact contact){ contactService.removeContact(contact); } /** * Reload contact information */ public void refresh(){ Log.d(TAG, "Refreshing contacts screen"); //Empty all existing local data structures peopleList = new ArrayList<>(); //Fill them with up-to-date data new GetPeopleThatCanSeeMe().execute(); } private void getPeopleList() { if (MainApplication.contacts == null) try { MainApplication.contacts = contactService.getFromCache(); } catch (IOException e) { Log.e(TAG, "getting contacts from cache failed"); e.printStackTrace(); MainApplication.contacts = new ArrayList<>(); } peopleList.addAll(MainApplication.contacts); Collections.sort(peopleList); Log.d(TAG, "Contact list: " + peopleList); } /** * Contacts search filter */ private void enableSearchFilter() { inputSearch.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) { // When user changed the Text if (adapter != null) { adapter.getFilter().filter(cs); } clearFilter.setVisibility(cs.length() == 0 ? View.INVISIBLE : View.VISIBLE); } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable arg0) { // TODO Auto-generated method stub } }); inputSearch.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AnalyticsUtils.eventHit(getString(R.string.analytics_category_ux), getString(R.string.analytics_action_click), getString(R.string.analytics_label_search_contacts_textbox)); } }); clearFilter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AnalyticsUtils.eventHit(getString(R.string.analytics_category_ux), getString(R.string.analytics_action_click), getString(R.string.analytics_label_clear_search_contacts_textbox_button)); inputSearch.setText(""); } }); } private void setListAdapter() { adapter = new ArrayAdapter(context, R.layout.people_row_layout, peopleList) { ViewHolder holder; @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = getActivity().getLayoutInflater().inflate(R.layout.people_row_layout, parent, false); holder = new ViewHolder(); holder.name = (TextView) convertView.findViewById(R.id.contact_name); holder.email = (TextView) convertView.findViewById(R.id.contact_email); holder.lastReport = (TextView) convertView.findViewById(R.id.last_report); holder.photo = (ImageView) convertView.findViewById(R.id.contact_photo); holder.checkICanSee = (CheckBox) convertView.findViewById(R.id.i_can_see); holder.checkCanSeeMe = (CheckBox) convertView.findViewById(R.id.can_see_me); holder.contextButton = (ImageButton) convertView.findViewById(R.id.people_context_menu_button); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } final Contact contact = getItem(position); inputSearch.setEnabled(true); inputSearch.setAlpha(1); //Allow user to rename contact by long pressing their bane AQuery aq = new AQuery(convertView); aq.id(holder.name).text(contact.toString()).longClicked(new View.OnLongClickListener(){ @Override public boolean onLongClick(View view){ showRenameDialog(contact); return true; } }); aq.id(holder.email).text(contact.getEmail()); avatarLoader.load(contact, holder.photo); aq.id(holder.lastReport).text((contact == null || contact.getLocation() == null || contact.getLocation().getTime() == null) ? "" : Utils.timestampText(contact.getLocation().getTime().getTime())); aq.id(holder.checkCanSeeMe).checked(contact.isCanSeeMe()).tag(contact); aq.id(holder.checkICanSee).tag(contact); aq.id(holder.checkICanSee).checked(!contact.isIgnored()); aq.id(holder.photo).clickable(!contact.isIgnored() && contact.isVisibleToMe()); holder.position = position; if (!contact.isVisibleToMe()) { aq.id(holder.checkICanSee).enabled(true); aq.id(holder.checkICanSee).checked(false); aq.id(holder.checkICanSee).getView().setAlpha(0.1f); aq.id(holder.checkICanSee).clicked(new View.OnClickListener() { @Override public void onClick(View view) { AnalyticsUtils.eventHit(getString(R.string.analytics_category_ux), getString(R.string.analytics_action_click), getString(R.string.analytics_label_disabled_show_on_map_checkbox)); Toast.makeText(context, R.string.seeing_contact_not_allowed, Toast.LENGTH_LONG).show(); CheckBox cb = (CheckBox) view; cb.setChecked(false); } }); } else { aq.id(holder.checkICanSee).enabled(true); } aq.id(holder.contextButton).clicked(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, "clicked contact context button"); v.showContextMenu(); } }); return convertView; } }; aq.id(R.id.headers).visibility(View.VISIBLE); aq.id(R.id.contacts_list_view).adapter(adapter); } /** * Shows a dialog window that allows the user to rename a contact * @param contact The contact to be renamed */ private void showRenameDialog(final Contact contact) { final EditText input = new EditText(getActivity()); String titleFormat = getString(R.string.rename_prompt); final String title = String.format(titleFormat, contact.toString()); new AlertDialog.Builder(getActivity()) .setTitle(title) .setMessage(R.string.rename_contact) .setView(input) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { AnalyticsUtils.eventHit(getString(R.string.analytics_category_ux), getString(R.string.analytics_action_click), getString(analytics_label_confirm_rename_contact_dialog)); String newName = input.getText().toString(); renameContact(contact, newName); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { AnalyticsUtils.eventHit(getString(R.string.analytics_category_ux), getString(R.string.analytics_action_click), getString(R.string.analytics_label_cancel_rename_contact_dialog)); } }) .show(); } /** * Sets the custom display name for a contact * @param contact The contact * @param newName A new name for the contact */ public void renameContact(Contact contact, String newName) { //Set new name in local lists used by the contacts fragment contact.setName(newName); contactService.renameContact(contact, newName); } static class ViewHolder { TextView name; TextView email; TextView lastReport; ImageView photo; CheckBox checkICanSee; CheckBox checkCanSeeMe; ImageButton contextButton; int position; } private class GetPeopleThatCanSeeMe extends AsyncTask { @Override protected Void doInBackground(Void... params) { getPeopleList(); return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); if (isAdded() && !cancelAsynTasks) { setListAdapter(); } } } } package p026rx.p390c.p393c; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Iterator; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import p026rx.C0126V.C0127a; import p026rx.C0137ja; import p026rx.exceptions.C14927a; import p026rx.p027b.C0128a; import p026rx.p029i.C0136c; import p026rx.p029i.C14978f; import p026rx.p390c.p395e.C14879g; import p026rx.p390c.p395e.C14882j; import p026rx.p390c.p395e.C14899t; import p026rx.p400f.C14948s; /* renamed from: rx.c.c.p */ /* compiled from: NewThreadWorker */ public class C14801p extends C0127a implements C0137ja { /* renamed from: a */ private static final boolean f44028a; /* renamed from: b */ public static final int f44029b = Integer.getInteger("rx.scheduler.jdk6.purge-frequency-millis", 1000).intValue(); /* renamed from: c */ private static final ConcurrentHashMap f44030c = new ConcurrentHashMap<>(); /* renamed from: d */ private static final AtomicReference f44031d = new AtomicReference<>(); /* renamed from: e */ private static volatile Object f44032e; /* renamed from: f */ private static final Object f44033f = new Object(); /* renamed from: g */ private final ScheduledExecutorService f44034g; /* renamed from: h */ volatile boolean f44035h; static { boolean purgeForce = Boolean.getBoolean("rx.scheduler.jdk6.purge-force"); int androidApiVersion = C14879g.m46595a(); f44028a = !purgeForce && (androidApiVersion == 0 || androidApiVersion >= 21); } /* renamed from: a */ public static void m46458a(ScheduledThreadPoolExecutor service) { while (true) { if (((ScheduledExecutorService) f44031d.get()) != null) { break; } ScheduledExecutorService exec = Executors.newScheduledThreadPool(1, new C14882j("RxSchedulerPurge-")); if (f44031d.compareAndSet(null, exec)) { C14800o oVar = new C14800o(); int i = f44029b; exec.scheduleAtFixedRate(oVar, (long) i, (long) i, TimeUnit.MILLISECONDS); break; } exec.shutdownNow(); } f44030c.putIfAbsent(service, service); } /* renamed from: a */ public static void m46457a(ScheduledExecutorService service) { f44030c.remove(service); } /* renamed from: c */ static void m46460c() { try { Iterator it = f44030c.keySet().iterator(); while (it.hasNext()) { ScheduledThreadPoolExecutor exec = (ScheduledThreadPoolExecutor) it.next(); if (!exec.isShutdown()) { exec.purge(); } else { it.remove(); } } } catch (Throwable t) { C14927a.m46678c(t); C14948s.m46719b(t); } } /* renamed from: c */ public static boolean m46461c(ScheduledExecutorService executor) { Method methodToCall; if (f44028a) { if (executor instanceof ScheduledThreadPoolExecutor) { Object localSetRemoveOnCancelPolicyMethod = f44032e; if (localSetRemoveOnCancelPolicyMethod == f44033f) { return false; } if (localSetRemoveOnCancelPolicyMethod == null) { Method method = m46459b(executor); f44032e = method != 0 ? method : f44033f; methodToCall = method; } else { methodToCall = (Method) localSetRemoveOnCancelPolicyMethod; } } else { methodToCall = m46459b(executor); } if (methodToCall != 0) { try { methodToCall.invoke(executor, new Object[]{Boolean.valueOf(true)}); return true; } catch (InvocationTargetException e) { C14948s.m46719b((Throwable) e); } catch (IllegalAccessException e2) { C14948s.m46719b((Throwable) e2); } catch (IllegalArgumentException e3) { C14948s.m46719b((Throwable) e3); } } } return false; } /* renamed from: b */ static Method m46459b(ScheduledExecutorService executor) { Method[] arr$; for (Method method : executor.getClass().getMethods()) { if (method.getName().equals("setRemoveOnCancelPolicy")) { Class[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length == 1 && parameterTypes[0] == Boolean.TYPE) { return method; } } } return null; } public C14801p(ThreadFactory threadFactory) { ScheduledExecutorService exec = Executors.newScheduledThreadPool(1, threadFactory); if (!m46461c(exec) && (exec instanceof ScheduledThreadPoolExecutor)) { m46458a((ScheduledThreadPoolExecutor) exec); } this.f44034g = exec; } /* renamed from: a */ public C0137ja mo3707a(C0128a action) { return mo3709a(action, 0, null); } /* renamed from: a */ public C0137ja mo3709a(C0128a action, long delayTime, TimeUnit unit) { if (this.f44035h) { return C14978f.m46782b(); } return mo45937b(action, delayTime, unit); } /* renamed from: b */ public C14805s mo45937b(C0128a action, long delayTime, TimeUnit unit) { Future f; C14805s run = new C14805s(C14948s.m46713a(action)); if (delayTime <= 0) { f = this.f44034g.submit(run); } else { f = this.f44034g.schedule(run, delayTime, unit); } run.mo45940a(f); return run; } /* renamed from: a */ public C14805s mo45936a(C0128a action, long delayTime, TimeUnit unit, C0136c parent) { Future f; C14805s run = new C14805s(C14948s.m46713a(action), parent); parent.mo3713a((C0137ja) run); if (delayTime <= 0) { f = this.f44034g.submit(run); } else { f = this.f44034g.schedule(run, delayTime, unit); } run.mo45940a(f); return run; } /* renamed from: a */ public C14805s mo45935a(C0128a action, long delayTime, TimeUnit unit, C14899t parent) { Future f; C14805s run = new C14805s(C14948s.m46713a(action), parent); parent.mo46107a((C0137ja) run); if (delayTime <= 0) { f = this.f44034g.submit(run); } else { f = this.f44034g.schedule(run, delayTime, unit); } run.mo45940a(f); return run; } public void unsubscribe() { this.f44035h = true; this.f44034g.shutdownNow(); m46457a(this.f44034g); } public boolean isUnsubscribed() { return this.f44035h; } } package com.example.euler; import java.util.stream.LongStream; /** * The prime factors of 13195 are 5, 7, 13 and 29. * *

What is the largest prime factor of the number 600851475143 ? */ public class Problem3 { public long solve(long maximum) { return LongStream.rangeClosed(1L, (long) Math.sqrt(maximum)) .parallel() .filter(i -> maximum % i == 0) .filter(Problem3::isPrime) .max() .getAsLong(); } public static boolean isPrime(long number) { return number > 1 && LongStream.rangeClosed(2, (long) Math.sqrt(number)).noneMatch(n -> (number % n == 0L)); } } /* * Copyright (c) 2010, . All Rights Reserved. * Copyright (c) 2010, . 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 org.qi4j.entitystore.sql.internal; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import org.qi4j.api.injection.scope.This; import org.qi4j.library.sql.common.SQLUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public interface DatabaseSQLServiceSpi { boolean schemaExists( Connection connection ) throws SQLException; String getCurrentSchemaName(); boolean tableExists( Connection connection ) throws SQLException; @SuppressWarnings( "PublicInnerClass" ) public abstract class CommonMixin implements DatabaseSQLServiceSpi { private static final Logger LOGGER = LoggerFactory.getLogger( DatabaseSQLServiceSpi.class ); @This private DatabaseSQLServiceState state; @Override public boolean schemaExists( Connection connection ) throws SQLException { ResultSet rs = null; try { Boolean schemaFound = false; rs = connection.getMetaData().getSchemas(); String schemaName = this.getCurrentSchemaName(); while ( rs.next() && !schemaFound ) { String eachResult = rs.getString( 1 ); LOGGER.trace( "Schema candidate: {}", eachResult ); schemaFound = eachResult.equalsIgnoreCase( schemaName ); } LOGGER.trace( "Schema {} found? {}", schemaName, schemaFound ); return schemaFound; } finally { SQLUtil.closeQuietly( rs ); } } @Override public String getCurrentSchemaName() { return this.state.schemaName().get(); } } } 1-10 // Copyright 2019 Yolean AB // // 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 se.yolean.kafka.keyvalue.onupdate.hc; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import org.mockito.Mockito; class RetryConnectionRefusedThreadSleepTest { @Test void testGetRetryIntervalMillis() { RetryDecisions decisions = Mockito.mock(RetryDecisions.class); RetryConnectionRefusedThreadSleep retry = new RetryConnectionRefusedThreadSleep(decisions); assertEquals(250, retry.getRetryInterval(1)); assertEquals(500, retry.getRetryInterval(2)); assertEquals(1000, retry.getRetryInterval(3)); } } package com.beyond.popscience.locationgoods.bean; public class MessageShuaxin { } 0 /* * @(#)OperationRead.java * * This file is part of MoWiDi. * * MoWiDi is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MoWiDi is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MoWiDi. If not, see . * * Copyright 2010 by PSE23-Team: * * , , * , , */ package edu.kit.ibds.mowidi.operations; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import edu.kit.ibds.mowidi.mobile.data.AuthorizationType; import fuse.FuseException; import android.os.Environment; import android.test.AndroidTestCase; import android.util.Log; /** * * @author */ public final class OperationReadTest extends AndroidTestCase { private byte[] testBuf = new byte[]{'H', 'A', 'L', 'L', 'O', ' ', 'W', 'E', 'l', 't', '!'}; @SuppressWarnings("static-access") public void testAuthorizationType() { AbstractOperation test = new OperationRead("", 0, new byte[0]); assertEquals(AuthorizationType.READ_ONLY, test.minAuthorizationType); } public void testDoOperationNoFile() { File root = Environment.getExternalStorageDirectory(); File file = new File(root, "noReadFile"); if (file.exists()) { file.delete(); } AbstractOperation test = new OperationRead("noReadFile", 0, new byte[1]); test.doOperation(); assertEquals(FuseException.ENOENT, ((FuseException) test.savedObject).getErrno()); } public void testDoOperationIsDir() { File root = Environment.getExternalStorageDirectory(); File dir = new File(root, "readDir"); if (!dir.exists()) { dir.mkdir(); } AbstractOperation test = new OperationRead("readDir", 0, new byte[1]); test.doOperation(); assertEquals(FuseException.EISDIR, ((FuseException) test.savedObject).getErrno()); } public void testDoOperation() { File root = Environment.getExternalStorageDirectory(); File file = new File(root, "readFile"); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { fail(e.getMessage()); } } try { FileOutputStream stream = new FileOutputStream(file); stream.write(testBuf); } catch (FileNotFoundException e) { fail(e.getMessage()); } catch (IOException e) { fail(e.getMessage()); } //Operation no offset not till end AbstractOperation test = new OperationRead("readFile", 0, new byte[9]); test.doOperation(); byte[] result = (byte[]) test.savedObject; assertEquals(9, result.length); for (int i = 0; i < 9; i++) { assertEquals(testBuf[i], result[i]); } //Operation with offset not till end test = new OperationRead("readFile", 5, new byte[4]); test.doOperation(); result = (byte[]) test.savedObject; assertEquals(4, result.length); for (int i = 5; i < 9; i++) { assertEquals(testBuf[i], result[i - 5]); } //Operation beyond end test = new OperationRead("readFile", 7, new byte[5]); test.doOperation(); result = (byte[]) test.savedObject; Log.i("Tester", new String(result)); for (int i = 7; i < 11; i++) { assertEquals(testBuf[i], result[i - 7]); } assertEquals(0, result[4]); } } 1-10 package com.rxmqtt.models; public class RxMqttUserStatusPayload { private long user_id; private String username; private String device_id; private String platform; private boolean is_online; private String client_id; public RxMqttUserStatusPayload(long user_id, String username, String device_id, String platform, boolean is_online, String client_id) { this.user_id = user_id; this.username = username; this.device_id = device_id; this.platform = platform; this.is_online = is_online; this.client_id = client_id; } public long getUser_id() { return user_id; } public RxMqttUserStatusPayload setUser_id(long user_id) { this.user_id = user_id; return this; } public String getUsername() { return username; } public RxMqttUserStatusPayload setUsername(String username) { this.username = username; return this; } public String getDevice_id() { return device_id; } public RxMqttUserStatusPayload setDevice_id(String device_id) { this.device_id = device_id; return this; } public String getPlatform() { return platform; } public RxMqttUserStatusPayload setPlatform(String platform) { this.platform = platform; return this; } public boolean isIs_online() { return is_online; } public RxMqttUserStatusPayload setIs_online(boolean is_online) { this.is_online = is_online; return this; } public String getClient_id() { return client_id; } public RxMqttUserStatusPayload setClient_id(String client_id) { this.client_id = client_id; return this; } }src/main/java/net/sagebits/weatherlink/data/live/LiveDataListener.java package net.sagebits.weatherlink.data.live; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; import java.nio.charset.StandardCharsets; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; /** * Listens to the Live Data updates broadcast over UDP * {@link LiveDataListener} * * @author */ public class LiveDataListener { final JsonFactory factory = new JsonFactory(); final ObjectMapper mapper = new ObjectMapper(factory); private final Logger log = LogManager.getLogger(LiveDataListener.class); boolean enable = true; final DatagramSocket datagramSocket; public LiveDataListener(int port) throws SocketException { datagramSocket = new DatagramSocket(port); final byte[] buffer = new byte[1024]; final DatagramPacket packet = new DatagramPacket(buffer, buffer.length); Thread t = new Thread(() -> { log.info("Live data listen thread starts"); while (enable) { try { datagramSocket.receive(packet); String liveData = new String(buffer, 0, packet.getLength(), StandardCharsets.UTF_8); log.trace("Live Data: {}", liveData); JsonNode liveRootNode = mapper.readTree(liveData); LiveData.getInstance().update(liveRootNode); } catch (IOException e) { if (!enable) { //be quiet } else { //IO probably means our socket it somehow messed up, and not recoverable. //The hourly check thread will restart a new socket when it checks. log.error("Error reading live data", e); enable = false; } } catch (Exception e) { log.error("Error parsing / reading live data", e); } } datagramSocket.close(); log.info("Live data listen thread ends"); }, "LiveDataListen"); t.start(); } public void stop() { enable = false; datagramSocket.close(); } public boolean running() { return enable; } } app/src/main/java/com/example/android/sunshine/app/LocationEditTextPreference.java package com.example.android.sunshine.app; import android.content.Context; import android.content.res.TypedArray; import android.preference.EditTextPreference; import android.util.AttributeSet; /** * Created by zengzhi on 2017/6/9. */ public class LocationEditTextPreference extends EditTextPreference { private static final int DEFAULT_MINIMUM_LOCATION_LENGTH = 2; private int mMinLength; public LocationEditTextPreference(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.getTheme().obtainStyledAttributes( attrs, R.styleable.LocationEditTextPreference, 0,0); try { mMinLength = a.getInteger(R.styleable.LocationEditTextPreference_minLength, DEFAULT_MINIMUM_LOCATION_LENGTH); } finally { a.recycle(); } } } 1-10 package com.BankingApp.service.impl; import com.BankingApp.dto.AccountMaster; import com.BankingApp.dto.BankUser; import com.BankingApp.dto.Customer; import com.BankingApp.dto.CustomerRequests; import com.BankingApp.exception.BankingException; import com.BankingApp.repository.AccountMasterRepository; import com.BankingApp.repository.BankUserRepository; import com.BankingApp.repository.CustomerRepository; import com.BankingApp.repository.CustomerRequestsRepository; import com.BankingApp.service.IRegistrationService; import org.apache.commons.lang3.RandomStringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCrypt; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.time.LocalDate; import java.util.List; @Service("registrationService") public class RegistrationService implements IRegistrationService { @Autowired private CustomerRequestsRepository customerRequestsRepository; @Autowired private AccountMasterRepository accountMasterRepository; @Autowired private BankUserRepository bankUserRepository; @Autowired private CustomerRepository customerRepository; @Override public void registerUser(CustomerRequests cr) throws BankingException { customerRequestsRepository.saveAndFlush(cr); } @Override public List getCustReqList() throws BankingException { return customerRequestsRepository.findAll(); } @Override public CustomerRequests getCustReq(String customerReqId) throws BankingException { return customerRequestsRepository.findById(customerReqId).get(); } @Override @Transactional public void insertCustomer(String custReqId) throws BankingException { AccountMaster accountMaster = new AccountMaster(); BankUser user = new BankUser(); Customer customer= new Customer(); CustomerRequests custReq = getCustReq(custReqId); accountMaster.setAccountId(RandomStringUtils.randomNumeric(6, 6)); user.setAccId(accountMaster.getAccountId()); user.setAnswer(custReq.getAnswer()); user.setLockStatus("N"); user.setPassword(BCrypt.hashpw(RandomStringUtils.randomAlphanumeric(6, 6),BCrypt.gensalt())); user.setSecretQues(custReq.getSecretQuest()); user.setTransPassword(BCrypt.hashpw(RandomStringUtils.randomAlphanumeric(6, 6),BCrypt.gensalt())); user.setUserId(RandomStringUtils.randomNumeric(6, 6)); accountMaster.setAccountType(custReq.getAccountType()); accountMaster.setChequeStatus(custReq.getChequeStatus()); accountMaster.setOpenDate(LocalDate.now()); accountMaster.setReqId(custReq.getCustReqId()); customer.setAccountId(user.getAccId()); customer.setAddress(custReq.getAddress()); customer.setCustName(custReq.getCustName()); customer.setCustomerId(RandomStringUtils.randomNumeric(6, 6)); customer.setEmail(custReq.getEmail()); customer.setMobileNo(custReq.getMobileNo()); customer.setPanNo(custReq.getPanNo()); custReq.setStatus("Closed"); accountMasterRepository.saveAndFlush(accountMaster); bankUserRepository.saveAndFlush(user); customerRepository.saveAndFlush(customer); customerRequestsRepository.saveAndFlush(custReq); } } package net.sf.opticalbot.ui; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BoxLayout; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.SpinnerNumberModel; import net.sf.opticalbot.omr.Orientation; import net.sf.opticalbot.resources.Dictionary; public class UIMultipleFieldsCreation extends JDialog { public enum Action { CANCEL, OK; } private static final long serialVersionUID = 1L; private final ActionListener actCancel = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { action = Action.CANCEL; dispose(); } }; private Action action = Action.CANCEL; private final ActionListener actOK = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { action = Action.OK; dispose(); } }; private final JButton btnCancel; private final JButton btnOK; private final JCheckBox chbMultiple; private final JComboBox cmbOrientation; private final JSpinner spnAutoNumberingStart; private final JSpinner spnRows; private final JSpinner spnValues; public UIMultipleFieldsCreation(Frame frame, int autoNumberingStart) { super(frame, true); this.setLayout(new BorderLayout()); this.setTitle(Dictionary.translate("field.properties.tab.name")); cmbOrientation = new JComboBox(); cmbOrientation.setModel(new DefaultComboBoxModel(Orientation .values())); chbMultiple = new JCheckBox(); chbMultiple.setSelected(false); spnRows = new JSpinner(); spnRows.setModel(new SpinnerNumberModel(1, 1, Integer.MAX_VALUE, 1)); spnValues = new JSpinner(); spnValues.setModel(new SpinnerNumberModel(1, 1, Integer.MAX_VALUE, 1)); spnAutoNumberingStart = new JSpinner(); spnAutoNumberingStart.setModel(new SpinnerNumberModel( autoNumberingStart, 1, Integer.MAX_VALUE, 1)); JPanel pnlOptions = new JPanel(); pnlOptions.setLayout(new BoxLayout(pnlOptions, BoxLayout.Y_AXIS)); pnlOptions.add(new JLabel(Dictionary .translate("field.properties.type.label"))); pnlOptions.add(cmbOrientation); pnlOptions.add(new JLabel(Dictionary .translate("field.properties.is.multiple"))); pnlOptions.add(chbMultiple); pnlOptions.add(new JLabel(Dictionary .translate("field.properties.number.rows.columns.label"))); pnlOptions.add(spnRows); pnlOptions.add(new JLabel(Dictionary .translate("field.properties.number.values.label"))); pnlOptions.add(spnValues); pnlOptions.add(new JLabel(Dictionary .translate("field.properties.auto.numbering.start.label"))); pnlOptions.add(spnAutoNumberingStart); // TODO: Improve design of this window for (java.awt.Component c: pnlOptions.getComponents()) { javax.swing.JComponent jc = (javax.swing.JComponent)c; jc.setAlignmentX(java.awt.Component.LEFT_ALIGNMENT); } btnOK = new JButton(); btnOK.addActionListener(actOK); btnOK.setText(Dictionary.translate("ok.button")); btnCancel = new JButton(); btnCancel.addActionListener(actCancel); btnCancel.setText(Dictionary.translate("cancel.button")); JPanel pnlOKCancel = new JPanel(new FlowLayout()); pnlOKCancel.add(btnOK); pnlOKCancel.add(btnCancel); this.add(pnlOptions, BorderLayout.CENTER); this.add(pnlOKCancel, BorderLayout.SOUTH); this.pack(); this.setLocationRelativeTo(frame); } public Action getAction() { return action; } public int getAutoNumberingStart() { return (Integer) spnAutoNumberingStart.getValue(); } public boolean getMultiple() { return chbMultiple.isSelected(); } public Orientation getOrientation() { return cmbOrientation.getItemAt(cmbOrientation.getSelectedIndex()); } public int getRowsNumber() { return (Integer) spnRows.getValue(); } public int getValuesNumber() { return (Integer) spnValues.getValue(); } } wangyiming/intellij-community // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.repo; import com.intellij.dvcs.ignore.IgnoredToExcludedSynchronizer; import com.intellij.dvcs.ignore.VcsIgnoredHolderUpdateListener; import com.intellij.dvcs.repo.RepositoryImpl; import com.intellij.openapi.Disposable; import com.intellij.openapi.progress.util.BackgroundTaskUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vcs.changes.ChangesViewI; import com.intellij.openapi.vcs.changes.ChangesViewManager; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.vcs.log.util.StopWatch; import git4idea.GitLocalBranch; import git4idea.GitUtil; import git4idea.GitVcs; import git4idea.branch.GitBranchesCollection; import git4idea.commands.Git; import git4idea.ignore.GitRepositoryIgnoredFilesHolder; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashSet; import static com.intellij.dvcs.DvcsUtil.getShortRepositoryName; import static com.intellij.openapi.progress.util.BackgroundTaskUtil.syncPublisher; import static com.intellij.util.ObjectUtils.assertNotNull; public class GitRepositoryImpl extends RepositoryImpl implements GitRepository { @NotNull private final GitVcs myVcs; @NotNull private final GitRepositoryReader myReader; @NotNull private final VirtualFile myGitDir; @NotNull private final GitRepositoryFiles myRepositoryFiles; @Nullable private final GitUntrackedFilesHolder myUntrackedFilesHolder; @Nullable private final GitRepositoryIgnoredFilesHolder myIgnoredRepositoryFilesHolder; @Nullable private final GitConflictsHolder myConflictsHolder; @NotNull private volatile GitRepoInfo myInfo; private GitRepositoryImpl(@NotNull VirtualFile rootDir, @NotNull VirtualFile gitDir, @NotNull Project project, @NotNull Disposable parentDisposable, final boolean light) { super(project, rootDir, parentDisposable); myVcs = GitVcs.getInstance(project); myGitDir = gitDir; myRepositoryFiles = GitRepositoryFiles.getInstance(gitDir); myReader = new GitRepositoryReader(myRepositoryFiles); myInfo = readRepoInfo(); if (!light) { myUntrackedFilesHolder = new GitUntrackedFilesHolder(this, myRepositoryFiles); Disposer.register(this, myUntrackedFilesHolder); myIgnoredRepositoryFilesHolder = new GitRepositoryIgnoredFilesHolder(project, this, GitRepositoryManager.getInstance(project), Git.getInstance()); Disposer.register(this, myIgnoredRepositoryFilesHolder); myIgnoredRepositoryFilesHolder.addUpdateStateListener(new MyRepositoryIgnoredHolderUpdateListener(project)); myIgnoredRepositoryFilesHolder.addUpdateStateListener(new IgnoredToExcludedSynchronizer(project, this)); myConflictsHolder = new GitConflictsHolder(this); Disposer.register(this, myConflictsHolder); } else { myUntrackedFilesHolder = null; myIgnoredRepositoryFilesHolder = null; myConflictsHolder = null; } } /** * @see GitRepositoryManager#getRepositoryForRoot */ @NotNull @Deprecated public static GitRepository getInstance(@NotNull VirtualFile root, @NotNull Project project, boolean listenToRepoChanges) { return getInstance(root, project, project, listenToRepoChanges); } @NotNull public static GitRepository getInstance(@NotNull VirtualFile root, @NotNull Project project, @NotNull Disposable parentDisposable, boolean listenToRepoChanges) { return getInstance(root, assertNotNull(GitUtil.findGitDir(root)), project, parentDisposable, listenToRepoChanges); } @NotNull public static GitRepository getInstance(@NotNull VirtualFile root, @NotNull VirtualFile gitDir, @NotNull Project project, @NotNull Disposable parentDisposable, boolean listenToRepoChanges) { GitRepositoryImpl repository = new GitRepositoryImpl(root, gitDir, project, parentDisposable, !listenToRepoChanges); if (listenToRepoChanges) { repository.getUntrackedFilesHolder().setupVfsListener(project); repository.getIgnoredFilesHolder().setupVfsListener(); repository.setupUpdater(); notifyListenersAsync(repository); } return repository; } private void setupUpdater() { GitRepositoryUpdater updater = new GitRepositoryUpdater(this, myRepositoryFiles); Disposer.register(this, updater); if (myIgnoredRepositoryFilesHolder != null) { myIgnoredRepositoryFilesHolder.startRescan(); } } @Deprecated @NotNull @Override public VirtualFile getGitDir() { return myGitDir; } @NotNull @Override public GitRepositoryFiles getRepositoryFiles() { return myRepositoryFiles; } @Override @NotNull public GitUntrackedFilesHolder getUntrackedFilesHolder() { if (myUntrackedFilesHolder == null) { throw new IllegalStateException("Using untracked files holder with light git repository instance " + this); } return myUntrackedFilesHolder; } @NotNull @Override public GitConflictsHolder getConflictsHolder() { if (myConflictsHolder == null) { throw new IllegalStateException("Using conflicts holder with light git repository instance " + this); } return myConflictsHolder; } @Override @NotNull public GitRepoInfo getInfo() { return myInfo; } @Override @Nullable public GitLocalBranch getCurrentBranch() { return myInfo.getCurrentBranch(); } @Nullable @Override public String getCurrentRevision() { return myInfo.getCurrentRevision(); } @NotNull @Override public State getState() { return myInfo.getState(); } @Nullable @Override public String getCurrentBranchName() { GitLocalBranch currentBranch = getCurrentBranch(); return currentBranch == null ? null : currentBranch.getName(); } @NotNull @Override public GitVcs getVcs() { return myVcs; } @NotNull @Override public Collection getSubmodules() { return myInfo.getSubmodules(); } /** * @return local and remote branches in this repository. */ @Override @NotNull public GitBranchesCollection getBranches() { GitRepoInfo info = myInfo; return new GitBranchesCollection(info.getLocalBranchesWithHashes(), info.getRemoteBranchesWithHashes()); } @Override @NotNull public Collection getRemotes() { return myInfo.getRemotes(); } @Override @NotNull public Collection getBranchTrackInfos() { return myInfo.getBranchTrackInfos(); } @Nullable @Override public GitBranchTrackInfo getBranchTrackInfo(@NotNull String localBranchName) { return myInfo.getBranchTrackInfosMap().get(localBranchName); } @Override public boolean isRebaseInProgress() { return getState() == State.REBASING; } @Override public boolean isOnBranch() { return getState() != State.DETACHED && getState() != State.REBASING; } @Override public boolean isFresh() { return getCurrentRevision() == null; } @Override public void update() { GitRepoInfo previousInfo = myInfo; myInfo = readRepoInfo(); notifyIfRepoChanged(this, previousInfo, myInfo); } @NotNull private GitRepoInfo readRepoInfo() { StopWatch sw = StopWatch.start("Reading Git repo info in " + getShortRepositoryName(this)); File configFile = myRepositoryFiles.getConfigFile(); GitConfig config = GitConfig.read(configFile); Collection remotes = config.parseRemotes(); GitBranchState state = myReader.readState(remotes); boolean isShallow = myReader.hasShallowCommits(); Collection trackInfos = config.parseTrackInfos(state.getLocalBranches().keySet(), state.getRemoteBranches().keySet()); GitHooksInfo hooksInfo = myReader.readHooksInfo(); Collection submodules = new GitModulesFileReader().read(getSubmoduleFile()); sw.report(); return new GitRepoInfo(state.getCurrentBranch(), state.getCurrentRevision(), state.getState(), new LinkedHashSet<>(remotes), new HashMap<>(state.getLocalBranches()), new HashMap<>(state.getRemoteBranches()), new LinkedHashSet<>(trackInfos), submodules, hooksInfo, isShallow); } @NotNull private File getSubmoduleFile() { return new File(VfsUtilCore.virtualToIoFile(getRoot()), ".gitmodules"); } private static void notifyIfRepoChanged(@NotNull final GitRepository repository, @NotNull GitRepoInfo previousInfo, @NotNull GitRepoInfo info) { if (!repository.getProject().isDisposed() && !info.equals(previousInfo)) { notifyListenersAsync(repository); } } private static void notifyListenersAsync(@NotNull GitRepository repository) { Runnable task = () -> syncPublisher(repository.getProject(), GIT_REPO_CHANGE).repositoryChanged(repository); BackgroundTaskUtil.executeOnPooledThread(repository, task); } @NotNull @Override public String toLogString() { return "GitRepository " + getRoot() + " : " + myInfo; } @NotNull @Override public GitRepositoryIgnoredFilesHolder getIgnoredFilesHolder() { if (myIgnoredRepositoryFilesHolder == null) throw new UnsupportedOperationException("Unsupported for light Git repository"); return myIgnoredRepositoryFilesHolder; } private static class MyRepositoryIgnoredHolderUpdateListener implements VcsIgnoredHolderUpdateListener { @NotNull private final ChangesViewI myChangesViewI; @NotNull private final Project myProject; MyRepositoryIgnoredHolderUpdateListener(@NotNull Project project) { myChangesViewI = ChangesViewManager.getInstance(project); myProject = project; } @Override public void updateStarted() { myChangesViewI.scheduleRefresh(); //TODO optimize: remove additional refresh } @Override public void updateFinished(@NotNull Collection ignoredPaths) { if(myProject.isDisposed()) return; myChangesViewI.scheduleRefresh(); } } } package tech.arauk.ark.arel.nodes; import tech.arauk.ark.arel.annotations.Beta; @Beta public class ArelNodeBetween extends ArelNodeBinary { public ArelNodeBetween(Object left, Object right) { super(left, right); } } code/crawler/src/org/archive/crawler/datamodel/UriUniqFilter.java /* UriUniqFilter * * Created on Apr 17, 2003 * * Copyright (C) 2003 Internet Archive. * * This file is part of the Heritrix web crawler (crawler.archive.org). * * Heritrix is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * any later version. * * Heritrix 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 Public License for more details. * * You should have received a copy of the GNU Lesser Public License * along with Heritrix; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.archive.crawler.datamodel; import java.io.File; /** * A UriUniqFilter passes URI objects to a destination * (receiver) if the passed URI object has not been previously seen. * * If already seen, the passed URI object is dropped. * *

For efficiency in comparison against a large history of * seen URIs, URI objects may not be passed immediately, unless * the addNow() is used or a flush() is forced. * * @author gojomo * @version $Date: 2005-12-16 03:10:54 +0000 (Fri, 16 Dec 2005) $, $Revision: 4036 $ */ public interface UriUniqFilter { /** * @return Count of already seen URIs. */ public long count(); /** * Count of items added, but not yet filtered in or out. * * Some implementations may buffer up large numbers of pending * items to be evaluated in a later large batch/scan/merge with * disk files. * * @return Count of items added not yet evaluated */ public long pending(); /** * Receiver of uniq URIs. * * Items that have not been seen before are pass through to this object. * @param receiver Object that will be passed items. Must implement * HasUriReceiver interface. */ public void setDestination(HasUriReceiver receiver); /** * Add given uri, if not already present. * @param key Usually a canonicalized version of value. * This is the key used doing lookups, forgets and insertions on the * already included list. * @param value item to add. */ public void add(String key, CandidateURI value); /** * Immediately add uri. * @param key Usually a canonicalized version of uri. * This is the key used doing lookups, forgets and insertions on the * already included list. * @param value item to add. */ public void addNow(String key, CandidateURI value); /** * Add given uri, all the way through to underlying destination, even * if already present. * * (Sometimes a URI must be fetched, or refetched, for example when * DNS or robots info expires or the operator forces a refetch. A * normal add() or addNow() would drop the URI without forwarding * on once it is determmined to already be in the filter.) * * @param key Usually a canonicalized version of uri. * This is the key used doing lookups, forgets and insertions on the * already included list. * @param value item to add. */ public void addForce(String key, CandidateURI value); /** * Note item as seen, without passing through to receiver. * @param key Usually a canonicalized version of an URI. * This is the key used doing lookups, forgets and insertions on the * already included list. */ public void note(String key); /** * Forget item was seen * @param key Usually a canonicalized version of an URI. * This is the key used doing lookups, forgets and insertions on the * already included list. * @param value item to add. */ public void forget(String key, CandidateURI value); /** * Request that any pending items be added/dropped. Implementors * may ignore the request if a flush would be too expensive/too * soon. * * @return Number added. */ public long requestFlush(); /** * Close down any allocated resources. * Makes sense calling this when checkpointing. */ public void close(); /** * Set a File to receive a log for replay profiling. */ public void setProfileLog(File logfile); /** * URIs that have not been seen before 'visit' this 'Visitor'. * * Usually implementations of Frontier implement this interface. * @author gojomo */ public interface HasUriReceiver { /** * @param item Candidate uri tem that is 'visiting'. */ public void receive(CandidateURI item); } }package com.example.switchdemo; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //get input from user in a String variable called command String command = "go east"; switch (command) { case "go east": Log.i("Player: ", "Moves to the East"); break; case "go west": Log.i("Player: ", "Moves to the West"); break; case "go north": Log.i("Player: ", "Moves to the North"); break; case "go south": Log.i("Player: ", "Moves to the South"); break; case "take sword": Log.i("Player: ", "Takes the silver sword"); break; //more possible cases default: Log.i("Message: ", "Sorry I don't speak Elfish"); break; } } }/* * #%L * de.metas.adempiere.adempiere.base * %% * Copyright (C) 2019 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * . * #L% */ package de.metas.location.geocoding.provider.openstreetmap; import de.metas.util.JSONObjectMapper; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; class NominatimOSMGeographicalCoordinatesJSONDeserialisationTest { @Test void canDeserializeGoodResponse() { final String serialisedResponse = " {\n" + " \"place_id\": 237626930,\n" + " \"licence\": \"Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright\",\n" + " \"boundingbox\": [\n" + " \"45.758244872052\",\n" + " \"45.758344872052\",\n" + " \"21.224939377961\",\n" + " \"21.225039377961\"\n" + " ],\n" + " \"lat\": \"45.75829487205204\",\n" + " \"lon\": \"21.224989377961297\",\n" + " \"display_name\": \", Timiș, 300078, Romania\",\n" + " \"class\": \"place\",\n" + " \"type\": \"postcode\",\n" + " \"importance\": 0.33499999999999996\n" + " }\n"; final NominatimOSMGeographicalCoordinatesJSON expected = NominatimOSMGeographicalCoordinatesJSON.builder() .display_name("ș, 300078, Romania") .lat("45.75829487205204") .lon("21.224989377961297") .build(); final NominatimOSMGeographicalCoordinatesJSON deserializedInvoiceCandidate = JSONObjectMapper.forClass(NominatimOSMGeographicalCoordinatesJSON.class).readValue(serialisedResponse); assertThat(deserializedInvoiceCandidate).isEqualTo(expected); } @Test void canDeserializeEmptyResponse() { final String serialisedResponse = "{}"; final NominatimOSMGeographicalCoordinatesJSON expected = NominatimOSMGeographicalCoordinatesJSON.builder() .build(); final NominatimOSMGeographicalCoordinatesJSON deserializedInvoiceCandidate = JSONObjectMapper.forClass(NominatimOSMGeographicalCoordinatesJSON.class).readValue(serialisedResponse); assertThat(deserializedInvoiceCandidate).isEqualTo(expected); } } package org.lecoder.easyflow.modules.leave.service.impl; import org.lecoder.easyflow.modules.leave.entity.LeaveEmployee; import org.lecoder.easyflow.modules.leave.mapper.LeaveEmployeeMapper; import org.lecoder.easyflow.modules.leave.service.ILeaveEmployeeService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** *

* 请假员工信息 服务实现类 *

* * @author lijile * @since 2021-11-15 */ @Service public class LeaveEmployeeServiceImpl extends ServiceImpl implements ILeaveEmployeeService { } bremersee/fac /* * Copyright 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bremersee.fac.domain.ldap; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.bremersee.comparator.ObjectComparator; import org.bremersee.comparator.ObjectComparatorFactory; import org.bremersee.comparator.model.ComparatorItem; import org.bremersee.fac.domain.FailedAccessDao; import org.bremersee.fac.model.FailedAccess; import org.bremersee.fac.model.FailedAccessDto; import org.bremersee.utils.CodingUtils; import org.bremersee.utils.TagUtils; import org.ldaptive.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.PostConstruct; import javax.inject.Named; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.LinkedList; import java.util.List; /** * @author */ @SuppressWarnings({"WeakerAccess", "unused"}) @Named("failedAccessLdapDao") public class FailedAccessLdapDao implements FailedAccessDao { protected final Logger log = LoggerFactory.getLogger(getClass()); protected ConnectionFactory connectionFactory; protected SearchRequest searchRequest; protected FailedAccessLdapMapper failedAccessLdapMapper; protected ObjectComparatorFactory objectComparatorFactory; private String searchFilter; private String loadFilter; private String obsoleteFilter; @PostConstruct public void init() { log.info("Initialzing " + getClass().getSimpleName() + " ..."); Validate.notNull(connectionFactory, "connectionFactory must not be null"); Validate.notNull(searchRequest, "searchRequest must not be null"); log.info("baseDn = " + searchRequest.getBaseDn()); if (failedAccessLdapMapper == null) { FailedAccessDefaultLdapMapper defaultLdapFailedAccessMapper = new FailedAccessDefaultLdapMapper(); defaultLdapFailedAccessMapper.init(); failedAccessLdapMapper = defaultLdapFailedAccessMapper; } if (objectComparatorFactory == null) { objectComparatorFactory = ObjectComparatorFactory.newInstance(); } if (StringUtils.isBlank(searchFilter)) { searchFilter = '(' + this.failedAccessLdapMapper.getIdAttribute() + "={0})"; } log.info("searchFilter = " + searchFilter); if (StringUtils.isBlank(loadFilter)) { loadFilter = "(objectClass=" + this.failedAccessLdapMapper.getObjectClass() + ')'; } log.info("loadFilter = " + loadFilter); if (StringUtils.isBlank(obsoleteFilter)) { String loadFilter = this.loadFilter; // NOSONAR if (!loadFilter.startsWith("(")) { loadFilter = "(" + loadFilter; } if (!loadFilter.endsWith("")) { loadFilter = loadFilter + ")"; } obsoleteFilter = "(&" + loadFilter + "(" + failedAccessLdapMapper.getModificationDateAttribute() + "<={0}))"; } log.info("obsoleteFilter = " + obsoleteFilter); log.info(getClass().getSimpleName() + " successfully initialized."); } public void setConnectionFactory(final ConnectionFactory connectionFactory) { this.connectionFactory = connectionFactory; } public void setSearchRequest(SearchRequest searchRequest) { this.searchRequest = searchRequest; } public void setFailedAccessLdapMapper(final FailedAccessLdapMapper failedAccessLdapMapper) { this.failedAccessLdapMapper = failedAccessLdapMapper; } public void setObjectComparatorFactory(final ObjectComparatorFactory objectComparatorFactory) { this.objectComparatorFactory = objectComparatorFactory; } public String getSearchFilter() { return searchFilter; } public void setSearchFilter(final String searchFilter) { this.searchFilter = searchFilter; } public String getLoadFilter() { return loadFilter; } public void setLoadFilter(final String loadFilter) { this.loadFilter = loadFilter; } public String getObsoleteFilter() { return obsoleteFilter; } public void setObsoleteFilter(final String obsoleteFilter) { this.obsoleteFilter = obsoleteFilter; } private String createUid(final FailedAccess failedAccess) { final FailedAccess fa = failedAccess == null ? new FailedAccessDto() : failedAccess; return createUid(fa.getResourceId(), fa.getRemoteHost()); } private String createUid(final String resourceId, final String remoteHost) { final String uid = resourceId + "@" + remoteHost; if (CodingUtils.toBytesSilently(uid, "UTF-8").length < 256) { return uid; } return CodingUtils.toHex(CodingUtils.digestSilently(CodingUtils.getMessageDigestSilently("MD5"), CodingUtils.toBytesSilently(uid, "UTF-8"))); } /** * Gets connection from the factory. Opens the connection if needed. * * @return the connection * @throws LdapException the ldap exception */ private Connection getConnection() throws LdapException { final Connection c = this.connectionFactory.getConnection(); if (!c.isOpen()) { c.open(); } return c; } /** * Close the given context and ignore any thrown exception. This is useful * for typical finally blocks in manual Ldap statements. * * @param context the Ldap connection to close */ private void closeConnection(final Connection context) { if (context != null && context.isOpen()) { try { context.close(); } catch (final Exception ex) { log.warn("Closing ldap connection failed.", ex); } } } /** * Checks to see if response has a result. * * @param response the response * @return true, if successful */ private boolean hasResults(final Response response) { final SearchResult result = response.getResult(); if (result != null && result.getEntry() != null) { return true; } if (log.isDebugEnabled()) { log.debug("Requested ldap operation did not return a result or an ldap entry [code = " + response.getResultCode() + ", message = " + response.getMessage() + "]"); } return false; } /** * Search for access failed entry by id. * * @param connection the connection * @param id the id * @return the response * @throws LdapException the ldap exception */ private Response searchForFailedAccessById(final Connection connection, final String id) throws LdapException { final SearchFilter filter = new SearchFilter(this.searchFilter); filter.setParameter(0, id); return executeSearchOperation(connection, filter); } /** * Execute search operation. * * @param connection the connection * @param filter the filter * @return the response * @throws LdapException the ldap exception */ private Response executeSearchOperation(final Connection connection, final SearchFilter filter) throws LdapException { final SearchOperation searchOperation = new SearchOperation(connection); final SearchRequest request = newRequest(filter); if (log.isDebugEnabled()) { log.debug("Using search request " + request.toString()); } return searchOperation.execute(request); } /** * Builds a new request. * * @param filter the filter * @return the search request */ private SearchRequest newRequest(final SearchFilter filter) { final SearchRequest sr = new SearchRequest(this.searchRequest.getBaseDn(), filter); sr.setBinaryAttributes(ReturnAttributes.ALL_USER.value()); sr.setDerefAliases(this.searchRequest.getDerefAliases()); sr.setSearchEntryHandlers(this.searchRequest.getSearchEntryHandlers()); sr.setSearchReferenceHandlers(this.searchRequest.getSearchReferenceHandlers()); sr.setReturnAttributes(ReturnAttributes.ALL_USER.value()); sr.setSearchScope(this.searchRequest.getSearchScope()); sr.setSizeLimit(this.searchRequest.getSizeLimit()); sr.setSortBehavior(this.searchRequest.getSortBehavior()); sr.setTypesOnly(this.searchRequest.getTypesOnly()); sr.setControls(this.searchRequest.getControls()); sr.setControls(this.searchRequest.getControls()); sr.setIntermediateResponseHandlers(this.searchRequest.getIntermediateResponseHandlers()); sr.setReferralHandler(this.searchRequest.getReferralHandler()); sr.setTimeLimit(this.searchRequest.getTimeLimit()); return sr; } /** * Update the ldap entry with the given failed access. * * @param failedAccess the rs * @return the registered service */ private FailedAccessDto update(final FailedAccess failedAccess) { Connection searchConnection = null; try { searchConnection = getConnection(); final Response response = searchForFailedAccessById(searchConnection, failedAccess.getId().toString()); if (hasResults(response)) { final String currentDn = response.getResult().getEntry().getDn(); Connection modifyConnection = null; try { // NOSONAR modifyConnection = getConnection(); final ModifyOperation operation = new ModifyOperation(searchConnection); final List mods = new ArrayList<>(); final LdapEntry entry = failedAccessLdapMapper .mapFromFailedAccessLdapEntity(this.searchRequest.getBaseDn(), failedAccess); for (final LdapAttribute attr : entry.getAttributes()) { // NOSONAR if (!attr.getName().equals(failedAccessLdapMapper.getIdAttribute())) { mods.add(new AttributeModification(AttributeModificationType.REPLACE, attr)); } } final ModifyRequest request = new ModifyRequest(currentDn, mods.toArray(new AttributeModification[]{})); operation.execute(request); } catch (final LdapException e) { String message = "Updating " + failedAccess + " failed."; // NOSONAR log.error(message, e); throw new RuntimeException(message, e); // NOSONAR } finally { closeConnection(modifyConnection); } return new FailedAccessDto(failedAccess); } else { FailedAccessDto dto = new FailedAccessDto(failedAccess); dto.setId(null); return save(dto); } } catch (final LdapException e) { String message = "Updating " + failedAccess + " failed."; log.error(message, e); throw new RuntimeException(message, e); // NOSONAR } finally { closeConnection(searchConnection); } } @Override public FailedAccessDto save(final FailedAccess failedAccess) { if (failedAccess.getId() != null) { return update(failedAccess); } FailedAccessDto entity = new FailedAccessDto(failedAccess); entity.setId(createUid(failedAccess)); Connection connection = null; try { connection = getConnection(); final AddOperation operation = new AddOperation(connection); final LdapEntry entry = this.failedAccessLdapMapper .mapFromFailedAccessLdapEntity(this.searchRequest.getBaseDn(), entity); operation.execute(new AddRequest(entry.getDn(), entry.getAttributes())); return entity; } catch (final LdapException e) { String message = "Saving " + failedAccess + " failed."; log.error(message, e); throw new RuntimeException(message, e); // NOSONAR } finally { closeConnection(connection); } } @Override public FailedAccessDto getById(final Serializable _id) { // NOSONAR if (_id == null) { return null; } String id = _id.toString(); Connection connection = null; try { connection = getConnection(); final Response response = searchForFailedAccessById(connection, id); if (hasResults(response)) { return failedAccessLdapMapper.mapToFailedAccessLdapEntity(response.getResult().getEntry()); } return null; } catch (final LdapException e) { String message = "Getting failed access by ID [" + _id + "] failed."; log.error(message, e); throw new RuntimeException(message, e); // NOSONAR } finally { closeConnection(connection); } } @Override public FailedAccessDto getByResourceIdAndRemoteHost(final String resourceId, final String remoteHost) { return getById(createUid(resourceId, remoteHost)); } @Override public boolean removeById(final Serializable _id) { // NOSONAR if (_id == null) { return false; } String id = _id.toString(); Connection connection = null; try { connection = getConnection(); final Response response = searchForFailedAccessById(connection, id); if (hasResults(response)) { final LdapEntry entry = response.getResult().getEntry(); final DeleteOperation delete = new DeleteOperation(connection); final DeleteRequest request = new DeleteRequest(entry.getDn()); final Response res = delete.execute(request); return res.getResultCode() == ResultCode.SUCCESS; } return false; } catch (final LdapException e) { String message = "Removing failed access by ID [" + _id + "] failed."; log.error(message, e); throw new RuntimeException(message, e); // NOSONAR } finally { closeConnection(connection); } } @Override public boolean removeByResourceIdAndRemoteHost(final String resourceId, final String remoteHost) { return removeById(createUid(resourceId, remoteHost)); } @Override public long count(final String searchValue) { return (long) find(searchValue).size(); } @Override public List find(final String searchValue, final Integer firstResult, final Integer maxResults, final ComparatorItem comparatorItem) { final int first = firstResult == null || firstResult < 0 ? 0 : firstResult; int max = maxResults == null || maxResults <= 0 ? Integer.MAX_VALUE : maxResults; List entities = find(searchValue); if (comparatorItem != null && StringUtils.isNotBlank(comparatorItem.getField())) { ObjectComparator objectComparator = objectComparatorFactory.newObjectComparator(comparatorItem); entities.sort(objectComparator); } if (first == 0 && max == Integer.MAX_VALUE) { return entities; } List resultList = new ArrayList<>(); max = Math.min(max, entities.size()); for (int i = first; i - first < max; i++) { resultList.add(entities.get(i)); } return resultList; } private List find(final String searchValue) { // NOSONAR Connection connection = null; final List list = new LinkedList<>(); try { String loadFilter; // NOSONAR if (StringUtils.isBlank(searchValue)) { loadFilter = this.loadFilter; } else { String[] tags = TagUtils.buildTags(searchValue); if (tags == null || tags.length == 0) { loadFilter = this.loadFilter; } else { StringBuilder sb = new StringBuilder(); sb.append("(&"); if (!this.loadFilter.startsWith("(")) { // NOSONAR sb.append("("); } sb.append(this.loadFilter); if (!this.loadFilter.endsWith(")")) { // NOSONAR sb.append(")"); } sb.append("(|"); for (String tag : tags) { // NOSONAR sb.append("(").append(failedAccessLdapMapper.getResourceIdAttribute()).append("=*").append(tag) .append("*)").append("(").append(failedAccessLdapMapper.getRemoteHostAttribute()) .append("=*").append(tag).append("*)"); } sb.append("))"); loadFilter = sb.toString(); } } connection = getConnection(); final Response response = executeSearchOperation(connection, new SearchFilter(loadFilter)); if (hasResults(response)) { for (final LdapEntry entry : response.getResult().getEntries()) { final FailedAccessDto failedAccessEntity = this.failedAccessLdapMapper .mapToFailedAccessLdapEntity(entry); list.add(failedAccessEntity); } } } catch (final LdapException e) { String message = "Finding failed access entries failed."; log.error(message, e); throw new RuntimeException(message, e); // NOSONAR } finally { closeConnection(connection); } return list; } @Override public List findObsolete(final long removeFailedAccessEntriesAfterMillis) { Connection connection = null; final List list = new LinkedList<>(); try { connection = getConnection(); final Object[] params = new Object[1]; params[0] = failedAccessLdapMapper.getSimpleDateFormat() .format(new Date(System.currentTimeMillis() - removeFailedAccessEntriesAfterMillis)); final Response response = executeSearchOperation(connection, new SearchFilter(obsoleteFilter, params)); if (hasResults(response)) { for (final LdapEntry entry : response.getResult().getEntries()) { final FailedAccessDto failedAccessEntity = this.failedAccessLdapMapper .mapToFailedAccessLdapEntity(entry); list.add(failedAccessEntity); } } } catch (final LdapException e) { String message = "Finding obsolete failed access entries failed."; log.error(message, e); throw new RuntimeException(message, e); // NOSONAR } finally { closeConnection(connection); } return list; } } src/leetcode_problems/easy/PalindromeList_234.java package leetcode_problems.easy; // todo not completed public class PalindromeList_234 { public boolean isPalindrome(ListNode node) { return true; } private class ListNode { int val; ListNode next; public ListNode(int val) { this.val = val; } } }package day_0514.a1; public class ToStringTest { public static void main(String[] args) { Object obj = new Object(); System.out.println(obj.toString()); String name = new String("이름"); System.out.println(name); } } agileway-sshclient/src/main/java/com/jn/agileway/ssh/client/sftp/attrs/FileAttrs.java package com.jn.agileway.ssh.client.sftp.attrs; import com.jn.langx.util.Dates; import com.jn.langx.util.collection.Collects; import com.jn.langx.util.io.file.FilePermission; import java.util.Date; import java.util.Map; import java.util.Set; public class FileAttrs { private Long size = null; public Long getSize() { return this.size; } public void setSize(long size) { this.size = size; } private Integer uid = null; public Integer getUid() { return this.uid; } public void setUid(int uid) { this.uid = uid; } private Integer gid = null; public Integer getGid() { return this.gid; } public void setGid(int gid) { this.gid = gid; } private FileMode fileMode; public FileMode getFileMode() { return this.fileMode; } public void setFileMode(FileMode fileMode) { this.fileMode = fileMode; } /** * access time: unit: s */ private Integer atime = null; public Integer getAccessTime() { return this.atime; } public void setAccessTime(int accessTime) { this.atime = accessTime; } /** * modify time: unit: s */ private Integer mtime = null; public Integer getModifyTime() { return this.mtime; } public void setModifyTime(int modifyTime) { this.mtime = modifyTime; } private Map extendProperties = Collects.emptyHashMap(); public String getExtend(String key) { return extendProperties.get(key); } public void setExtend(String key, String value) { this.extendProperties.put(key, value); } public Set getExtendKeys() { return this.extendProperties.keySet(); } public boolean isDirectory() { if (this.fileMode != null) { return this.fileMode.getType() == FileType.DIRECTORY; } return false; } public boolean isFile() { if (this.fileMode != null) { return this.fileMode.getType() == FileType.REGULAR; } return false; } public boolean isSocket() { if (this.fileMode != null) { return this.fileMode.getType() == FileType.SOCKET_SPECIAL; } return false; } public boolean isBlock() { if (this.fileMode != null) { return this.fileMode.getType() == FileType.BLOCK_SPECIAL; } return false; } public boolean isChar() { if (this.fileMode != null) { return this.fileMode.getType() == FileType.CHAR_SPECIAL; } return false; } public boolean isLink() { if (this.fileMode != null) { return this.fileMode.getType() == FileType.SYMBOLIC_LINK; } return false; } public boolean isFIFO() { if (this.fileMode != null) { return this.fileMode.getType() == FileType.FIFO_SPECIAL; } return false; } @Override public String toString() { // https://www.cnblogs.com/gezp/p/12875219.html StringBuilder builder = new StringBuilder(256); if (fileMode != null) { builder.append(fileMode.getType().getDisplayText()); Set filePermissions = fileMode.getPermissions(); builder.append(filePermissions.contains(FilePermission.USR_R) ? "r" : "-"); builder.append(filePermissions.contains(FilePermission.USR_W) ? "w" : "-"); builder.append(filePermissions.contains(FilePermission.USR_X) ? "x" : "-"); builder.append(filePermissions.contains(FilePermission.GRP_R) ? "r" : "-"); builder.append(filePermissions.contains(FilePermission.GRP_W) ? "w" : "-"); builder.append(filePermissions.contains(FilePermission.GRP_X) ? "x" : "-"); builder.append(filePermissions.contains(FilePermission.OTH_R) ? "r" : "-"); builder.append(filePermissions.contains(FilePermission.OTH_W) ? "w" : "-"); builder.append(filePermissions.contains(FilePermission.OTH_X) ? "x" : "-"); builder.append(" "); } if (this.size != null) { builder.append(this.size).append(" "); } if(this.mtime!=null){ builder.append(Dates.format(new Date(this.mtime * 1000), Dates.yyyy_MM_dd_HH_mm_ss)) .append(" "); } return builder.toString(); } } package com.example.tests; import java.io.File; import java.io.FileReader; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Properties; import java.util.Random; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import com.example.fw.ApplicationManager; import static com.example.tests.GroupDataGenerator.generateRandomGroups; public class TestBase { protected ApplicationManager app; @BeforeTest public void setUp() throws Exception { Properties properties = new Properties(); properties.load(new FileReader (new File( "application.properties")) ); app=new ApplicationManager(properties); } @AfterTest public void tearDown() throws Exception { app.stop(); } @DataProvider public Iterator randomValidGroupGenerator(){ return wrapGroupsForDataProvider(generateRandomGroups(5)).iterator(); } public static List wrapGroupsForDataProvider(List groups) { Listlist= new ArrayList(); for(GroupData group: groups){ list.add(new Object[]{group}); } return list; } public static List wrapContactsForDataProvider(List contacts) { Listlist= new ArrayList(); for(ContactData contact: contacts){ list.add(new Object[]{contact}); } return list; } public String generateRandomDay(){ Random rnd =new Random(); if(rnd.nextInt(3)==0){ return"-"; } else return "1"+ rnd.nextInt(3); } public String generateRandomMonths(){ Random rnd =new Random(); String months[] = { "January", "February", "June", "July", "December"}; int mon=rnd.nextInt(months.length); return months[mon]; } public String generateRandomYear(){ Random rnd =new Random(); return "198"+ rnd.nextInt(3); } /*public Calendar generateRandomDate(){ GregorianCalendar gc = new GregorianCalendar(); int year = randBetween(2000, 2015); gc.set(Calendar.YEAR, year); int dayOfYear = randBetween(1, gc.getActualMaximum(Calendar.DAY_OF_YEAR)); gc.set(Calendar.DAY_OF_YEAR, dayOfYear); return gc; } public static int randBetween(int start, int end) { return start + (int)Math.round(Math.random() * (end - start)); } */ public static String generateRandomString(){ Random rnd =new Random(); if(rnd.nextInt(3)==0){ return""; } else return "test"+ rnd.nextInt(); } /* @DataProvider public Iterator randomValidContactGenerator(){ Listlist= new ArrayList(); for( int i =0;i<2;i++){ ContactData contacts = new ContactData() .withFirstName(generateRandomString()) .withLastName(generateRandomString()) .withAddr(generateRandomString()) .withEmail(generateRandomString()) .withPhone(generateRandomString()) .withBirthDay(generateRandomDate().get(Calendar.DAY_OF_MONTH)) .withBirthMonth(generateRandomDate().getDisplayName(Calendar.MONTH, Calendar.LONG,new Locale("eng", "US"))) .withBirthYear(generateRandomDate().get(Calendar.YEAR)); list.add(new Object[]{contacts}); } return list.iterator(); } */ } mgpavlov/SoftUni package cars.controllers; import cars.dto.bindings.CustomerImportDto; import cars.dto.bindings.CustomersImportXmlDto; import cars.dto.views.customer.CustomerTotalSalesViewDto; import cars.dto.views.customer.CustomersTotalSalesXmlViewDto; import cars.dto.views.customer.OrderedCustomersViewDto; import cars.dto.views.customer.OrderedCustomersXmlViewDto; import cars.serializers.Serializer; import cars.services.CustomerService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import java.util.Arrays; import java.util.List; @Controller public class CustomerController { private static final String CUSTOMERS_JSON_INPUT_PATH = "/json/input/customers.json"; private static final String CUSTOMERS_XML_INPUT_PATH = "/xml/input/customers.xml"; private static final String ORDERED_CUSTOMERS_JSON_OUTPUT_PATH = "/src/main/resources/json/output/ordered-customer.json"; private static final String ORDERED_CUSTOMERS_XML_OUTPUT_PATH = "src/main/resources/xml/output/ordered-customer.xml"; private static final String CUSTOMERS_TOTAL_SALES_JSON_OUTPUT_PATH = "/src/main/resources/json/output/customer-total-sales.json"; private static final String CUSTOMERS_TOTAL_SALES_XML_OUTPUT_PATH = "src/main/resources/xml/output/customer-total-sales.xml"; private final CustomerService customerService; private final Serializer jsonSerializer; private final Serializer xmlSerializer; @Autowired public CustomerController(CustomerService customerService, @Qualifier("json") Serializer jsonSerializer, @Qualifier("xml") Serializer xmlSerializer) { this.customerService = customerService; this.jsonSerializer = jsonSerializer; this.xmlSerializer = xmlSerializer; } public void importCustomersFromJson() { CustomerImportDto[] customerImportDtos = this.jsonSerializer.deserialize(CustomerImportDto[].class, CUSTOMERS_JSON_INPUT_PATH); this.customerService.createMany(Arrays.asList(customerImportDtos)); } public void importCustomersFromXml() { CustomersImportXmlDto customersImportXmlDto = this.xmlSerializer.deserialize(CustomersImportXmlDto.class, CUSTOMERS_XML_INPUT_PATH); this.customerService.createMany(customersImportXmlDto.getCustomerImportDtos()); } public void exportOrderedCustomersToJson() { List orderedCustomersViewDtos = this.customerService.orderedCustomers(); this.jsonSerializer.serialize(orderedCustomersViewDtos, ORDERED_CUSTOMERS_JSON_OUTPUT_PATH); } public void exportOrderedCustomersToXml() { List orderedCustomersViewDtos = this.customerService.orderedCustomers(); OrderedCustomersXmlViewDto orderedCustomersXmlViewDto = new OrderedCustomersXmlViewDto(); orderedCustomersXmlViewDto.setOrderedCustomersViewDtos(orderedCustomersViewDtos); this.xmlSerializer.serialize(orderedCustomersXmlViewDto, ORDERED_CUSTOMERS_XML_OUTPUT_PATH); } public void exportTotalSalesByCustomerToJson() { List customerTotalSalesViewDtos = this.customerService.getTotalSalesByCustomer(); this.jsonSerializer.serialize(customerTotalSalesViewDtos, CUSTOMERS_TOTAL_SALES_JSON_OUTPUT_PATH); } public void exportTotalSalesByCustomerToXml() { List customerTotalSalesViewDtos = this.customerService.getTotalSalesByCustomer(); CustomersTotalSalesXmlViewDto customersTotalSalesXmlViewDto = new CustomersTotalSalesXmlViewDto(); customersTotalSalesXmlViewDto.setCustomerTotalSalesViewDtos(customerTotalSalesViewDtos); this.xmlSerializer.serialize(customersTotalSalesXmlViewDto, CUSTOMERS_TOTAL_SALES_XML_OUTPUT_PATH); } } package com.onlineshop.service; import com.onlineshop.model.User; import org.springframework.stereotype.Component; /** * Created by neo on 16/6/2. */ @Component public interface AccountService { void register(User user); } app/src/main/java/com/hapis/customer/ui/adapters/NavMenuDrawerAdapter.java0 package com.hapis.customer.ui.adapters; import android.annotation.TargetApi; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.v7.widget.AppCompatImageView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.hapis.customer.R; import com.hapis.customer.ui.models.NavDrawerItem; import java.util.Collections; import java.util.List; /** * Created by Javeed on 03-10-2018. */ public class NavMenuDrawerAdapter extends RecyclerView.Adapter { List data = Collections.emptyList(); private LayoutInflater inflater; private Context context; private Drawable bgDrawable; public NavMenuDrawerAdapter(Context context, List data) { this.context = context; inflater = LayoutInflater.from(context); this.data = data; } public void delete(int position) { data.remove(position); notifyItemRemoved(position); } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = inflater.inflate(R.layout.nav_item_row, parent, false); MyViewHolder holder = new MyViewHolder(view); return holder; } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Override public void onBindViewHolder(MyViewHolder holder, final int position) { NavDrawerItem current = data.get(position); holder.title.setText(current.getTitle()); // Drawable myDrawable = context.getResources().getDrawable(R.drawable.ic_change_password/*current.getIcon()*/); // holder.icon.setImageDrawable(myDrawable); holder.icon.setImageResource(current.getIcon()); holder.itemLay.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { setShowNotify(position); notifyDataSetChanged(); } }); /*if(current.isShowNotify()){ bgDrawable = context.getResources().getDrawable(R.drawable.nav_item_clicked_bg); } else { bgDrawable = context.getResources().getDrawable(R.drawable.nav_item_unclicked_bg); } holder.icon.setBackground(bgDrawable);*/ } @Override public int getItemCount() { return data.size(); } class MyViewHolder extends RecyclerView.ViewHolder { TextView title; AppCompatImageView icon; LinearLayout itemLay; public MyViewHolder(View itemView) { super(itemView); title = itemView.findViewById(R.id.title); icon = itemView.findViewById(R.id.item_icon); itemLay = itemView.findViewById(R.id.item_lay); } } private void setShowNotify(int position) { for (int i = 0; i < data.size(); i++) { if (i == position) { data.get(i).setShowNotify(true); } else { data.get(i).setShowNotify(false); } notifyDataSetChanged(); } } } SoftmedTanzania/UNFPA_UzaziSalama_CHW package org.ei.opensrp.service; import org.ei.opensrp.DristhiConfiguration; import org.ei.opensrp.domain.DownloadStatus; import org.ei.opensrp.domain.FetchStatus; import org.ei.opensrp.domain.FormDefinitionVersion; import org.ei.opensrp.domain.Response; import org.ei.opensrp.domain.SyncStatus; import org.ei.opensrp.repository.FormsVersionRepository; import org.ei.opensrp.util.EasyMap; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import java.io.File; import java.util.Collections; import java.util.List; import java.util.Map; import static java.util.Arrays.asList; import static junit.framework.Assert.assertEquals; import static org.ei.opensrp.domain.FetchStatus.fetched; import static org.ei.opensrp.domain.FetchStatus.nothingFetched; import static org.ei.opensrp.domain.ResponseStatus.success; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; /** * Created by on 3/31/15. */ @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class AllFormVersionSyncServiceTest { @Mock HTTPAgent httpAgent; @Mock DristhiConfiguration configuration; @Mock FormsVersionRepository formsVersionRepository; @Mock FormPathService formPathService; @Mock File file; @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); private AllFormVersionSyncService service; private List expectedFormDefinitionVersion; @Before public void setUp() throws Exception { initMocks(this); service = Mockito.spy(new AllFormVersionSyncService(httpAgent, configuration, formsVersionRepository)); expectedFormDefinitionVersion = asList(new FormDefinitionVersion("form_ec", "ec_dir", "2")); when(configuration.dristhiBaseURL()).thenReturn("http://opensrp_base_url"); } @Test public void shouldNotDownloadIfThereIsNoPendingForms() throws Exception { when(formsVersionRepository.getAllFormWithSyncStatus(SyncStatus.PENDING)) .thenReturn(Collections.emptyList()); DownloadStatus status = service.downloadAllPendingFormFromServer(); assertEquals(status, DownloadStatus.nothingDownloaded); verify(formsVersionRepository).getAllFormWithSyncStatus(SyncStatus.PENDING); verifyNoMoreInteractions(formsVersionRepository); verifyZeroInteractions(httpAgent); } @Test public void shouldDownloadIfThereIsAPendingForms() throws Exception { when(formsVersionRepository.getAllFormWithSyncStatus(SyncStatus.PENDING)) .thenReturn(this.expectedFormDefinitionVersion); when(httpAgent.downloadFromUrl("http://opensrp_base_url/form/form-files?formDirName=ec_dir", "ec_dir.zip")) .thenReturn(DownloadStatus.downloaded); DownloadStatus status = service.downloadAllPendingFormFromServer(); assertEquals(status, DownloadStatus.downloaded); verify(formsVersionRepository).getAllFormWithSyncStatus(SyncStatus.PENDING); verify(httpAgent).downloadFromUrl("http://opensrp_base_url/form/form-files?formDirName=ec_dir", "ec_dir.zip"); } @Test public void shouldReturnWhenThereIsNoFileInFolder() throws Exception { when(service.listFormFiles()).thenReturn(null); service.verifyFormsInFolder(); verify(formsVersionRepository).deleteAll(); verifyNoMoreInteractions(formsVersionRepository); verifyNoMoreInteractions(file); } @Test public void shouldUpdateRepoWhenThereIsNoFileInFolder() throws Exception { final File file1 = temporaryFolder.newFile("ec_registration"); File[] formFiles = new File[] {file1}; Map repoFile1 = EasyMap.create("formName", "ec_registration") .put("formDirName", "ec_registration") .put("formDataDefinitionVersion", "1") .put("id", "1") .put("syncStatus", "SYNCED") .map(); Map repoFile2 = EasyMap.create("formName", "anc_registration") .put("formDirName", "anc_registration") .put("formDataDefinitionVersion", "1") .put("id", "1") .put("syncStatus", "SYNCED") .map(); when(service.listFormFiles()).thenReturn(formFiles); when(formsVersionRepository.getAllFormWithSyncStatusAsMap(SyncStatus.SYNCED)).thenReturn(asList(repoFile1, repoFile2)); service.verifyFormsInFolder(); verify(formsVersionRepository).updateSyncStatus("anc_registration", SyncStatus.PENDING); } @Test public void shouldAddToRepoWhenThereIsFilesInFolder() throws Exception { File file1 = temporaryFolder.newFile("ec_registration"); File file2 = temporaryFolder.newFile("anc_registration"); File[] formFiles = new File[] {file1, file2}; FormDefinitionVersion f1 = new FormDefinitionVersion("ec_registration", "ec_registration", "1"); FormDefinitionVersion f2 = new FormDefinitionVersion("anc_registration", "anc_registration", "1"); when(service.listFormFiles()).thenReturn(formFiles); doReturn(f1).when(service).getFormDefinitionFromFile(file1); doReturn(f2).when(service).getFormDefinitionFromFile(file2); when(formsVersionRepository.formExists("ec_registration")).thenReturn(false); when(formsVersionRepository.formExists("anc_registration")).thenReturn(false); service.verifyFormsInFolder(); verify(formsVersionRepository).formExists("ec_registration"); verify(formsVersionRepository).formExists("anc_registration"); verify(formsVersionRepository).addFormVersionFromObject(f1); verify(formsVersionRepository).addFormVersionFromObject(f2); } @Test public void shouldUpdateVersionIfThereIsNewerVersion() throws Exception { String jsonObject = "{\"formVersions\" : [{\"formName\": \"EC_ENGKAN\", \"formDirName\": \"ec_dir\", \"formDataDefinitionVersion\": \"3\"}] }"; when(httpAgent.fetch("http://opensrp_base_url/form/latest-form-versions")).thenReturn(new Response(success,jsonObject)); List repoForm = asList(new FormDefinitionVersion("form_ec", "ec_dir", "1")); when(formsVersionRepository.formExists("ec_dir")).thenReturn(true); when(formsVersionRepository.getAllFormWithSyncStatus(SyncStatus.PENDING)) .thenReturn(repoForm); when(formsVersionRepository.getFormByFormDirName("ec_dir")).thenReturn(new FormDefinitionVersion("EC_ENGAN", "ec_dir", "1")); when(formsVersionRepository.getVersion("ec_dir")).thenReturn("1"); FetchStatus fetchStatus = service.pullFormDefinitionFromServer(); assertEquals(fetched, fetchStatus); verify(httpAgent).fetch("http://opensrp_base_url/form/latest-form-versions"); verify(formsVersionRepository).updateFormName("ec_dir", "EC_ENGKAN"); verify(formsVersionRepository).formExists("ec_dir"); verify(formsVersionRepository).updateServerVersion("ec_dir", "3"); verify(formsVersionRepository).updateSyncStatus("ec_dir", SyncStatus.PENDING); } @Test public void shouldNotUpdateIfLocalFormIsTheLatestVersion() throws Exception { String jsonObject = "{\"formVersions\" : [{\"formName\": \"EC_ENGKAN\", \"formDirName\": \"ec_dir\", \"formDataDefinitionVersion\": \"2\"}] }"; when(httpAgent.fetch("http://opensrp_base_url/form/latest-form-versions")).thenReturn(new Response(success,jsonObject)); List repoForm = asList(new FormDefinitionVersion("form_ec", "ec_dir", "3")); when(formsVersionRepository.formExists("ec_dir")).thenReturn(true); when(formsVersionRepository.getAllFormWithSyncStatus(SyncStatus.PENDING)) .thenReturn(repoForm); when(formsVersionRepository.getFormByFormDirName("ec_dir")).thenReturn(new FormDefinitionVersion("EC_ENGAN", "ec_dir", "3")); when(formsVersionRepository.getVersion("ec_dir")).thenReturn("3"); FetchStatus fetchStatus = service.pullFormDefinitionFromServer(); assertEquals(nothingFetched, fetchStatus); } } src/main/java/ru/fusionsoft/lib/path/TempFilePath.java /* * Copyright (C) 2018-2022 FusionSoft * * 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.fusionsoft.lib.path; import java.nio.file.Path; import java.util.Random; import org.cactoos.Scalar; import org.cactoos.scalar.Unchecked; import org.cactoos.text.Concatenated; /** * The scalar of temp file random {@link Path}, resolved from some root {@link Path}. * @since 0.1 * @checkstyle MagicNumberCheck (100 lines) */ public class TempFilePath implements Scalar { /** * The scalar of Path encapsulated. */ private final Unchecked scalar; /** * Instantiates a new Temp file path. * @param scalar The {@link Scalar} to be encapsulated. */ private TempFilePath(final Scalar scalar) { this.scalar = new Unchecked<>(scalar); } /** * Instantiates a new Temp file path. * @param inside The root path {@link Scalar} to be encapsulated. * @param prefix The prefix {@link CharSequence} to be encapsulated. */ public TempFilePath(final Scalar inside, final CharSequence prefix) { this( () -> { return inside.value().resolve( new Concatenated( prefix, String.format( "#%06x", new Random().nextInt(256 * 256 * 256) ) ).asString() ); } ); } /** * Instantiates a new Temp file path. * @param inside The root {@link Path} to be encapsulated. * @param prefix The prefix {@link CharSequence} to be encapsulated. */ public TempFilePath(final Path inside, final CharSequence prefix) { this( () -> inside, prefix ); } @Override public final Path value() { return this.scalar.value(); } } package com.github.mnestor0.java.exercises; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertEquals; class SerializeBinaryTreeTest { @ParameterizedTest @MethodSource("serializeTestData") public void serializeTest(BinaryTreeNode treeBinaryTreeNode, String expectedResult) { SerializeBinaryTree serializer = new SerializeBinaryTree(); assertEquals(expectedResult, serializer.serialize(treeBinaryTreeNode)); } static Stream serializeTestData() { return Stream.of( Arguments.of(new BinaryTreeNode(""), "<;>"), Arguments.of(new BinaryTreeNode("", new BinaryTreeNode("")), "<<;>;>"), Arguments.of(nodeWithRightChild("", new BinaryTreeNode("")), "<;<;>>"), Arguments.of(new BinaryTreeNode("root"), "root<;>"), Arguments.of(new BinaryTreeNode("root", new BinaryTreeNode("left")), "root;>"), Arguments.of(new BinaryTreeNode("root", new BinaryTreeNode("left", new BinaryTreeNode("left.left"))), "root;>;>"), Arguments.of(new BinaryTreeNode("root", new BinaryTreeNode("left"), new BinaryTreeNode("right")), "root;right<;>>") ); } @ParameterizedTest @MethodSource("deserializeTestData") public void deserializeTest(String serializedTree, BinaryTreeNode expectedTree) { SerializeBinaryTree serializer = new SerializeBinaryTree(); assertEquals(expectedTree, serializer.deserialize(serializedTree)); } static Stream deserializeTestData() { return Stream.of( Arguments.of("<;>", new BinaryTreeNode("")), Arguments.of("<<;>;>", new BinaryTreeNode("", new BinaryTreeNode(""))), Arguments.of("<;<;>>", nodeWithRightChild("", new BinaryTreeNode(""))), Arguments.of("root<;>", new BinaryTreeNode("root")), Arguments.of("root;>", new BinaryTreeNode("root", new BinaryTreeNode("left")), Arguments.of("root;>;>", new BinaryTreeNode("root", new BinaryTreeNode("left", new BinaryTreeNode("left.left")))), Arguments.of("root;right<;>>", new BinaryTreeNode("root", new BinaryTreeNode("left"), new BinaryTreeNode("right")))) ); } static BinaryTreeNode nodeWithRightChild(String value, BinaryTreeNode right) { BinaryTreeNode node = new BinaryTreeNode(value); node.right = right; return node; } }package gulimall.order.vo; import java.math.BigDecimal; import java.util.List; /** * 订单确认页数据 * * @author 孙启新 *
FileName: OrderConfirmVo *
Date: 2020/08/09 10:13:18 */ public class OrderConfirmVo { /** * 收货地址列表 */ private List addressVos; /** * 所有选中商品 */ private List orderItemVos; /** * 会员积分 */ private Integer integration; /** * 原商品总价格 */ private BigDecimal totalOriginalPrice; /** * 应付总价 */ private BigDecimal totalPricePayable; /** * 所有商品总件数 */ private Integer totalCount; /** * 防重复提交令牌 */ private String orderToken; public List getAddressVos() { return addressVos; } public void setAddressVos(List addressVos) { this.addressVos = addressVos; } public List getOrderItemVos() { return orderItemVos; } public void setOrderItemVos(List orderItemVos) { this.orderItemVos = orderItemVos; } public Integer getIntegration() { return integration; } public void setIntegration(Integer integration) { this.integration = integration; } public BigDecimal getTotalOriginalPrice() { this.totalOriginalPrice = new BigDecimal(0); //计算原商品价格 if (orderItemVos != null && orderItemVos.size() > 0) { for (OrderItemVo orderItemVo : orderItemVos) { BigDecimal multiply = orderItemVo.getPrice().multiply(new BigDecimal(orderItemVo.getCount())); this.totalOriginalPrice = this.totalOriginalPrice.add(multiply); } } return totalOriginalPrice; } public void setTotalOriginalPrice(BigDecimal totalOriginalPrice) { this.totalOriginalPrice = totalOriginalPrice; } public BigDecimal getTotalPricePayable() { this.totalPricePayable = new BigDecimal(0); //计算应付价格 if (orderItemVos != null && orderItemVos.size() > 0) { for (OrderItemVo orderItemVo : orderItemVos) { BigDecimal multiply = orderItemVo.getPrice().multiply(new BigDecimal(orderItemVo.getCount())); this.totalPricePayable = this.totalPricePayable.add(multiply); } } if (this.integration!=null){ BigDecimal reduction = new BigDecimal(this.integration/2); this.totalPricePayable = this.totalPricePayable.subtract(reduction); } return totalPricePayable; } public void setTotalPricePayable(BigDecimal totalPricePayable) { this.totalPricePayable = totalPricePayable; } public Integer getTotalCount() { this.totalCount = 0; //计算应付价格 if (orderItemVos != null && orderItemVos.size() > 0) { for (OrderItemVo orderItemVo : orderItemVos) { this.totalCount = this.totalCount+orderItemVo.getCount(); } } return totalCount; } public void setTotalCount(Integer totalCount) { this.totalCount = totalCount; } public String getOrderToken() { return orderToken; } public void setOrderToken(String orderToken) { this.orderToken = orderToken; } } package mullak99.mullak99sMod.gui; import mullak99.mullak99sMod.container.ContainerMCrafting; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.util.ResourceLocation; import net.minecraft.util.StatCollector; import net.minecraft.world.World; public class MCraftingGUI extends GuiContainer { public MCraftingGUI(InventoryPlayer par1InventoryPlayer, World par2World, int par3, int par4, int par5) { super(new ContainerMCrafting(par1InventoryPlayer, par2World, par3, par4, par5)); } public static String GuiTexturePrefix = "mullak99" + ":" + "textures/gui/"; public static ResourceLocation MCrafting = new ResourceLocation(GuiTexturePrefix + "MCrafting.png"); protected void drawGuiContainerForegroundLayer(int par1, int par2) { this.fontRenderer.drawString("Advanced Crafting Table", 40 + 5, - 10 - 10, 4210752); this.fontRenderer.drawString(StatCollector.translateToLocal("container.inventory"), 50 + 14, this.ySize - 96 - 10 - 19, 4210752); } protected void drawGuiContainerBackgroundLayer(float par1, int par2, int par3) { this.mc.getTextureManager().bindTexture(MCrafting); this.ySize = 231; this.xSize = 176; int var5 = (this.width - this.xSize) / 2; int var6 = (this.height - this.ySize) / 2; int var7; this.drawTexturedModalRect(var5, var6, 0, 0, this.xSize, this.ySize); } }blueblueblue/infinispan1-10 package org.infinispan.configuration.parsing; import java.util.ArrayList; import java.util.List; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; public enum ParsedCacheMode { LOCAL("l", "local"), REPL("r", "repl", "replication"), DIST("d", "dist", "distribution"), INVALIDATION("i", "invl", "invalidation"); private static final Log log = LogFactory.getLog(ParsedCacheMode.class); private final List synonyms; private ParsedCacheMode(String... synonyms) { this.synonyms = new ArrayList(); for (String synonym : synonyms) { this.synonyms.add(synonym.toUpperCase()); } } public boolean matches(String candidate) { String c = candidate.toUpperCase(); for (String synonym : synonyms) { if (c.equals(synonym)) return true; } if (c.toUpperCase().startsWith(name().toUpperCase().substring(0, 1))) { log.randomCacheModeSynonymsDeprecated(candidate, name(), synonyms); return true; } return false; } } talhakoylu/JavaHRMSBackendsrc/main/java/net/ahmettalha/javahrmsbackend/business/abstracts/CandidateForeignLanguageService.java package net.ahmettalha.javahrmsbackend.business.abstracts; import net.ahmettalha.javahrmsbackend.entities.concretes.CandidateForeignLanguage; public interface CandidateForeignLanguageService extends BaseService { } package cz.sobotik.ipblocker.core.service; import java.net.InetAddress; import java.util.List; import java.util.stream.Collectors; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Service; import cz.sobotik.ipblocker.api.model.domain.IpAddressRangeEntity; import cz.sobotik.ipblocker.api.model.dto.City; import cz.sobotik.ipblocker.api.model.dto.IpAddressRange; import cz.sobotik.ipblocker.api.repository.IAddressRangeRepository; import cz.sobotik.ipblocker.api.service.IPAddressService; import cz.sobotik.ipblocker.core.rest.converter.EntityToJsonMapper; import cz.sobotik.ipblocker.core.rest.converter.InetAddressToLongConverter; @Primary @Service public class IPAddressServiceImpl implements IPAddressService { @Autowired IAddressRangeRepository addressRangeRepository; @Autowired InetAddressToLongConverter inetAddressToLongConverter; @Autowired EntityToJsonMapper entityToJsonMapper; @Nonnull @Override public List getAllCityIPAddressRanges(@Nonnull Long cityId) { List allRanges = addressRangeRepository.findByCity_Id(cityId); return allRanges.stream().map(entityToJsonMapper::convertRange).collect(Collectors.toList()); } @Nullable @Override public City guessCityForIPAddress(@Nonnull InetAddress ipAddress) { long numAddress = inetAddressToLongConverter.convert(ipAddress); IpAddressRangeEntity range = addressRangeRepository.findOneByIpFromLessThanEqualAndIpToGreaterThanEqual(numAddress, numAddress); if (range == null) { return null; } return entityToJsonMapper.convertCity(range.getCity()); } } liyongquan/leetcode-project package com.liyongquan.dp; import lombok.extern.slf4j.Slf4j; import org.junit.Test; import static org.junit.Assert.*; @Slf4j public class NumSquaresTest { private NumSquares ns = new NumSquares(); @Test public void numSquares() { int i = ns.numSquares(12); log.info("{}", i); } }/* * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.security.cert; import java.util.Set; /** * Interface for an X.509 extension. * *

The extensions defined for X.509 v3 * {@link X509Certificate Certificates} and v2 * {@link X509CRL CRLs} (Certificate Revocation * Lists) provide methods * for associating additional attributes with users or public keys, * for managing the certification hierarchy, and for managing CRL * distribution. The X.509 extensions format also allows communities * to define private extensions to carry information unique to those * communities. * *

Each extension in a certificate/CRL may be designated as * critical or non-critical. A certificate/CRL-using system (an application * validating a certificate/CRL) must reject the certificate/CRL if it * encounters a critical extension it does not recognize. A non-critical * extension may be ignored if it is not recognized. *

* The ASN.1 definition for this is: *

 * Extensions  ::=  SEQUENCE SIZE (1..MAX) OF Extension
 *
 * Extension  ::=  SEQUENCE  {
 *     extnId        OBJECT IDENTIFIER,
 *     critical      BOOLEAN DEFAULT FALSE,
 *     extnValue     OCTET STRING
 *                   -- contains a DER encoding of a value
 *                   -- of the type registered for use with
 *                   -- the extnId object identifier value
 * }
 * 
* Since not all extensions are known, the {@code getExtensionValue} * method returns the DER-encoded OCTET STRING of the * extension value (i.e., the {@code extnValue}). This can then * be handled by a Class that understands the extension. * * @author */ public interface X509Extension { /** * Check if there is a critical extension that is not supported. * * @return {@code true} if a critical extension is found that is * not supported, otherwise {@code false}. */ public boolean hasUnsupportedCriticalExtension(); /** * Gets a Set of the OID strings for the extension(s) marked * CRITICAL in the certificate/CRL managed by the object * implementing this interface. * * Here is sample code to get a Set of critical extensions from an * X509Certificate and print the OIDs: *
{@code
     * X509Certificate cert = null;
     * try (InputStream inStrm = new FileInputStream("DER-encoded-Cert")) {
     *     CertificateFactory cf = CertificateFactory.getInstance("X.509");
     *     cert = (X509Certificate)cf.generateCertificate(inStrm);
     * }
     *
     * Set critSet = cert.getCriticalExtensionOIDs();
     * if (critSet != null && !critSet.isEmpty()) {
     *     System.out.println("Set of critical extensions:");
     *     for (String oid : critSet) {
     *         System.out.println(oid);
     *     }
     * }
     * }
* @return a Set (or an empty Set if none are marked critical) of * the extension OID strings for extensions that are marked critical. * If there are no extensions present at all, then this method returns * null. */ public Set getCriticalExtensionOIDs(); /** * Gets a Set of the OID strings for the extension(s) marked * NON-CRITICAL in the certificate/CRL managed by the object * implementing this interface. * * Here is sample code to get a Set of non-critical extensions from an * X509CRL revoked certificate entry and print the OIDs: *
{@code
     * CertificateFactory cf = null;
     * X509CRL crl = null;
     * try (InputStream inStrm = new FileInputStream("DER-encoded-CRL")) {
     *     cf = CertificateFactory.getInstance("X.509");
     *     crl = (X509CRL)cf.generateCRL(inStrm);
     * }
     *
     * byte[] certData = 
     * ByteArrayInputStream bais = new ByteArrayInputStream(certData);
     * X509Certificate cert = (X509Certificate)cf.generateCertificate(bais);
     * X509CRLEntry badCert =
     *              crl.getRevokedCertificate(cert.getSerialNumber());
     *
     * if (badCert != null) {
     *     Set nonCritSet = badCert.getNonCriticalExtensionOIDs();
     *     if (nonCritSet != null)
     *         for (String oid : nonCritSet) {
     *             System.out.println(oid);
     *         }
     * }
     * }
* * @return a Set (or an empty Set if none are marked non-critical) of * the extension OID strings for extensions that are marked non-critical. * If there are no extensions present at all, then this method returns * null. */ public Set getNonCriticalExtensionOIDs(); /** * Gets the DER-encoded OCTET string for the extension value * (extnValue) identified by the passed-in {@code oid} * String. * The {@code oid} string is * represented by a set of nonnegative whole numbers separated * by periods. * *

For example:
* * * * * * * * * * * * * * * * * * * * * * * * *
OID (Object Identifier)Extension Name
172.16.17.32SubjectKeyIdentifier
172.16.17.32KeyUsage
172.16.58.3PrivateKeyUsage
172.16.17.32SubjectAlternativeName
192.168.127.12IssuerAlternativeName
172.16.58.3BasicConstraints
172.16.31.10NameConstraints
172.16.17.32PolicyMappings
172.16.17.32AuthorityKeyIdentifier
172.16.58.3PolicyConstraints
* * @param oid the Object Identifier value for the extension. * @return the DER-encoded octet string of the extension value or * null if it is not present. */ public byte[] getExtensionValue(String oid); } 100-1000 /* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT 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. * #L% */ package io.joynr.messaging.routing; import java.util.ArrayList; import java.util.List; import java.util.Optional; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.joynr.messaging.MulticastReceiverRegistrar; import io.joynr.provider.Deferred; import io.joynr.provider.DeferredVoid; import io.joynr.provider.Promise; import io.joynr.runtime.GlobalAddressProvider; import io.joynr.runtime.ReplyToAddressProvider; import joynr.exceptions.ProviderRuntimeException; import joynr.system.RoutingAbstractProvider; import joynr.system.RoutingTypes.Address; import joynr.system.RoutingTypes.BinderAddress; import joynr.system.RoutingTypes.MqttAddress; import joynr.system.RoutingTypes.RoutingTypesUtil; import joynr.system.RoutingTypes.UdsAddress; import joynr.system.RoutingTypes.UdsClientAddress; import joynr.system.RoutingTypes.WebSocketAddress; import joynr.system.RoutingTypes.WebSocketClientAddress; /** * Implements the RoutingProvider interface to receive routing information from connected libjoynrs * */ public class RoutingProviderImpl extends RoutingAbstractProvider { private MessageRouter messageRouter; private MulticastReceiverRegistrar multicastReceiverRegistrar; private String globalAddressString; private String replyToAddressString; private List> unresolvedGlobalAddressDeferreds = new ArrayList>(); private List> unresolvedReplyToAddressDeferreds = new ArrayList>(); private static final Logger logger = LoggerFactory.getLogger(RoutingProviderImpl.class); /** * @param messageRouter handles the logic for the RoutingProvider * @param multicastReceiverRegistrar registry for multicast subscriber participantIds * @param globalAddressProvider provider for the global address of a single cluster controller or a clustered application if shared subscriptions are enabled * @param replyToAddressProvider provider for the cluster controller's replyTo address */ @Inject public RoutingProviderImpl(final MessageRouter messageRouter, final MulticastReceiverRegistrar multicastReceiverRegistrar, GlobalAddressProvider globalAddressProvider, ReplyToAddressProvider replyToAddressProvider) { this.messageRouter = messageRouter; this.multicastReceiverRegistrar = multicastReceiverRegistrar; globalAddressProvider.registerGlobalAddressesReadyListener(new TransportReadyListener() { @Override public void transportReady(Optional

address) { synchronized (unresolvedGlobalAddressDeferreds) { globalAddressString = RoutingTypesUtil.toAddressString(address.isPresent() ? address.get() : null); for (Deferred globalAddressDeferred : unresolvedGlobalAddressDeferreds) { globalAddressDeferred.resolve(globalAddressString); } unresolvedGlobalAddressDeferreds.clear(); globalAddressChanged(globalAddressString); } } }); replyToAddressProvider.registerGlobalAddressesReadyListener(new TransportReadyListener() { @Override public void transportReady(Optional
address) { synchronized (unresolvedReplyToAddressDeferreds) { replyToAddressString = RoutingTypesUtil.toAddressString(address.isPresent() ? address.get() : null); for (Deferred replyToAddressDeferred : unresolvedReplyToAddressDeferreds) { replyToAddressDeferred.resolve(replyToAddressString); } unresolvedReplyToAddressDeferreds.clear(); replyToAddressChanged(replyToAddressString); } } }); } private Promise resolvedDeferred() { final DeferredVoid deferred = new DeferredVoid(); deferred.resolve(); return new Promise<>(deferred); } @Override public Promise addNextHop(String participantId, joynr.system.RoutingTypes.ChannelAddress address, Boolean isGloballyVisible) { throw new IllegalArgumentException(joynr.system.RoutingTypes.ChannelAddress.class.getCanonicalName() + " no longer supported."); } @Override public Promise addNextHop(String participantId, MqttAddress address, Boolean isGloballyVisible) { messageRouter.addNextHop(participantId, address, isGloballyVisible); return resolvedDeferred(); } @Override public Promise addNextHop(String participantId, joynr.system.RoutingTypes.BrowserAddress address, Boolean isGloballyVisible) { throw new IllegalArgumentException(joynr.system.RoutingTypes.BrowserAddress.class.getCanonicalName() + " no longer supported."); } @Override public Promise addNextHop(String participantId, WebSocketAddress address, Boolean isGloballyVisible) { messageRouter.addNextHop(participantId, address, isGloballyVisible); return resolvedDeferred(); } @Override public Promise addNextHop(String participantId, UdsAddress address, Boolean isGloballyVisible) { final DeferredVoid deferred = new DeferredVoid(); final String message = "UdsAddress is not supported in Java"; logger.error(message); deferred.reject(new ProviderRuntimeException(message)); return new Promise<>(deferred); } @Override public Promise addNextHop(String participantId, BinderAddress binderAddress, Boolean isGloballyVisible) { messageRouter.addNextHop(participantId, binderAddress, isGloballyVisible); return resolvedDeferred(); } @Override public Promise addNextHop(String participantId, WebSocketClientAddress address, Boolean isGloballyVisible) { messageRouter.addNextHop(participantId, address, isGloballyVisible); return resolvedDeferred(); } @Override public Promise addNextHop(String participantId, UdsClientAddress address, Boolean isGloballyVisible) { final DeferredVoid deferred = new DeferredVoid(); final String msg = "UdsClientAddress is not supported in Java"; logger.error(msg); deferred.reject(new ProviderRuntimeException(msg)); return new Promise<>(deferred); } @Override public Promise removeNextHop(String participantId) { messageRouter.removeNextHop(participantId); return resolvedDeferred(); } @Override public Promise resolveNextHop(String participantId) { boolean resolved = messageRouter.resolveNextHop(participantId); ResolveNextHopDeferred deferred = new ResolveNextHopDeferred(); deferred.resolve(resolved); return new Promise<>(deferred); } @Override public Promise addMulticastReceiver(String multicastId, String subscriberParticipantId, String providerParticipantId) { multicastReceiverRegistrar.addMulticastReceiver(multicastId, subscriberParticipantId, providerParticipantId); return resolvedDeferred(); } @Override public Promise removeMulticastReceiver(String multicastId, String subscriberParticipantId, String providerParticipantId) { multicastReceiverRegistrar.removeMulticastReceiver(multicastId, subscriberParticipantId, providerParticipantId); return resolvedDeferred(); } @Override public Promise> getGlobalAddress() { Deferred globalAddressDeferred = new Deferred(); synchronized (unresolvedGlobalAddressDeferreds) { if (globalAddressString != null) { globalAddressDeferred.resolve(globalAddressString); } else { unresolvedGlobalAddressDeferreds.add(globalAddressDeferred); } } return new Promise>(globalAddressDeferred); } @Override public Promise> getReplyToAddress() { Deferred replyToAddressDeferred = new Deferred(); synchronized (unresolvedReplyToAddressDeferreds) { if (replyToAddressString != null) { replyToAddressDeferred.resolve(replyToAddressString); } else { unresolvedReplyToAddressDeferreds.add(replyToAddressDeferred); } } return new Promise>(replyToAddressDeferred); } } 0 package test; import java.net.URI; import java.net.URL; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class Test { public static void main(String[] args) throws NoSuchAlgorithmException { // System.out.println(URI.create("ftp://user:password@hello.test/path/sub").getPort()); MessageDigest.getInstance("SHA-512"); } } package com.dexburger.burgers.factory; import com.dexburger.burgers.BurgersInfo; interface AbstracBurgerFactory { T create(BurgersInfo burgerInfo); T create(Long id); } openthos/oto_packages_apps_OtoPhotoManager /* * Copyright 2010, 2011, 2012, 2013 mapsforge.org * Copyright 2014 * Copyright 2015-2016 devemux86 * * This program is free software: you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with * this program. If not, see . */ package org.mapsforge.core.model; import org.mapsforge.core.util.LatLongUtils; import org.mapsforge.core.util.MercatorProjection; import java.io.Serializable; import java.util.List; /** * A BoundingBox represents an immutable set of two latitude and two longitude coordinates. */ public class BoundingBox implements Serializable { private static final long serialVersionUID = 1L; /** * Creates a new BoundingBox from a comma-separated string of coordinates in the order minLat, minLon, maxLat, * maxLon. All coordinate values must be in degrees. * * @param boundingBoxString the string that describes the BoundingBox. * @return a new BoundingBox with the given coordinates. * @throws IllegalArgumentException if the string cannot be parsed or describes an invalid BoundingBox. */ public static BoundingBox fromString(String boundingBoxString) { double[] coordinates = LatLongUtils.parseCoordinateString(boundingBoxString, 4); return new BoundingBox(coordinates[0], coordinates[1], coordinates[2], coordinates[3]); } /** * The maximum latitude coordinate of this BoundingBox in degrees. */ public final double maxLatitude; /** * The maximum longitude coordinate of this BoundingBox in degrees. */ public final double maxLongitude; /** * The minimum latitude coordinate of this BoundingBox in degrees. */ public final double minLatitude; /** * The minimum longitude coordinate of this BoundingBox in degrees. */ public final double minLongitude; /** * @param minLatitude the minimum latitude coordinate in degrees. * @param minLongitude the minimum longitude coordinate in degrees. * @param maxLatitude the maximum latitude coordinate in degrees. * @param maxLongitude the maximum longitude coordinate in degrees. * @throws IllegalArgumentException if a coordinate is invalid. */ public BoundingBox(double minLatitude, double minLongitude, double maxLatitude, double maxLongitude) { LatLongUtils.validateLatitude(minLatitude); LatLongUtils.validateLongitude(minLongitude); LatLongUtils.validateLatitude(maxLatitude); LatLongUtils.validateLongitude(maxLongitude); if (minLatitude > maxLatitude) { throw new IllegalArgumentException("invalid latitude range: " + minLatitude + ' ' + maxLatitude); } else if (minLongitude > maxLongitude) { throw new IllegalArgumentException("invalid longitude range: " + minLongitude + ' ' + maxLongitude); } this.minLatitude = minLatitude; this.minLongitude = minLongitude; this.maxLatitude = maxLatitude; this.maxLongitude = maxLongitude; } /** * @param latLongs the coordinates list. */ public BoundingBox(List latLongs) { double minLatitude = Double.POSITIVE_INFINITY; double minLongitude = Double.POSITIVE_INFINITY; double maxLatitude = Double.NEGATIVE_INFINITY; double maxLongitude = Double.NEGATIVE_INFINITY; for (LatLong latLong : latLongs) { double latitude = latLong.latitude; double longitude = latLong.longitude; minLatitude = Math.min(minLatitude, latitude); minLongitude = Math.min(minLongitude, longitude); maxLatitude = Math.max(maxLatitude, latitude); maxLongitude = Math.max(maxLongitude, longitude); } this.minLatitude = minLatitude; this.minLongitude = minLongitude; this.maxLatitude = maxLatitude; this.maxLongitude = maxLongitude; } /** * @param latitude the latitude coordinate in degrees. * @param longitude the longitude coordinate in degrees. * @return true if this BoundingBox contains the given coordinates, false otherwise. */ public boolean contains(double latitude, double longitude) { return this.minLatitude <= latitude && this.maxLatitude >= latitude && this.minLongitude <= longitude && this.maxLongitude >= longitude; } /** * @param latLong the LatLong whose coordinates should be checked. * @return true if this BoundingBox contains the given LatLong, false otherwise. */ public boolean contains(LatLong latLong) { return contains(latLong.latitude, latLong.longitude); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } else if (!(obj instanceof BoundingBox)) { return false; } BoundingBox other = (BoundingBox) obj; if (Double.doubleToLongBits(this.maxLatitude) != Double.doubleToLongBits(other.maxLatitude)) { return false; } else if (Double.doubleToLongBits(this.maxLongitude) != Double.doubleToLongBits(other.maxLongitude)) { return false; } else if (Double.doubleToLongBits(this.minLatitude) != Double.doubleToLongBits(other.minLatitude)) { return false; } else if (Double.doubleToLongBits(this.minLongitude) != Double.doubleToLongBits(other.minLongitude)) { return false; } return true; } /** * @param boundingBox the BoundingBox which this BoundingBox should be extended if it is larger * @return a BoundingBox that covers this BoundingBox and the given BoundingBox. */ public BoundingBox extendBoundingBox(BoundingBox boundingBox) { return new BoundingBox(Math.min(this.minLatitude, boundingBox.minLatitude), Math.min(this.minLongitude, boundingBox.minLongitude), Math.max(this.maxLatitude, boundingBox.maxLatitude), Math.max(this.maxLongitude, boundingBox.maxLongitude)); } /** * Creates a BoundingBox extended up to coordinates (but does not cross date line/poles). * * @param latitude up to the extension * @param longitude up to the extension * @return an extended BoundingBox or this (if contains coordinates) */ public BoundingBox extendCoordinates(double latitude, double longitude) { if (contains(latitude, longitude)) { return this; } double minLat = Math.max(MercatorProjection.LATITUDE_MIN, Math.min(this.minLatitude, latitude)); double minLon = Math.max(-180, Math.min(this.minLongitude, longitude)); double maxLat = Math.min(MercatorProjection.LATITUDE_MAX, Math.max(this.maxLatitude, latitude)); double maxLon = Math.min(180, Math.max(this.maxLongitude, longitude)); return new BoundingBox(minLat, minLon, maxLat, maxLon); } /** * Creates a BoundingBox extended up to LatLong (but does not cross date line/poles). * * @param latLong coordinates up to the extension * @return an extended BoundingBox or this (if contains coordinates) */ public BoundingBox extendCoordinates(LatLong latLong) { return extendCoordinates(latLong.latitude, latLong.longitude); } /** * Creates a BoundingBox that is a fixed degree amount larger on all sides (but does not cross date line/poles). * * @param verticalExpansion degree extension (must be >= 0) * @param horizontalExpansion degree extension (must be >= 0) * @return an extended BoundingBox or this (if degrees == 0) */ public BoundingBox extendDegrees(double verticalExpansion, double horizontalExpansion) { if (verticalExpansion == 0 && horizontalExpansion == 0) { return this; } else if (verticalExpansion < 0 || horizontalExpansion < 0) { throw new IllegalArgumentException("BoundingBox extend operation does not accept negative values"); } double minLat = Math.max(MercatorProjection.LATITUDE_MIN, this.minLatitude - verticalExpansion); double minLon = Math.max(-180, this.minLongitude - horizontalExpansion); double maxLat = Math.min(MercatorProjection.LATITUDE_MAX, this.maxLatitude + verticalExpansion); double maxLon = Math.min(180, this.maxLongitude + horizontalExpansion); return new BoundingBox(minLat, minLon, maxLat, maxLon); } /** * Creates a BoundingBox that is a fixed margin factor larger on all sides (but does not cross date line/poles). * * @param margin extension (must be > 0) * @return an extended BoundingBox or this (if margin == 1) */ public BoundingBox extendMargin(float margin) { if (margin == 1) { return this; } else if (margin <= 0) { throw new IllegalArgumentException("BoundingBox extend operation does not accept negative or zero values"); } double verticalExpansion = (this.getLatitudeSpan() * margin - this.getLatitudeSpan()) * 0.5; double horizontalExpansion = (this.getLongitudeSpan() * margin - this.getLongitudeSpan()) * 0.5; double minLat = Math.max(MercatorProjection.LATITUDE_MIN, this.minLatitude - verticalExpansion); double minLon = Math.max(-180, this.minLongitude - horizontalExpansion); double maxLat = Math.min(MercatorProjection.LATITUDE_MAX, this.maxLatitude + verticalExpansion); double maxLon = Math.min(180, this.maxLongitude + horizontalExpansion); return new BoundingBox(minLat, minLon, maxLat, maxLon); } /** * Creates a BoundingBox that is a fixed meter amount larger on all sides (but does not cross date line/poles). * * @param meters extension (must be >= 0) * @return an extended BoundingBox or this (if meters == 0) */ public BoundingBox extendMeters(int meters) { if (meters == 0) { return this; } else if (meters < 0) { throw new IllegalArgumentException("BoundingBox extend operation does not accept negative values"); } double verticalExpansion = LatLongUtils.latitudeDistance(meters); double horizontalExpansion = LatLongUtils.longitudeDistance(meters, Math.max(Math.abs(minLatitude), Math.abs(maxLatitude))); double minLat = Math.max(MercatorProjection.LATITUDE_MIN, this.minLatitude - verticalExpansion); double minLon = Math.max(-180, this.minLongitude - horizontalExpansion); double maxLat = Math.min(MercatorProjection.LATITUDE_MAX, this.maxLatitude + verticalExpansion); double maxLon = Math.min(180, this.maxLongitude + horizontalExpansion); return new BoundingBox(minLat, minLon, maxLat, maxLon); } /** * @return a new LatLong at the horizontal and vertical center of this BoundingBox. */ public LatLong getCenterPoint() { double latitudeOffset = (this.maxLatitude - this.minLatitude) / 2; double longitudeOffset = (this.maxLongitude - this.minLongitude) / 2; return new LatLong(this.minLatitude + latitudeOffset, this.minLongitude + longitudeOffset); } /** * @return the latitude span of this BoundingBox in degrees. */ public double getLatitudeSpan() { return this.maxLatitude - this.minLatitude; } /** * @return the longitude span of this BoundingBox in degrees. */ public double getLongitudeSpan() { return this.maxLongitude - this.minLongitude; } /** * Computes the coordinates of this bounding box relative to a tile. * * @param tile the tile to compute the relative position for. * @return rectangle giving the relative position. */ public Rectangle getPositionRelativeToTile(Tile tile) { Point upperLeft = MercatorProjection.getPixelRelativeToTile(new LatLong(this.maxLatitude, minLongitude), tile); Point lowerRight = MercatorProjection.getPixelRelativeToTile(new LatLong(this.minLatitude, maxLongitude), tile); return new Rectangle(upperLeft.x, upperLeft.y, lowerRight.x, lowerRight.y); } @Override public int hashCode() { final int prime = 31; int result = 1; long temp; temp = Double.doubleToLongBits(this.maxLatitude); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(this.maxLongitude); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(this.minLatitude); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(this.minLongitude); result = prime * result + (int) (temp ^ (temp >>> 32)); return result; } /** * @param boundingBox the BoundingBox which should be checked for intersection with this BoundingBox. * @return true if this BoundingBox intersects with the given BoundingBox, false otherwise. */ public boolean intersects(BoundingBox boundingBox) { if (this == boundingBox) { return true; } return this.maxLatitude >= boundingBox.minLatitude && this.maxLongitude >= boundingBox.minLongitude && this.minLatitude <= boundingBox.maxLatitude && this.minLongitude <= boundingBox.maxLongitude; } /** * Returns if an area built from the latLongs intersects with a bias towards * returning true. * The method returns fast if any of the points lie within the bbox. If none of the points * lie inside the box, it constructs the outer bbox for all the points and tests for intersection * (so it is possible that the area defined by the points does not actually intersect) * * @param latLongs the points that define an area * @return false if there is no intersection, true if there could be an intersection */ public boolean intersectsArea(LatLong[][] latLongs) { if (latLongs.length == 0 || latLongs[0].length == 0) { return false; } for (LatLong[] outer : latLongs) { for (LatLong latLong : outer) { if (this.contains(latLong)) { // if any of the points is inside the bbox return early return true; } } } // no fast solution, so accumulate boundary points double tmpMinLat = latLongs[0][0].latitude; double tmpMinLon = latLongs[0][0].longitude; double tmpMaxLat = latLongs[0][0].latitude; double tmpMaxLon = latLongs[0][0].longitude; for (LatLong[] outer : latLongs) { for (LatLong latLong : outer) { tmpMinLat = Math.min(tmpMinLat, latLong.latitude); tmpMaxLat = Math.max(tmpMaxLat, latLong.latitude); tmpMinLon = Math.min(tmpMinLon, latLong.longitude); tmpMaxLon = Math.max(tmpMaxLon, latLong.longitude); } } return this.intersects(new BoundingBox(tmpMinLat, tmpMinLon, tmpMaxLat, tmpMaxLon)); } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("minLatitude="); stringBuilder.append(this.minLatitude); stringBuilder.append(", minLongitude="); stringBuilder.append(this.minLongitude); stringBuilder.append(", maxLatitude="); stringBuilder.append(this.maxLatitude); stringBuilder.append(", maxLongitude="); stringBuilder.append(this.maxLongitude); return stringBuilder.toString(); } } 1-10 package com.fuyunwang.surveillance.upms.biz.config; import com.fuyunwang.surveillance.common.handler.ChuoyueAccessDeniedHandler; import com.fuyunwang.surveillance.common.handler.ChuoyueAuthExceptionEntryPoint; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; /** * @Description: * @Author: FuyunWang * @Date: 2020/12/30 21:05 */ @Configuration @EnableResourceServer @EnableGlobalMethodSecurity(prePostEnabled = true) public class SurveillanceUpmsBizResourceServerConfig extends ResourceServerConfigurerAdapter { @Autowired private ChuoyueAuthExceptionEntryPoint chuoyueAuthExceptionEntryPoint; @Autowired private ChuoyueAccessDeniedHandler chuoyueAccessDeniedHandler; @Override public void configure(HttpSecurity http) throws Exception { http.csrf().disable() .requestMatchers().antMatchers("/**") .and() .authorizeRequests() .antMatchers("/swagger-ui.html","/webjars/**","/swagger-resources/**","/v2/api-docs/**","/csrf","/").permitAll() .antMatchers("/actuator/**").permitAll() .antMatchers("/**").authenticated(); } @Override public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.accessDeniedHandler(chuoyueAccessDeniedHandler).authenticationEntryPoint(chuoyueAuthExceptionEntryPoint); } } 0 package demo1; import org.apache.commons.io.IOUtils; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.annotation.*; import java.io.FileInputStream; import java.io.IOException; @WebServlet(urlPatterns = "/demo18") public class servletdemo18 extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { FileInputStream fileInputStream = new FileInputStream("D:\\Pictures\\壁纸\\bg.png"); ServletOutputStream outputStream = response.getOutputStream(); // byte[] buff = new byte[1024]; // int len=0; // while((len=fileInputStream.read(buff))!=-1){ // outputStream.write(buff,0,len); // } IOUtils.copy(fileInputStream,outputStream); fileInputStream.close(); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } } 1-10 /* * Copyright (C) 2011, the original authors * * ==================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== */ package org.jclouds.karaf.itests.live; import static org.junit.Assert.assertTrue; import static org.openengsb.labs.paxexam.karaf.options.KarafDistributionOption.keepRuntimeFolder; import static org.openengsb.labs.paxexam.karaf.options.KarafDistributionOption.logLevel; import static org.ops4j.pax.exam.CoreOptions.scanFeatures; import org.jclouds.compute.ComputeService; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.openengsb.labs.paxexam.karaf.options.LogLevelOption; import org.ops4j.pax.exam.MavenUtils; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.Configuration; import org.ops4j.pax.exam.junit.ExamReactorStrategy; import org.ops4j.pax.exam.junit.JUnit4TestRunner; import org.ops4j.pax.exam.spi.reactors.AllConfinedStagedReactorFactory; @RunWith(JUnit4TestRunner.class) @ExamReactorStrategy(AllConfinedStagedReactorFactory.class) public class AwsEc2LiveTest extends JcloudsLiveTestSupport { String group = "karaf"; @Before public void setUp() throws Exception { identity = System.getProperty("jclouds.aws.identity"); credential = System.getProperty("jclouds.aws.credential"); regions = System.getProperty("jclouds.aws.region"); image = System.getProperty("jclouds.aws.image"); location = System.getProperty("jclouds.aws.location"); user = System.getProperty("jclouds.aws.user"); if (isComputeLiveConfigured()) { installAndCheckFeature("jclouds-commands"); Thread.sleep(DEFAULT_TIMEOUT); } else { System.err.println("Aborting test."); System.err.flush(); } } @After public void tearDown() { if (isComputeLiveConfigured()) { executeCommand("jclouds:node-destroy-all "); } } @Test public void testCreateNodeLive() throws InterruptedException { if (isComputeLiveConfigured()) { createManagedComputeService("aws-ec2", false); ComputeService computeService = getOsgiService(ComputeService.class,1000000L); System.err.println(executeCommand("jclouds:image-list")); System.err.println(executeCommand("jclouds:node-create --imageId " + image + " --locationId " + location + " " + group)); System.err.println(executeCommand("jclouds:group-runscript -d ls -u " + user + " " + group)); assertTrue("Expected at least one node", computeService.listNodes().size() >= 1); } } @Configuration public Option[] config() { return new Option[]{ jcloudsDistributionConfiguration(), keepRuntimeFolder(), logLevel(LogLevelOption.LogLevel.ERROR), systemProperty("jclouds.aws.identity"), systemProperty("jclouds.aws.credential"), systemProperty("jclouds.aws.region"), systemProperty("jclouds.aws.image"), systemProperty("jclouds.aws.location"), systemProperty("jclouds.aws.user"), scanFeatures(String.format(JCLOUDS_FEATURE_FORMAT, MavenUtils.getArtifactVersion(JCLOUDS_KARAF_GROUP_ID, JCLOUDS_KARAF_ARTIFACT_ID)),"jclouds", "jclouds-compute", "jclouds-aws-ec2").start() }; } } src/main/java/com/tabnine/prediction/TabNineCompletion.java package com.tabnine.prediction; import com.intellij.codeInsight.lookup.impl.LookupCellRenderer; import com.intellij.openapi.util.TextRange; import com.intellij.util.containers.FList; import com.tabnine.binary.requests.autocomplete.UserIntent; import com.tabnine.general.CompletionKind; import com.tabnine.general.CompletionOrigin; import java.util.ArrayList; import java.util.List; public class TabNineCompletion { public final String oldPrefix; public final String newPrefix; public final String oldSuffix; public final String newSuffix; public final int index; public String cursorPrefix; public String cursorSuffix; public CompletionOrigin origin; public CompletionKind completionKind; public Boolean isCached; public UserIntent snippet_intent; public String detail = null; public boolean deprecated = false; private String fullSuffix = null; public TabNineCompletion( String oldPrefix, String newPrefix, String oldSuffix, String newSuffix, int index, String cursorPrefix, String cursorSuffix, CompletionOrigin origin, CompletionKind completionKind, Boolean isCached, UserIntent snippet_intent) { this.oldPrefix = oldPrefix; this.newPrefix = newPrefix; this.oldSuffix = oldSuffix; this.newSuffix = newSuffix; this.index = index; this.cursorPrefix = cursorPrefix; this.cursorSuffix = cursorSuffix; this.origin = origin; this.completionKind = completionKind; this.isCached = isCached; this.snippet_intent = snippet_intent; } public CompletionOrigin getOrigin() { return origin; } public String getSuffix() { if (fullSuffix != null) { return fullSuffix; } String itemText = this.newPrefix + this.newSuffix; String prefix = this.oldPrefix; if (prefix.isEmpty()) { return fullSuffix = itemText; } FList fragments = LookupCellRenderer.getMatchingFragments(prefix, itemText); if (fragments != null && !fragments.isEmpty()) { List list = new ArrayList<>(fragments); return fullSuffix = itemText.substring(list.get(list.size() - 1).getEndOffset()); } return fullSuffix = ""; } } package com.cpxiao.hexagon.mode.extra; import java.util.Random; /** * 组合六边形块 * * @author cpxiao on 2017/7/30. */ public final class MultiHexBaseExtra { private static final int[][] _1A = { {1} }; private static final int[][] _2A = { {1, 0, 1} }; private static final int[][] _2B1 = { {1, 0}, {0, 1} }; private static final int[][] _2B2 = { {0, 1}, {1, 0} }; private static final int[][] _3A = { {1, 0, 1, 0, 1} }; private static final int[][] _3B1 = { {1, 0, 1}, {0, 1, 0} }; private static final int[][] _3B2 = { {0, 1, 0}, {1, 0, 1} }; private static final int[][] _3C1 = { {1, 0, 0}, {0, 1, 0}, {0, 0, 1} }; private static final int[][] _3C2 = { {0, 0, 1}, {0, 1, 0}, {1, 0, 0} }; private static final int[][] _3D1 = { {1, 0}, {0, 1}, {1, 0} }; private static final int[][] _3D2 = { {0, 1}, {1, 0}, {0, 1} }; private static final int[][] _3E1 = { {1, 0, 0, 0}, {0, 1, 0, 1} }; private static final int[][] _3E2 = { {0, 0, 0, 1}, {1, 0, 1, 0} }; private static final int[][] _3E3 = { {0, 1, 0, 1}, {1, 0, 0, 0} }; private static final int[][] _3E4 = { {1, 0, 1, 0}, {0, 0, 0, 1} }; private static final int[][] _4A = { {1, 0, 1, 0, 1, 0, 1} }; private static final int[][] _4B1 = { {1, 0, 0, 0, 1}, {0, 1, 0, 1, 0} }; private static final int[][] _4B2 = { {0, 1, 0, 1, 0}, {1, 0, 0, 0, 1} }; private static final int[][] _4C = { {0, 1, 0}, {1, 0, 1}, {0, 1, 0} }; private static final int[][] _4D1 = { {0, 1, 0, 1}, {1, 0, 1, 0} }; private static final int[][] _4D2 = { {1, 0, 1, 0}, {0, 1, 0, 1} }; private static final int[][] _4E1 = { {1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1} }; private static final int[][] _4E2 = { {0, 0, 0, 1}, {0, 0, 1, 0}, {0, 1, 0, 0}, {1, 0, 0, 0} }; private static final int[][] _4F1 = { {1, 0, 1}, {0, 1, 0}, {1, 0, 0} }; private static final int[][] _4F2 = { {1, 0, 1}, {0, 1, 0}, {0, 0, 1} }; private static final int[][] _4F3 = { {0, 0, 1}, {0, 1, 0}, {1, 0, 1} }; private static final int[][] _4F4 = { {1, 0, 0}, {0, 1, 0}, {1, 0, 1} }; private static final int[][] _4G1 = { {0, 0, 0, 0, 1}, {0, 0, 0, 1, 0}, {1, 0, 1, 0, 0} }; private static final int[][] _4G2 = { {1, 0, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 0, 1, 0, 1} }; private static final int[][] _4G3 = { {0, 0, 1, 0, 1}, {0, 1, 0, 0, 0}, {1, 0, 0, 0, 0} }; private static final int[][] _4G4 = { {1, 0, 1, 0, 0}, {0, 0, 0, 1, 0}, {0, 0, 0, 0, 1} }; private static final int[][] _5A1 = { {1, 0, 1, 0, 1}, {0, 1, 0, 1, 0} }; private static final int[][] _5A2 = { {0, 1, 0, 1, 0}, {1, 0, 1, 0, 1} }; private static final int[][] _5B1 = { {0, 0, 1, 0, 0}, {0, 1, 0, 1, 0}, {1, 0, 0, 0, 1} }; private static final int[][] _5B2 = { {1, 0, 0, 0, 1}, {0, 1, 0, 1, 0}, {0, 0, 1, 0, 0} }; private static final int[][] _6A1 = { {0, 0, 1, 0, 0}, {0, 1, 0, 1, 0}, {1, 0, 1, 0, 1} }; private static final int[][] _6A2 = { {1, 0, 1, 0, 1}, {0, 1, 0, 1, 0}, {0, 0, 1, 0, 0} }; private static final int[][][] DATA_R_5 = { _1A, _2A, _2B1, _2B2, _3A, _3B1, _3B2, _4A, _4B1, _4B2, _4C, _4D1, _4D2, _4F1, _4F2, _4F3, _4F4 }; private static final int[][][] DATA_R_6 = { _1A, _2A, _2B1, _2B2, _3A, _3B1, _3B2, _3C1, _3C2, _3D1, _3D2, _4A, _4B1, _4B2, _4C, _4D1, _4D2, _4F1, _4F2, _4F3, _4F4 }; private static final int[][][] DATA_R_7 = { _1A, _2A, _2B1, _2B2, _3A, _3B1, _3B2, _3C1, _3C2, _3D1, _3D2, _3E1, _3E2, _3E3, _3E4, _4A, _4B1, _4B2, _4C, _4D1, _4D2, _4E1, _4E2, _4F1, _4F2, _4F3, _4F4, _5B1, _5B2 }; private static final int[][][] DATA_R_8 = { _1A, _2A, _2B1, _2B2, _3A, _3B1, _3B2, _3C1, _3C2, _3D1, _3D2, _3E1, _3E2, _3E3, _3E4, _4A, _4B1, _4B2, _4C, _4D1, _4D2, _4E1, _4E2, _4F1, _4F2, _4F3, _4F4, _4G1, _4G2, _4G3, _4G4, _5A1, _5A2, _5B1, _5B2, _6A1, _6A2 }; private static Random mRandom = new Random(); public static int[][] getData(int gameMode) { // return _2A; if (gameMode == GameMode.MODE_R_5) { return DATA_R_5[mRandom.nextInt(DATA_R_5.length)]; } else if (gameMode == GameMode.MODE_R_6) { return DATA_R_6[mRandom.nextInt(DATA_R_6.length)]; } else if (gameMode == GameMode.MODE_R_7) { return DATA_R_7[mRandom.nextInt(DATA_R_7.length)]; } else if (gameMode == GameMode.MODE_R_8) { return DATA_R_8[mRandom.nextInt(DATA_R_8.length)]; } else { return DATA_R_5[mRandom.nextInt(DATA_R_5.length)]; } } } app/src/main/java/com/vietxongxoa/ui/article/detail/ArticleDetailMvpView.java package com.vietxongxoa.ui.article.detail; import com.vietxongxoa.model.Article; import com.vietxongxoa.model.Comment; import com.vietxongxoa.model.Data; import com.vietxongxoa.ui.base.MvpView; import java.util.List; public interface ArticleDetailMvpView extends MvpView { void showData(Data
data); void showError(String error); void showDataComments(List> commens); void showErrorComments(String error); void showPostComment(Data comment); void showErrorPostComment(String error); void showLove(String status, int position); void showUnLove(String status, int position); } package com.yammer.dropwizard.db; import com.google.inject.Inject; import com.google.inject.Provider; public class OnDemandDAOProvider implements Provider { private final Class onDemandDAOClass; private T onDemandDAO; public static OnDemandDAOProvider newProvider(Class daoType) { return new OnDemandDAOProvider(daoType); } private OnDemandDAOProvider(Class daoType) { onDemandDAOClass = daoType; } @Inject private void setDatabase(Database db) { onDemandDAO = db.onDemand(onDemandDAOClass); } @Override public T get() { return onDemandDAO; } } package achan.nl.uitstelgedrag.ui.activities; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.Spinner; import android.widget.Switch; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import achan.nl.uitstelgedrag.R; import achan.nl.uitstelgedrag.persistence.Settings; import achan.nl.uitstelgedrag.persistence.UitstelgedragOpenHelper; import achan.nl.uitstelgedrag.ui.Themer; import achan.nl.uitstelgedrag.ui.Themes; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import static achan.nl.uitstelgedrag.ui.Themes.AUTO; import static achan.nl.uitstelgedrag.ui.Themes.DARK; import static achan.nl.uitstelgedrag.ui.Themes.LIGHT; /** * Shows basic and advanced settings. */ public class SettingsActivity extends Base { // todo sharedpreferences @BindView(R.id.settings_semi_automatic_attendance_tracking_switch) Switch attendanceTrackingSwitch; @BindView(R.id.settings_theme_spinner) Spinner themeSpinner; @BindView(R.id.settings_mic_trigger_spinner) Spinner micTriggerSwitch; @BindView(R.id.settings_wipe_database_button) Button wipeDatabaseButton; @BindView(R.id.settings_gesture_based_interaction_switch) Switch enableGesturesButton; Activity activity; Context context; Settings settings; @Override Activities getCurrentActivity() { return Activities.SETTINGS; } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); ButterKnife.bind(this); context = this; settings = new Settings(this); activity = this; //set spinner to current theme //if current theme is current theme, do nothing //else, change. Themes theme_current = settings.getTheme() == 0? LIGHT : DARK; themeSpinner.setSelection(theme_current.id); themeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { // fixme - default id vs selecteditempos. // if(themeSpinner.getSelectedItemPosition() == theme_current.id) // return; boolean changed = false; Log.i("Settings", "Changed theme! Selector value: " + themeSpinner.getSelectedItemPosition()); if (themeSpinner.getSelectedItem().toString().equals("light")) { // settings.setTheme(LIGHT.id); changed = Themer.setTheme(activity, LIGHT); Log.i("Settings", "Changed theme to light theme."); } else if (themeSpinner.getSelectedItem().toString().equals("dark")){ // settings.setTheme(DARK.id); changed = Themer.setTheme(activity, DARK); Log.i("Settings", "Changed theme to dark theme."); } else { // settings.setTheme(AUTO.id); changed = Themer.setTheme(activity, AUTO); Log.i("Settings", "Changed theme to auto theme."); } if (changed) recreate(); // note - causes loop } @Override public void onNothingSelected(AdapterView parent) {} }); } // todo proximity / accel setting // @OnClick(R.id.settings_mic_trigger_spinner) void setMicTriggerMode(){ // String state = ""; // Log.i("Settings", "Microphone trigger set to " + state); // } // // @OnClick(R.id.settings_gesture_based_interaction_switch) void toggleGestures(){ // String state = ""; // Log.i("Settings", "Gestures " + state); // } @OnClick(R.id.settings_wipe_database_button) void wipeDatabase(){ new AlertDialog.Builder(context) .setTitle("Verwijder alle gegevens") .setMessage("Weet je het zeker?") .setNegativeButton("Annuleren", null) .setPositiveButton("Verwijderen", (dialog, which) -> { UitstelgedragOpenHelper database = new UitstelgedragOpenHelper(context, null); database.wipe(); }) .create() .show(); } // todo day/night theme } package comunicaciones; import java.io.Serializable; import java.util.ArrayList; public class MsjListaSala implements Serializable { /** * */ private static final long serialVersionUID = 1L; private ArrayList nombreSalas; public MsjListaSala(ArrayList nombreSalas) { this.nombreSalas = nombreSalas; } public ArrayList getNombreSalas() { return nombreSalas; } } /* * Copyright © 2020 , 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 io.cdap.plugin.batch.aggregator.function; import io.cdap.cdap.api.data.format.StructuredRecord; import io.cdap.cdap.api.data.schema.Schema; import java.util.HashSet; import java.util.Set; /** * Count distinct values of a specific column */ public class CountDistinct implements AggregateFunction { private final String fieldName; private final Set collectSet; public CountDistinct(String fieldName) { this.fieldName = fieldName; this.collectSet = new HashSet<>(); } @Override public void beginFunction() { collectSet.clear(); } @Override public void operateOn(StructuredRecord record) { collectSet.add(record.get(fieldName)); } @Override public Integer getAggregate() { return collectSet.size(); } @Override public Schema getOutputSchema() { return Schema.of(Schema.Type.INT); } } antop-dev/glory-of-rest package org.antop.repository; import org.antop.entity.Location; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; @RepositoryRestResource public interface LocationRepository extends JpaRepository { } package com.insulin.controllers; import com.insulin.service.abstraction.MLService; import com.insulin.utils.model.ClassificationModel; import com.insulin.utils.model.ModelResult; import com.insulin.utils.model.RegressionModel; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.io.IOException; @RestController @RequestMapping("/classification") public class MLController { private final MLService mlService; @Autowired public MLController(MLService mlService) { this.mlService = mlService; } @PostMapping("/predict") @PreAuthorize("hasAnyAuthority('PATIENT', 'ADMIN')") public ResponseEntity predictDiabetes(@Valid @RequestBody ClassificationModel dataModel) throws IOException, InterruptedException { mlService.adaptClassificationModelValues(dataModel); return new ResponseEntity<>(mlService.sendToModel(dataModel), HttpStatus.OK); } @PostMapping("/evolution") @PreAuthorize("hasAnyAuthority('PATIENT', 'ADMIN')") public ResponseEntity predictEvolution(@Valid @RequestBody RegressionModel dataModel) throws IOException, InterruptedException { mlService.adaptRegressionModelValues(dataModel); return new ResponseEntity<>(mlService.sendToModel(dataModel), HttpStatus.OK); } } fagarine/dangkang package cn.laoshini.dk.client; import cn.laoshini.dk.exception.DkRuntimeException; /** * 当康游戏客户端异常 * * @author fagarine */ public class ClientException extends DkRuntimeException { public ClientException(String message, Throwable cause) { super(message, cause); } public ClientException(String message) { super("client.exception.key", message); } } 1-10 package GOF23.C9_State; public class MyRequest { private String url; // 请求地址 private String method; // 请求方法 private boolean isMethodNessary; // 是否需要请求方法 public boolean isMethodNessary() { return isMethodNessary; } public void setMethodNessary(boolean methodNessary) { isMethodNessary = methodNessary; } public MyRequest(String url, String method, boolean isMethodNessary) { this.url = url; this.method = method; this.isMethodNessary = isMethodNessary; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } } package me.next.captureview; import android.content.Context; import android.util.DisplayMetrics; import android.util.TypedValue; /** * Created by NeXT on 17/1/11. */ public class ScreenUtils { public static float dipToPixels(Context context, float dipValue) { DisplayMetrics metrics = context.getResources().getDisplayMetrics(); return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, metrics); } } /* * 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.ignite.internal.processors.hadoop; import org.jetbrains.annotations.*; /** * Enumeration of optional properties supported by Ignite for Apache Hadoop. */ public enum HadoopJobProperty { /** * Initial size for hashmap which stores output of mapper and will be used as input of combiner. *

* Setting it right allows to avoid rehashing. */ COMBINER_HASHMAP_SIZE, /** * Initial size for hashmap which stores output of mapper or combiner and will be used as input of reducer. *

* Setting it right allows to avoid rehashing. */ PARTITION_HASHMAP_SIZE, /** * Specifies number of concurrently running mappers for external execution mode. *

* If not specified, defaults to {@code Runtime.getRuntime().availableProcessors()}. */ EXTERNAL_CONCURRENT_MAPPERS, /** * Specifies number of concurrently running reducers for external execution mode. *

* If not specified, defaults to {@code Runtime.getRuntime().availableProcessors()}. */ EXTERNAL_CONCURRENT_REDUCERS, /** * Delay in milliseconds after which Ignite server will reply job status. */ JOB_STATUS_POLL_DELAY, /** * Size in bytes of single memory page which will be allocated for data structures in shuffle. *

* By default is {@code 32 * 1024}. */ SHUFFLE_OFFHEAP_PAGE_SIZE, /** * If set to {@code true} then input for combiner will not be sorted by key. * Internally hash-map will be used instead of sorted one, so {@link Object#equals(Object)} * and {@link Object#hashCode()} methods of key must be implemented consistently with * comparator for that type. Grouping comparator is not supported if this setting is {@code true}. *

* By default is {@code false}. */ SHUFFLE_COMBINER_NO_SORTING, /** * If set to {@code true} then input for reducer will not be sorted by key. * Internally hash-map will be used instead of sorted one, so {@link Object#equals(Object)} * and {@link Object#hashCode()} methods of key must be implemented consistently with * comparator for that type. Grouping comparator is not supported if this setting is {@code true}. *

* By default is {@code false}. */ SHUFFLE_REDUCER_NO_SORTING; /** */ private final String ptyName; /** * */ HadoopJobProperty() { ptyName = "ignite." + name().toLowerCase().replace('_', '.'); } /** * @return Property name. */ public String propertyName() { return ptyName; } /** * @param jobInfo Job info. * @param pty Property. * @param dflt Default value. * @return Property value. */ public static String get(HadoopJobInfo jobInfo, HadoopJobProperty pty, @Nullable String dflt) { String res = jobInfo.property(pty.propertyName()); return res == null ? dflt : res; } /** * @param jobInfo Job info. * @param pty Property. * @param dflt Default value. * @return Property value. */ public static int get(HadoopJobInfo jobInfo, HadoopJobProperty pty, int dflt) { String res = jobInfo.property(pty.propertyName()); return res == null ? dflt : Integer.parseInt(res); } /** * @param jobInfo Job info. * @param pty Property. * @param dflt Default value. * @return Property value. */ public static boolean get(HadoopJobInfo jobInfo, HadoopJobProperty pty, boolean dflt) { String res = jobInfo.property(pty.propertyName()); return res == null ? dflt : Boolean.parseBoolean(res); } } package com.system.management.task.commands.add; import com.system.management.task.commands.creation.BaseCommand; import com.system.management.task.core.RepositoryHelper; import com.system.management.task.models.contracts.Member; import com.system.management.task.models.contracts.Task; import com.system.management.task.utils.ParsingHelpers; import com.system.management.task.utils.ValidationHelpers; import java.util.ArrayList; import java.util.List; import static com.system.management.task.commands.CommandConstants.ASSIGN_TASK; public class AssignTaskCommand extends BaseCommand { private static final int EXPECTED_NUMBER_OF_ARGUMENTS = 2; public AssignTaskCommand(RepositoryHelper repoHelper) { super(repoHelper); } @Override protected String executeCommand(List parameters) { ValidationHelpers.validateArgumentsCount(parameters, EXPECTED_NUMBER_OF_ARGUMENTS); int id = ParsingHelpers.tryParseInt(parameters.get(0), "Id must be a number"); String memberName = parameters.get(1); assignTask(id, memberName); return String.format(ASSIGN_TASK, id, memberName); } private void assignTask(int id, String memberName) { List res = new ArrayList<>(); res.addAll(getRepoHelper().getBugs()); res.addAll(getRepoHelper().getStories()); Task task = getRepoHelper().findElementById(id, res); Member member = getRepoHelper().findMemberByName(memberName); task.setAssignee(member); member.addTask(task); } } 1-10 package com.dianping.cat.analysis; import junit.framework.Assert; import org.junit.Test; import org.unidal.lookup.ComponentTestCase; import com.dianping.cat.analysis.Configurator.MockAnalyzer1; import com.dianping.cat.analysis.Configurator.MockAnalyzer2; import com.dianping.cat.analysis.Configurator.MockAnalyzer3; public class DefaultMessageAnalyzerManagerTest extends ComponentTestCase { @Test public void test() throws Exception { DefaultMessageAnalyzerManager manager = (DefaultMessageAnalyzerManager) lookup(MessageAnalyzerManager.class); Assert.assertEquals(3, manager.getAnalyzerNames().size()); long hour = 3600 * 1000L; long time = System.currentTimeMillis(); long current = time - time % hour; long last = time - hour; long lastTwo = time - 2 * hour; long lastThree = time - 3 * hour; MockAnalyzer1 analyzer0 = (MockAnalyzer1) manager.getAnalyzer("mock1", lastThree); MockAnalyzer1 analyzer1 = (MockAnalyzer1) manager.getAnalyzer("mock1", lastTwo); MockAnalyzer2 analyzer2 = (MockAnalyzer2) manager.getAnalyzer("mock2", last); MockAnalyzer3 analyzer3 = (MockAnalyzer3) manager.getAnalyzer("state", current); Assert.assertEquals(1, analyzer0.m_count); Assert.assertEquals(1, analyzer1.m_count); Assert.assertEquals(2, analyzer2.m_count); Assert.assertEquals(3, analyzer3.m_count); } } springtest/src/main/java/com/mfun/service/PersonServiceImpl.java0 package com.mfun.service; import com.mfun.bean.Person; import org.springframework.stereotype.Service; @Service public class PersonServiceImpl implements PersonService{ @Override public Person getPerson() { Person p = new Person(); p.setName("Service"); return p; } } public class Filme { private int codigo; private String titulo; private String sinopse; private int faixaEtaria; // 1..18 anos private int duracao; // 1..* minutos private int ano; private String idioma; // original/dublado private String legenda; // pt/spn/ing/nenhuma /* thumb? */ public Filme(int codigo, String titulo, String sinopse, int faixaEtaria, int duracao, int ano, String idioma, String legenda) { this.codigo = codigo; this.titulo = titulo; this.sinopse = sinopse; this.faixaEtaria = faixaEtaria; this.duracao = duracao; this.ano = ano; this.idioma = idioma; this.legenda = legenda; } public int getCodigo() { return codigo; } public void setCodigo(int codigo) { this.codigo = codigo; } public String getTitulo() { return titulo; } public void setTitulo(String titulo) { this.titulo = titulo; } public int getFaixaEtaria() { return faixaEtaria; } public void setFaixaEtaria(int faixaEtaria) { this.faixaEtaria = faixaEtaria; } public String getSinopse() { return sinopse; } public void setSinopse(String sinopse) { this.sinopse = sinopse; } public int getDuracao() { return duracao; } public void setDuracao(int duracao) { this.duracao = duracao; } public int getAno() { return ano; } public void setAno(int ano) { this.ano = ano; } public String getIdioma() { return idioma; } public void setIdioma(String idioma) { this.idioma = idioma; } public String getLegenda() { return legenda; } public void setLegenda(String legenda) { this.legenda = legenda; } } 0 import java.util.Observable; import java.util.Observer; public class PossibleSolution extends Solution implements Observer{ String question; String solution; @Override public void solve() { String temp[ ] = question.split(" "); if (temp[0].equals("POSSIBLE") == true) { //System.out.println(temp[0]); String vw = temp[1]; String v = vw.substring(0, 1); String w = vw.substring(1,2); String limit = vw.substring(2); int vpoint = WeightedGraph.getInstance().indexOf(v); int wpoint = WeightedGraph.getInstance().indexOf(w); int limitation = Integer.parseInt(limit); DlsPaths solver = new DlsPaths(vpoint,wpoint,limitation); solution = solver.toString(); //System.out.println(solver.toString()); QuestionList.getInstance().addAnswer(toString()); QuestionList.getInstance().solvedQestion(); } } @Override public void update(Observable o, Object arg) { if (o instanceof QuestionList) { question = (String) arg; solve(); } } public String toString() { return question + " = " + solution; } } autobahn/src/main/java/io/crossbar/autobahn/wamp/messages/Challenge.java /////////////////////////////////////////////////////////////////////////////// // // AutobahnJava - http://crossbar.io/autobahn // // Copyright (c) Crossbar.io Technologies GmbH and contributors // // Licensed under the MIT License. // http://www.opensource.org/licenses/mit-license.php // /////////////////////////////////////////////////////////////////////////////// package io.crossbar.autobahn.wamp.messages; import java.util.ArrayList; import java.util.List; import java.util.Map; import io.crossbar.autobahn.wamp.interfaces.IMessage; import io.crossbar.autobahn.wamp.utils.MessageUtil; public class Challenge implements IMessage { public static final int MESSAGE_TYPE = 4; public final String method; public final Map extra; public Challenge(String method, Map extra) { this.method = method; this.extra = extra; } public static Challenge parse(List wmsg) { MessageUtil.validateMessage(wmsg, MESSAGE_TYPE, "CHALLENGE", 3); return new Challenge((String) wmsg.get(1), (Map) wmsg.get(2)); } @Override public List marshal() { List marshaled = new ArrayList<>(); marshaled.add(MESSAGE_TYPE); marshaled.add(method); marshaled.add(extra); return marshaled; } } src/com/quchen/flappycow/sprites/Obstacle.java /** * An obstacle: spider + logHead * * @author * Copyright (c) <2014> < - Quchen> */ package com.quchen.flappycow.sprites; import com.quchen.flappycow.Game; import com.quchen.flappycow.GameView; import com.quchen.flappycow.MainActivity; import com.quchen.flappycow.R; import android.graphics.Canvas; public class Obstacle extends Sprite{ private Spider spider; private WoodLog log; private static int collideSound = -1; private static int passSound = -1; /** Necessary so the onPass method is just called once */ public boolean isAlreadyPassed = false; public Obstacle(GameView view, Game game) { super(view, game); spider = new Spider(view, game); log = new WoodLog(view, game); if(collideSound == -1){ collideSound = Game.soundPool.load(game, R.raw.crash, 1); } if(passSound == -1){ passSound = Game.soundPool.load(game, R.raw.pass, 1); } initPos(); } /** * Creates a spider and a wooden log at the right of the screen. * With a certain gap between them. * The vertical position is in a certain area random. */ private void initPos(){ int height = game.getResources().getDisplayMetrics().heightPixels; int gab = height / 4 - view.getSpeedX(); if(gab < height / 5){ gab = height / 5; } int random = (int) (Math.random() * height * 2 / 5); int y1 = (height / 10) + random - spider.height; int y2 = (height / 10) + random + gab; spider.init(game.getResources().getDisplayMetrics().widthPixels, y1); log.init(game.getResources().getDisplayMetrics().widthPixels, y2); } /** * Draws spider and log. */ @Override public void draw(Canvas canvas) { spider.draw(canvas); log.draw(canvas); } /** * Checks whether both, spider and log, are out of range. */ @Override public boolean isOutOfRange() { return spider.isOutOfRange() && log.isOutOfRange(); } /** * Checks whether the spider or the log is colliding with the sprite. */ @Override public boolean isColliding(Sprite sprite) { return spider.isColliding(sprite) || log.isColliding(sprite); } /** * Moves both, spider and log. */ @Override public void move() { spider.move(); log.move(); } /** * Sets the speed of the spider and the log. */ @Override public void setSpeedX(float speedX) { spider.setSpeedX(speedX); log.setSpeedX(speedX); } /** * Checks whether the spider and the log are passed. */ @Override public boolean isPassed(){ return spider.isPassed() && log.isPassed(); } /** * Will call obstaclePassed of the game, if this is the first pass of this obstacle. */ public void onPass(){ if(!isAlreadyPassed){ isAlreadyPassed = true; view.getGame().increasePoints(); Game.soundPool.play(passSound, MainActivity.volume, MainActivity.volume, 0, 0, 1); } } @Override public void onCollision() { super.onCollision(); Game.soundPool.play(collideSound, MainActivity.volume, MainActivity.volume, 0, 0, 1); } } drools-core/src/main/java/org/drools/core/reteoo/PropagationQueuingNode.java /* * Copyright 2010 JBoss 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 org.drools.core.reteoo; import org.drools.core.RuleBaseConfiguration; import org.drools.core.RuntimeDroolsException; import org.drools.core.common.InternalFactHandle; import org.drools.core.common.InternalKnowledgeRuntime; import org.drools.core.common.InternalWorkingMemory; import org.drools.core.common.Memory; import org.drools.core.common.MemoryFactory; import org.drools.core.common.WorkingMemoryAction; import org.drools.core.impl.StatefulKnowledgeSessionImpl; import org.drools.core.marshalling.impl.MarshallerReaderContext; import org.drools.core.marshalling.impl.MarshallerWriteContext; import org.drools.core.marshalling.impl.ProtobufMessages; import org.drools.core.reteoo.builder.BuildContext; import org.drools.core.spi.PropagationContext; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.List; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; import static org.drools.core.util.BitMaskUtil.intersect; /** * A node that will add the propagation to the working memory actions queue, * in order to allow multiple threads to concurrently assert objects to multiple * entry points. */ public class PropagationQueuingNode extends ObjectSource implements ObjectSinkNode, MemoryFactory { private static final long serialVersionUID = 510l; // should we make this one configurable? private static final int PROPAGATION_SLICE_LIMIT = 1000; private ObjectSinkNode previousObjectSinkNode; private ObjectSinkNode nextObjectSinkNode; private PropagateAction action; public PropagationQueuingNode() { } /** * Construct a PropagationQueuingNode that will queue up * propagations until it the engine reaches a safe propagation point, * when all the queued facts are propagated. * * @param id Node's ID * @param objectSource Node's object source * @param context */ public PropagationQueuingNode(final int id, final ObjectSource objectSource, final BuildContext context) { super( id, context.getPartitionId(), context.getRuleBase().getConfiguration().isMultithreadEvaluation(), objectSource, context.getRuleBase().getConfiguration().getAlphaNodeHashingThreshold() ); this.action = new PropagateAction( this ); initDeclaredMask(context); } @Override public long calculateDeclaredMask(List settableProperties) { return 0; } public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { super.readExternal( in ); action = (PropagateAction) in.readObject(); } public void writeExternal( ObjectOutput out ) throws IOException { super.writeExternal( out ); out.writeObject( action ); } public short getType() { return NodeTypeEnums.PropagationQueuingNode; } /** * @see org.kie.reteoo.ObjectSource#updateSink(org.kie.reteoo.ObjectSink, org.kie.spi.PropagationContext, org.kie.common.InternalWorkingMemory) */ public void updateSink( ObjectSink sink, PropagationContext context, InternalWorkingMemory workingMemory ) { final PropagationQueueingNodeMemory memory = (PropagationQueueingNodeMemory) workingMemory.getNodeMemory( this ); // this is just sanity code. We may remove it in the future, but keeping it for now. if ( !memory.isEmpty() ) { throw new RuntimeDroolsException( "Error updating sink. Not safe to update sink as the PropagatingQueueingNode memory is not empty at node: " + this.toString() ); } // as this node is simply a queue, ask object source to update the child sink directly this.source.updateSink( sink, context, workingMemory ); } public void attach( BuildContext context ) { this.source.addObjectSink( this ); // this node does not require update, so nothing else to do. } /** * @see org.kie.reteoo.ObjectSinkNode#getNextObjectSinkNode() */ public ObjectSinkNode getNextObjectSinkNode() { return this.nextObjectSinkNode; } /** * @see org.kie.reteoo.ObjectSinkNode#getPreviousObjectSinkNode() */ public ObjectSinkNode getPreviousObjectSinkNode() { return this.previousObjectSinkNode; } /** * @see org.kie.reteoo.ObjectSinkNode#setNextObjectSinkNode(org.kie.reteoo.ObjectSinkNode) */ public void setNextObjectSinkNode( ObjectSinkNode next ) { this.nextObjectSinkNode = next; } /** * @see org.kie.reteoo.ObjectSinkNode#setPreviousObjectSinkNode(org.kie.reteoo.ObjectSinkNode) */ public void setPreviousObjectSinkNode( ObjectSinkNode previous ) { this.previousObjectSinkNode = previous; } public boolean isObjectMemoryEnabled() { return true; } /** * @see org.kie.reteoo.ObjectSink#assertObject(InternalFactHandle, org.kie.spi.PropagationContext, org.kie.common.InternalWorkingMemory) */ public void assertObject( InternalFactHandle factHandle, PropagationContext context, InternalWorkingMemory workingMemory ) { final PropagationQueueingNodeMemory memory = (PropagationQueueingNodeMemory) workingMemory.getNodeMemory( this ); memory.addAction( new AssertAction( factHandle, context ) ); // if not queued yet, we need to queue it up if ( memory.isQueued().compareAndSet( false, true ) ) { workingMemory.queueWorkingMemoryAction( this.action ); } } public void retractObject( InternalFactHandle handle, PropagationContext context, InternalWorkingMemory workingMemory ) { final PropagationQueueingNodeMemory memory = (PropagationQueueingNodeMemory) workingMemory.getNodeMemory( this ); memory.addAction( new RetractAction( handle, context ) ); // if not queued yet, we need to queue it up if ( memory.isQueued().compareAndSet( false, true ) ) { workingMemory.queueWorkingMemoryAction( this.action ); } } public void modifyObject(InternalFactHandle factHandle, ModifyPreviousTuples modifyPreviousTuples, PropagationContext context, InternalWorkingMemory workingMemory) { final PropagationQueueingNodeMemory memory = (PropagationQueueingNodeMemory) workingMemory.getNodeMemory( this ); // for ( ObjectSink s : this.sink.getSinks() ) { // RightTuple rightTuple = modifyPreviousTuples.removeRightTuple( (RightTupleSink) s ); // if ( rightTuple != null ) { // rightTuple.reAdd(); // // RightTuple previously existed, so continue as modify // memory.addAction( new ModifyToSinkAction( rightTuple, // context, // (RightTupleSink) s ) ); // } else { // // RightTuple does not exist, so create and continue as assert // memory.addAction( new AssertToSinkAction( factHandle, // context, // s ) ); // } // } for ( ObjectSink s : this.sink.getSinks() ) { BetaNode betaNode = (BetaNode) s; RightTuple rightTuple = modifyPreviousTuples.peekRightTuple(); while ( rightTuple != null && rightTuple.getRightTupleSink().getRightInputOtnId().before( betaNode.getRightInputOtnId() ) ) { modifyPreviousTuples.removeRightTuple(); // we skipped this node, due to alpha hashing, so retract now rightTuple.getRightTupleSink().retractRightTuple( rightTuple, context, workingMemory ); rightTuple = modifyPreviousTuples.peekRightTuple(); } if ( rightTuple != null && rightTuple.getRightTupleSink().getRightInputOtnId().equals( betaNode.getRightInputOtnId() ) ) { modifyPreviousTuples.removeRightTuple(); rightTuple.reAdd(); if ( intersect( context.getModificationMask(), betaNode.getRightInferredMask() ) ) { // RightTuple previously existed, so continue as modify memory.addAction( new ModifyToSinkAction( rightTuple, context, betaNode ) ); } } else { if ( intersect( context.getModificationMask(), betaNode.getRightInferredMask() ) ) { // RightTuple does not exist for this node, so create and continue as assert memory.addAction( new AssertToSinkAction( factHandle, context, betaNode ) ); } } } // if not queued yet, we need to queue it up if ( memory.isQueued().compareAndSet( false, true ) ) { workingMemory.queueWorkingMemoryAction( this.action ); } } public void byPassModifyToBetaNode (final InternalFactHandle factHandle, final ModifyPreviousTuples modifyPreviousTuples, final PropagationContext context, final InternalWorkingMemory workingMemory) { modifyObject( factHandle, modifyPreviousTuples, context, workingMemory ); } /** * Propagate all queued actions (asserts and retracts). *

* This method implementation is based on optimistic behavior to avoid the * use of locks. There may eventually be a minimum wasted effort, but overall * it will be better than paying for the lock's cost. * * @param workingMemory */ public void propagateActions( InternalWorkingMemory workingMemory ) { final PropagationQueueingNodeMemory memory = (PropagationQueueingNodeMemory) workingMemory.getNodeMemory( this ); // first we clear up the action queued flag memory.isQueued().compareAndSet( true, false ); // we limit the propagation to avoid a hang when this queue is never empty Action next; for ( int counter = 0; counter < PROPAGATION_SLICE_LIMIT; counter++ ) { next = memory.getNextAction(); if ( next != null ) { next.execute( this.sink, workingMemory ); } else { break; } } if ( memory.hasNextAction() && memory.isQueued().compareAndSet( false, true ) ) { // add action to the queue again. workingMemory.queueWorkingMemoryAction( this.action ); } } public void setObjectMemoryEnabled( boolean objectMemoryOn ) { throw new UnsupportedOperationException( "PropagationQueueingNode must have its node memory enabled." ); } public Memory createMemory(RuleBaseConfiguration config, InternalWorkingMemory wm) { return new PropagationQueueingNodeMemory(); } public int hashCode() { return this.source.hashCode(); } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(final Object object) { if ( this == object ) { return true; } if ( object == null || !(object instanceof PropagationQueuingNode) ) { return false; } final PropagationQueuingNode other = (PropagationQueuingNode) object; return this.source.equals( other.source ); } /** * Memory implementation for the node */ public static class PropagationQueueingNodeMemory implements Memory { private static final long serialVersionUID = 7372028632974484023L; private ConcurrentLinkedQueue queue; // "singleton" action - there is one of this for each node in each working memory private AtomicBoolean isQueued; public PropagationQueueingNodeMemory() { super(); this.queue = new ConcurrentLinkedQueue(); this.isQueued = new AtomicBoolean( false ); } public boolean isEmpty() { return this.queue.isEmpty(); } public void addAction( Action action ) { this.queue.add( action ); } public Action getNextAction() { return this.queue.poll(); } public boolean hasNextAction() { return this.queue.peek() != null; } public AtomicBoolean isQueued() { return isQueued; } public long getSize() { return this.queue.size(); } public short getNodeType() { return NodeTypeEnums.PropagationQueueingNode; } public Memory getPrevious() { throw new UnsupportedOperationException(); } public void setPrevious(Memory previous) { throw new UnsupportedOperationException(); } public void setNext(Memory next) { throw new UnsupportedOperationException(); } public Memory getNext() { throw new UnsupportedOperationException(); } public SegmentMemory getSegmentMemory() { throw new UnsupportedOperationException(); } public void setSegmentMemory(SegmentMemory segmentMemory) { throw new UnsupportedOperationException(); } } private static abstract class Action implements Externalizable { protected InternalFactHandle handle; protected PropagationContext context; public Action(InternalFactHandle handle, PropagationContext context) { super(); this.handle = handle; this.context = context; } public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { handle = (InternalFactHandle) in.readObject(); context = (PropagationContext) in.readObject(); } public void writeExternal( ObjectOutput out ) throws IOException { out.writeObject( handle ); out.writeObject( context ); } public abstract void execute( final ObjectSinkPropagator sink, final InternalWorkingMemory workingMemory ); } private static class AssertAction extends Action { private static final long serialVersionUID = -8478488926430845209L; public AssertAction(final InternalFactHandle handle, final PropagationContext context) { super( handle, context ); } public void execute( final ObjectSinkPropagator sink, final InternalWorkingMemory workingMemory ) { sink.propagateAssertObject( this.handle, this.context, workingMemory ); context.evaluateActionQueue( workingMemory ); } } private static class AssertToSinkAction extends Action { private static final long serialVersionUID = -8478488926430845209L; private ObjectSink nodeSink; public AssertToSinkAction(final InternalFactHandle handle, final PropagationContext context, final ObjectSink sink) { super( handle, context ); nodeSink = sink; } public void execute( final ObjectSinkPropagator sink, final InternalWorkingMemory workingMemory ) { nodeSink.assertObject( this.handle, this.context, workingMemory ); context.evaluateActionQueue( workingMemory ); } @Override public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { super.readExternal( in ); nodeSink = (ObjectSink) in.readObject(); } @Override public void writeExternal( ObjectOutput out ) throws IOException { super.writeExternal( out ); out.writeObject( nodeSink ); } } private static class RetractAction extends Action { private static final long serialVersionUID = -84784886430845209L; public RetractAction(final InternalFactHandle handle, final PropagationContext context) { super( handle, context ); } public void execute( final ObjectSinkPropagator sink, final InternalWorkingMemory workingMemory ) { for ( RightTuple rightTuple = this.handle.getFirstRightTuple(); rightTuple != null; rightTuple = rightTuple.getHandleNext() ) { rightTuple.getRightTupleSink().retractRightTuple( rightTuple, context, workingMemory ); } this.handle.clearRightTuples(); for ( LeftTuple leftTuple = this.handle.getLastLeftTuple(); leftTuple != null; leftTuple = leftTuple.getLeftParentNext() ) { leftTuple.getLeftTupleSink().retractLeftTuple( leftTuple, context, workingMemory ); } this.handle.clearLeftTuples(); context.evaluateActionQueue( workingMemory ); } } private static class ModifyToSinkAction extends Action { private static final long serialVersionUID = -8478488926430845209L; private RightTupleSink nodeSink; private RightTuple rightTuple; public ModifyToSinkAction(final RightTuple rightTuple, final PropagationContext context, final RightTupleSink nodeSink) { super( rightTuple.getFactHandle(), context ); this.nodeSink = nodeSink; this.rightTuple = rightTuple; } public void execute( final ObjectSinkPropagator sink, final InternalWorkingMemory workingMemory ) { nodeSink.modifyRightTuple( rightTuple, context, workingMemory ); context.evaluateActionQueue( workingMemory ); } @Override public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { super.readExternal( in ); nodeSink = (RightTupleSink) in.readObject(); rightTuple = (RightTuple) in.readObject(); } @Override public void writeExternal( ObjectOutput out ) throws IOException { super.writeExternal( out ); out.writeObject( nodeSink ); out.writeObject( rightTuple ); } } /** * This is the action that is added to the working memory actions queue, so that * this node propagation can be triggered at a safe point */ public static class PropagateAction implements WorkingMemoryAction { private static final long serialVersionUID = 6765029029501617115L; private PropagationQueuingNode node; public PropagateAction() { } public PropagateAction(PropagationQueuingNode node) { this.node = node; } public PropagateAction(MarshallerReaderContext context) throws IOException { this.node = (PropagationQueuingNode) context.sinks.get( context.readInt() ); } public PropagateAction(MarshallerReaderContext context, ProtobufMessages.ActionQueue.Action _action) { this.node = (PropagationQueuingNode) context.sinks.get( _action.getPropagate().getNodeId() ); } public void write( MarshallerWriteContext context ) throws IOException { context.writeShort( WorkingMemoryAction.PropagateAction ); context.write( node.getId() ); } public ProtobufMessages.ActionQueue.Action serialize( MarshallerWriteContext context ) { return ProtobufMessages.ActionQueue.Action.newBuilder() .setType( ProtobufMessages.ActionQueue.ActionType.PROPAGATE ) .setPropagate( ProtobufMessages.ActionQueue.Propagate.newBuilder() .setNodeId( node.getId() ) .build() ) .build(); } public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { node = (PropagationQueuingNode) in.readObject(); } public void writeExternal( ObjectOutput out ) throws IOException { out.writeObject( node ); } public void execute( InternalWorkingMemory workingMemory ) { this.node.propagateActions( workingMemory ); } public void execute( InternalKnowledgeRuntime kruntime ) { execute( ((StatefulKnowledgeSessionImpl) kruntime).getInternalWorkingMemory() ); } } } /* * * * Copyright 2018 Symphony Communication Services, LLC. * * Licensed to The Symphony Software Foundation (SSF) 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.symphonyoss.s2.canon.runtime.jjwt; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; import io.jsonwebtoken.JwtBuilder; import io.jsonwebtoken.SignatureAlgorithm; /** * HMAC based implementation of JwtGenerator. * * @author * @param The concrete type of the generator for fluent methods. * */ public class AbstractHsJwtGenerator> extends JwtGenerator { /** The signature algorithm used. */ private final SignatureAlgorithm signatureAlgorithm_; private final SecretKey key_; /** * Constructor. * * @param type The concrete type of the generator. * @param signatureAlgorithm The signing algorithm to use * @param secretKeyBase64 The shared secret key encoded as Base64. */ public AbstractHsJwtGenerator(Class type, SignatureAlgorithm signatureAlgorithm, String secretKeyBase64) { super(type); signatureAlgorithm_ = signatureAlgorithm; key_ = new SecretKeySpec(Base64.decodeBase64(secretKeyBase64), signatureAlgorithm_.getJcaName()); } @Override protected String sign(JwtBuilder builder) { // This is for JJWT 0.10.5 // return builder.signWith(key_, signatureAlgorithm_).compact(); return builder.signWith(signatureAlgorithm_, key_).compact(); } /** * * @return The shared secret key. */ public SecretKey getKey() { return key_; } /** * * @return The signature algorithm used. */ public SignatureAlgorithm getSignatureAlgorithm() { return signatureAlgorithm_; } } package mekanism.generators.client; import mekanism.api.EnumGas; import mekanism.generators.common.TileEntityElectrolyticSeparator; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.tileentity.TileEntity; import org.lwjgl.opengl.GL11; public class RenderElectrolyticSeparator extends TileEntitySpecialRenderer { private ModelElectrolyticSeparator model = new ModelElectrolyticSeparator(); @Override public void renderTileEntityAt(TileEntity var1, double var2, double var4, double var6, float var8) { renderAModelAt((TileEntityElectrolyticSeparator) var1, var2, var4, var6, 1F); } private void renderAModelAt(TileEntityElectrolyticSeparator tileEntity, double x, double y, double z, float f) { GL11.glPushMatrix(); GL11.glTranslatef((float) x + 0.5f, (float) y + 1.5f, (float) z + 0.5f); bindTextureByName(tileEntity.outputType == EnumGas.HYDROGEN ? "/mods/mekanism/render/ElectrolyticSeparatorHydrogen.png" : (tileEntity.outputType == EnumGas.OXYGEN ? "/mods/mekanism/render/ElectrolyticSeparatorOxygen.png" : "/mods/mekanism/render/ElectrolyticSeparatorNone.png")); switch(tileEntity.facing) { case 2: GL11.glRotatef(270, 0.0F, 1.0F, 0.0F); break; case 3: GL11.glRotatef(90, 0.0F, 1.0F, 0.0F); break; case 4: GL11.glRotatef(0, 0.0F, 1.0F, 0.0F); break; case 5: GL11.glRotatef(180, 0.0F, 1.0F, 0.0F); break; } GL11.glRotatef(180F, 0.0F, 0.0F, 1.0F); GL11.glRotatef(90F, 0.0F, 1.0F, 0.0F); model.render(0.0625F); GL11.glPopMatrix(); } } package js.web.webrtc; import org.teavm.jso.JSProperty; import javax.annotation.Nullable; public interface RTCIceCandidatePairStats extends RTCStats { @JSProperty int getAvailableIncomingBitrate(); @JSProperty void setAvailableIncomingBitrate(int availableIncomingBitrate); @JSProperty int getAvailableOutgoingBitrate(); @JSProperty void setAvailableOutgoingBitrate(int availableOutgoingBitrate); @JSProperty int getBytesReceived(); @JSProperty void setBytesReceived(int bytesReceived); @JSProperty int getBytesSent(); @JSProperty void setBytesSent(int bytesSent); @JSProperty @Nullable String getLocalCandidateId(); @JSProperty void setLocalCandidateId(String localCandidateId); @JSProperty boolean isNominated(); @JSProperty void setNominated(boolean nominated); @JSProperty int getPriority(); @JSProperty void setPriority(int priority); @JSProperty boolean isReadable(); @JSProperty void setReadable(boolean readable); @JSProperty @Nullable String getRemoteCandidateId(); @JSProperty void setRemoteCandidateId(String remoteCandidateId); @JSProperty double getRoundTripTime(); @JSProperty void setRoundTripTime(double roundTripTime); @JSProperty @Nullable RTCStatsIceCandidatePairState getState(); @JSProperty void setState(RTCStatsIceCandidatePairState state); @JSProperty @Nullable String getTransportId(); @JSProperty void setTransportId(String transportId); @JSProperty boolean isWritable(); @JSProperty void setWritable(boolean writable); } package org.devocative.ares.entity.oservice; import org.devocative.demeter.entity.*; import org.hibernate.envers.Audited; import org.hibernate.envers.NotAudited; import javax.persistence.*; import java.util.Date; import java.util.List; @Audited @Entity @Table(name = "t_ars_service", uniqueConstraints = { @UniqueConstraint(name = "uk_ars_service", columnNames = {"c_name"}) }) public class OService implements ICreationDate, ICreatorUser, IModificationDate, IModifierUser { private static final long serialVersionUID = -110639388094098969L; @Id @GeneratedValue(generator = "ars_service") @org.hibernate.annotations.GenericGenerator(name = "ars_service", strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator", parameters = { //@org.hibernate.annotations.Parameter(name = "optimizer", value = "pooled"), @org.hibernate.annotations.Parameter(name = "initial_value", value = "1"), @org.hibernate.annotations.Parameter(name = "increment_size", value = "1"), @org.hibernate.annotations.Parameter(name = "sequence_name", value = "ars_service") }) private Long id; @Column(name = "c_name", nullable = false) private String name; @Column(name = "c_conn_pattern", length = 1000) private String connectionPattern; @Column(name = "n_admin_port") private Integer adminPort; @Column(name = "c_ports") private String ports; @Column(name = "c_username_reg_ex") private String usernameRegEx; @OneToMany(fetch = FetchType.EAGER, mappedBy = "service") private List properties; // --------------- CREATE / MODIFY @NotAudited @Column(name = "d_creation", nullable = false, columnDefinition = "date") private Date creationDate; @NotAudited @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "f_creator_user", nullable = false, insertable = false, updatable = false, foreignKey = @ForeignKey(name = "service_crtrusr2user")) private User creatorUser; @NotAudited @Column(name = "f_creator_user", nullable = false) private Long creatorUserId; @Column(name = "d_modification", columnDefinition = "date") private Date modificationDate; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "f_modifier_user", insertable = false, updatable = false, foreignKey = @ForeignKey(name = "service_mdfrusr2user")) private User modifierUser; @Column(name = "f_modifier_user") private Long modifierUserId; @Version @Column(name = "n_version", nullable = false) private Integer version = 0; // ------------------------------ public OService() { } public OService(String name) { this.name = name; } // ------------------------------ 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 String getConnectionPattern() { return connectionPattern; } public void setConnectionPattern(String connectionPattern) { this.connectionPattern = connectionPattern; } public Integer getAdminPort() { return adminPort; } public void setAdminPort(Integer adminPort) { this.adminPort = adminPort; } public String getPorts() { return ports; } public void setPorts(String ports) { this.ports = ports; } public String getUsernameRegEx() { return usernameRegEx; } public void setUsernameRegEx(String usernameRegEx) { this.usernameRegEx = usernameRegEx; } public List getProperties() { return properties; } public void setProperties(List properties) { this.properties = properties; } // --------------- CREATE / MODIFY @Override public Date getCreationDate() { return creationDate; } @Override public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } public User getCreatorUser() { return creatorUser; } @Override public Long getCreatorUserId() { return creatorUserId; } @Override public void setCreatorUserId(Long creatorUserId) { this.creatorUserId = creatorUserId; } @Override public Date getModificationDate() { return modificationDate; } @Override public void setModificationDate(Date modificationDate) { this.modificationDate = modificationDate; } public User getModifierUser() { return modifierUser; } @Override public Long getModifierUserId() { return modifierUserId; } @Override public void setModifierUserId(Long modifierUserId) { this.modifierUserId = modifierUserId; } @Override public Integer getVersion() { return version; } @Override public void setVersion(Integer version) { this.version = version; } // ------------------------------ @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof OService)) return false; OService that = (OService) o; return !(getId() != null ? !getId().equals(that.getId()) : that.getId() != null); } @Override public int hashCode() { return getId() != null ? getId().hashCode() : 0; } @Override public String toString() { return getName(); } } package com.works.repositories; import com.works.entities.NewCase; import org.springframework.data.jpa.repository.JpaRepository; public interface CaseRepository extends JpaRepository { } src/utils/src/main/java/org/tio/utils/date/DateUtils.java package org.tio.utils.date; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; /** * @author tanyaowu 2018年6月10日 上午7:58:23 */ public class DateUtils { /** * 当前时间生成符合http响应头中的Date格式的字符串 * * @return * @author tanyaowu */ public static String httpDate() { return httpDate(new Date()); } // private static final FastDateFormat HTTP_DATE_FORMATTER = FastDateFormat.getInstance("EEE, d MMM yyyy HH:mm:ss 'GMT'", Locale.US); /** * 把date生成符合http响应头中的Date格式的字符串 * * @param date * @return * @author tanyaowu */ public static String httpDate(Date date) { SimpleDateFormat greenwichDate = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss 'GMT'", Locale.US); return greenwichDate.format(date); // return HTTP_DATE_FORMATTER.format(date); } public static String httpDate(long millis) { return httpDate(new Date(millis)); // return HTTP_DATE_FORMATTER.format(millis); } /** * 格式化日期时间
* 格式 yyyy-MM-dd HH:mm:ss * * @param date 被格式化的日期 * @return 格式化后的日期 */ public static String formatDateTime(Date date) { if (null == date) { return null; } SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return format.format(date); } } package io.moneytransfer.di.providers; import io.moneytransfer.service.AccountService; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.Provider; @Provider public class AccountServiceProvider implements ContextResolver { private AccountService accountService = new AccountService(); @Override public AccountService getContext(Class klass) { return accountService; } } Sphericone/archi /******************************************************************************* * Copyright 2005, CHISEL Group, University of Victoria, Victoria, BC, Canada. * All rights reserved. This program and the accompanying materials are made * available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: The Chisel Group, University of Victoria *******************************************************************************/ package org.eclipse.zest.layouts; /** * Super interface for both Layout Entities and Layout Relationships * * @author * */ public interface LayoutItem { public void setGraphData(Object o); public Object getGraphData(); } package com.company.modifiers; import java.util.ArrayList; public interface IButtonModifier { public ArrayList modify(ArrayList buttons); } ObserveRTC/WebRTC-Observer package org.observertc.observer.evaluators; import io.micronaut.context.BeanProvider; import io.micronaut.context.annotation.Prototype; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.subjects.PublishSubject; import io.reactivex.rxjava3.subjects.Subject; import jakarta.inject.Inject; import org.observertc.observer.configs.ObserverConfig; import org.observertc.observer.dto.ClientDTO; import org.observertc.observer.dto.MediaTrackDTO; import org.observertc.observer.dto.PeerConnectionDTO; import org.observertc.observer.dto.StreamDirection; import org.observertc.observer.evaluators.depots.ClientDTOsDepot; import org.observertc.observer.evaluators.depots.MediaTrackDTOsDepot; import org.observertc.observer.evaluators.depots.PeerConnectionDTOsDepot; import org.observertc.observer.metrics.EvaluatorMetrics; import org.observertc.observer.repositories.tasks.*; import org.observertc.observer.samples.ClientSampleVisitor; import org.observertc.observer.samples.ObservedClientSamples; import org.observertc.observer.samples.ServiceRoomId; import org.observertc.schemas.samples.Samples; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.Instant; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.UUID; import java.util.function.Consumer; import java.util.stream.Collectors; @Prototype public class CallEntitiesUpdater implements Consumer { private static final Logger logger = LoggerFactory.getLogger(CallEntitiesUpdater.class); private static final String METRIC_COMPONENT_NAME = CallEntitiesUpdater.class.getSimpleName(); @Inject EvaluatorMetrics exposedMetrics; @Inject BeanProvider createCallIfNotExistsTaskProvider; @Inject BeanProvider findCallsTaskProvider; @Inject BeanProvider refreshCallsTaskProvider; @Inject BeanProvider addClientsTaskProvider; @Inject BeanProvider peerConnectionsTaskProvider; @Inject BeanProvider addMediaTrackTaskProvider; @Inject BeanProvider removeCallsTasks; @Inject ObserverConfig.EvaluatorsConfig.CallUpdater config; private Subject output = PublishSubject.create(); private final ClientDTOsDepot clientsDepot = new ClientDTOsDepot(); private final PeerConnectionDTOsDepot peerConnectionsDepot = new PeerConnectionDTOsDepot(); private final MediaTrackDTOsDepot mediaTracksDepot = new MediaTrackDTOsDepot(); public Observable observableClientSamples() { return this.output; } public void accept(ObservedClientSamples observedClientSamples) { Instant started = Instant.now(); try { this.process(observedClientSamples); } finally { this.exposedMetrics.addTaskExecutionTime(METRIC_COMPONENT_NAME, started, Instant.now()); } } private void process(ObservedClientSamples observedClientSamples) { if (observedClientSamples.isEmpty()) { return; } var roomsToCallIds = this.getRoomsToCallIds(observedClientSamples); if (roomsToCallIds == null) { logger.warn("No room has found"); return; } var findDTOs = this.refreshCallsTaskProvider.get() .withClientIds(observedClientSamples.getClientIds()) .withPeerConnectionIds(observedClientSamples.getPeerConnectionIds()) .withMediaTrackIds(observedClientSamples.getMediaTrackIds()) // .withUnmodifiableResult(false) ; if (!findDTOs.execute().succeeded()) { logger.warn("Interrupted execution of component due to unsuccessful task execution"); return; } var findDTOsTaskResult = findDTOs.getResult(); var foundClientIds = findDTOsTaskResult.foundClientIds; var foundPeerConnectionIds = findDTOsTaskResult.foundClientIds; var foundMediaTrackIds = findDTOsTaskResult.foundTrackIds; for (var observedClientSample : observedClientSamples) { var serviceRoomId = observedClientSample.getServiceRoomId(); var clientSample = observedClientSample.getClientSample(); UUID callId = roomsToCallIds.get(serviceRoomId); if (Objects.isNull(callId)) { callId = this.createCallIfNotExists(serviceRoomId, clientSample); if (Objects.isNull(callId)) { logger.warn("Cannot assign callId to clientSample {}", clientSample); continue; } roomsToCallIds.put(serviceRoomId, callId); } clientSample.callId = callId; if (!foundClientIds.contains(clientSample.clientId)) { this.clientsDepot.addFromObservedClientSample(observedClientSample); } ClientSampleVisitor.streamPeerConnectionTransports(clientSample).forEach(pcTransport -> { if (foundPeerConnectionIds.contains(pcTransport.peerConnectionId)) return; this.peerConnectionsDepot .setObservedClientSample(observedClientSample) .setPeerConnectionTransport(pcTransport) .assemble(); }); ClientSampleVisitor.streamInboundAudioTracks(clientSample).forEach(track -> { if (foundMediaTrackIds.contains(track.trackId) || track.trackId == null) return; this.mediaTracksDepot .setObservedClientSample(observedClientSample) .setTrackId(track.trackId) .setSfuStreamId(track.sfuStreamId) .setSfuSinkId(track.sfuSinkId) .setStreamDirection(StreamDirection.INBOUND) .setPeerConnectionId(track.peerConnectionId) .setSSRC(track.ssrc) .assemble(); }); ClientSampleVisitor.streamInboundVideoTracks(clientSample).forEach(track -> { if (foundMediaTrackIds.contains(track.trackId) || track.trackId == null) return; this.mediaTracksDepot .setObservedClientSample(observedClientSample) .setTrackId(track.trackId) .setSfuStreamId(track.sfuStreamId) .setSfuSinkId(track.sfuSinkId) .setStreamDirection(StreamDirection.INBOUND) .setPeerConnectionId(track.peerConnectionId) .setSSRC(track.ssrc) .assemble(); }); ClientSampleVisitor.streamOutboundAudioTracks(clientSample).forEach(track -> { if (foundMediaTrackIds.contains(track.trackId) || track.trackId == null) return; this.mediaTracksDepot .setObservedClientSample(observedClientSample) .setTrackId(track.trackId) .setSfuStreamId(track.sfuStreamId) // .setSfuSinkId(track.sfuSinkId) .setStreamDirection(StreamDirection.OUTBOUND) .setPeerConnectionId(track.peerConnectionId) .setSSRC(track.ssrc) .assemble(); }); ClientSampleVisitor.streamOutboundVideoTracks(clientSample).forEach(track -> { if (foundMediaTrackIds.contains(track.trackId) || track.trackId == null) return; this.mediaTracksDepot .setObservedClientSample(observedClientSample) .setTrackId(track.trackId) .setSfuStreamId(track.sfuStreamId) // .setSfuSinkId(track.sfuSinkId) .setStreamDirection(StreamDirection.OUTBOUND) .setPeerConnectionId(track.peerConnectionId) .setSSRC(track.ssrc) .assemble(); }); } var newClientDTOs = this.clientsDepot.get(); var newPeerConnectionDTOs = this.peerConnectionsDepot.get(); var newMediaTrackDTOs = this.mediaTracksDepot.get(); if (0 < newClientDTOs.size()) { this.addNewClients(newClientDTOs); } if (0 < newPeerConnectionDTOs.size()) { this.addNewPeerConnections(newPeerConnectionDTOs); } if (0 < newMediaTrackDTOs.size()) { this.addNewMediaTracks(newMediaTrackDTOs); } if (0 < observedClientSamples.size()) { synchronized (this) { this.output.onNext(observedClientSamples); } } } private Map getRoomsToCallIds(ObservedClientSamples observedClientSamples) { var findCallsTask = findCallsTaskProvider.get() .whereServiceRoomIds(observedClientSamples.getServiceRoomIds()) .withUnmodifiableResult(false) ; if (!findCallsTask.execute().succeeded()) { logger.warn("Interrupted execution of component due to unsuccessful task execution"); return null; } Map roomsToCallIds = findCallsTask.getResult(); if (this.config != null && ObserverConfig.EvaluatorsConfig.CallUpdater.CallIdAssignMode.SLAVE.equals(this.config.callIdAssignMode)) { var serviceRoomIdsToRemove = new HashSet(); var callIdsToRemove = observedClientSamples.stream() .filter(observedClientSample -> observedClientSample.getClientSample().callId != null) .filter(observedClientSample -> roomsToCallIds.get(observedClientSample.getServiceRoomId()) != null) .filter(observedClientSample -> { var existingCallId = roomsToCallIds.get(observedClientSample.getServiceRoomId()); var samplesCallId = observedClientSample.getClientSample().callId; var match = existingCallId.equals(samplesCallId); return match == false; }) .map(observedClientSample -> { serviceRoomIdsToRemove.add(observedClientSample.getServiceRoomId()); return roomsToCallIds.get(observedClientSample.getServiceRoomId()); }) .filter(Objects::nonNull) .collect(Collectors.toSet()); if (0 < callIdsToRemove.size()) { if (!this.removeCallsTasks.get().whereCallIds(callIdsToRemove).execute().succeeded()) { logger.warn("Interrupted execution of component due to unsuccessful task execution"); return null; } serviceRoomIdsToRemove.forEach(roomsToCallIds::remove); } } return roomsToCallIds; } private UUID createCallIfNotExists(ServiceRoomId serviceRoomId, Samples.ClientSample clientSample) { var task = createCallIfNotExistsTaskProvider.get(); task.withServiceRoomId(serviceRoomId) .withStartedTimestamp(clientSample.timestamp) .withCallId(clientSample.callId) .execute(); if (!task.succeeded()) { return null; } var result = task.getResult(); return result; } private void addNewMediaTracks(Map newMediaTracks) { var task = addMediaTrackTaskProvider.get().withMediaTrackDTOs(newMediaTracks); if (!task.execute().succeeded()) { logger.warn("{} task execution failed, repository may become inconsistent!", task.getClass().getSimpleName()); } } private void addNewPeerConnections(Map newPeerConnections) { var task = peerConnectionsTaskProvider.get() .withPeerConnectionDTOs(newPeerConnections) ; if (!task.execute().succeeded()) { logger.warn("{} task execution failed, repository may become inconsistent!", task.getClass().getSimpleName()); } } private void addNewClients(Map newClients) { var task = addClientsTaskProvider.get() .withClientDTOs(newClients) ; if (!task.execute().succeeded()) { logger.warn("{} task execution failed, repository may become inconsistent!", task.getClass().getSimpleName()); } } } src/main/java/com/blastedstudios/gdxworld/util/ExtensionFileFilter.java package com.blastedstudios.gdxworld.util; import java.io.File; import java.io.FileFilter; public class ExtensionFileFilter implements FileFilter{ private String extension, name; public ExtensionFileFilter(String extension, String name){ this.extension = extension; this.name = name; } @Override public boolean accept(File f) { if(f.isDirectory()) return true; if(FileUtil.getExtension(f) == null) return false; return FileUtil.getExtension(f).equalsIgnoreCase(extension); } public String getDescription() { return name + " (*." + extension + ")"; } public String getExtension(){ return extension; } }0 package es.nimio.nimiogcs.jpa.specs; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import org.springframework.data.jpa.domain.Specification; import es.nimio.nimiogcs.jpa.entidades.sistema.entornos.DestinoPublicacion; import es.nimio.nimiogcs.jpa.entidades.sistema.entornos.relaciones.RelacionEntornoServidor; public final class EntornosServidores { private EntornosServidores() {} /** * Los servidores que pertenecen a un entorno determinado */ public static Specification servidoresEntorno(final DestinoPublicacion entorno) { return new Specification() { @Override public Predicate toPredicate(Root root, CriteriaQuery cq, CriteriaBuilder cb) { return cb.equal(root.get("entorno").get("id"), entorno.getId()); } }; } } package com.publiccms.entities.sys; // Generated 2016-1-19 11:28:06 by Hibernate Tools 4.3.1 import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Id; import javax.persistence.Table; import com.sanluan.common.source.entity.MyColumn; /** * SystemRole generated by hbm2java */ @Entity @Table(name = "sys_role") public class SysRole implements java.io.Serializable { /** * */ private static final long serialVersionUID = 1L; @MyColumn(title = "ID") private Integer id; @MyColumn(title = "站点", condition = true) private int siteId; @MyColumn(title = "名称") private String name; @MyColumn(title = "拥有全部权限") private boolean ownsAllRight; @MyColumn(title = "显示全部模块") private boolean showAllMoudle; public SysRole() { } public SysRole(int siteId, String name, boolean ownsAllRight, boolean showAllMoudle) { this.siteId = siteId; this.name = name; this.ownsAllRight = ownsAllRight; this.showAllMoudle = showAllMoudle; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "id", unique = true, nullable = false) public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } @Column(name = "site_id", nullable = false) public int getSiteId() { return this.siteId; } public void setSiteId(int siteId) { this.siteId = siteId; } @Column(name = "name", nullable = false, length = 50) public String getName() { return this.name; } public void setName(String name) { this.name = name; } @Column(name = "owns_all_right", nullable = false) public boolean isOwnsAllRight() { return this.ownsAllRight; } public void setOwnsAllRight(boolean ownsAllRight) { this.ownsAllRight = ownsAllRight; } @Column(name = "show_all_moudle", nullable = false) public boolean isShowAllMoudle() { return this.showAllMoudle; } public void setShowAllMoudle(boolean showAllMoudle) { this.showAllMoudle = showAllMoudle; } } anukritijha/enmasseapi-model/src/test/java/io/enmasse/iot/model/v1/IoTProjectTest.java /* * Copyright 2018, EnMasse authors. * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). */ package io.enmasse.iot.model.v1; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import java.io.IOException; import java.net.URL; import java.nio.ByteBuffer; import org.junit.jupiter.api.Test; import com.fasterxml.jackson.databind.ObjectMapper; public class IoTProjectTest { @Test void testCreateManaged() { IoTProject project = new IoTProjectBuilder() .withNewMetadata() .withName("proj") .endMetadata() .withNewSpec() .withNewDownstream() .endDownstream() .endSpec() .build(); assertEquals("proj", project.getMetadata().getName()); } @Test public void testParse() throws IOException { final ObjectMapper mapper = new ObjectMapper(); final URL url = IoTProjectTest.class.getResource("resources/simple-project.json"); final IoTProject value = mapper.readValue(url, IoTProject.class); assertThat(value, notNullValue()); assertThat(value.getMetadata(), notNullValue()); assertThat(value.getMetadata().getName(), is("iot")); assertThat(value.getSpec(), notNullValue()); assertThat(value.getSpec().getDownstream(), notNullValue()); } } summer-spring-boot-autoconfigure/src/main/java/com/summer/mq/spring/autoconfigure/MessagePersistentConfiguration.java1-10 package com.summer.mq.spring.autoconfigure; import com.summer.mq.producer.DataBaseProducer; import com.summer.mq.producer.RedisMessageProducer; import com.summer.mq.service.MessagePersistentService; import com.summer.mq.service.RedisService; import com.summer.mq.service.impl.DefaultMessagePersistentService; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.jdbc.core.JdbcTemplate; @Slf4j @ConditionalOnClass({RedisMessageProducer.class, JdbcTemplate.class, RedisService.class}) public class MessagePersistentConfiguration { @Bean @ConditionalOnMissingBean(MessagePersistentService.class) public DefaultMessagePersistentService defaultMessagePersistentService() { return new DefaultMessagePersistentService(); } @Bean @ConditionalOnMissingBean(DataBaseProducer.class) public DataBaseProducer dataBaseProducer() { final DataBaseProducer dataBaseProducer = new DataBaseProducer(); return dataBaseProducer; } } package businesslogic; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Properties; import javax.mail.Address; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; public class EmailService { /** * The e-mail that reset password emails will come from. */ public static final String EMAIL_FROM = ""; public static void sendMail(String to, String subject, String template, HashMap contents) throws FileNotFoundException, IOException, MessagingException, NamingException { BufferedReader br = new BufferedReader(new FileReader(new File(template))); StringBuilder body = new StringBuilder(); String line = br.readLine(); while(line != null) { body.append(line); line = br.readLine(); } String bodyString = body.toString(); for(String key : contents.keySet()) { bodyString = bodyString.replace("{{" + key + "}}", contents.get(key)); } sendMail(to, subject, bodyString, true); } public static void sendMail(String to, String subject, String body, boolean bodyIsHTML) throws MessagingException, NamingException { Context env = (Context)new InitialContext().lookup("java:comp/env"); String username = (String)env.lookup("webmail-username"); String password = (String)env.lookup("webmail-password"); Properties props = new Properties(); props.put("mail.transport.protocol", (String)env.lookup("webmail-protocol")); props.put("mail.smtps.host", (String)env.lookup("webmail-hostname")); props.put("mail.smtps.port", (Integer)env.lookup("webmail-port")); props.put("mail.smtps.auth", "true"); props.put("mail.smtps.quitwait", "false"); Session session = Session.getDefaultInstance(props); session.setDebug(true); // create a message Message message = new MimeMessage(session); message.setSubject(subject); if (bodyIsHTML) { message.setContent(body, "text/html"); } else { message.setText(body); } // address the message Address fromAddress = new InternetAddress(EMAIL_FROM); Address toAddress = new InternetAddress(to); message.setFrom(fromAddress); message.setRecipient(Message.RecipientType.TO, toAddress); // send the message Transport transport = session.getTransport(); transport.connect(username, password); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } }1-10 package org.dllwh.core.configuration; import org.springframework.context.annotation.Configuration; /** * 把今天最好的表现当作明天最新的起点..~ * * Today the best performance as tomorrow newest starter! * * @类描述: 多数据源配置 * @创建者: 皇族灬战狼 * @联系方式: * @创建时间: 2018年10月10日 下午7:10:21 * @版本: V1.0 * @since: JDK 1.8 */ @Configuration public class DataSourceConfig { }/* * Property */ package vpCamping.object; import java.util.ArrayList; import java.util.List; import com.google.common.base.Objects; import com.google.common.collect.Lists; /** * @author LRC */ public final class SaleParameters { private String saleIdValue; private String expectedMarkValue; private List expectedSubMenuList; private List expectedSizeList; private int scrollPageFrequence; private SaleParameters(Builder builder) { this.saleIdValue = builder.saleIdValue; this.expectedMarkValue = builder.expectedMarkValue; this.expectedSizeList = builder.expectedSizeList; this.expectedSubMenuList = builder.expectedSubMenuList; this.scrollPageFrequence = builder.scrollPageFrequence; } /** * @return the saleIdValue */ public String getSaleIdValue() { return saleIdValue; } /** * @return the expectedMarkValue */ public String getExpectedMarkValue() { return expectedMarkValue; } /** * @return the expectedSubMenuList */ public List getExpectedSubMenuList() { return expectedSubMenuList; } /** * @return the expectedSizeList */ public List getExpectedSizeList() { return expectedSizeList; } /** * @return the scrollPageFrequence */ public int getScrollPageFrequence() { return scrollPageFrequence; } @Override public int hashCode() { return Objects.hashCode(saleIdValue, expectedMarkValue, expectedSubMenuList, expectedSizeList, scrollPageFrequence); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } final SaleParameters other = (SaleParameters) obj; return Objects.equal(this.saleIdValue, other.saleIdValue) && Objects.equal(this.expectedMarkValue, other.expectedMarkValue) && Objects.equal(this.expectedSubMenuList, other.expectedSubMenuList) && Objects.equal(this.expectedSizeList, other.expectedSizeList) && Objects.equal(this.scrollPageFrequence, other.scrollPageFrequence); } public static final class Builder { private String saleIdValue; private String expectedMarkValue; private List expectedSubMenuList; private List expectedSizeList; private int scrollPageFrequence; public Builder() { } public Builder(SaleParameters saleParameters) { this.saleIdValue = saleParameters.saleIdValue; this.expectedMarkValue = saleParameters.expectedMarkValue; this.expectedSizeList = Lists.newArrayList(saleParameters.expectedSizeList); this.expectedSubMenuList = Lists.newArrayList(saleParameters.expectedSubMenuList); this.scrollPageFrequence = saleParameters.scrollPageFrequence; } public Builder withSaleIdValue(String saleIdValue) { this.saleIdValue = saleIdValue; return this; } public Builder withExpectedMarkValue(String expectedMarkValue) { this.expectedMarkValue = expectedMarkValue; return this; } public Builder withExpectedSubMenuList(List expectedSubMenuList) { this.expectedSubMenuList = new ArrayList(expectedSubMenuList); return this; } public Builder withExpecedSizeList(List expecedSizeList) { this.expectedSizeList = new ArrayList(expecedSizeList); return this; } public Builder withScrollPageFrequence(int scrollPageFrequence) { this.scrollPageFrequence = scrollPageFrequence; return this; } public SaleParameters build() { return new SaleParameters(this); } } } package org.nhindirect.policy.impl; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; import org.nhindirect.policy.PolicyOperator; import org.nhindirect.policy.PolicyValue; import org.nhindirect.policy.PolicyValueFactory; public class UnaryIntegerPolicyOperatorExecutor_executeTest { @Test public void testExecute_size_assertResults() { // size 1 PolicyValue> op1 = PolicyValueFactory.getInstance(Arrays.asList("A")); UnaryIntegerPolicyOperatorExecutor> operator = new UnaryIntegerPolicyOperatorExecutor>(op1, PolicyOperator.SIZE); assertEquals(1, operator.execute().getPolicyValue().intValue()); // size 0 op1 = PolicyValueFactory.getInstance(Arrays.asList(new String[] {})); operator = new UnaryIntegerPolicyOperatorExecutor>(op1, PolicyOperator.SIZE); assertEquals(0, operator.execute().getPolicyValue().intValue()); } } 1-10 package edu.pse.beast.types.cbmctypes; import java.util.Iterator; import java.util.List; import edu.pse.beast.electionSimulator.ElectionSimulation; import edu.pse.beast.toolbox.CodeArrayListBeautifier; import edu.pse.beast.types.InputType; public abstract class CBMCInputType extends InputType { @Override protected void getHelper() { super.helper = new CbmcHelpMethods(); } @Override public void addCheckerSpecificHeaders(CodeArrayListBeautifier code) { // add the headers CBMC needs; code.add("#include "); code.add("#include "); code.add("#include "); code.add(""); code.add("unsigned int nondet_uint();"); code.add("int nondet_int();"); code.add(""); code.add("#define assert2(x, y) __CPROVER_assert(x, y)"); code.add("#define assume(x) __CPROVER_assume(x)"); code.add(""); } public String getVoteDescriptionString(List> origVotes) { String votesString = ""; int voterIndex = 0; for (Iterator> iterator = origVotes.iterator(); iterator.hasNext();) { //iterate over the voters List list = (List) iterator.next(); String oneVoter = ""; try { oneVoter = ElectionSimulation.getVoterName(voterIndex); } catch (Exception e) { oneVoter = "" + voterIndex; } oneVoter = oneVoter + ": "; voterIndex++; int partyIndex = 0; for (Iterator iterator2 = list.iterator(); iterator2.hasNext();) { //iterate over the candidates String voteAmount = (String) iterator2.next(); try { oneVoter = oneVoter + ElectionSimulation.getPartyName(partyIndex); } catch (Exception e) { oneVoter = "" + partyIndex; } oneVoter = oneVoter + ": " + voteAmount + ", "; partyIndex++; } votesString = votesString + oneVoter + "\n"; } return votesString; } } package server.security; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import org.pac4j.core.authorization.authorizer.ProfileAuthorizer; import org.pac4j.core.context.WebContext; import org.pac4j.core.exception.HttpAction; import org.pac4j.core.exception.TechnicalException; import org.pac4j.core.profile.CommonProfile; import org.pac4j.oauth.profile.facebook.FacebookProfile; import server.entity.TriFunction; import server.service.DatabaseService; import java.util.List; import java.util.stream.Stream; import static org.pac4j.core.exception.HttpAction.redirect; import static org.pac4j.core.util.CommonHelper.addParameter; import static server.router.AuthRouter.AUTH_LOGOUT; import static server.router.DatabaseRouter.DISPLAY_MESSAGE; import static server.router.UiRouter.UI_LOGIN; import static server.service.DatabaseService.Column.*; import static server.service.DatabaseService.getRows; import static server.util.StringUtils.genString; import static server.util.StringUtils.hash; /** * Authorizer that checks against database whether authenticated user is allowed to access resources. */ public class DatabaseAuthorizer extends ProfileAuthorizer { public static final String UNAUTHORIZED = "AUTHORIZER_UNAUTHORIZED"; public static final String URL = "url"; private final DatabaseService database; public DatabaseAuthorizer(DatabaseService database) { this.database = database; } // TODO: 19.05.2017 enum is short but ugly -> rewrite // TODO: 19.05.2017 database stuff is sync -> use worker or async pac4j /** * Checks whether Pac4j user profile is authorized. */ @Override protected boolean isProfileAuthorized(WebContext context, CommonProfile profile) { return profile != null && ProfileAuthorizer.isAuthorized(database, profile, getRows(database.getUser(profile.getEmail()).rxSetHandler().toBlocking().value())); } @Override public boolean isAuthorized(WebContext context, List profiles) throws HttpAction { return isAnyAuthorized(context, profiles); } /** * On error user is deauthenticated and redirected to login screen with appropriate message. */ @Override protected boolean handleError(WebContext context) throws HttpAction { throw redirect(UNAUTHORIZED, context, addParameter(AUTH_LOGOUT, URL, addParameter(UI_LOGIN, DISPLAY_MESSAGE, UNAUTHORIZED))); } /** * Defines authorization methods for different Pac4j profiles. */ public enum ProfileAuthorizer { FACEBOOK(FacebookProfile.class, oAuth2Authorization()), GOOGLE(GoogleProfile.class, oAuth2Authorization()), IDCARD(IdCardProfile.class, (IdCardProfile p, Stream stream, DatabaseService database) -> stream .anyMatch(json -> p.getSerial().equals(json.getString(USERNAME.getName()))) || database.insertUser(p.getSerial(), genString(), p.getFirstName(), p.getFamilyName()) .rxSetHandler().toBlocking().value() != null), FORM(FormProfile.class, (FormProfile p, Stream stream, DatabaseService database) -> stream .filter(json -> json.getString(USERNAME.getName()).equals(p.getEmail())) .filter(json -> json.getString(VERIFIED.getName()).equals("1")) .anyMatch(json -> hash(p.getPassword(), p.getSalt()).equals(json.getString(PASSWORD.getName())))); private final Class type; private final TriFunction, DatabaseService, Boolean> checker; ProfileAuthorizer(Class type, TriFunction, DatabaseService, Boolean> checker) { this.type = type; this.checker = uncheckedCast(checker); } /** * Checks profile against defined authorizers. */ public static boolean isAuthorized(DatabaseService database, CommonProfile profile, JsonArray users) { for (ProfileAuthorizer authorizer : values()) { if (authorizer.type.isInstance(profile)) { return authorizer.checker.apply(profile, users.stream().map(obj -> (JsonObject) obj), database); } } return false; } @SuppressWarnings("unchecked") private static TriFunction, DatabaseService, Boolean> uncheckedCast(TriFunction, DatabaseService, Boolean> authChecker) { return (TriFunction, DatabaseService, Boolean>) authChecker; } /** * Authorization for Facebook and Google profiles. */ private static TriFunction, DatabaseService, Boolean> oAuth2Authorization() { return (p, stream, database) -> { boolean isAuthorized = stream.anyMatch(json -> json.getString(USERNAME.getName()).equals(p.getEmail())); if (isAuthorized) { return true; } if (p.getEmail() == null) { // TODO: 2.03.2017 redirect user to login with message: "you need to allow access to email" throw new TechnicalException("User email not found."); } return database.insertUser(p.getEmail(), genString(), p.getFirstName(), p.getFamilyName()) .rxSetHandler().toBlocking().value() != null; }; } } }package com.cgfay.media.recorder; import android.media.AudioFormat; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.ShortBuffer; /** * 音频倍速转码器, reference from ExoPlayer's SonicAudioProcessor */ public final class AudioTranscoder { /** * A value for various fields to indicate that the field's value is unknown or not applicable. */ public static final int NO_VALUE = -1; /** * An empty, direct {@link ByteBuffer}. */ private ByteBuffer EMPTY_BUFFER = ByteBuffer.allocateDirect(0).order(ByteOrder.nativeOrder()); /** * The maximum allowed playback speed in {@link #setSpeed(float)}. */ public static final float MAXIMUM_SPEED = 8.0f; /** * The minimum allowed playback speed in {@link #setSpeed(float)}. */ public static final float MINIMUM_SPEED = 0.1f; /** * The maximum allowed pitch in {@link #setPitch(float)}. */ public static final float MAXIMUM_PITCH = 8.0f; /** * The minimum allowed pitch in {@link #setPitch(float)}. */ public static final float MINIMUM_PITCH = 0.1f; /** * Indicates that the output sample rate should be the same as the input. */ public static final int SAMPLE_RATE_NO_CHANGE = -1; /** * The threshold below which the difference between two pitch/speed factors is negligible. */ private static final float CLOSE_THRESHOLD = 0.01f; /** * The minimum number of output bytes at which the speedup is calculated using the input/output * byte counts, rather than using the current playback parameters speed. */ private static final int MIN_BYTES_FOR_SPEEDUP_CALCULATION = 1024; private int pendingOutputSampleRateHz; private int channelCount; private int sampleRateHz; private Sonic sonic; private float speed; private float pitch; private int outputSampleRateHz; private ByteBuffer buffer; private ShortBuffer shortBuffer; private ByteBuffer outputBuffer; private long inputBytes; private long outputBytes; private boolean inputEnded; /** * Creates a new audio processor. */ public AudioTranscoder() { speed = 1f; pitch = 1f; channelCount = NO_VALUE; sampleRateHz = NO_VALUE; outputSampleRateHz = NO_VALUE; buffer = EMPTY_BUFFER; shortBuffer = buffer.asShortBuffer(); outputBuffer = EMPTY_BUFFER; pendingOutputSampleRateHz = SAMPLE_RATE_NO_CHANGE; } /** * Sets the playback speed. The new speed will take effect after a call to {@link #flush()}. * * @param speed The requested new playback speed. * @return The actual new playback speed. */ public float setSpeed(float speed) { this.speed = constrainValue(speed, MINIMUM_SPEED, MAXIMUM_SPEED); return this.speed; } /** * Sets the playback pitch. The new pitch will take effect after a call to {@link #flush()}. * * @param pitch The requested new pitch. * @return The actual new pitch. */ public float setPitch(float pitch) { this.pitch = constrainValue(pitch, MINIMUM_PITCH, MAXIMUM_PITCH); return pitch; } /** * Sets the sample rate for output audio, in hertz. Pass {@link #SAMPLE_RATE_NO_CHANGE} to output * audio at the same sample rate as the input. After calling this method, call * {@link #configure(int, int, int)} to start using the new sample rate. * * @param sampleRateHz The sample rate for output audio, in hertz. * @see #configure(int, int, int) */ public void setOutputSampleRateHz(int sampleRateHz) { pendingOutputSampleRateHz = sampleRateHz; } /** * Returns the specified duration scaled to take into account the speedup factor of this instance, * in the same units as {@code duration}. * * @param duration The duration to scale taking into account speedup. * @return The specified duration scaled to take into account speedup, in the same units as * {@code duration}. */ public long scaleDurationForSpeedup(long duration) { if (outputBytes >= MIN_BYTES_FOR_SPEEDUP_CALCULATION) { return outputSampleRateHz == sampleRateHz ? scaleLargeTimestamp(duration, inputBytes, outputBytes) : scaleLargeTimestamp(duration, inputBytes * outputSampleRateHz, outputBytes * sampleRateHz); } else { return (long) ((double) speed * duration); } } /** * Configures the processor to process input audio with the specified format. After calling this * method, {@link #isActive()} returns whether the processor needs to handle buffers; if not, the * processor will not accept any buffers until it is reconfigured. Returns {@code true} if the * processor must be flushed, or if the value returned by {@link #isActive()} has changed as a * result of the call. If it's active, {@link #getOutputSampleRateHz()}, * {@link #getOutputChannelCount()} and {@link #getOutputEncoding()} return the processor's output * format. * * @param sampleRateHz The sample rate of input audio in Hz. * @param channelCount The number of interleaved channels in input audio. * @param encoding The encoding of input audio. * @return {@code true} if the processor must be flushed or the value returned by * {@link #isActive()} has changed as a result of the call. * @throws UnhandledFormatException Thrown if the specified format can't be handled as input. */ public boolean configure(int sampleRateHz, int channelCount, int encoding) throws UnhandledFormatException { if (encoding != AudioFormat.ENCODING_PCM_16BIT) { throw new UnhandledFormatException(sampleRateHz, channelCount, encoding); } int outputSampleRateHz = pendingOutputSampleRateHz == SAMPLE_RATE_NO_CHANGE ? sampleRateHz : pendingOutputSampleRateHz; if (this.sampleRateHz == sampleRateHz && this.channelCount == channelCount && this.outputSampleRateHz == outputSampleRateHz) { return false; } this.sampleRateHz = sampleRateHz; this.channelCount = channelCount; this.outputSampleRateHz = outputSampleRateHz; return true; } /** * Returns whether the processor is configured and active. */ public boolean isActive() { return Math.abs(speed - 1f) >= CLOSE_THRESHOLD || Math.abs(pitch - 1f) >= CLOSE_THRESHOLD || outputSampleRateHz != sampleRateHz; } /** * Returns the number of audio channels in the data output by the processor. The value may change * as a result of calling {@link #configure(int, int, int)} and is undefined if the instance is * not active. */ public int getOutputChannelCount() { return channelCount; } /** * Returns the audio encoding used in the data output by the processor. The value may change as a * result of calling {@link #configure(int, int, int)} and is undefined if the instance is not * active. */ public int getOutputEncoding() { return AudioFormat.ENCODING_PCM_16BIT; } /** * Returns the sample rate of audio output by the processor, in hertz. The value may change as a * result of calling {@link #configure(int, int, int)} and is undefined if the instance is not * active. */ public int getOutputSampleRateHz() { return outputSampleRateHz; } /** * Queues audio data between the position and limit of the input {@code buffer} for processing. * {@code buffer} must be a direct byte buffer with native byte order. Its contents are treated as * read-only. Its position will be advanced by the number of bytes consumed (which may be zero). * The caller retains ownership of the provided buffer. Calling this method invalidates any * previous buffer returned by {@link #getOutput()}. * * @param inputBuffer The input buffer to process. */ public void queueInput(ByteBuffer inputBuffer) { if (inputBuffer.hasRemaining()) { ShortBuffer shortBuffer = inputBuffer.asShortBuffer(); int inputSize = inputBuffer.remaining(); inputBytes += inputSize; sonic.queueInput(shortBuffer); inputBuffer.position(inputBuffer.position() + inputSize); } int outputSize = sonic.getSamplesAvailable() * channelCount * 2; if (outputSize > 0) { if (buffer.capacity() < outputSize) { buffer = ByteBuffer.allocateDirect(outputSize).order(ByteOrder.nativeOrder()); shortBuffer = buffer.asShortBuffer(); } else { buffer.clear(); shortBuffer.clear(); } sonic.getOutput(shortBuffer); outputBytes += outputSize; buffer.limit(outputSize); outputBuffer = buffer; } } /** * Queues an end of stream signal. After this method has been called, * {@link #queueInput(ByteBuffer)} may not be called until after the next call to * {@link #flush()}. Calling {@link #getOutput()} will return any remaining output data. Multiple * calls may be required to read all of the remaining output data. {@link #isEnded()} will return * {@code true} once all remaining output data has been read. */ public void endOfStream() { sonic.queueEndOfStream(); inputEnded = true; } /** * Returns a buffer containing processed output data between its position and limit. The buffer * will always be a direct byte buffer with native byte order. Calling this method invalidates any * previously returned buffer. The buffer will be empty if no output is available. * * @return A buffer containing processed output data between its position and limit. */ public ByteBuffer getOutput() { ByteBuffer outputBuffer = this.outputBuffer; this.outputBuffer = EMPTY_BUFFER; return outputBuffer; } /** * Returns whether this processor will return no more output from {@link #getOutput()} until it * has been {@link #flush()}ed and more input has been queued. */ public boolean isEnded() { return inputEnded && (sonic == null || sonic.getSamplesAvailable() == 0); } /** * Clears any state in preparation for receiving a new stream of input buffers. */ public void flush() { sonic = new Sonic(sampleRateHz, channelCount, speed, pitch, outputSampleRateHz); outputBuffer = EMPTY_BUFFER; inputBytes = 0; outputBytes = 0; inputEnded = false; } /** * Resets the processor to its unconfigured state. */ public void reset() { sonic = null; buffer = EMPTY_BUFFER; shortBuffer = buffer.asShortBuffer(); outputBuffer = EMPTY_BUFFER; channelCount = NO_VALUE; sampleRateHz = NO_VALUE; outputSampleRateHz = NO_VALUE; inputBytes = 0; outputBytes = 0; inputEnded = false; pendingOutputSampleRateHz = SAMPLE_RATE_NO_CHANGE; } /** * Constrains a value to the specified bounds. * * @param value The value to constrain. * @param min The lower bound. * @param max The upper bound. * @return The constrained value {@code Math.max(min, Math.min(value, max))}. */ private static float constrainValue(float value, float min, float max) { return Math.max(min, Math.min(value, max)); } /** * Scales a large timestamp. *

* Logically, scaling consists of a multiplication followed by a division. The actual operations * performed are designed to minimize the probability of overflow. * * @param timestamp The timestamp to scale. * @param multiplier The multiplier. * @param divisor The divisor. * @return The scaled timestamp. */ private static long scaleLargeTimestamp(long timestamp, long multiplier, long divisor) { if (divisor >= multiplier && (divisor % multiplier) == 0) { long divisionFactor = divisor / multiplier; return timestamp / divisionFactor; } else if (divisor < multiplier && (multiplier % divisor) == 0) { long multiplicationFactor = multiplier / divisor; return timestamp * multiplicationFactor; } else { double multiplicationFactor = (double) multiplier / divisor; return (long) (timestamp * multiplicationFactor); } } /** * Exception thrown when a processor can't be configured for a given input audio format. */ final class UnhandledFormatException extends Exception { public UnhandledFormatException(int sampleRateHz, int channelCount, int encoding) { super("Unhandled format: " + sampleRateHz + " Hz, " + channelCount + " channels in encoding " + encoding); } } } grusso14/eprotsrc/it/finsiel/siged/mvc/presentation/actionform/protocollo/ListaEmailLogForm.java0 package it.finsiel.siged.mvc.presentation.actionform.protocollo; import it.finsiel.siged.constant.EmailConstants; import java.util.ArrayList; import java.util.Collection; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; public class ListaEmailLogForm extends ActionForm { static Logger logger = Logger.getLogger(ListaEmailLogForm.class.getName()); private int tipoEvento; private String[] emailSelezionateId; private Collection listaEmail = new ArrayList(); public ListaEmailLogForm() { } public Collection getListaEmail() { return listaEmail; } public void setListaEmail(Collection listaEmail) { this.listaEmail = listaEmail; } public void reset(ActionMapping arg0, HttpServletRequest arg1) { super.reset(arg0, arg1); tipoEvento = EmailConstants.LOG_EMAIL_INGRESSO; } public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { ActionErrors errors = new ActionErrors(); if (request.getParameter("elimina") != null) { String[] ids = getEmailSelezionateId(); if (ids == null || ids.length == 0) { errors.add("emailSelezionateId", new ActionMessage( "selezione.obbligatoria", "i log", "da eliminare")); } } else if (request.getParameter("visualizza") != null) { if (getTipoEvento() != EmailConstants.LOG_EMAIL_INGRESSO && getTipoEvento() != EmailConstants.LOG_EMAIL_USCITA && getTipoEvento() != EmailConstants.LOG_CRL) errors.add("tipoEvento", new ActionMessage( "email.logs.selezionare")); } return errors; } public int getTipoEvento() { return tipoEvento; } public void setTipoEvento(int tipoEvento) { this.tipoEvento = tipoEvento; } public String[] getEmailSelezionateId() { return emailSelezionateId; } public void setEmailSelezionateId(String[] emailSelezionateId) { this.emailSelezionateId = emailSelezionateId; } }package org.ovirt.engine.core.common.flow; /** *

 * The {@link Handler} interface allows chaining of activities in a tree-like structure.
 * It supports the following design goals:
 *
 * - divide business logic into modular, independent and reusable units
 * - allow easy implementation of complex flow charts and multiple-branch decision trees
 * - separate the business logic from the logic of the flow chart
 * - support AND OR NOT handlers, which can be used to combine other handlers
 * - be able to graphically view the whole tree using {@link Handler#print}
 * - accept a context object to share state between handlers
 * - instantiate the chain only once in the life time of the program, because all handlers
 *   are stateless - promotes dependency injection as well as less memory thrashing and gc
 *
 * A handler must return a signal about the outcome of its action when it is completed.
 * The signal is one of the {@link HandlerOutcome} entries. These signals may be interpreted
 * in different ways depending on the desired scenario and type of outcome.
 *
 * Some example usages:
 *
 * 1. Handlers transform or format data\state (e.g. similar to piped commands in linux cli):
 * - 'success' could mean 'no more handling required'
 * - 'failure' could mean 'cannot continue to next handler'
 * - 'neutral' could mean 'continue to next handler'.
 *
 * 2. Handlers are validators of user input:
 * - 'success' could mean 'current validation passed'
 * - 'failure' could mean 'current validation failed'
 * - 'neutral' might mean 'cannot decide'.
 *
 * 3. Handlers are filters of events (e.g. similar to firewall rules):
 * - 'success' could mean 'event is accepted - no other filters need be consulted'
 * - 'failure' could mean 'event is denied - no other filters need be consulted'
 * - 'neutral' could mean 'event should be passed to other filters. if there are no other filters,
 *   it is accepted'
 *
 * 
* * @param the context which holds the state of the whole operation */ public interface Handler { /** * Handle the business logic of the current node in the {@link Flow}. * The context C is passed between all handlers which make * up the flow, and should be the only object which holds * the state of the flow. Handlers can get and set state * on it, and share state among themselves with it. * * @return an outcome which is used by the process() method to determine * which handler to execute next. */ HandlerOutcome handle(C ctx) throws Exception; /** * Process the flow: * run the handle() method of this handler and branch to the next handler * according to the {@link HandlerOutcome} returned by the handle() method * @param ctx the state of the whole flow */ void process(C ctx); /** * The next handler to process if this handler is successful * @param successHandler the next handler * @return this handler */ Handler setOnSuccess(Handler successHandler); /** * The next handler to process if this handler is neutral about the outcome. * @param neutralHandler the next handler * @return this handler */ Handler setOnNeutral(Handler neutralHandler); /** * The next handler to process if this handler fails * @param failureHandler the next handler * @return this handler */ Handler setOnFailure(Handler failureHandler); /** * The next handler to process if this handler throws an exception * @param exceptionHandler the next handler * @return this handler */ Handler setOnException(Handler exceptionHandler); /** * @return name of this handler */ String getName(); /** * set name of this handler */ void setName(String name); /** * Recursively print a digraph representation of this handler * and subsequent ones. The output of this method may be inserted * into a digraph viewer (for example http://www.webgraphviz.com) * which displays the flow graph visually in order to analyze the * correctness of the flow. * @param sb accumulator of the output */ void print(StringBuilder sb); } /* * Copyright (c) 2014, Apptentive, Inc. All Rights Reserved. * Please refer to the LICENSE file for the terms and conditions * under which redistribution and use of this file is permitted. */ package com.apptentive.android.sdk.model; import com.apptentive.android.sdk.Log; import org.json.JSONException; import java.util.Date; /** * @author */ public class TimeExtendedData extends ExtendedData { private static final String KEY_TIMESTAMP = "timestamp"; private static final int VERSION = 1; @Override protected void init() { setType(Type.time); setVersion(VERSION); } public TimeExtendedData() { super(); setTimestamp(System.currentTimeMillis()); } public TimeExtendedData(String json) throws JSONException { super(json); } public TimeExtendedData(Date date) { super(); setTimestamp(date); } public TimeExtendedData(long millis) { super(); setTimestamp(millis); } public TimeExtendedData(double seconds) { super(); setTimestamp(seconds); } protected void setTimestamp(Date date) { if (date != null) { setTimestamp(date.getTime()); } else { setTimestamp(System.currentTimeMillis()); } } protected void setTimestamp(long millis) { setTimestamp(((double) millis) / 1000); } protected void setTimestamp(double dateInSeconds) { try { put(KEY_TIMESTAMP, dateInSeconds); } catch (JSONException e) { Log.w("Error adding %s to TimeExtendedData.", KEY_TIMESTAMP, e); } } } 0 package hackerrank; import linkedlist.singly.LinkedList; import linkedlist.singly.Node; public class visaTest { public static void main(String[] args) { linkedlist.singly.LinkedList list = new LinkedList(); list.addElementAtBegining("3"); list.addElementAtBegining("2"); list.addElementAtBegining("1"); list.addElementAtBegining("300"); list.addElementAtBegining("19"); list.addElementAtBegining("3"); list.addElementAtBegining("81"); list.addElementAtBegining("59"); System.out.println("Head -> " + list.head.data); Node newHead = removeNodes(list.head,3); while(newHead != null){ System.out.println(newHead.data); newHead = newHead.next; } } public static Node removeNodes(Node listHead, int x) { Node head= listHead; Node current= listHead; Node previous = listHead; int i=0; while(current != null){ if(Integer.parseInt(current.data) > x){ previous.next=current.next; current = current.next; if(i==0){ head = current; } } else{ previous = current; current = current.next; i++; } } return head; } } ag-sc/SCIOExtraction package de.uni.bielefeld.sc.hterhors.psink.scio.semanticmr.ner.groupname.templates; import java.util.ArrayList; import java.util.List; import de.hterhors.semanticmr.crf.model.AbstractFactorScope; import de.hterhors.semanticmr.crf.model.Factor; import de.hterhors.semanticmr.crf.structure.annotations.DocumentLinkedAnnotation; import de.hterhors.semanticmr.crf.templates.AbstractFeatureTemplate; import de.hterhors.semanticmr.crf.variables.Document; import de.hterhors.semanticmr.crf.variables.State; /** * WBF: first word in between if more than two words in between WBL: last word * in between if more than two words in between */ public class WBFGroupNamesTemplate_FAST extends AbstractFeatureTemplate { private static boolean WBFACTIVE = true; private static boolean WBLACTIVE = false; static class WBScope extends AbstractFactorScope { public final String annoOne; public final String annoTwo; public final String word; public final boolean first; public WBScope(AbstractFeatureTemplate template, String annoOne, String annoTwo, String word, boolean first) { super(template); this.annoOne = annoOne; this.annoTwo = annoTwo; this.word = word; this.first = first; } @Override public int implementHashCode() { return 0; } @Override public boolean implementEquals(Object obj) { return false; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; WBScope other = (WBScope) obj; if (annoOne == null) { if (other.annoOne != null) return false; } else if (!annoOne.equals(other.annoOne)) return false; if (annoTwo == null) { if (other.annoTwo != null) return false; } else if (!annoTwo.equals(other.annoTwo)) return false; if (first != other.first) return false; if (word == null) { if (other.word != null) return false; } else if (!word.equals(other.word)) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((annoOne == null) ? 0 : annoOne.hashCode()); result = prime * result + ((annoTwo == null) ? 0 : annoTwo.hashCode()); result = prime * result + (first ? 1231 : 1237); result = prime * result + ((word == null) ? 0 : word.hashCode()); return result; } } @Override public List generateFactorScopes(State state) { List factors = new ArrayList<>(); Document document = state.getInstance().getDocument(); List annotations = super.getPredictedAnnotations(state); for (int i = 0; i < annotations.size(); i++) { final int a1Index = annotations.get(i).relatedTokens.get(annotations.get(i).relatedTokens.size() - 1) .getDocTokenIndex(); for (int j = i + 1; j < annotations.size(); j++) { final int a2Index = annotations.get(j).relatedTokens.get(0).getDocTokenIndex(); if (Math.abs(a1Index - a2Index) < 3 || Math.abs(a1Index - a2Index) > 20) continue; if (a2Index < a1Index) { if (WBFACTIVE) { factors.add(new WBScope(this, annotations.get(i).getSurfaceForm(), annotations.get(j).getSurfaceForm(), document.tokenList.get(a2Index + 1).getText(), true)); } if (WBLACTIVE) { factors.add(new WBScope(this, annotations.get(i).getSurfaceForm(), annotations.get(j).getSurfaceForm(), document.tokenList.get(a1Index - 1).getText(), false)); } } else { // swap annotations if (WBFACTIVE) { factors.add(new WBScope(this, annotations.get(j).getSurfaceForm(), annotations.get(i).getSurfaceForm(), document.tokenList.get(a1Index + 1).getText(), true)); } if (WBLACTIVE) { factors.add(new WBScope(this, annotations.get(j).getSurfaceForm(), annotations.get(i).getSurfaceForm(), document.tokenList.get(a2Index - 1).getText(), false)); } } } } return factors; } @Override public void generateFeatureVector(Factor factor) { factor.getFeatureVector() .set((factor.getFactorScope().first ? "First" : "Last") + " word inbetween: <\"" + factor.getFactorScope().annoOne + "\", \"" + factor.getFactorScope().annoTwo + "\"> " + factor.getFactorScope().word, true); } } package co.yixiang.gen.domain; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; public class YxCouponTempExample { protected String orderByClause; protected boolean distinct; protected List oredCriteria; public YxCouponTempExample() { oredCriteria = new ArrayList(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public YxCouponTempExample orderBy(String orderByClause) { this.setOrderByClause(orderByClause); return this; } public YxCouponTempExample orderBy(String ... orderByClauses) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < orderByClauses.length; i++) { sb.append(orderByClauses[i]); if (i < orderByClauses.length - 1) { sb.append(" , "); } } this.setOrderByClause(sb.toString()); return this; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(this); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } public static Criteria newAndCreateCriteria() { YxCouponTempExample example = new YxCouponTempExample(); return example.createCriteria(); } public YxCouponTempExample when(boolean condition, IExampleWhen then) { if (condition) { then.example(this); } return this; } public YxCouponTempExample when(boolean condition, IExampleWhen then, IExampleWhen otherwise) { if (condition) { then.example(this); } else { otherwise.example(this); } return this; } protected abstract static class GeneratedCriteria { protected List criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList(); } public boolean isValid() { return criteria.size() > 0; } public List getAllCriteria() { return criteria; } public List getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andCouponTempIdIsNull() { addCriterion("coupon_temp_id is null"); return (Criteria) this; } public Criteria andCouponTempIdIsNotNull() { addCriterion("coupon_temp_id is not null"); return (Criteria) this; } public Criteria andCouponTempIdEqualTo(Integer value) { addCriterion("coupon_temp_id =", value, "couponTempId"); return (Criteria) this; } public Criteria andCouponTempIdEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_temp_id = ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponTempIdNotEqualTo(Integer value) { addCriterion("coupon_temp_id <>", value, "couponTempId"); return (Criteria) this; } public Criteria andCouponTempIdNotEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_temp_id <> ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponTempIdGreaterThan(Integer value) { addCriterion("coupon_temp_id >", value, "couponTempId"); return (Criteria) this; } public Criteria andCouponTempIdGreaterThanColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_temp_id > ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponTempIdGreaterThanOrEqualTo(Integer value) { addCriterion("coupon_temp_id >=", value, "couponTempId"); return (Criteria) this; } public Criteria andCouponTempIdGreaterThanOrEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_temp_id >= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponTempIdLessThan(Integer value) { addCriterion("coupon_temp_id <", value, "couponTempId"); return (Criteria) this; } public Criteria andCouponTempIdLessThanColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_temp_id < ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponTempIdLessThanOrEqualTo(Integer value) { addCriterion("coupon_temp_id <=", value, "couponTempId"); return (Criteria) this; } public Criteria andCouponTempIdLessThanOrEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_temp_id <= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponTempIdIn(List values) { addCriterion("coupon_temp_id in", values, "couponTempId"); return (Criteria) this; } public Criteria andCouponTempIdNotIn(List values) { addCriterion("coupon_temp_id not in", values, "couponTempId"); return (Criteria) this; } public Criteria andCouponTempIdBetween(Integer value1, Integer value2) { addCriterion("coupon_temp_id between", value1, value2, "couponTempId"); return (Criteria) this; } public Criteria andCouponTempIdNotBetween(Integer value1, Integer value2) { addCriterion("coupon_temp_id not between", value1, value2, "couponTempId"); return (Criteria) this; } public Criteria andCouponPriceIsNull() { addCriterion("coupon_price is null"); return (Criteria) this; } public Criteria andCouponPriceIsNotNull() { addCriterion("coupon_price is not null"); return (Criteria) this; } public Criteria andCouponPriceEqualTo(BigDecimal value) { addCriterion("coupon_price =", value, "couponPrice"); return (Criteria) this; } public Criteria andCouponPriceEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_price = ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponPriceNotEqualTo(BigDecimal value) { addCriterion("coupon_price <>", value, "couponPrice"); return (Criteria) this; } public Criteria andCouponPriceNotEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_price <> ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponPriceGreaterThan(BigDecimal value) { addCriterion("coupon_price >", value, "couponPrice"); return (Criteria) this; } public Criteria andCouponPriceGreaterThanColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_price > ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponPriceGreaterThanOrEqualTo(BigDecimal value) { addCriterion("coupon_price >=", value, "couponPrice"); return (Criteria) this; } public Criteria andCouponPriceGreaterThanOrEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_price >= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponPriceLessThan(BigDecimal value) { addCriterion("coupon_price <", value, "couponPrice"); return (Criteria) this; } public Criteria andCouponPriceLessThanColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_price < ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponPriceLessThanOrEqualTo(BigDecimal value) { addCriterion("coupon_price <=", value, "couponPrice"); return (Criteria) this; } public Criteria andCouponPriceLessThanOrEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_price <= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponPriceIn(List values) { addCriterion("coupon_price in", values, "couponPrice"); return (Criteria) this; } public Criteria andCouponPriceNotIn(List values) { addCriterion("coupon_price not in", values, "couponPrice"); return (Criteria) this; } public Criteria andCouponPriceBetween(BigDecimal value1, BigDecimal value2) { addCriterion("coupon_price between", value1, value2, "couponPrice"); return (Criteria) this; } public Criteria andCouponPriceNotBetween(BigDecimal value1, BigDecimal value2) { addCriterion("coupon_price not between", value1, value2, "couponPrice"); return (Criteria) this; } public Criteria andCouponOptionIdIsNull() { addCriterion("coupon_option_id is null"); return (Criteria) this; } public Criteria andCouponOptionIdIsNotNull() { addCriterion("coupon_option_id is not null"); return (Criteria) this; } public Criteria andCouponOptionIdEqualTo(Integer value) { addCriterion("coupon_option_id =", value, "couponOptionId"); return (Criteria) this; } public Criteria andCouponOptionIdEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_option_id = ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponOptionIdNotEqualTo(Integer value) { addCriterion("coupon_option_id <>", value, "couponOptionId"); return (Criteria) this; } public Criteria andCouponOptionIdNotEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_option_id <> ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponOptionIdGreaterThan(Integer value) { addCriterion("coupon_option_id >", value, "couponOptionId"); return (Criteria) this; } public Criteria andCouponOptionIdGreaterThanColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_option_id > ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponOptionIdGreaterThanOrEqualTo(Integer value) { addCriterion("coupon_option_id >=", value, "couponOptionId"); return (Criteria) this; } public Criteria andCouponOptionIdGreaterThanOrEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_option_id >= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponOptionIdLessThan(Integer value) { addCriterion("coupon_option_id <", value, "couponOptionId"); return (Criteria) this; } public Criteria andCouponOptionIdLessThanColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_option_id < ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponOptionIdLessThanOrEqualTo(Integer value) { addCriterion("coupon_option_id <=", value, "couponOptionId"); return (Criteria) this; } public Criteria andCouponOptionIdLessThanOrEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_option_id <= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponOptionIdIn(List values) { addCriterion("coupon_option_id in", values, "couponOptionId"); return (Criteria) this; } public Criteria andCouponOptionIdNotIn(List values) { addCriterion("coupon_option_id not in", values, "couponOptionId"); return (Criteria) this; } public Criteria andCouponOptionIdBetween(Integer value1, Integer value2) { addCriterion("coupon_option_id between", value1, value2, "couponOptionId"); return (Criteria) this; } public Criteria andCouponOptionIdNotBetween(Integer value1, Integer value2) { addCriterion("coupon_option_id not between", value1, value2, "couponOptionId"); return (Criteria) this; } public Criteria andCouponStartTimeIsNull() { addCriterion("coupon_start_time is null"); return (Criteria) this; } public Criteria andCouponStartTimeIsNotNull() { addCriterion("coupon_start_time is not null"); return (Criteria) this; } public Criteria andCouponStartTimeEqualTo(Date value) { addCriterion("coupon_start_time =", value, "couponStartTime"); return (Criteria) this; } public Criteria andCouponStartTimeEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_start_time = ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponStartTimeNotEqualTo(Date value) { addCriterion("coupon_start_time <>", value, "couponStartTime"); return (Criteria) this; } public Criteria andCouponStartTimeNotEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_start_time <> ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponStartTimeGreaterThan(Date value) { addCriterion("coupon_start_time >", value, "couponStartTime"); return (Criteria) this; } public Criteria andCouponStartTimeGreaterThanColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_start_time > ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponStartTimeGreaterThanOrEqualTo(Date value) { addCriterion("coupon_start_time >=", value, "couponStartTime"); return (Criteria) this; } public Criteria andCouponStartTimeGreaterThanOrEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_start_time >= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponStartTimeLessThan(Date value) { addCriterion("coupon_start_time <", value, "couponStartTime"); return (Criteria) this; } public Criteria andCouponStartTimeLessThanColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_start_time < ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponStartTimeLessThanOrEqualTo(Date value) { addCriterion("coupon_start_time <=", value, "couponStartTime"); return (Criteria) this; } public Criteria andCouponStartTimeLessThanOrEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_start_time <= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponStartTimeIn(List values) { addCriterion("coupon_start_time in", values, "couponStartTime"); return (Criteria) this; } public Criteria andCouponStartTimeNotIn(List values) { addCriterion("coupon_start_time not in", values, "couponStartTime"); return (Criteria) this; } public Criteria andCouponStartTimeBetween(Date value1, Date value2) { addCriterion("coupon_start_time between", value1, value2, "couponStartTime"); return (Criteria) this; } public Criteria andCouponStartTimeNotBetween(Date value1, Date value2) { addCriterion("coupon_start_time not between", value1, value2, "couponStartTime"); return (Criteria) this; } public Criteria andCouponTimeOutIsNull() { addCriterion("coupon_time_out is null"); return (Criteria) this; } public Criteria andCouponTimeOutIsNotNull() { addCriterion("coupon_time_out is not null"); return (Criteria) this; } public Criteria andCouponTimeOutEqualTo(Date value) { addCriterion("coupon_time_out =", value, "couponTimeOut"); return (Criteria) this; } public Criteria andCouponTimeOutEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_time_out = ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponTimeOutNotEqualTo(Date value) { addCriterion("coupon_time_out <>", value, "couponTimeOut"); return (Criteria) this; } public Criteria andCouponTimeOutNotEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_time_out <> ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponTimeOutGreaterThan(Date value) { addCriterion("coupon_time_out >", value, "couponTimeOut"); return (Criteria) this; } public Criteria andCouponTimeOutGreaterThanColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_time_out > ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponTimeOutGreaterThanOrEqualTo(Date value) { addCriterion("coupon_time_out >=", value, "couponTimeOut"); return (Criteria) this; } public Criteria andCouponTimeOutGreaterThanOrEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_time_out >= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponTimeOutLessThan(Date value) { addCriterion("coupon_time_out <", value, "couponTimeOut"); return (Criteria) this; } public Criteria andCouponTimeOutLessThanColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_time_out < ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponTimeOutLessThanOrEqualTo(Date value) { addCriterion("coupon_time_out <=", value, "couponTimeOut"); return (Criteria) this; } public Criteria andCouponTimeOutLessThanOrEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_time_out <= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponTimeOutIn(List values) { addCriterion("coupon_time_out in", values, "couponTimeOut"); return (Criteria) this; } public Criteria andCouponTimeOutNotIn(List values) { addCriterion("coupon_time_out not in", values, "couponTimeOut"); return (Criteria) this; } public Criteria andCouponTimeOutBetween(Date value1, Date value2) { addCriterion("coupon_time_out between", value1, value2, "couponTimeOut"); return (Criteria) this; } public Criteria andCouponTimeOutNotBetween(Date value1, Date value2) { addCriterion("coupon_time_out not between", value1, value2, "couponTimeOut"); return (Criteria) this; } public Criteria andCouponImgIsNull() { addCriterion("coupon_img is null"); return (Criteria) this; } public Criteria andCouponImgIsNotNull() { addCriterion("coupon_img is not null"); return (Criteria) this; } public Criteria andCouponImgEqualTo(String value) { addCriterion("coupon_img =", value, "couponImg"); return (Criteria) this; } public Criteria andCouponImgEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_img = ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponImgNotEqualTo(String value) { addCriterion("coupon_img <>", value, "couponImg"); return (Criteria) this; } public Criteria andCouponImgNotEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_img <> ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponImgGreaterThan(String value) { addCriterion("coupon_img >", value, "couponImg"); return (Criteria) this; } public Criteria andCouponImgGreaterThanColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_img > ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponImgGreaterThanOrEqualTo(String value) { addCriterion("coupon_img >=", value, "couponImg"); return (Criteria) this; } public Criteria andCouponImgGreaterThanOrEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_img >= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponImgLessThan(String value) { addCriterion("coupon_img <", value, "couponImg"); return (Criteria) this; } public Criteria andCouponImgLessThanColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_img < ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponImgLessThanOrEqualTo(String value) { addCriterion("coupon_img <=", value, "couponImg"); return (Criteria) this; } public Criteria andCouponImgLessThanOrEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_img <= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponImgLike(String value) { addCriterion("coupon_img like", value, "couponImg"); return (Criteria) this; } public Criteria andCouponImgNotLike(String value) { addCriterion("coupon_img not like", value, "couponImg"); return (Criteria) this; } public Criteria andCouponImgIn(List values) { addCriterion("coupon_img in", values, "couponImg"); return (Criteria) this; } public Criteria andCouponImgNotIn(List values) { addCriterion("coupon_img not in", values, "couponImg"); return (Criteria) this; } public Criteria andCouponImgBetween(String value1, String value2) { addCriterion("coupon_img between", value1, value2, "couponImg"); return (Criteria) this; } public Criteria andCouponImgNotBetween(String value1, String value2) { addCriterion("coupon_img not between", value1, value2, "couponImg"); return (Criteria) this; } public Criteria andCouponNameIsNull() { addCriterion("coupon_name is null"); return (Criteria) this; } public Criteria andCouponNameIsNotNull() { addCriterion("coupon_name is not null"); return (Criteria) this; } public Criteria andCouponNameEqualTo(String value) { addCriterion("coupon_name =", value, "couponName"); return (Criteria) this; } public Criteria andCouponNameEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_name = ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponNameNotEqualTo(String value) { addCriterion("coupon_name <>", value, "couponName"); return (Criteria) this; } public Criteria andCouponNameNotEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_name <> ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponNameGreaterThan(String value) { addCriterion("coupon_name >", value, "couponName"); return (Criteria) this; } public Criteria andCouponNameGreaterThanColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_name > ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponNameGreaterThanOrEqualTo(String value) { addCriterion("coupon_name >=", value, "couponName"); return (Criteria) this; } public Criteria andCouponNameGreaterThanOrEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_name >= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponNameLessThan(String value) { addCriterion("coupon_name <", value, "couponName"); return (Criteria) this; } public Criteria andCouponNameLessThanColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_name < ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponNameLessThanOrEqualTo(String value) { addCriterion("coupon_name <=", value, "couponName"); return (Criteria) this; } public Criteria andCouponNameLessThanOrEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_name <= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponNameLike(String value) { addCriterion("coupon_name like", value, "couponName"); return (Criteria) this; } public Criteria andCouponNameNotLike(String value) { addCriterion("coupon_name not like", value, "couponName"); return (Criteria) this; } public Criteria andCouponNameIn(List values) { addCriterion("coupon_name in", values, "couponName"); return (Criteria) this; } public Criteria andCouponNameNotIn(List values) { addCriterion("coupon_name not in", values, "couponName"); return (Criteria) this; } public Criteria andCouponNameBetween(String value1, String value2) { addCriterion("coupon_name between", value1, value2, "couponName"); return (Criteria) this; } public Criteria andCouponNameNotBetween(String value1, String value2) { addCriterion("coupon_name not between", value1, value2, "couponName"); return (Criteria) this; } public Criteria andCouponTypeIsNull() { addCriterion("coupon_type is null"); return (Criteria) this; } public Criteria andCouponTypeIsNotNull() { addCriterion("coupon_type is not null"); return (Criteria) this; } public Criteria andCouponTypeEqualTo(Integer value) { addCriterion("coupon_type =", value, "couponType"); return (Criteria) this; } public Criteria andCouponTypeEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_type = ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponTypeNotEqualTo(Integer value) { addCriterion("coupon_type <>", value, "couponType"); return (Criteria) this; } public Criteria andCouponTypeNotEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_type <> ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponTypeGreaterThan(Integer value) { addCriterion("coupon_type >", value, "couponType"); return (Criteria) this; } public Criteria andCouponTypeGreaterThanColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_type > ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponTypeGreaterThanOrEqualTo(Integer value) { addCriterion("coupon_type >=", value, "couponType"); return (Criteria) this; } public Criteria andCouponTypeGreaterThanOrEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_type >= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponTypeLessThan(Integer value) { addCriterion("coupon_type <", value, "couponType"); return (Criteria) this; } public Criteria andCouponTypeLessThanColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_type < ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponTypeLessThanOrEqualTo(Integer value) { addCriterion("coupon_type <=", value, "couponType"); return (Criteria) this; } public Criteria andCouponTypeLessThanOrEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("coupon_type <= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCouponTypeIn(List values) { addCriterion("coupon_type in", values, "couponType"); return (Criteria) this; } public Criteria andCouponTypeNotIn(List values) { addCriterion("coupon_type not in", values, "couponType"); return (Criteria) this; } public Criteria andCouponTypeBetween(Integer value1, Integer value2) { addCriterion("coupon_type between", value1, value2, "couponType"); return (Criteria) this; } public Criteria andCouponTypeNotBetween(Integer value1, Integer value2) { addCriterion("coupon_type not between", value1, value2, "couponType"); return (Criteria) this; } public Criteria andShopIdIsNull() { addCriterion("shop_id is null"); return (Criteria) this; } public Criteria andShopIdIsNotNull() { addCriterion("shop_id is not null"); return (Criteria) this; } public Criteria andShopIdEqualTo(Integer value) { addCriterion("shop_id =", value, "shopId"); return (Criteria) this; } public Criteria andShopIdEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("shop_id = ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andShopIdNotEqualTo(Integer value) { addCriterion("shop_id <>", value, "shopId"); return (Criteria) this; } public Criteria andShopIdNotEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("shop_id <> ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andShopIdGreaterThan(Integer value) { addCriterion("shop_id >", value, "shopId"); return (Criteria) this; } public Criteria andShopIdGreaterThanColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("shop_id > ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andShopIdGreaterThanOrEqualTo(Integer value) { addCriterion("shop_id >=", value, "shopId"); return (Criteria) this; } public Criteria andShopIdGreaterThanOrEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("shop_id >= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andShopIdLessThan(Integer value) { addCriterion("shop_id <", value, "shopId"); return (Criteria) this; } public Criteria andShopIdLessThanColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("shop_id < ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andShopIdLessThanOrEqualTo(Integer value) { addCriterion("shop_id <=", value, "shopId"); return (Criteria) this; } public Criteria andShopIdLessThanOrEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("shop_id <= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andShopIdIn(List values) { addCriterion("shop_id in", values, "shopId"); return (Criteria) this; } public Criteria andShopIdNotIn(List values) { addCriterion("shop_id not in", values, "shopId"); return (Criteria) this; } public Criteria andShopIdBetween(Integer value1, Integer value2) { addCriterion("shop_id between", value1, value2, "shopId"); return (Criteria) this; } public Criteria andShopIdNotBetween(Integer value1, Integer value2) { addCriterion("shop_id not between", value1, value2, "shopId"); return (Criteria) this; } public Criteria andClassTypeIsNull() { addCriterion("class_type is null"); return (Criteria) this; } public Criteria andClassTypeIsNotNull() { addCriterion("class_type is not null"); return (Criteria) this; } public Criteria andClassTypeEqualTo(Integer value) { addCriterion("class_type =", value, "classType"); return (Criteria) this; } public Criteria andClassTypeEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("class_type = ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andClassTypeNotEqualTo(Integer value) { addCriterion("class_type <>", value, "classType"); return (Criteria) this; } public Criteria andClassTypeNotEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("class_type <> ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andClassTypeGreaterThan(Integer value) { addCriterion("class_type >", value, "classType"); return (Criteria) this; } public Criteria andClassTypeGreaterThanColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("class_type > ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andClassTypeGreaterThanOrEqualTo(Integer value) { addCriterion("class_type >=", value, "classType"); return (Criteria) this; } public Criteria andClassTypeGreaterThanOrEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("class_type >= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andClassTypeLessThan(Integer value) { addCriterion("class_type <", value, "classType"); return (Criteria) this; } public Criteria andClassTypeLessThanColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("class_type < ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andClassTypeLessThanOrEqualTo(Integer value) { addCriterion("class_type <=", value, "classType"); return (Criteria) this; } public Criteria andClassTypeLessThanOrEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("class_type <= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andClassTypeIn(List values) { addCriterion("class_type in", values, "classType"); return (Criteria) this; } public Criteria andClassTypeNotIn(List values) { addCriterion("class_type not in", values, "classType"); return (Criteria) this; } public Criteria andClassTypeBetween(Integer value1, Integer value2) { addCriterion("class_type between", value1, value2, "classType"); return (Criteria) this; } public Criteria andClassTypeNotBetween(Integer value1, Integer value2) { addCriterion("class_type not between", value1, value2, "classType"); return (Criteria) this; } public Criteria andCrtTimeIsNull() { addCriterion("crt_time is null"); return (Criteria) this; } public Criteria andCrtTimeIsNotNull() { addCriterion("crt_time is not null"); return (Criteria) this; } public Criteria andCrtTimeEqualTo(Date value) { addCriterion("crt_time =", value, "crtTime"); return (Criteria) this; } public Criteria andCrtTimeEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("crt_time = ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCrtTimeNotEqualTo(Date value) { addCriterion("crt_time <>", value, "crtTime"); return (Criteria) this; } public Criteria andCrtTimeNotEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("crt_time <> ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCrtTimeGreaterThan(Date value) { addCriterion("crt_time >", value, "crtTime"); return (Criteria) this; } public Criteria andCrtTimeGreaterThanColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("crt_time > ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCrtTimeGreaterThanOrEqualTo(Date value) { addCriterion("crt_time >=", value, "crtTime"); return (Criteria) this; } public Criteria andCrtTimeGreaterThanOrEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("crt_time >= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCrtTimeLessThan(Date value) { addCriterion("crt_time <", value, "crtTime"); return (Criteria) this; } public Criteria andCrtTimeLessThanColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("crt_time < ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCrtTimeLessThanOrEqualTo(Date value) { addCriterion("crt_time <=", value, "crtTime"); return (Criteria) this; } public Criteria andCrtTimeLessThanOrEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("crt_time <= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andCrtTimeIn(List values) { addCriterion("crt_time in", values, "crtTime"); return (Criteria) this; } public Criteria andCrtTimeNotIn(List values) { addCriterion("crt_time not in", values, "crtTime"); return (Criteria) this; } public Criteria andCrtTimeBetween(Date value1, Date value2) { addCriterion("crt_time between", value1, value2, "crtTime"); return (Criteria) this; } public Criteria andCrtTimeNotBetween(Date value1, Date value2) { addCriterion("crt_time not between", value1, value2, "crtTime"); return (Criteria) this; } public Criteria andUpdTimeIsNull() { addCriterion("upd_time is null"); return (Criteria) this; } public Criteria andUpdTimeIsNotNull() { addCriterion("upd_time is not null"); return (Criteria) this; } public Criteria andUpdTimeEqualTo(Date value) { addCriterion("upd_time =", value, "updTime"); return (Criteria) this; } public Criteria andUpdTimeEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("upd_time = ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andUpdTimeNotEqualTo(Date value) { addCriterion("upd_time <>", value, "updTime"); return (Criteria) this; } public Criteria andUpdTimeNotEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("upd_time <> ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andUpdTimeGreaterThan(Date value) { addCriterion("upd_time >", value, "updTime"); return (Criteria) this; } public Criteria andUpdTimeGreaterThanColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("upd_time > ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andUpdTimeGreaterThanOrEqualTo(Date value) { addCriterion("upd_time >=", value, "updTime"); return (Criteria) this; } public Criteria andUpdTimeGreaterThanOrEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("upd_time >= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andUpdTimeLessThan(Date value) { addCriterion("upd_time <", value, "updTime"); return (Criteria) this; } public Criteria andUpdTimeLessThanColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("upd_time < ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andUpdTimeLessThanOrEqualTo(Date value) { addCriterion("upd_time <=", value, "updTime"); return (Criteria) this; } public Criteria andUpdTimeLessThanOrEqualToColumn(YxCouponTemp.Column column) { addCriterion(new StringBuilder("upd_time <= ").append(column.getEscapedColumnName()).toString()); return (Criteria) this; } public Criteria andUpdTimeIn(List values) { addCriterion("upd_time in", values, "updTime"); return (Criteria) this; } public Criteria andUpdTimeNotIn(List values) { addCriterion("upd_time not in", values, "updTime"); return (Criteria) this; } public Criteria andUpdTimeBetween(Date value1, Date value2) { addCriterion("upd_time between", value1, value2, "updTime"); return (Criteria) this; } public Criteria andUpdTimeNotBetween(Date value1, Date value2) { addCriterion("upd_time not between", value1, value2, "updTime"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { private YxCouponTempExample example; protected Criteria(YxCouponTempExample example) { super(); this.example = example; } public YxCouponTempExample example() { return this.example; } @Deprecated public Criteria andIf(boolean ifAdd, ICriteriaAdd add) { if (ifAdd) { add.add(this); } return this; } public Criteria when(boolean condition, ICriteriaWhen then) { if (condition) { then.criteria(this); } return this; } public Criteria when(boolean condition, ICriteriaWhen then, ICriteriaWhen otherwise) { if (condition) { then.criteria(this); } else { otherwise.criteria(this); } return this; } @Deprecated public interface ICriteriaAdd { Criteria add(Criteria add); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } public interface ICriteriaWhen { void criteria(Criteria criteria); } public interface IExampleWhen { void example(co.yixiang.gen.domain.YxCouponTempExample example); } }s1n7ax/circles-life-assignment package org.s1n7ax.silenium.core; import java.lang.reflect.Method; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import org.openqa.selenium.WebDriver; import org.s1n7ax.silenium.core.annotations.TestMeta; import org.s1n7ax.silenium.core.impl.DefaultDriverManagerFactory; import org.s1n7ax.silenium.core.impl.DefaultWebDriverFactory; import org.testng.ITestContext; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Optional; import org.testng.annotations.Parameters; public abstract class WebAutomationBase implements WebDriverManagerFactoryConfigurer, WebDriverFactoryConfigurer { private final ThreadLocal threadLocalDriver = new ThreadLocal<>(); private final Map driverManagerMap = new ConcurrentHashMap<>(); protected final WebDriver getDriver() { return threadLocalDriver.get(); } private void setDriver(final WebDriver driver) { threadLocalDriver.set(driver); } @Override public WebDriverManagerFactory getWebDriverManagerFactory() { return new DefaultDriverManagerFactory(); } @Override public WebDriverFactory getWebDriverFactory() { return new DefaultWebDriverFactory(); } @Parameters({ "browser", "base.url", "timeout.implicit", "silenium.timeout.pageload", "silenium.timeout.script" }) @BeforeMethod() protected synchronized final void defaultBeforeTest1(@Optional final String browser, @Optional final String baseURL, @Optional("0") final String implicitTimeout, @Optional("0") final String pageloadTimeout, @Optional("0") final String scriptTimeout, final Method method, final ITestContext context) { context.setAttribute("silenium.browser", browser); context.setAttribute("silenium.base.url", baseURL); var pageloadTimeoutLocal = Long.parseLong(pageloadTimeout); var implicitTimeoutLocal = Long.parseLong(implicitTimeout); var scriptTimeoutLocal = Long.parseLong(scriptTimeout); context.setAttribute("silenium.timeout.pageload", pageloadTimeoutLocal); context.setAttribute("silenium.timeout.implicit", implicitTimeoutLocal); context.setAttribute("silenium.timeout.script", scriptTimeoutLocal); var testMeta = method.getDeclaringClass().getAnnotation(TestMeta.class); if (browser == null) context.setAttribute("silenium.browser", testMeta.browser()); if (baseURL == null) context.setAttribute("silenium.base.url", testMeta.baseURL()); if (implicitTimeoutLocal < 1) context.setAttribute("silenium.timeout.implicit", testMeta.implicitTimeout()); if (pageloadTimeoutLocal < 1) context.setAttribute("silenium.timeout.pageload", testMeta.pageloadTimeout()); if (scriptTimeoutLocal < 1) context.setAttribute("silenium.timeout.script", testMeta.scriptTimeout()); } @BeforeMethod() protected synchronized final void defaultBeforeTest2(final ITestContext context) { final var browser = (String) context.getAttribute("silenium.browser"); final var baseURL = (String) context.getAttribute("silenium.base.url"); final var implicitTimeout = (long) context.getAttribute("silenium.timeout.implicit"); final var pageloadTimeout = (long) context.getAttribute("silenium.timeout.pageload"); final var scriptTimeout = (long) context.getAttribute("silenium.timeout.script"); final var driver = getWebDriver(browser); if (baseURL != null) driver.get(baseURL); if (implicitTimeout > 0) driver.manage().timeouts().implicitlyWait(implicitTimeout, TimeUnit.MILLISECONDS); if (pageloadTimeout > 0) driver.manage().timeouts().implicitlyWait(implicitTimeout, TimeUnit.MILLISECONDS); if (scriptTimeout > 0) driver.manage().timeouts().implicitlyWait(scriptTimeout, TimeUnit.MILLISECONDS); setDriver(driver); } @AfterMethod protected final void defaultAfterTest() { getDriver().quit(); } @AfterSuite protected final void defaultAfterSuite() { driverManagerMap.forEach((key, driverManager) -> { driverManager.stopService(); }); } private synchronized final WebDriver getWebDriver(final String browser) { var driverManager = driverManagerMap.get(browser); if (driverManager == null) { driverManager = getWebDriverManagerFactory().getManager(browser); driverManager.startService(); driverManagerMap.put(browser, driverManager); } return getWebDriverFactory().getDriver(browser); } } package com.ikkong.platform.service; import com.ikkong.core.base.service.IService; import com.ikkong.platform.model.Customer; /** * Generated by Blade. * 2017-11-20 11:19:32 */ public interface CustomerService extends IService{ } package io.github.foundationgames.deathrun.game.element.deathtrap; import com.mojang.serialization.Codec; import com.mojang.serialization.codecs.RecordCodecBuilder; import io.github.foundationgames.deathrun.game.element.DeathTrap; import io.github.foundationgames.deathrun.game.state.DRGame; import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; import net.minecraft.server.world.ServerWorld; import net.minecraft.util.math.BlockPos; import xyz.nucleoid.map_templates.BlockBounds; public class InvisiblePathDeathTrap extends ResettingDeathTrap { public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance.group( BlockState.CODEC.optionalFieldOf("block", Blocks.AMETHYST_BLOCK.getDefaultState()).forGetter(trap -> trap.state), Codec.INT.optionalFieldOf("down", 2).forGetter(trap -> trap.down) ).apply(instance, InvisiblePathDeathTrap::new) ); private final BlockState state; private final int down; public InvisiblePathDeathTrap(BlockState state, int down) { this.state = state; this.down = down; } @Override public void trigger(DRGame game, ServerWorld world, BlockBounds zone) { for (BlockPos pos : zone) { var state = world.getBlockState(pos); if (state.isOf(Blocks.BARRIER)) { world.setBlockState(pos.down(down), Blocks.WATER.getDefaultState()); } } } @Override public void reset(DRGame game, ServerWorld world, BlockBounds zone) { for (BlockPos pos : zone) { var state = world.getBlockState(pos); if (state.isOf(Blocks.BARRIER)) { world.setBlockState(pos.down(down), this.state); } } } @Override public Codec getCodec() { return CODEC; } } src/main/java/com/devwithimagination/microprofile/experiments/config/featureflag/FeatureFlagConfigSource.java package com.devwithimagination.microprofile.experiments.config.featureflag; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import javax.json.bind.Jsonb; import javax.json.bind.JsonbBuilder; import org.eclipse.microprofile.config.spi.ConfigSource; /** * Implementation of ConfigSource for loading feature flag information. * * This implementation will load from a file containing a JSON array, but * equally could have performed an HTTP call to get this JSON array. */ public class FeatureFlagConfigSource implements ConfigSource { /** * Map of the key to the JSON blob representing the feature definition. */ private final Map configurationData; /** * Create a new FeatureFlagConfigSource. * * This will read the configuration file in as part of the object construction. */ public FeatureFlagConfigSource() { Jsonb json = JsonbBuilder.create(); this.configurationData = new HashMap<>(); /* * Load data from the input stream This could be driven by a configuration * option somewhere to use a URL instead */ try (InputStream in = FeatureFlagConfigSource.class.getResourceAsStream("/META-INF/feature-flags.json")) { Feature[] features = json.fromJson(in, Feature[].class); Arrays.stream(features) .forEach(feature -> this.configurationData.put(feature.getName(), json.toJson(feature))); } catch (IOException e) { e.printStackTrace(); throw new IllegalStateException("Failed to configure flag data", e); } } @Override public int getOrdinal() { return 112; } @Override public Map getProperties() { return this.configurationData; } @Override public String getValue(String propertyName) { return this.configurationData.get(propertyName); } @Override public String getName() { return FeatureFlagConfigSource.class.getSimpleName(); } }TeamSPoon/CYC_JRTL_with_CommonLisp_OLDplatform/main/opencyc-local/org/opencyc/api/CommResponseHandler.java package org.opencyc.api; import java.util.concurrent.TimeUnit; import java.util.concurrent.RejectedExecutionException; import java.util.Date; import org.opencyc.util.StringUtils; import java.util.logging.Level; import org.opencyc.util.Log; import org.opencyc.cycobject.CycSymbol; import java.util.concurrent.Semaphore; import org.opencyc.api.CycConnection.WaitingWorkerInfo; import org.opencyc.cycobject.CycList; import java.net.Socket; import java.net.ServerSocket; class CommResponseHandler extends Thread { public static final int MAX_LOCAL_CLIENT_CLIENTS = 50; protected ServerSocket listenerSocket; protected Socket inboundSocket; public CfaslInputStream inboundStream; protected CfaslOutputStream inboundOutputStream; protected Thread parentThread; protected CycList ignoreMessage; protected CycConnection cycConnection; private volatile boolean isClosed; volatile boolean isClosing; private Semaphore initializedSemaphore; private volatile boolean initialized; private volatile Exception initializationError; static final int TASK_PROCESSOR_RESPONSE_ID = 2; static final int TASK_PROCESSOR_RESPONSE_RESPONSE = 5; static final int TASK_PROCESSOR_RESPONSE_STATUS = 6; static final int TASK_PROCESSOR_RESPONSE_FINISHED_FLAG = 7; private final CycConnection cycComm; public CommResponseHandler(final Thread parentThread, final CycConnection cycConnection, final CycConnection cycComm) { this.listenerSocket = null; this.inboundSocket = null; this.isClosed = false; this.isClosing = false; this.initializationError = null; this.cycComm = cycComm; this.parentThread = parentThread; this.cycConnection = cycConnection; (this.ignoreMessage = new CycList()).add((Object) new CycSymbol("IGNORE")); } @Override public void start() { this.initializeSynchronization(); super.start(); this.waitOnSetupToComplete(); } @Override public void run() { Thread.currentThread().setName("TaskProcessorBinaryResponseHandler"); Exception closingException = null; try { if (!this.isClosed && !this.isClosing) { try { this.inboundStream = this.cycComm.cfaslInputStream; this.inboundStream.trace = this.cycComm.trace; } catch (Exception e) { if (!this.isClosed && !this.isClosing) { closingException = e; Log.current.printStackTrace(e); Log.current.errorPrintln("Communication with Cyc cannot be started: host-" + this.cycComm.hostName + " port-" + this.cycComm.cfaslPort); this.notifySetupCompleted(e); } return; } } this.notifySetupCompleted(null); while (!this.isClosed && !this.isClosing) { Object status = null; CycList taskProcessorResponse = null; boolean isInvalidObject = false; if (this.isClosed) { break; } if (this.isClosing) { break; } try { this.inboundStream.resetIsInvalidObject(); status = this.inboundStream.readObject(); this.inboundStream.resetIsInvalidObject(); final Object currentResponse = this.inboundStream.readObject(); if (!(currentResponse instanceof CycList)) { throw new Exception("Invalid task processor response: " + currentResponse); } taskProcessorResponse = (CycList) currentResponse; if (this.cycComm.logger.isLoggable(Level.FINE)) { this.cycComm.logger.fine("API response: " + taskProcessorResponse.stringApiValue()); } isInvalidObject = this.inboundStream.isInvalidObject(); } catch (Exception e2) { if (this.cycComm.taskProcessingEnded && this.cycComm.trace > 0) { Log.current.println("Ending binary mode task processor handler."); } if (!this.isClosed && !this.isClosing) { this.cycComm.logger.fine("Exception: " + e2.getMessage()); if (e2 instanceof CfaslInputStreamClosedException) { if (this.cycComm.trace > 0) { Log.current.errorPrintln(e2.getMessage()); Log.current.printStackTrace(e2); } } else if (e2 instanceof RuntimeException) { Log.current.errorPrintln(e2.getMessage()); Log.current.printStackTrace(e2); continue; } closingException = e2; Log.current.println("Cyc Server ended binary mode task processor handler.\n" + StringUtils.getStringForException((Throwable) e2)); } return; } final boolean objectIsInvalid = isInvalidObject; this.cycComm.logger.finest("API status: " + status); if (this.cycComm.trace >= 2) { Log.current.println("cyc --> (" + status + ") " + taskProcessorResponse.toString()); } if (taskProcessorResponse.equals((Object) this.ignoreMessage)) { continue; } try { if (this.cycComm.trace >= 1) { Log.current.println(CycConnection.df.format(new Date()) + "\n Got response: (" + taskProcessorResponse + ")"); } if (!(taskProcessorResponse.get(2) instanceof Integer)) { Log.current.println(CycConnection.df.format(new Date()) + "\n Got invalid response id: (" + taskProcessorResponse + ")"); } final Integer id = (Integer) taskProcessorResponse.get(2); final Object taskStatus = taskProcessorResponse.get(6); final Object finishedFlag = (taskProcessorResponse.size() > 7) ? taskProcessorResponse.get(7) : CycObjectFactory.t; final boolean finished = finishedFlag != CycObjectFactory.nil; final CycConnection.WaitingWorkerInfo waitingWorkerInfo = (WaitingWorkerInfo) this.cycComm.getWaitingReplyThreads().get(id); if (waitingWorkerInfo == null) { if (this.cycComm.trace < 1) { continue; } Log.current.println(CycConnection.df.format(new Date()) + "\n Got response with no waiting working: (" + taskProcessorResponse + ")"); } else { final SubLWorker worker = waitingWorkerInfo.getWorker(); final Object response = waitingWorkerInfo.isReturnWholeTaskProcessorResponse ? taskProcessorResponse : taskProcessorResponse.get(5); final Runnable notificationTask = (Runnable) new NotificationTask(taskStatus, objectIsInvalid, worker, response, finished, id, this.cycComm); try { this.cycComm.apiPool.execute(notificationTask); } catch (RejectedExecutionException e3) { e3.printStackTrace(); System.err.println("Rejected notification from " + worker); } } } catch (Exception xcpt) { if (this.isClosed || this.isClosing) { continue; } Log.current.errorPrintln(xcpt.getMessage()); Log.current.printStackTrace(xcpt); } } } catch (Exception e) { closingException = e; } finally { if (closingException != null) { this.cycComm.logger.log(Level.SEVERE, "TaskProcessor terminated because of exception.", closingException); } this.cycComm.taskProcessingThreadDead = true; this.cycComm.logger.finer("TaskProcessor is closing now."); this.notifySetupCompleted(closingException); this.cycComm.forciblyUnblockAllWaitingWorkers(closingException); this.close(); } } public synchronized void close() { if (this.isClosed) { return; } this.isClosed = true; if (this.cycComm.apiPool != null) { try { this.cycComm.apiPool.shutdownNow(); } catch (Exception ex) { } try { this.cycComm.apiPool.setMaximumPoolSize(0); } catch (Exception ex2) { } try { this.cycComm.apiPool.setKeepAliveTime(0L, TimeUnit.MILLISECONDS); } catch (Exception ex3) { } } if (this.inboundOutputStream != null) { try { this.inboundOutputStream.close(); } catch (Exception e) { } finally { this.inboundOutputStream = null; } } if (this.inboundStream != null) { try { this.inboundStream.close(); } catch (Exception e) { } finally { this.inboundStream = null; } } if (this.cycComm.trace > 0) { Log.current.println("closed inbound socket associated with " + this.cycComm.uuid); } } private void waitOnSetupToComplete() { try { this.initializedSemaphore.acquire(); } catch (InterruptedException xcpt) { this.initializationError = new IllegalStateException("Unable to initialize Cyc communication."); System.err.println("Interrupted during wait(): " + xcpt); } if (this.initializationError != null) { throw new CycApiException("Cannot start communications to Cyc.", (Throwable) this.initializationError); } } private void initializeSynchronization() { synchronized (this) { this.initialized = false; this.initializedSemaphore = new Semaphore(0); } } private void notifySetupCompleted(final Exception e) { synchronized (this) { this.initializationError = e; this.initialized = true; } this.initializedSemaphore.release(); } } /* DECOMPILATION REPORT Decompiled from: G:\opt\CYC_JRTL_with_CommonLisp\platform\lib\client-lib\opencyc-0.0.1-SNAPSHOT.jar Total time: 208 ms Decompiled with Procyon 0.5.32. */src/main/java/org/apache/pluto/driver/services/impl/resource/SupportedModesServiceImpl.java /* * Copyright (c) 2008-2016 Computer Network Information Center (CNIC), Chinese Academy of Sciences. * * This file is part of Duckling project. * * 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.pluto.driver.services.impl.resource; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import javax.portlet.PortletConfig; import javax.portlet.PortletMode; import javax.servlet.ServletContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.pluto.PortletContainer; import org.apache.pluto.PortletContainerException; import org.apache.pluto.descriptors.portlet.CustomPortletModeType; import org.apache.pluto.driver.AttributeKeys; import org.apache.pluto.driver.config.DriverConfigurationException; import org.apache.pluto.driver.services.portal.PortletWindowConfig; import org.apache.pluto.driver.services.portal.PropertyConfigService; import org.apache.pluto.driver.services.portal.SupportedModesService; import org.apache.pluto.om.portlet.PortletDefinition; import org.apache.pluto.om.portlet.PortletApplicationDefinition; import org.apache.pluto.om.portlet.Supports; import org.apache.pluto.services.PlutoServices; import org.apache.pluto.spi.optional.PortletContextService; import org.apache.pluto.spi.optional.PortletRegistryService; /** * Allows clients to determine if a particular PortletMode is supported * by the portal, a particular portlet, or both. * * This implementation depends on {@link PropertyConfigService}. * * The service implementations are injected by Spring. * * @version $Id: SupportedModesServiceImpl.java,v 1.3 2009/05/21 01:44:07 kevin Exp $ * @since September 9, 2006 */ public class SupportedModesServiceImpl implements SupportedModesService { /** Logger */ private static final Log LOG = LogFactory.getLog(SupportedModesServiceImpl.class); /** PortletMode objects supported by the portal */ private Set supportedPortletModesByPortal = new HashSet(); /** PortletRegistryService used to obtain PortletApplicationConfig objects */ private PortletRegistryService portletRegistry; /** PropertyConfig Service used to obtain supported portal modes */ private PropertyConfigService propertyService; /** The portal's servletContext **/ private ServletContext servletContext; private PortletContextService portletContextService; /** * Constructs a SupportedModesService with its dependencies. * * @param propertyService the PropertyConfigService */ public SupportedModesServiceImpl(PropertyConfigService propertyService) { this.propertyService = propertyService; } // SupportedModesService Implementation ----------------- public boolean isPortletModeSupported(String portletId, String mode) { return (isPortletModeSupportedByPortal(mode) && isPortletModeSupportedByPortlet(portletId, mode) || isPortletManagedMode(portletId, mode)); } public boolean isPortletModeSupportedByPortal(String mode) { return supportedPortletModesByPortal.contains(new PortletMode(mode)); } public boolean isPortletModeSupportedByPortlet(String portletId, String mode) { String applicationId = PortletWindowConfig.parseContextPath(portletId); String applicationName = applicationId; if (applicationName.length() >0 ) { applicationName = applicationName.substring(1); } String portletName = PortletWindowConfig.parsePortletName(portletId); // since SupportedModesService is consulted per portal portal mode per portlet // per render request, store a reference to the registry instead of looking // it up each time. Is this premature optimization? if (portletRegistry == null) { portletRegistry = ((PortletContainer)servletContext .getAttribute(AttributeKeys.PORTLET_CONTAINER)) .getOptionalContainerServices() .getPortletRegistryService(); } try { if (portletRegistry == null) { LOG.error("Optional Portlet Registry Service not found."); throw new PortletContainerException("Optional Portlet Registry Service not found."); } PortletApplicationDefinition ctx = portletRegistry.getPortletApplication(applicationName); Iterator i = ctx.getPortlets().iterator(); while(i.hasNext()) { PortletDefinition dd = (PortletDefinition)i.next(); if(portletName.equals(dd.getPortletName())) { Iterator i2 = dd.getSupports().iterator(); while(i2.hasNext()) { Supports sd = (Supports)i2.next(); if (sd.getPortletModes()==null){ if (mode.equalsIgnoreCase(PortletMode.VIEW.toString())) return true; } else{ Iterator pd = sd.getPortletModes().iterator(); while(pd.hasNext()) { if(mode.equalsIgnoreCase((String)pd.next())) { return true; } } } } } } } catch (PortletContainerException e) { LOG.error("Error determining mode support.", e); } LOG.info("Portlet mode '"+mode+"' not found for portletId: '"+portletId+"'"); return false; } // DriverConfiguration Lifecycle Implementation --------- public void destroy() throws DriverConfigurationException { LOG.debug("Destroying Supported Modes Service..."); supportedPortletModesByPortal = null; portletRegistry = null; propertyService = null; LOG.debug("Supported Modes Service destroyed."); } public void init(ServletContext ctx) throws DriverConfigurationException { this.servletContext = ctx; this.portletContextService = PlutoServices.getServices().getPortletContextService(); loadPortalModes(); } /** Populates the supportedPortletModesByPortal set. */ private void loadPortalModes() { // Add the PortletModes supported by the portal to the // supportedPortletModesByPortal set. LOG.debug("Loading supported portal modes..."); Iterator modes = propertyService.getSupportedPortletModes().iterator(); while (modes.hasNext()) { String mode = (String) modes.next(); LOG.debug("Loading mode [" + mode + "]"); supportedPortletModesByPortal.add(new PortletMode(mode)); } LOG.debug("Loaded [" + supportedPortletModesByPortal.size() + "] supported portal modes"); } public boolean isPortletManagedMode(String portletId, String mode) { if (portletRegistry == null) { portletRegistry = ((PortletContainer)servletContext .getAttribute(AttributeKeys.PORTLET_CONTAINER)) .getOptionalContainerServices() .getPortletRegistryService(); } // // String applicationId = PortletWindowConfig.parseContextPath(portletId); String applicationName = applicationId; if (applicationName.length() > 0 ) { applicationName = applicationName.substring(1); } try { PortletApplicationDefinition portletApp = portletRegistry.getPortletApplication(applicationName); Iterator customModes = portletApp.getCustomPortletModes().iterator(); while (customModes.hasNext()) { CustomPortletModeType customMode = (CustomPortletModeType)customModes.next(); boolean isPortletManagedMode = !customMode.isPortalManaged(); if (isPortletManagedMode && customMode.getPortletMode().equalsIgnoreCase(mode)) { return true; } } } catch (PortletContainerException e) { LOG.error("Error determining portlet managed mode support, so we assume that it is false.", e); } return false; } /** * Gets all modes supported by a portlet that are defined in the portlet's supports child element * in portlet.xml. * * @param portlet of interest. * @return all portlet modes supported by a portlet. */ public Set getSupportedPortletModes(String portletId) throws PortletContainerException { Set modeSet = new HashSet(); String applicationId = PortletWindowConfig.parseContextPath(portletId); String applicationName = applicationId; if (applicationName.length() >0 ) { applicationName = applicationName.substring(1); } String portletName = PortletWindowConfig.parsePortletName(portletId); // since SupportedModesService is consulted per portal portal mode per portlet // per render request, store a reference to the registry instead of looking // it up each time. Is this premature optimization? if (portletRegistry == null) { portletRegistry = ((PortletContainer)servletContext .getAttribute(AttributeKeys.PORTLET_CONTAINER)) .getOptionalContainerServices() .getPortletRegistryService(); } if (portletRegistry == null) { LOG.error("Optional Portlet Registry Service not found."); throw new PortletContainerException("Optional Portlet Registry Service not found."); } PortletApplicationDefinition portletApp = portletRegistry.getPortletApplication(applicationName); Iterator i = portletApp.getPortlets().iterator(); while(i.hasNext()) { PortletDefinition dd = (PortletDefinition)i.next(); if(portletName.equals(dd.getPortletName())) { Iterator i2 = dd.getSupports().iterator(); while(i2.hasNext()) { Supports sd = (Supports)i2.next(); if (sd.getPortletModes()== null){ modeSet.add(PortletMode.VIEW); } else{ Iterator pd = sd.getPortletModes().iterator(); while(pd.hasNext()) { modeSet.add(new PortletMode(pd.next())); } } } } } return modeSet; } public PortletConfig getPortletConfig(String portletId) throws PortletContainerException { String applicationId = PortletWindowConfig.parseContextPath(portletId); String applicationName = applicationId; if (applicationName.length() >0 ) { applicationName = applicationName.substring(1); } String portletName = PortletWindowConfig.parsePortletName(portletId); if (portletRegistry == null) { portletRegistry = ((PortletContainer)servletContext .getAttribute(AttributeKeys.PORTLET_CONTAINER)) .getOptionalContainerServices() .getPortletRegistryService(); } return portletContextService.getPortletConfig(applicationName, portletName); } } package rs.raf.storage.spec.search; import rs.raf.storage.spec.core.File; /** * Holds search query and type of search. */ public final class Criteria { private final CriteriaType type; private final String query; /** * One and only contructor that accepts search query adn type of search. * @param type Type of search to be used. * @param query Query to be searched by. */ public Criteria(CriteriaType type, String query) { this.type = type; this.query = query; } public final CriteriaType getType() { return type; } public final String getQuery() { return query; } /** * Checks if provided file matches search query and search type. * @param file File to be checked for a match. * @return {@code true} if provided file matches search or {@code false} otherwise. */ public final boolean matches(File file) { return type.matches(this, file); } } /* * Copyright (c) 2019. All rights reserved. * Licensed under the MIT License. See LICENSE file in the project root for full license information. */ package org.m_ld.guicicle.test; import org.junit.Test; import org.m_ld.guicicle.PartialFluentProxy; import org.m_ld.guicicle.PartialFluentProxy.Delegate; import static java.lang.invoke.MethodHandles.lookup; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; /** * This class is in a different package to its test class, to verify object member access */ public class PartialFluentProxyTest { public interface Target { int delegated(); String notDelegated(); Target fluentDelegated(String value); Target fluentNotDelegated(String value); } class TargetImpl implements Target { String value = "Hello"; @Override public int delegated() { return 1; } @Override public String notDelegated() { return value; } @Override public Target fluentDelegated(String value) { this.value = value; return this; } @Override public Target fluentNotDelegated(String value) { this.value = value; return this; } } @SuppressWarnings("unused") static class PartialDelegate { final Target target; PartialDelegate(Target target) { this.target = target; } int delegated() { return 2; } Target fluentDelegated(String value) { return target.fluentDelegated("Override!"); } } @Test public void testNotDelegated() { Target proxy = PartialFluentProxy.factory(Target.class, lookup().in(PartialDelegate.class), PartialDelegate::new) .apply(new TargetImpl()); assertEquals("Hello", proxy.notDelegated()); } @Test public void testDelegated() { Target proxy = PartialFluentProxy.factory(Target.class, lookup().in(PartialDelegate.class), PartialDelegate::new) .apply(new TargetImpl()); assertEquals(2, proxy.delegated()); } @Test public void testFluentNotDelegated() { Target proxy = PartialFluentProxy.factory(Target.class, lookup().in(PartialDelegate.class), PartialDelegate::new) .apply(new TargetImpl()); assertEquals(2, proxy.fluentNotDelegated("Goodbye").delegated()); assertEquals("Goodbye", proxy.fluentNotDelegated("Goodbye").notDelegated()); } @Test public void testFluentDelegated() { Target proxy = PartialFluentProxy.factory(Target.class, lookup().in(PartialDelegate.class), PartialDelegate::new) .apply(new TargetImpl()); assertEquals(2, proxy.fluentDelegated("Goodbye").delegated()); assertEquals("Override!", proxy.fluentDelegated("Goodbye").notDelegated()); } @Test public void testCreateWithAnonymousDelegate() { final TargetImpl target = new TargetImpl(); //noinspection unused Target proxy = PartialFluentProxy.create( Target.class, target, new Delegate(target, lookup()) { int delegated() { assertNotNull(proxy); return 2; } Target fluentDelegated(String value) { return inner.fluentDelegated("Override!"); } }); assertEquals(2, proxy.delegated()); assertEquals("Override!", proxy.fluentDelegated("Goodbye").notDelegated()); } }src/main/java/com/kishan/springboot/testapis/dao/EmployeeDao.java package com.kishan.springboot.testapis.dao; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import com.kishan.springboot.testapis.entities.Employee; @Repository public interface EmployeeDao extends JpaRepository{ @Query(value = "SELECT emp FROM Employee emp WHERE emp.employeeDepartment = :employeeDepartment", nativeQuery = false) List findByDepartmentName(@Param("employeeDepartment") String emplDept); @Query(value = "SELECT * FROM Employee emp WHERE emp.EMPLOYEE_DEPARTMENT = :employeeDepartment", nativeQuery = true) List findByDepartmentName2(@Param("employeeDepartment") String emplDept); @Query(value = "SELECT emp FROM Employee emp WHERE emp.employeeName = ?1", nativeQuery = false) List findByEmployeeName(String employeeName); @Query(value = "SELECT * FROM Employee emp WHERE emp.EMPLOYEE_NAME = ?1", nativeQuery = true) List findByEmployeeName2(String employeeName); @Modifying @Query(value = "update Employee emp set emp.employeeSalary = :employeeSalary where emp.employeeName = :employeeName", nativeQuery = false) int updateEmployeeSalaryUsingName(String employeeName, int employeeSalary); //return number of rows updated @Modifying @Query(value = "update Employee emp set emp.EMPLOYEE_SALARY = ? where emp.EMPLOYEE_NAME = ?", nativeQuery = true) int updateEmployeeSalaryUsingName2(int employeeSalary, String employeeName); //same for insert query but return type void ... @Modifying @Query and insert query } package com.threedevs.aj.HwInfoReceiver.Networking; import android.os.AsyncTask; import android.util.Log; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; /** * UNUSED!!! * * Created by AJ on 14.07.2014. */ public class NetworkTask extends AsyncTask { private Socket nsocket; //Network Socket private InputStream nis; //Network Input Stream private OutputStream nos; //Network Output Stream private String ip = null; public NetworkTask(String ip) { this.ip = ip; } @Override protected void onPreExecute() { Log.i("AsyncTask", "onPreExecute"); } @Override protected Boolean doInBackground(Void... params) { //This runs on a different thread boolean result = false; try { Log.i("AsyncTask", "doInBackground: Creating socket"); SocketAddress sockaddr = new InetSocketAddress(ip, 8881); nsocket = new Socket(); nsocket.connect(sockaddr, 5000); //10 second connection timeout if (nsocket.isConnected()) { nis = nsocket.getInputStream(); nos = nsocket.getOutputStream(); Log.i("AsyncTask", "doInBackground: Socket created, streams assigned"); Log.i("AsyncTask", "doInBackground: Waiting for inital data..."); byte[] buffer = new byte[4096]; int read = nis.read(buffer, 0, 4096); //This is blocking while((read != -1) || !isCancelled()){ byte[] tempdata = new byte[read]; System.arraycopy(buffer, 0, tempdata, 0, read); publishProgress(tempdata); Log.i("AsyncTask", "doInBackground: Got some data"); read = nis.read(buffer, 0, 4096); //This is blocking } } } catch (IOException e) { e.printStackTrace(); Log.i("AsyncTask", "doInBackground: IOException"); result = true; } catch (Exception e) { e.printStackTrace(); Log.i("AsyncTask", "doInBackground: Exception"); result = true; } finally { try { nis.close(); nos.close(); nsocket.close(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } Log.i("AsyncTask", "doInBackground: Finished"); } return result; } public void SendDataToNetwork(String cmd) { //You run this from the menu_main thread. try { if (nsocket.isConnected()) { Log.i("AsyncTask", "SendDataToNetwork: Writing received message to socket"); nos.write(cmd.getBytes()); } else { Log.i("AsyncTask", "SendDataToNetwork: Cannot send message. Socket is closed"); } } catch (Exception e) { Log.i("AsyncTask", "SendDataToNetwork: Message send failed. Caught an exception: " + e); } } @Override protected void onProgressUpdate(byte[]... values) { if (values.length > 0) { Log.i("AsyncTask", "onProgressUpdate: " + values[0].length + " bytes received."); //TODO: //textStatus.setText(new String(values[0])); } } @Override protected void onCancelled() { Log.i("AsyncTask", "Cancelled."); //TODO: //btnStart.setVisibility(View.VISIBLE); } @Override protected void onPostExecute(Boolean result) { if (result) { Log.i("AsyncTask", "onPostExecute: Completed with an Error."); //TODO: //textStatus.setText("There was a connection error."); } else { Log.i("AsyncTask", "onPostExecute: Completed."); } //TODO: //btnStart.setVisibility(View.VISIBLE); } } 1-10 // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.xdebugger; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.extensions.ExtensionPoint; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.testFramework.HeavyPlatformTestCase; import com.intellij.util.xmlb.annotations.Attribute; import com.intellij.xdebugger.breakpoints.*; import com.intellij.xdebugger.impl.breakpoints.XBreakpointManagerImpl; import org.jetbrains.annotations.NotNull; public abstract class XDebuggerTestCase extends HeavyPlatformTestCase { public static final MyLineBreakpointType MY_LINE_BREAKPOINT_TYPE = new MyLineBreakpointType(); protected static final MySimpleBreakpointType MY_SIMPLE_BREAKPOINT_TYPE = new MySimpleBreakpointType(); @NotNull static XBreakpoint addBreakpoint(XBreakpointManagerImpl breakpointManager, MyBreakpointProperties abc) { return WriteAction.compute(() -> breakpointManager.addBreakpoint(MY_SIMPLE_BREAKPOINT_TYPE, abc)); } @NotNull static XLineBreakpoint addLineBreakpoint(XBreakpointManagerImpl breakpointManager, String url, int line, MyBreakpointProperties properties) { return WriteAction.compute(() -> breakpointManager.addLineBreakpoint(MY_LINE_BREAKPOINT_TYPE, url, line, properties)); } static void removeBreakPoint(XBreakpointManagerImpl breakpointManager, XBreakpoint breakpoint) { WriteAction.run(() -> breakpointManager.removeBreakpoint(breakpoint)); } @Override protected void initApplication() throws Exception { super.initApplication(); final ExtensionPoint point = XBreakpointType.EXTENSION_POINT_NAME.getPoint(null); point.registerExtension(MY_LINE_BREAKPOINT_TYPE, getTestRootDisposable()); point.registerExtension(MY_SIMPLE_BREAKPOINT_TYPE, getTestRootDisposable()); } public static class MyLineBreakpointType extends XLineBreakpointType { public MyLineBreakpointType() { super("testLine", "239"); } @Override public MyBreakpointProperties createBreakpointProperties(@NotNull final VirtualFile file, final int line) { return null; } @Override public MyBreakpointProperties createProperties() { return new MyBreakpointProperties(); } } public static class MySimpleBreakpointType extends XBreakpointType,MyBreakpointProperties> { public MySimpleBreakpointType() { super("test", "239"); } @Override public String getDisplayText(final XBreakpoint breakpoint) { return ""; } @Override public MyBreakpointProperties createProperties() { return new MyBreakpointProperties(); } @Override public XBreakpoint createDefaultBreakpoint(@NotNull XBreakpointCreator creator) { final XBreakpoint breakpoint = creator.createBreakpoint(new MyBreakpointProperties("default")); breakpoint.setEnabled(true); return breakpoint; } } protected static class MyBreakpointProperties extends XBreakpointProperties { @Attribute("option") public String myOption; public MyBreakpointProperties() { } public MyBreakpointProperties(final String option) { myOption = option; } @Override public MyBreakpointProperties getState() { return this; } @Override public void loadState(@NotNull final MyBreakpointProperties state) { myOption = state.myOption; } } } asoran/ejbank package com.ejbank.test; import com.ejbank.repositories.AccountRepository; import javax.ejb.LocalBean; import javax.ejb.Stateless; import javax.inject.Inject; @Stateless @LocalBean public class TestBean implements TestBeanLocal { // @Inject // private AccountRepository accountHaricot; @Override public String test() { // accountHaricot.getAll(); return "Hello world from EJB"; } } src/test/java/com/richard/mmseg4j/KeyTreeTest.java0 package com.richard.mmseg4j; import junit.framework.TestCase; public class KeyTreeTest extends TestCase { protected void setUp() throws Exception { super.setUp(); } public void testMatch() { char[] w = "为什么".toCharArray(); CharNode.KeyTree kt = new CharNode.KeyTree(); kt.add(w); assertTrue(kt.match(w, 0, w.length)); assertFalse(kt.match(w, 0, 2)); assertFalse(kt.match("怎么样".toCharArray(), 0, 3)); w = "国人民银行".toCharArray(); kt.add(w); int tailLen = kt.maxMatch("中国人民银行".toCharArray(), 1); assertEquals(tailLen, w.length); } public void testMatch2() { Dictionary dic = Dictionary.getInstance(); int tailLen = dic.maxMatch("中国人民银行".toCharArray(), 0); assertEquals(tailLen, 5); } } backend/services/osm-data-processor-service/src/main/java/com/navigation/osmdataprocessor/OsmDataProcessorApplication.java package com.navigation.osmdataprocessor; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class OsmDataProcessorApplication { public static void main(String[] args) { SpringApplication.run(OsmDataProcessorApplication.class, args); } } 0 package com.kaz.test; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridLayout; import java.awt.Point; import java.awt.Polygon; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.imageio.ImageIO; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; import com.jhlabs.image.ScaleFilter; import com.jhlabs.image.WarpFilter; import com.jhlabs.image.WarpGrid; public class App { public static void main(String[] args) throws IOException { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { createAndShowGUI(); } }); } private static void createAndShowGUI() { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(new GridLayout(1, 1)); frame.getContentPane().add(new WarpImageTest()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } class WarpImageTest extends JPanel { /** * */ private static final long serialVersionUID = 1L; private BufferedImage inputImage; private BufferedImage outputImage; private WarpGrid srcGrid; private WarpGrid dstGrid; private WarpFilter warpFilter; private static final int GRID_NUMBER = 20; private Graphics2D graphics; private Point clickedPoint; private Point releasedPoint; private List nearestPoints; private int radii = 100; private int radius = radii / 2; private boolean isPolygon = true; private boolean drawNow; private List xPoints; private List yPoints; private Polygon polygon; private JButton fileChooserButton; private JFileChooser fileChooser; private BufferedImage scaleImage; public WarpImageTest() { try { fileChooserButton = new JButton("Choose an Image"); add(fileChooserButton); } catch (Exception e) { e.printStackTrace(); } fileChooserButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { fileChooser = new JFileChooser(); ExtensionFileFilter fileFilter = new ExtensionFileFilter(null, new String[] { "jpeg", "jpg", "png" }); fileChooser.setFileFilter(fileFilter); int returnValue = fileChooser.showOpenDialog(null); File file = new File("D:/Image/image.jpg"); if (returnValue == JFileChooser.APPROVE_OPTION) { file = fileChooser.getSelectedFile(); } try { scaleImage = ImageIO.read(file); int xDime, yDime; xDime = scaleImage.getWidth() > 1000 ? 1000 : scaleImage.getWidth(); yDime = scaleImage.getHeight() > 600 ? 600 : scaleImage.getHeight(); inputImage = new BufferedImage(xDime, yDime, BufferedImage.TYPE_INT_ARGB); ScaleFilter scaleFilter = new ScaleFilter(xDime, yDime); scaleFilter.filter(scaleImage, inputImage); outputImage = new BufferedImage(inputImage.getWidth(), inputImage.getHeight(), BufferedImage.TYPE_INT_ARGB); srcGrid = new WarpGrid(GRID_NUMBER, GRID_NUMBER, inputImage.getWidth(), inputImage.getHeight()); dstGrid = new WarpGrid(GRID_NUMBER, GRID_NUMBER, inputImage.getWidth(), inputImage.getHeight()); warpImage(1, 1, srcGrid.xGrid[1], srcGrid.yGrid[1]); setPreferredSize(new Dimension(inputImage.getWidth(), inputImage.getHeight())); // //drawLines(dstGrid, Color.BLACK); repaint(); } catch (Exception e) { } } }); addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent event) { } @Override public void mousePressed(MouseEvent e) { clickedPoint = new Point(e.getX(), e.getY()); if (!isPolygon) { warpImage(1, 1, dstGrid.xGrid[1], dstGrid.yGrid[1]); repaint(); } else { if (!drawNow) { xPoints = new ArrayList(); yPoints = new ArrayList(); xPoints.add(clickedPoint.x); yPoints.add(clickedPoint.y); } else { } } } @Override public void mouseReleased(MouseEvent e) { if (clickedPoint.x == e.getX() && clickedPoint.y == e.getY() && !drawNow) return; warpImage(1, 1, dstGrid.xGrid[1], dstGrid.yGrid[1]); inputImage = outputImage; outputImage = new BufferedImage(inputImage.getWidth(), inputImage.getHeight(), BufferedImage.TYPE_INT_ARGB); srcGrid = new WarpGrid(GRID_NUMBER, GRID_NUMBER, inputImage.getWidth(), inputImage.getHeight()); dstGrid = new WarpGrid(GRID_NUMBER, GRID_NUMBER, inputImage.getWidth(), inputImage.getHeight()); warpImage(1, 1, dstGrid.xGrid[1], dstGrid.yGrid[1]); // //drawLines(dstGrid, Color.BLACK); if (isPolygon) { if (!drawNow) drawPolygon(); drawNow = !drawNow; } repaint(); } }); addMouseMotionListener(new MouseAdapter() { @Override public void mouseDragged(MouseEvent e) { if (clickedPoint.x == e.getX() && clickedPoint.y == e.getY()) return; if (isPolygon) { if (drawNow) { releasedPoint = new Point(e.getX(), e.getY()); int deltaX = releasedPoint.x - clickedPoint.x; int deltaY = releasedPoint.y - clickedPoint.y; clickedPoint.x = releasedPoint.x; clickedPoint.y = releasedPoint.y; nearestPoints = new ArrayList(); findPointsInsidePolygon(); for (Point p : nearestPoints) { dstGrid.xGrid[p.x] = dstGrid.xGrid[p.x] + deltaX; dstGrid.yGrid[p.y] = dstGrid.yGrid[p.y] + deltaY; } for (int i = 0; i < xPoints.size(); i++) { xPoints.set(i, xPoints.get(i) + deltaX); yPoints.set(i, yPoints.get(i) + deltaY); } warpImage(1, 1, dstGrid.xGrid[1], dstGrid.yGrid[1]); } else { releasedPoint = new Point(e.getX(), e.getY()); xPoints.add(releasedPoint.x); yPoints.add(releasedPoint.y); } drawPolygon(); // //drawLines(dstGrid, Color.BLACK); repaint(); } } @Override public void mouseMoved(MouseEvent e) { } }); } public void drawCircle(Point point, int radius, Color color) { graphics = (Graphics2D) outputImage.createGraphics(); graphics.setStroke(new BasicStroke(2)); graphics.setColor(color); graphics.drawOval(point.x, point.y, radius, radius); } @Override protected void paintComponent(Graphics g) { graphics = (Graphics2D) g; if (outputImage != null) { g.drawImage(outputImage, 0, 0, outputImage.getWidth(), outputImage.getHeight(), null); } } public void warpImage(int x, int y, float xVal, float yVal) { dstGrid.xGrid[x] = xVal; dstGrid.yGrid[y] = yVal; warpFilter = new WarpFilter(srcGrid, dstGrid); // warpFilter.setMorphImage(morphImage); warpFilter.filter(inputImage, outputImage); } public Dimension getPreferredSize() { if (inputImage != null) return new Dimension(inputImage.getWidth(), inputImage.getHeight()); return new Dimension(600, 600); } public void drawLines(WarpGrid srcGrid, Color color) { graphics = (Graphics2D) outputImage.getGraphics(); graphics.setColor(color); graphics.setStroke(new BasicStroke(1)); int index = 0; for (int i = 0; i < GRID_NUMBER; i++) for (int j = 0; j < GRID_NUMBER - 1; j++) { index = i * GRID_NUMBER + j; int x1 = (int) srcGrid.xGrid[index]; int y1 = (int) srcGrid.yGrid[index]; int x2 = (int) srcGrid.xGrid[index + 1]; int y2 = (int) srcGrid.yGrid[index + 1]; graphics.drawLine(x1, y1, x2, y2); } index = 0; for (int i = 0; i < GRID_NUMBER; i++) for (int j = 0; j < GRID_NUMBER - 1; j++) { index = j * GRID_NUMBER + i; int x1 = (int) srcGrid.xGrid[index]; int y1 = (int) srcGrid.yGrid[index]; int x2 = (int) srcGrid.xGrid[index + GRID_NUMBER]; int y2 = (int) srcGrid.yGrid[index + GRID_NUMBER]; graphics.drawLine(x1, y1, x2, y2); } } public void drawLine(Point p1, Point p2) { graphics = (Graphics2D) outputImage.getGraphics(); graphics.setColor(Color.BLACK); graphics.setStroke(new BasicStroke(1)); graphics.drawLine(p1.x, p1.y, p2.x, p2.y); } public void drawPolygon() { graphics = (Graphics2D) outputImage.getGraphics(); graphics.setColor(Color.BLACK); graphics.setStroke(new BasicStroke(1)); int x[] = xPoints.stream().mapToInt(i -> i).toArray(); int y[] = yPoints.stream().mapToInt(i -> i).toArray(); graphics.drawPolyline(x, y, xPoints.size()); } public Point findIndex(int x, int y) { Point point = new Point(); int minDistance = 214748364; for (int i = 0; i < GRID_NUMBER * GRID_NUMBER; i++) for (int j = 0; j < GRID_NUMBER * GRID_NUMBER; j++) { int calculatedDistance = (int) Math.sqrt(Math.pow((x - dstGrid.xGrid[i]), 2) + Math.pow((y - dstGrid.yGrid[j]), 2)); if (calculatedDistance < minDistance && i == j) { minDistance = calculatedDistance; point.x = i; point.y = j; } } return point; } public void findAllNearestPoints(Point point, int distance) { int maxDistance = (int) Math.sqrt(distance); for (int j = 0 - maxDistance; j < maxDistance; j++) { for (int i = point.x - maxDistance; i <= point.x + maxDistance; i++) { int x = j * GRID_NUMBER + i; if (x >= 0 && x < GRID_NUMBER * GRID_NUMBER) { if ((Math.pow((dstGrid.xGrid[x] - clickedPoint.x), 2) + Math.pow( (dstGrid.yGrid[x] - clickedPoint.y), 2)) <= distance * distance) { nearestPoints.add(new Point(x, x)); } } } } } public void findPointsInsidePolygon() { polygon = new Polygon(xPoints.stream().mapToInt(i -> i).toArray(), yPoints.stream().mapToInt(i -> i).toArray(), xPoints.size()); for (int i = 0; i < GRID_NUMBER * GRID_NUMBER; i++) { Point p = new Point((int) dstGrid.xGrid[i], (int) dstGrid.yGrid[i]); if (polygon.contains(p)) { nearestPoints.add(new Point(i, i)); } } } }package org.vaadin.simplemde; public enum SimpleMarkdownToolbarIcon { BOLD, ITALIC, STRIKETHROUGH, HEADING, HEADING_SMALLER, HEADING_BIGGER, HEADING_1, HEADING_2, HEADING_3, CODE, QUOTE, UNORDERED_LIST, ORDERED_LIST, CLEAN_BLOCK, LINK, IMAGE, TABLE, HORIZONTAL_RULE, PREVIEW, SIDE_BY_SIDE, FULLSCREEN, GUIDE } ontology/TascuApi/src/main/java/org/purl/ontology/bibo/domain/CourtReporter.java package org.purl.ontology.bibo.domain; import java.util.List; /** * Code generated from http://purl.org/ontology/bibo/ ontology */ public interface CourtReporter extends Periodical { void remHasPart(LegalDocument val); List getAllHasPart(); void addHasPart(LegalDocument val); } soupply/javabedrock261/src/main/java/soupply/bedrock261/protocol/play/ModalFormResponse.java package soupply.bedrock261.protocol.play; import java.util.*; import soupply.util.*; public class ModalFormResponse extends soupply.bedrock261.Packet { public static final int ID = 101; public int formId; public String data; public ModalFormResponse() { } public ModalFormResponse(int formId, String data) { this.formId = formId; this.data = data; } @Override public int getId() { return ID; } @Override public void encodeBody(Buffer _buffer) { _buffer.writeVaruint(formId); byte[] zfy = _buffer.convertString(data); _buffer.writeVaruint((int)zfy.length); _buffer.writeBytes(zfy); } @Override public void decodeBody(Buffer _buffer) throws DecodeException { formId = _buffer.readVaruint(); final int bvzfy = _buffer.readVaruint(); data = _buffer.readString(bvzfy); } public static ModalFormResponse fromBuffer(byte[] buffer) { ModalFormResponse packet = new ModalFormResponse(); packet.safeDecode(buffer); return packet; } } package com.everis.everledger.ifaces.account; import java.util.Collection; /** * This interface defines a simple NON-normative * example contract that an AccountManger must * implement for local NON-ILP related operations. * Most probably any ledger will implement other interfaces * * The concrete implementation, on the otherside, must * also implement the standard/normative * IfaceILPSpecAccountManager in order to provide support * for the Interledger ILP protocol. * See SimpleLedgerAccountManager for more info. * */ public interface IfaceLocalAccountManager { int getTotalAccounts(); boolean hasAccount(String name); IfaceAccount getAccountByName(String name); Collection getAccounts(int page, int pageSize); // If update == false and account already registered => throw exception IfaceAccount store(IfaceAccount account, boolean update); } package org.newsclub.net.unix; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import org.junit.Test; /** * Tests breaking out of accept. * * @see Issue * 6 */ public class CancelAcceptTest extends SocketTestBase { public CancelAcceptTest() throws IOException { super(); } private boolean serverSocketClosed = false; @Test public void issue6test1() throws Exception { serverSocketClosed = false; final ServerThread st = new ServerThread() { @Override protected boolean handleConnection(final Socket sock) throws IOException { return true; } @Override protected void onServerSocketClose() { serverSocketClosed = true; } }; AFUNIXSocket sock; sock = connectToServer(); sock.close(); sock = connectToServer(); sock.close(); final ServerSocket servSock = st.getServerSocket(); assertFalse("ServerSocket should not be closed now", serverSocketClosed && !servSock.isClosed()); servSock.close(); try { sock = connectToServer(); } catch (final SocketException e) { // as expected } assertTrue("ServerSocket should be closed now", serverSocketClosed || servSock.isClosed()); try { sock = connectToServer(); fail("ServerSocket should have been closed already"); } catch (final SocketException e) { // as expected } } } adamkorzeniak/master-datasrc/main/java/com/adamkorzeniak/masterdata/features/movie/model/dto/MovieDTO.java package com.adamkorzeniak.masterdata.features.movie.model.dto; import java.time.LocalDate; import java.util.List; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @Getter @Setter @NoArgsConstructor @ToString public class MovieDTO { private Long id; @NotBlank @NotNull private String title; @NotBlank private String originalTitle; @Min(1800) @Max(2999) @NotNull private Integer year; @Min(0) @Max(1000) @NotNull private Integer duration; @NotBlank private String directors; @NotBlank private String productionCountries; @Min(0) @Max(10) private Float filmwebRating; @Min(0) private Integer filmwebRatingCount; @Min(0) private Integer filmwebTopRanking; @Min(0) @Max(10) private Integer rating; @Min(0) @Max(5) private Integer watchPriority; private String filmPlot; private String description; private String review; private String plotSummary; private LocalDate reviewDate; private List genres; } package org.java.core; import java.util.Scanner; /* * Write a java program to check input no is part of Fibonacci series or not? * print Fibonacci series till that point */ public class Fibonacci { public static void main(String ...strings) { int number; Scanner sc=new Scanner(System.in); number=sc.nextInt(); fibonacci(number); } public static void fibonacci(Integer number) { int a=0,b=1,c=0,i; System.out.print(a+" "+b); for(i=2;c ** ** Licenced under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License ** ** Licence summary: ** Under this licence you are free to: ** Share — copy and redistribute the material in any medium or format ** Adapt — remix, transform, and build upon the material ** The licensor cannot revoke these freedoms as long as you follow the license terms. ** ** Under the following terms: ** Attribution — You must give appropriate credit, provide a link to the license, and indicate ** if changes were made. You may do so in any reasonable manner, but not in any ** way that suggests the licensor endorses you or your use. ** NonCommercial — You may not use the material for commercial purposes. ** ShareAlike — If you remix, transform, or build upon the material, you must distribute your ** contributions under the same license as the original. ** No additional restrictions ** — You may not apply legal terms or technological measures that legally restrict ** others from doing anything the license permits. ** ** See full licencing details here: http://creativecommons.org/licenses/by-nc-sa/3.0/ ** ** For additional licencing rights please contact ** */ package state2vec; import java.util.ArrayList; import java.util.Arrays; public abstract class KDTree{ //use a big bucketSize so that we have less node bounds (for more cache hits) and better splits private static final int _bucketSize = 50; private final int _dimensions; private int _nodes; private final Node root; private final ArrayList nodeList = new ArrayList(); //prevent GC from having to collect _bucketSize*dimensions*8 bytes each time a leaf splits private double[] mem_recycle; //the starting values for bounding boxes, for easy access private final double[] bounds_template; //one big self-expanding array to keep all the node bounding boxes so that they stay in cache // node bounds available at: //low: 2 * _dimensions * node.index + 2 * dim //high: 2 * _dimensions * node.index + 2 * dim + 1 private final ContiguousDoubleArrayList nodeMinMaxBounds; private KDTree(int dimensions){ _dimensions = dimensions; //initialise this big so that it ends up in 'old' memory nodeMinMaxBounds = new ContiguousDoubleArrayList(512 * 1024 / 8 + 2*_dimensions); mem_recycle = new double[_bucketSize*dimensions]; bounds_template = new double[2*_dimensions]; Arrays.fill(bounds_template,Double.NEGATIVE_INFINITY); for(int i = 0, max = 2*_dimensions; i < max; i+=2) bounds_template[i] = Double.POSITIVE_INFINITY; //and.... start! root = new Node(); } public int nodes(){ return _nodes; } public int size(){ return root.entries; } public int addPoint(double[] location, T payload){ Node addNode = root; //Do a Depth First Search to find the Node where 'location' should be stored while(addNode.pointLocations == null){ addNode.expandBounds(location); if(location[addNode.splitDim] < addNode.splitVal) addNode = nodeList.get(addNode.lessIndex); else addNode = nodeList.get(addNode.moreIndex); } addNode.expandBounds(location); int nodeSize = addNode.add(location,payload); if(nodeSize % _bucketSize == 0) //try splitting again once every time the node passes a _bucketSize multiple //in case it is full of points of the same location and won't split addNode.split(); return root.entries; } public ArrayList> nearestNeighbours(double[] searchLocation, int K){ IntStack stack = new IntStack(); PrioQueue results = new PrioQueue(K,true); stack.push(root.index); int added = 0; while(stack.size() > 0 ){ int nodeIndex = stack.pop(); if(added < K || results.peekPrio() > pointRectDist(nodeIndex,searchLocation)){ Node node = nodeList.get(nodeIndex); if(node.pointLocations == null) node.search(searchLocation,stack); else added += node.search(searchLocation,results); } } ArrayList> returnResults = new ArrayList>(K); double[] priorities = results.priorities; Object[] elements = results.elements; for(int i = 0; i < K; i++){//forward (closest first) SearchResult s = new SearchResult(priorities[i],(T)elements[i]); returnResults.add(s); } return returnResults; } public ArrayList ballSearch(double[] searchLocation, double radius){ IntStack stack = new IntStack(); ArrayList results = new ArrayList(); stack.push(root.index); while(stack.size() > 0 ){ int nodeIndex = stack.pop(); if(radius > pointRectDist(nodeIndex, searchLocation)){ Node node = nodeList.get(nodeIndex); if(node.pointLocations == null) stack.push(node.moreIndex).push(node.lessIndex); else node.searchBall(searchLocation, radius, results); } } return results; } public ArrayList rectSearch(double[] mins, double[] maxs){ IntStack stack = new IntStack(); ArrayList results = new ArrayList(); stack.push(root.index); while(stack.size() > 0 ){ int nodeIndex = stack.pop(); if(overlaps(mins,maxs,nodeIndex)){ Node node = nodeList.get(nodeIndex); if(node.pointLocations == null) stack.push(node.moreIndex).push(node.lessIndex); else node.searchRect(mins, maxs, results); } } return results; } abstract double pointRectDist(int offset, final double[] location); abstract double pointDist(double[] arr, double[] location, int index); boolean contains(double[] arr, double[] mins, double[] maxs, int index){ int offset = (index+1)*mins.length; for(int i = mins.length; i-- > 0 ;){ double d = arr[--offset]; if(mins[i] > d | d > maxs[i]) return false; } return true; } boolean overlaps(double[] mins, double[] maxs, int offset){ offset *= (2*maxs.length); final double[] array = nodeMinMaxBounds.array; for(int i = 0; i < maxs.length; i++,offset += 2){ double bmin = array[offset], bmax = array[offset+1]; if(mins[i] > bmax | maxs[i] < bmin) return false; } return true; } public static class Euclidean extends KDTree{ public Euclidean(int dims){ super(dims); } double pointRectDist(int offset, final double[] location){ offset *= (2*super._dimensions); double distance=0; final double[] array = super.nodeMinMaxBounds.array; for(int i = 0; i < location.length; i++,offset += 2){ double diff = 0; double bv = array[offset]; double lv = location[i]; if(bv > lv) diff = bv-lv; else{ bv=array[offset+1]; if(lv>bv) diff = lv-bv; } distance += sqr(diff); } return distance; } double pointDist(double[] arr, double[] location, int index){ double distance = 0; int offset = (index+1)*super._dimensions; for(int i = super._dimensions; i-- > 0 ;){ distance += sqr(arr[--offset] - location[i]); } return distance; } } public static class Manhattan extends KDTree{ public Manhattan(int dims){ super(dims); } double pointRectDist(int offset, final double[] location){ offset *= (2*super._dimensions); double distance=0; final double[] array = super.nodeMinMaxBounds.array; for(int i = 0; i < location.length; i++,offset += 2){ double diff = 0; double bv = array[offset]; double lv = location[i]; if(bv > lv) diff = bv-lv; else{ bv=array[offset+1]; if(lv>bv) diff = lv-bv; } distance += (diff); } return distance; } double pointDist(double[] arr, double[] location, int index){ double distance = 0; int offset = (index+1)*super._dimensions; for(int i = super._dimensions; i-- > 0 ;){ distance += Math.abs(arr[--offset] - location[i]); } return distance; } } public static class WeightedManhattan extends KDTree{ double[] weights; public WeightedManhattan(int dims){ super(dims); } public void setWeights(double[] newWeights){ weights = newWeights; } double pointRectDist(int offset, final double[] location){ offset *= (2*super._dimensions); double distance=0; final double[] array = super.nodeMinMaxBounds.array; for(int i = 0; i < location.length; i++,offset += 2){ double diff = 0; double bv = array[offset]; double lv = location[i]; if(bv > lv) diff = bv-lv; else{ bv=array[offset+1]; if(lv>bv) diff = lv-bv; } distance += (diff)*weights[i]; } return distance; } double pointDist(double[] arr, double[] location, int index){ double distance = 0; int offset = (index+1)*super._dimensions; for(int i = super._dimensions; i-- > 0 ;){ distance += Math.abs(arr[--offset] - location[i])*weights[i]; } return distance; } } //NB! This Priority Queue keeps things with the LOWEST priority. //If you want highest priority items kept, negate your values private static class PrioQueue{ Object[] elements; double[] priorities; private double minPrio; private int size; PrioQueue(int size, boolean prefill){ elements = new Object[size]; priorities = new double[size]; Arrays.fill(priorities,Double.POSITIVE_INFINITY); if(prefill){ minPrio = Double.POSITIVE_INFINITY; this.size = size; } } //uses O(log(n)) comparisons and one big shift of size O(N) //and is MUCH simpler than a heap --> faster on small sets, faster JIT void addNoGrow(S value, double priority){ int index = searchFor(priority); int nextIndex = index + 1; int length = size - index - 1; System.arraycopy(elements,index,elements,nextIndex,length); System.arraycopy(priorities,index,priorities,nextIndex,length); elements[index]=value; priorities[index]=priority; minPrio = priorities[size-1]; } int searchFor(double priority){ int i = size-1; int j = 0; while(i>=j){ int index = (i+j)>>>1; if( priorities[index] < priority) j = index+1; else i = index-1; } return j; } double peekPrio(){ return minPrio; } } public static class SearchResult{ public double distance; public S payload; SearchResult(double dist, S load){ distance = dist; payload = load; } @Override public String toString() { return "" + payload.toString(); } } private class Node { //for accessing bounding box data // - if trees weren't so unbalanced might be better to use an implicit heap? int index; //keep track of size of subtree int entries; //leaf ContiguousDoubleArrayList pointLocations ; ArrayList pointPayloads = new ArrayList(_bucketSize); //stem //Node less, more; int lessIndex, moreIndex; int splitDim; double splitVal; Node(){ this(new double[_bucketSize*_dimensions]); } Node(double[] pointMemory){ pointLocations = new ContiguousDoubleArrayList(pointMemory); index = _nodes++; nodeList.add(this); nodeMinMaxBounds.add(bounds_template); } void search(double[] searchLocation, IntStack stack){ if(searchLocation[splitDim] < splitVal) stack.push(moreIndex).push(lessIndex);//less will be popped first else stack.push(lessIndex).push(moreIndex);//more will be popped first } //returns number of points added to results int search(double[] searchLocation, PrioQueue results){ int updated = 0; for(int j = entries; j-- > 0;){ double distance = pointDist(pointLocations.array,searchLocation,j); if(results.peekPrio() > distance){ updated++; results.addNoGrow(pointPayloads.get(j),distance); } } return updated; } void searchBall(double[] searchLocation, double radius, ArrayList results){ for(int j = entries; j-- > 0;){ double distance = pointDist(pointLocations.array,searchLocation,j); if(radius >= distance){ results.add(pointPayloads.get(j)); } } } void searchRect(double[] mins, double[] maxs, ArrayList results){ for(int j = entries; j-- > 0;) if(contains(pointLocations.array,mins,maxs,j)) results.add(pointPayloads.get(j)); } void expandBounds(double[] location){ entries++; int mio = index*2*_dimensions; for(int i = 0; i < _dimensions;i++){ nodeMinMaxBounds.array[mio] = Math.min(nodeMinMaxBounds.array[mio++],location[i]); nodeMinMaxBounds.array[mio] = Math.max(nodeMinMaxBounds.array[mio++],location[i]); } } int add(double[] location, T load){ pointLocations.add(location); pointPayloads.add(load); return entries; } void split(){ int offset = index*2*_dimensions; double diff = 0; for(int i = 0; i < _dimensions; i++){ double min = nodeMinMaxBounds.array[offset]; double max = nodeMinMaxBounds.array[offset+1]; if(max-min>diff){ double mean = 0; for(int j = 0; j < entries; j++) mean += pointLocations.array[i+_dimensions*j]; mean = mean/entries; double varianceSum = 0; for(int j = 0; j < entries; j++) varianceSum += sqr(mean-pointLocations.array[i+_dimensions*j]); if(varianceSum>diff*entries){ diff = varianceSum/entries; splitVal = mean; splitDim = i; } } offset += 2; } //kill all the nasties if(splitVal == Double.POSITIVE_INFINITY) splitVal = Double.MAX_VALUE; else if(splitVal == Double.NEGATIVE_INFINITY) splitVal = Double.MIN_VALUE; else if(splitVal == nodeMinMaxBounds.array[index*2*_dimensions + 2*splitDim + 1]) splitVal = nodeMinMaxBounds.array[index*2*_dimensions + 2*splitDim]; Node less = new Node(mem_recycle);//recycle that memory! Node more = new Node(); lessIndex = less.index; moreIndex = more.index; //reduce garbage by factor of _bucketSize by recycling this array double[] pointLocation = new double[_dimensions]; for(int i = 0; i < entries; i++){ System.arraycopy(pointLocations.array,i*_dimensions,pointLocation,0,_dimensions); T load = pointPayloads.get(i); if(pointLocation[splitDim] < splitVal){ less.expandBounds(pointLocation); less.add(pointLocation,load); } else{ more.expandBounds(pointLocation); more.add(pointLocation,load); } } if(less.entries*more.entries == 0){ //one of them was 0, so the split was worthless. throw it away. _nodes -= 2;//recall that bounds memory nodeList.remove(moreIndex); nodeList.remove(lessIndex); } else{ //we won't be needing that now, so keep it for the next split to reduce garbage mem_recycle = pointLocations.array; pointLocations = null; pointPayloads.clear(); pointPayloads = null; } } } private static class ContiguousDoubleArrayList{ double[] array; int size; ContiguousDoubleArrayList(){this(300);} ContiguousDoubleArrayList(int size){this(new double[size]);} ContiguousDoubleArrayList(double[] data){array = data;} ContiguousDoubleArrayList add(double[] da){ if(size + da.length > array.length) array = Arrays.copyOf(array,(array.length+da.length)*2); System.arraycopy(da,0,array,size,da.length); size += da.length; return this; } } private static class IntStack{ int[] array; int size; IntStack(){this(64);} IntStack(int size){this(new int[size]);} IntStack(int[] data){array = data;} IntStack push(int i){ if(size>= array.length) array = Arrays.copyOf(array,(array.length+1)*2); array[size++] = i; return this; } int pop(){ return array[--size]; } int size(){ return size; } } static final double sqr(double d){ return d*d;} }christian-morin/quarkus package io.quarkus.opentelemetry.runtime.tracing.vertx; import static io.opentelemetry.context.Context.current; import static io.opentelemetry.semconv.trace.attributes.SemanticAttributes.HTTP_CLIENT_IP; import static io.opentelemetry.semconv.trace.attributes.SemanticAttributes.HTTP_FLAVOR; import static io.opentelemetry.semconv.trace.attributes.SemanticAttributes.HTTP_HOST; import static io.opentelemetry.semconv.trace.attributes.SemanticAttributes.HTTP_METHOD; import static io.opentelemetry.semconv.trace.attributes.SemanticAttributes.HTTP_ROUTE; import static io.opentelemetry.semconv.trace.attributes.SemanticAttributes.HTTP_SCHEME; import static io.opentelemetry.semconv.trace.attributes.SemanticAttributes.HTTP_STATUS_CODE; import static io.opentelemetry.semconv.trace.attributes.SemanticAttributes.HTTP_TARGET; import static io.opentelemetry.semconv.trace.attributes.SemanticAttributes.HTTP_URL; import static io.opentelemetry.semconv.trace.attributes.SemanticAttributes.HTTP_USER_AGENT; import static io.quarkus.opentelemetry.runtime.tracing.vertx.VertxUtil.extractClientIP; import static io.vertx.core.http.HttpHeaders.CONTENT_LENGTH; import static io.vertx.core.http.HttpHeaders.USER_AGENT; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.function.BiConsumer; import javax.enterprise.inject.spi.CDI; import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.SpanBuilder; import io.opentelemetry.api.trace.StatusCode; import io.opentelemetry.api.trace.Tracer; import io.opentelemetry.context.Scope; import io.opentelemetry.context.propagation.TextMapGetter; import io.opentelemetry.context.propagation.TextMapPropagator; import io.opentelemetry.context.propagation.TextMapSetter; import io.opentelemetry.semconv.trace.attributes.SemanticAttributes; import io.vertx.core.Context; import io.vertx.core.http.HttpServerRequest; import io.vertx.core.http.HttpServerResponse; import io.vertx.core.http.HttpVersion; import io.vertx.core.impl.ContextInternal; import io.vertx.core.spi.VertxTracerFactory; import io.vertx.core.spi.tracing.SpanKind; import io.vertx.core.spi.tracing.TagExtractor; import io.vertx.core.spi.tracing.VertxTracer; import io.vertx.core.tracing.TracingOptions; import io.vertx.core.tracing.TracingPolicy; public class VertxTracingAdapter extends TracingOptions implements VertxTracer, VertxTracerFactory { private static final String SCOPE_KEY = VertxTracingAdapter.class.getName() + ".scope"; private static final String SPAN_KEY = VertxTracingAdapter.class.getName() + ".activeSpan"; private static TextMapPropagator TEXT_MAP_PROPAGATOR; private Tracer tracer; public void init() { tracer = CDI.current().select(Tracer.class).get(); TEXT_MAP_PROPAGATOR = GlobalOpenTelemetry.getPropagators().getTextMapPropagator(); } // TracingOptions overrides @Override public VertxTracerFactory getFactory() { return this; } // VertxTracerFactory overrides @Override public VertxTracer tracer(final TracingOptions options) { return this; } // VertxTracer overrides @Override public Span receiveRequest( final Context context, final SpanKind kind, final TracingPolicy policy, final R request, final String operation, final Iterable> headers, final TagExtractor tagExtractor) { ((ContextInternal) context).dispatch(() -> { io.opentelemetry.context.Context currentContext = current(); // Retrieve any incoming Span io.opentelemetry.context.Context propagatedContext = TEXT_MAP_PROPAGATOR.extract(currentContext, headers, GETTER); SpanBuilder builder; // Create new span builder = tracer.spanBuilder(operationName(request, operation)) .setParent(propagatedContext) .setSpanKind(SpanKind.RPC.equals(kind) ? io.opentelemetry.api.trace.SpanKind.SERVER : io.opentelemetry.api.trace.SpanKind.CONSUMER); //TODO - Figure out how to handle span name in a better way. if (request instanceof HttpServerRequest) { HttpServerRequest httpServerRequest = (HttpServerRequest) request; // Add attributes builder.setAttribute(HTTP_FLAVOR, convertHttpVersion(httpServerRequest.version())); builder.setAttribute(HTTP_METHOD, httpServerRequest.method().name()); builder.setAttribute(HTTP_TARGET, httpServerRequest.path()); builder.setAttribute(HTTP_SCHEME, httpServerRequest.scheme()); builder.setAttribute(HTTP_HOST, httpServerRequest.host()); builder.setAttribute(HTTP_CLIENT_IP, extractClientIP(httpServerRequest)); builder.setAttribute(HTTP_USER_AGENT, httpServerRequest.getHeader(USER_AGENT)); String contentLength = httpServerRequest.getHeader(CONTENT_LENGTH); if (contentLength != null && contentLength.length() > 0 && Long.parseLong(contentLength) > 0) { builder.setAttribute(SemanticAttributes.HTTP_REQUEST_CONTENT_LENGTH, Long.valueOf(contentLength)); } else { builder.setAttribute(SemanticAttributes.HTTP_REQUEST_CONTENT_LENGTH, httpServerRequest.bytesRead()); } } final Span currentSpan = builder.startSpan(); context.putLocal(SPAN_KEY, currentSpan); context.putLocal(SCOPE_KEY, currentSpan.makeCurrent()); }); return context.getLocal(SPAN_KEY); } private String operationName(R request, String operationName) { if (request instanceof HttpServerRequest) { return ((HttpServerRequest) request).uri().substring(1); } return operationName; } @Override public void sendResponse( final Context context, final R response, final Span span, final Throwable failure, final TagExtractor tagExtractor) { context.removeLocal(SPAN_KEY); if (span == null) { return; } // Update Span name if parameterized path present String pathTemplate = context.getLocal("UrlPathTemplate"); if (pathTemplate != null && !pathTemplate.isEmpty()) { span.updateName(pathTemplate.substring(1)); span.setAttribute(HTTP_ROUTE, pathTemplate); } ((ContextInternal) context).dispatch(() -> { if (failure != null) { span.setStatus(StatusCode.ERROR); span.recordException(failure); } if (response != null) { if (response instanceof HttpServerResponse) { HttpServerResponse httpServerResponse = (HttpServerResponse) response; span.setAttribute(HTTP_STATUS_CODE, httpServerResponse.getStatusCode()); } } span.end(); Scope spanScope = context.getLocal(SCOPE_KEY); if (spanScope != null) { spanScope.close(); context.removeLocal(SCOPE_KEY); } }); } @Override public Span sendRequest( final Context context, final SpanKind kind, final TracingPolicy policy, final R request, final String operation, final BiConsumer headers, final TagExtractor tagExtractor) { if (policy.equals(TracingPolicy.IGNORE)) { /* * SmallRye Reactive Messaging with Kafka is responsible for creating spans for outgoing messages. * In this SPI call there is no way to know whether it has happened. * The current approach to prevent duplicate spans is for the Kafka client in SmallRye Reactive Messaging * to set TracingPolicy.IGNORE * Disabling tracing in Quarkus will not be done with TracingPolicy.IGNORE, * allowing it to be used for this purpose. */ return null; } ((ContextInternal) context).dispatch(() -> { // Create new span SpanBuilder builder = tracer.spanBuilder(operationName(request, operation)) .setSpanKind(SpanKind.RPC.equals(kind) ? io.opentelemetry.api.trace.SpanKind.CLIENT : io.opentelemetry.api.trace.SpanKind.PRODUCER); if (request instanceof HttpServerRequest) { HttpServerRequest httpServerRequest = (HttpServerRequest) request; // Add attributes builder.setAttribute(HTTP_METHOD, httpServerRequest.method().name()); builder.setAttribute(HTTP_URL, httpServerRequest.uri()); } final Span outgoingSpan = builder.startSpan(); TEXT_MAP_PROPAGATOR.inject(io.opentelemetry.context.Context.current().with(outgoingSpan), headers, SETTER); context.putLocal(SPAN_KEY, outgoingSpan); }); return context.getLocal(SPAN_KEY); } @Override public void receiveResponse( final Context context, final R response, final Span span, final Throwable failure, final TagExtractor tagExtractor) { context.removeLocal(SPAN_KEY); if (span == null) { return; } ((ContextInternal) context).dispatch(() -> { if (failure != null) { span.recordException(failure); } if (response != null) { if (response instanceof HttpServerResponse) { HttpServerResponse httpServerResponse = (HttpServerResponse) response; // Add attributes span.setAttribute(HTTP_STATUS_CODE, httpServerResponse.getStatusCode()); } } span.end(); }); } private static String convertHttpVersion(HttpVersion version) { switch (version) { case HTTP_1_0: return "1.0"; case HTTP_1_1: return "1.1"; case HTTP_2: return "2.0"; default: return ""; } } public static final TextMapGetter>> GETTER = new TextMapGetter>>() { @Override public Iterable keys(final Iterable> carrier) { final Set keys = new HashSet<>(); for (Map.Entry entry : carrier) { keys.add(entry.getKey()); } return keys; } @Override public String get(final Iterable> carrier, final String key) { if (carrier == null) { return null; } for (Map.Entry entry : carrier) { if (entry.getKey().equalsIgnoreCase(key)) { return entry.getValue(); } } return null; } }; public static final TextMapSetter> SETTER = new TextMapSetter>() { @Override public void set(BiConsumer carrier, String key, String value) { if (carrier == null) { return; } carrier.accept(key, value); } }; } vania-pooh/perspective-backend package org.meridor.perspective.mock; import org.meridor.perspective.beans.Image; import org.meridor.perspective.config.Cloud; import org.meridor.perspective.config.OperationType; import org.meridor.perspective.worker.misc.IdGenerator; import org.meridor.perspective.worker.operation.ProcessingOperation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.function.Supplier; import static org.meridor.perspective.config.OperationType.ADD_IMAGE; @Component public class AddImageOperation implements ProcessingOperation { private static final Logger LOG = LoggerFactory.getLogger(AddImageOperation.class); @Autowired private ImagesStorage images; @Autowired private IdGenerator idGenerator; @Override public Image perform(Cloud cloud, Supplier supplier) { Image image = supplier.get(); if (images.add(image)) { String id = idGenerator.getImageId(cloud, image.getName()); image.setId(id); image.setRealId(id); LOG.info("Added image {} ({})", image.getName(), image.getId()); return image; } else { LOG.info("Failed to add image {} ({})", image.getName(), image.getId()); return null; } } @Override public OperationType[] getTypes() { return new OperationType[]{ADD_IMAGE}; } } package chylex.hee.mechanics.wand; import net.minecraft.item.ItemStack; public enum WandType{ BASIC(2,13), ADVANCED(3,17), EPIC(4,25); public static WandType[] values = values(); public final byte slots; public final byte baseDamage; WandType(int slots, int baseDamage){ this.slots = (byte)slots; this.baseDamage = (byte)baseDamage; } public static WandType fromItemStack(ItemStack is){ int dmg = is.getItemDamage(); return dmg >= 0 && dmg < values.length ? values[dmg] : BASIC; } } 1-10 package com.ln.question18; public class HasSubTree { /** * 判断树中是否包含子树 * 判断根节点是否相等 * 不相等就返回false * 相等就继续检查左右结点是否相等 * @param root * @param child * @return */ public static boolean tree1hastree2(TreeNode root,TreeNode child){ // Boolean flag= false; if(child==null){ return true; } if(root==null){ return false; } if(root.value!=child.value){ return false; } return tree1hastree2(root.leftChild,child.leftChild)&&tree1hastree2(root.rightChild,child.rightChild); } /** * 先从根节点开始判断是否与子树相等 * 如果不想等先遍历左子树 再遍历右子树 * * @param root * @param child * @return */ public static boolean Hastree(TreeNode root,TreeNode child){ boolean flag = false; if(root!=null&&child!=null){ flag = tree1hastree2(root,child); if(!flag){ flag = Hastree(root.leftChild,child); } if(!flag){ flag = Hastree(root.rightChild,child); }} return flag; } public static void main(String[] args) { TreeNode t1 = new TreeNode(1); TreeNode t2 = new TreeNode(2); TreeNode t3 = new TreeNode(3); TreeNode t4 = new TreeNode(4); TreeNode t5 = new TreeNode(5); t1.leftChild=t2; t1.rightChild=t3; t2.leftChild=t4; t2.rightChild=t5; TreeNode q = new TreeNode(2); TreeNode q1 = new TreeNode(4); TreeNode q2 = new TreeNode(5); q.leftChild=q1; q.rightChild=q2; System.out.println(Hastree(t1,q)); } } phoneProfilesPlus/src/main/java/sk/henrichg/phoneprofilesplus/PreferenceActivity.java package sk.henrichg.phoneprofilesplus; import android.annotation.TargetApi; import android.app.FragmentTransaction; import android.os.Build; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; abstract class PreferenceActivity extends AppCompatPreferenceActivity { Toolbar toolbar; @TargetApi(Build.VERSION_CODES.HONEYCOMB) void setPreferenceFragment(PreferenceFragment preferenceFragment) { //First check if it's already loaded (configuration change) so we don't overlap fragments if(getFragmentManager() .findFragmentByTag("sk.henrichg.phoneprofilesplus.MainFragment") != null){ return; } FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction(); //if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { fragmentTransaction.replace(R.id.content, preferenceFragment, "sk.henrichg.phoneprofilesplus.MainFragment"); //}else{ // fragmentTransaction.replace(android.R.id.content, preferenceFragment, // "sk.henrichg.phoneprofilesplus.MainFragment"); //} fragmentTransaction.commit(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mp_activity_settings); if (Build.VERSION.SDK_INT >= 21) { View toolbarShadow = findViewById(R.id.mp_activity_settings_toolbar_shadow); if (toolbarShadow != null) toolbarShadow.setVisibility(View.GONE); } toolbar = findViewById(R.id.mp_toolbar); setSupportActionBar(toolbar); getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } @Override protected void onStart() { super.onStart(); GlobalGUIRoutines.lockScreenOrientation(this); } @Override protected void onStop() { super.onStop(); GlobalGUIRoutines.unlockScreenOrientation(this); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: if (getFragmentManager().getBackStackEntryCount() > 0) { getFragmentManager().popBackStack(); } else { finish(); } return true; } return super.onOptionsItemSelected(item); } PreferenceFragment getFragment() { int id; //if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { id = R.id.content; //} else { // id = android.R.id.content; //} return (PreferenceFragment) getFragmentManager().findFragmentById(id); } } package io.i4tech.odata.test.model.employee; import com.fasterxml.jackson.annotation.JsonValue; import io.i4tech.odata.common.model.ODataEnum; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; @XmlType(name = "EmployeeLanguageCode") @XmlEnum public enum EmployeeLanguageCode implements ODataEnum { @XmlEnumValue("DE") GERMAN("DE"), @XmlEnumValue("EN") ENGLISH("EN"), @XmlEnumValue("ES") SPANISH("ES"), @XmlEnumValue("FR") FRENCH("FR"), @XmlEnumValue("IT") ITALIAN("IT"), @XmlEnumValue("JA") JAPANESE("JA"), @XmlEnumValue("NL") DUTCH("NL"), @XmlEnumValue("PT") PORTUGUESE("PT"), @XmlEnumValue("ZH") CHINESE("ZH"); private final String value; EmployeeLanguageCode(String v) { value = v; } @JsonValue public String value() { return value; } public static EmployeeLanguageCode fromValue(String v) { for (EmployeeLanguageCode c: EmployeeLanguageCode.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } public static EmployeeLanguageCode fromNullable(String v) { try { return fromValue(v); } catch (Exception e) { return null; } } } 0 package flyway.userlayer; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import fi.nls.oskari.db.DBHandler; import fi.nls.oskari.db.DatasourceHelper; import org.flywaydb.core.api.migration.jdbc.JdbcMigration; import fi.nls.oskari.log.LogFactory; import fi.nls.oskari.log.Logger; import fi.nls.oskari.util.PropertyUtil; import javax.sql.DataSource; public class V1_0_11__populate_userlayer_wkt implements JdbcMigration { private static final Logger LOG = LogFactory.getLogger(V1_0_11__populate_userlayer_wkt.class); private static final int WGS84_SRID = 4326; public void migrate(Connection connection) throws Exception { // userlayers _can_ use other db than the default one // -> Use connection to default db for this migration DataSource ds = DatasourceHelper.getInstance().getDataSource(); if (ds == null) { ds = DatasourceHelper.getInstance().createDataSource(); } String srsName = getSrsName(ds.getConnection()); if (srsName == null){ LOG.error("Cannot get srs name for userlayer data"); throw new IllegalArgumentException("Cannot get srs name for userlayer data"); } int srid = getSRID(srsName); String geometryColumn = PropertyUtil.get("userlayer.geometry.name", "geometry"); String subselect = String.format("SELECT ST_AsText(ST_Transform(ST_SetSRID(ST_Extent(b.%s),%d),%d)) " + "FROM user_layer_data b " + "WHERE a.id = b.user_layer_id", geometryColumn, srid, WGS84_SRID); String sql = "UPDATE user_layer a SET wkt = (" + subselect + ")"; LOG.debug(sql); try (PreparedStatement ps = connection.prepareStatement(sql)) { int updated = ps.executeUpdate(); LOG.info("Updated wkt for ", updated, "user_layer rows"); } } private int getSRID(String srsName) { int i = srsName.lastIndexOf(':'); int srid = Integer.parseInt(srsName.substring(i + 1)); LOG.debug("Parsed SRID", srid, "from", srsName); return srid; } private String getSrsName(Connection conn) throws SQLException { String fromProperty = PropertyUtil.getOptionalNonLocalized("oskari.native.srs"); if (fromProperty != null && !fromProperty.isEmpty()) { return fromProperty; } LOG.debug("Could not find 'oskari.native.srs' property"); int baselayerId = PropertyUtil.getOptional("userlayer.baselayer.id", -1); String sql = "SELECT srs_name FROM oskari_maplayer WHERE id=?"; try (PreparedStatement statement = conn.prepareStatement(sql)) { statement.setInt(1, baselayerId); try (ResultSet rs = statement.executeQuery()) { if (rs.next()){ return rs.getString("srs_name"); } return null; } } } } package ch.hsr.ogv.dataaccess; import ch.hsr.ogv.model.ModelClass; import ch.hsr.ogv.model.Relation; import org.xml.sax.helpers.DefaultHandler; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.Map; /** * This class is the Definition for a XMI Handler. * * @author , * @version 3DCOV 3.0, May 2007 / OGV 3.1, May 2015 */ public class XMIHandler extends DefaultHandler { protected ArrayList xmiRelations = new ArrayList(); protected StringBuffer characters = new StringBuffer(); protected Map idClassMap = new LinkedHashMap(); /* * (non-Javadoc) * * @see org.xml.sax.helpers.DefaultHandler#characters(char[], int, int) */ public void characters(char[] pCH, int pStart, int pLength) { characters.append(pCH, pStart, pLength); } /** * Calls the mapping method and returns the class associations * * @return the read class associations */ public ArrayList getRelations() { return finalizeXMIRelations(); } /** * Returns the read classes * * @return read classes */ public ArrayList getClasses() { return new ArrayList(idClassMap.values()); } /** * Maps the read classes to the class relations using the class id's */ private ArrayList finalizeXMIRelations() { ArrayList relations = new ArrayList(); for (XMIRelation xmiRelation : xmiRelations) { ModelClass sourceClass = idClassMap.get(xmiRelation.getSourceID()); ModelClass targetClass = idClassMap.get(xmiRelation.getTargetID()); if (sourceClass != null && targetClass != null) { Relation relation = new Relation(sourceClass, targetClass, xmiRelation.getType()); relations.add(relation); relation.setName(xmiRelation.getName()); relation.getStart().setRoleName(xmiRelation.getSourceRoleName()); relation.getStart().setMultiplicity(xmiRelation.getSourceMultiplicity()); relation.getEnd().setRoleName(xmiRelation.getTargetRoleName()); relation.getEnd().setMultiplicity(xmiRelation.getTargetMultiplicity()); } } return relations; } }mjoyner-vbservices-net/CherokeeDictionaryShared package net.cherokeedictionary.model; import java.util.ArrayList; import java.util.Date; import java.util.List; public class DictionaryEntry implements Comparable { public int id; public String source; public String pos; public List forms=new ArrayList<>(); public List definitions=new ArrayList<>(); public List examples=new ArrayList<>(); public List notes=new ArrayList<>(); public List crossreferences=new ArrayList<>(); public Date modified; public DictionaryEntry() { } /** * Creates a new object that is a shallow copy of the source. * @param entry */ public DictionaryEntry(DictionaryEntry entry){ id=entry.id; source=entry.source; pos=entry.pos; forms.addAll(entry.forms); definitions.addAll(entry.definitions); examples.addAll(entry.examples); notes.addAll(entry.notes); crossreferences.addAll(entry.crossreferences); modified=entry.modified; } public static class EntryForm { public EntryForm() { } public EntryForm(EntryFormType formType, String syllabary, String pronunciation, String latin) { this.formType=formType; this.syllabary=syllabary; this.pronunciation=pronunciation; this.latin=latin; } public EntryFormType formType=EntryFormType.Other; public String syllabary; public String pronunciation; public String latin; } public static class EntryExample { public EntryExample() { } public EntryExample(String syllabary, String latin, String english) { this.syllabary=syllabary; this.latin=latin; this.english=english; } public String syllabary; public String latin; public String english; } public static enum EntryFormType { Verb3rdPrc, Verb1stPrc, Verb3rdPast, Verb3rdHab, Verb2ndImp, Verb3rdImp, Verb3rdInf, Other; } public static class Note { public Note() { } public Note(String note) { this.note=note; } public String note; } public static class Crossreference { public Crossreference() { } public Crossreference(String crossreferencet) { this.crossReference=crossreferencet; } public String crossReference; } private String _sortKey=null; private String getSortKey(){ if (_sortKey!=null) { return _sortKey; } StringBuilder sb = new StringBuilder(); for (EntryForm form: forms){ if (form.syllabary!=null&&!form.syllabary.isEmpty()) { if (sb.length()!=0) { sb.append("-"); } sb.append(form.syllabary); } } for (EntryForm form: forms){ if (form.pronunciation!=null&&!form.pronunciation.isEmpty()) { if (sb.length()!=0) { sb.append("-"); } sb.append(form.pronunciation); } } _sortKey=sb.toString(); return _sortKey; } @Override public int compareTo(DictionaryEntry o) { return getSortKey().compareTo(o.getSortKey()); } } v3/sophia_scaffolding/sophia_common/sophia_common_security/src/main/java/com/scaffolding/sophia/common/security/component/SophiaAuth2ExceptionSerializer.java package com.scaffolding.sophia.common.security.component; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.std.StdSerializer; import com.scaffolding.sophia.common.base.constants.GlobalsConstants; import com.scaffolding.sophia.common.security.exception.SophiaAuth2Exception; import lombok.SneakyThrows; /** * @author: LHL * @ProjectName: sophia_scaffolding * @Package: com.scaffolding.sophia.common.security.component * @ClassName: SophiaAuth2ExceptionSerializer * @Description: OAuth2 异常格式化 * @Version: 1.0 */ public class SophiaAuth2ExceptionSerializer extends StdSerializer { public SophiaAuth2ExceptionSerializer() { super(SophiaAuth2Exception.class); } @Override @SneakyThrows public void serialize(SophiaAuth2Exception value, JsonGenerator gen, SerializerProvider provider) { gen.writeStartObject(); gen.writeObjectField("code", GlobalsConstants.FAIL); gen.writeStringField("msg", value.getMessage()); gen.writeStringField("data", value.getErrorCode()); gen.writeEndObject(); } } src/main/java/hr/vkeglevic/doomsdayterminal/model/events/ReadDataEvent.java package hr.vkeglevic.doomsdayterminal.model.events; /** * * @author vanja */ public class ReadDataEvent { private final byte[] data; public ReadDataEvent(byte[] data) { this.data = data; } public byte[] getData() { return data; } } package com.vmware.vim25; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** *

Java class for VMwareDvsLacpLoadBalanceAlgorithm. * *

The following schema fragment specifies the expected content contained within this class. *

*

 * <simpleType name="VMwareDvsLacpLoadBalanceAlgorithm">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *     <enumeration value="srcMac"/>
 *     <enumeration value="destMac"/>
 *     <enumeration value="srcDestMac"/>
 *     <enumeration value="destIpVlan"/>
 *     <enumeration value="srcIpVlan"/>
 *     <enumeration value="srcDestIpVlan"/>
 *     <enumeration value="destTcpUdpPort"/>
 *     <enumeration value="srcTcpUdpPort"/>
 *     <enumeration value="srcDestTcpUdpPort"/>
 *     <enumeration value="destIpTcpUdpPort"/>
 *     <enumeration value="srcIpTcpUdpPort"/>
 *     <enumeration value="srcDestIpTcpUdpPort"/>
 *     <enumeration value="destIpTcpUdpPortVlan"/>
 *     <enumeration value="srcIpTcpUdpPortVlan"/>
 *     <enumeration value="srcDestIpTcpUdpPortVlan"/>
 *     <enumeration value="destIp"/>
 *     <enumeration value="srcIp"/>
 *     <enumeration value="srcDestIp"/>
 *     <enumeration value="vlan"/>
 *     <enumeration value="srcPortId"/>
 *   </restriction>
 * </simpleType>
 * 
* */ @XmlType(name = "VMwareDvsLacpLoadBalanceAlgorithm") @XmlEnum public enum VMwareDvsLacpLoadBalanceAlgorithm { @XmlEnumValue("srcMac") SRC_MAC("srcMac"), @XmlEnumValue("destMac") DEST_MAC("destMac"), @XmlEnumValue("srcDestMac") SRC_DEST_MAC("srcDestMac"), @XmlEnumValue("destIpVlan") DEST_IP_VLAN("destIpVlan"), @XmlEnumValue("srcIpVlan") SRC_IP_VLAN("srcIpVlan"), @XmlEnumValue("srcDestIpVlan") SRC_DEST_IP_VLAN("srcDestIpVlan"), @XmlEnumValue("destTcpUdpPort") DEST_TCP_UDP_PORT("destTcpUdpPort"), @XmlEnumValue("srcTcpUdpPort") SRC_TCP_UDP_PORT("srcTcpUdpPort"), @XmlEnumValue("srcDestTcpUdpPort") SRC_DEST_TCP_UDP_PORT("srcDestTcpUdpPort"), @XmlEnumValue("destIpTcpUdpPort") DEST_IP_TCP_UDP_PORT("destIpTcpUdpPort"), @XmlEnumValue("srcIpTcpUdpPort") SRC_IP_TCP_UDP_PORT("srcIpTcpUdpPort"), @XmlEnumValue("srcDestIpTcpUdpPort") SRC_DEST_IP_TCP_UDP_PORT("srcDestIpTcpUdpPort"), @XmlEnumValue("destIpTcpUdpPortVlan") DEST_IP_TCP_UDP_PORT_VLAN("destIpTcpUdpPortVlan"), @XmlEnumValue("srcIpTcpUdpPortVlan") SRC_IP_TCP_UDP_PORT_VLAN("srcIpTcpUdpPortVlan"), @XmlEnumValue("srcDestIpTcpUdpPortVlan") SRC_DEST_IP_TCP_UDP_PORT_VLAN("srcDestIpTcpUdpPortVlan"), @XmlEnumValue("destIp") DEST_IP("destIp"), @XmlEnumValue("srcIp") SRC_IP("srcIp"), @XmlEnumValue("srcDestIp") SRC_DEST_IP("srcDestIp"), @XmlEnumValue("vlan") VLAN("vlan"), @XmlEnumValue("srcPortId") SRC_PORT_ID("srcPortId"); private final String value; VMwareDvsLacpLoadBalanceAlgorithm(String v) { value = v; } public String value() { return value; } public static VMwareDvsLacpLoadBalanceAlgorithm fromValue(String v) { for (VMwareDvsLacpLoadBalanceAlgorithm c: VMwareDvsLacpLoadBalanceAlgorithm.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } } filedossier-document-validation/src/main/java/ru/ilb/filedossier/filedossier/document/validation/ValidationReport.java /* * Copyright 2019 kuznetsov_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 ru.ilb.filedossier.filedossier.document.validation; import java.util.ArrayList; import java.util.List; /** * * @author kuznetsov_me */ public class ValidationReport { private List errors; public ValidationReport() { errors = new ArrayList<>(); } public boolean isOk() { return errors.isEmpty(); } public List getErrors() { return errors; } public void addError(String error) { errors.add(error); } } package com.itwa.domain; public class ApplicationConfiguration { private String internalParameter1; private String internalParameter2; private String internalParameter3; public String getInternalParameter1() { return internalParameter1; } public void setInternalParameter1(String internalParameter1) { this.internalParameter1 = internalParameter1; } public String getInternalParameter2() { return internalParameter2; } public void setInternalParameter2(String internalParameter2) { this.internalParameter2 = internalParameter2; } public String getInternalParameter3() { return internalParameter3; } public void setInternalParameter3(String internalParameter3) { this.internalParameter3 = internalParameter3; } } package com.wisdom.example.service; import com.wisdom.example.entity.User; import com.wisdom.common.service.BaseService; /** * 用户表 业务层 * * @author captain * @version 1.0 */ public interface UserService extends BaseService { } package com.fkaking.daggerexample.module; import com.fkaking.daggerexample.MyApplication; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; @Module @Singleton public class AppModule { MyApplication myApplication; public AppModule(MyApplication application) { this.myApplication = application; } @Provides @Singleton MyApplication provideMyApp() { return myApplication; } } 10-100 package pl.koziarz.specificationexample.domain.entity; public class Toy { private String name; private String color; private ToyType type; private double weight; public Toy(String name, String color, ToyType type, double weight) { super(); this.name = name; this.color = color; this.type = type; this.weight = weight; } public Toy() { } public String getColor() { return color; } public String getName() { return name; } public ToyType getType() { return type; } public void setColor(String color) { this.color = color; } public void setName(String name) { this.name = name; } public void setType(ToyType type) { this.type = type; } public double getWeight() { return weight; } public void setWeight(double weight) { this.weight = weight; } @Override public String toString() { return "Toy [name=" + name + ", color=" + color + ", type=" + type + ", weight=" + weight + "]"; } } java/java-psi-api/src/com/intellij/lang/jvm/annotation/JvmAnnotationArrayValue.java // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.lang.jvm.annotation; import org.jetbrains.annotations.NotNull; import java.util.List; /** * Represents an array_value struct. */ public interface JvmAnnotationArrayValue extends JvmAnnotationAttributeValue { @NotNull List getValues(); } package com.yongj.util; import com.yongj.exceptions.IllegalPathException; import org.springframework.util.StringUtils; import java.io.File; /** * Utility class for path * * @author yongjie.zhuang */ public final class PathUtils { private PathUtils() { } /** * Extract file name (short name) from the path * * @throws IllegalArgumentException if the path is null or empty */ public static String extractFileName(String path) { if (!StringUtils.hasLength(path)) throw new IllegalPathException("Path doesn't have length, cannot extract filename"); int i = path.lastIndexOf(File.separator); if (i == -1) return path; if (i == path.length() - 1) throw new IllegalPathException("Path is illegal, it should not end with path separator"); return path.substring(i + 1); } } package moze_intel.projecte.network.packets.to_client; import moze_intel.projecte.network.packets.IPEPacket; import net.minecraft.client.Minecraft; import net.minecraft.network.PacketBuffer; import net.minecraftforge.fml.network.NetworkEvent.Context; public class StepHeightPKT implements IPEPacket { private final float value; public StepHeightPKT(float value) { this.value = value; } @Override public void handle(Context context) { if (Minecraft.getInstance().player != null) { Minecraft.getInstance().player.stepHeight = value; } } @Override public void encode(PacketBuffer buffer) { buffer.writeFloat(value); } public static StepHeightPKT decode(PacketBuffer buffer) { return new StepHeightPKT(buffer.readFloat()); } }package com.wjiec.springaio.javawiring; import com.wjiec.springaio.javawiring.model.Address; import com.wjiec.springaio.javawiring.model.User; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.ComponentScan; import java.util.concurrent.ThreadLocalRandom; @ComponentScan public class Application { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(Application.class); context.refresh(); System.out.println(context.getBean(Address.class)); System.out.println(context.getBean(User.class)); System.out.println(context.getBean("jayson")); } } asantoz/trinotesting/trino-benchmark/src/main/java/io/trino/benchmark/AbstractSqlBenchmark.java1000+ /* * 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.trino.benchmark; import io.trino.operator.Driver; import io.trino.operator.TaskContext; import io.trino.testing.LocalQueryRunner; import io.trino.testing.NullOutputOperator.NullOutputFactory; import org.intellij.lang.annotations.Language; import java.util.List; public abstract class AbstractSqlBenchmark extends AbstractOperatorBenchmark { @Language("SQL") private final String query; protected AbstractSqlBenchmark( LocalQueryRunner localQueryRunner, String benchmarkName, int warmupIterations, int measuredIterations, @Language("SQL") String query) { super(localQueryRunner, benchmarkName, warmupIterations, measuredIterations); this.query = query; } @Override protected List createDrivers(TaskContext taskContext) { return localQueryRunner.createDrivers(session, query, new NullOutputFactory(), taskContext); } } eu.dariolucia.reatmetric.processing/src/main/java/eu/dariolucia/reatmetric/processing/definition/EnumCalibration.java10-100 /* * Copyright (c) 2020 (https://www.dariolucia.eu) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.dariolucia.reatmetric.processing.definition; import eu.dariolucia.reatmetric.api.processing.scripting.IBindingResolver; import eu.dariolucia.reatmetric.api.value.ValueTypeEnum; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @XmlAccessorType(XmlAccessType.FIELD) public class EnumCalibration extends CalibrationDefinition implements Serializable { @XmlAttribute(name = "default") private String defaultValue; @XmlElement(name = "point", required = true) private List points; public EnumCalibration() { } public EnumCalibration(String defaultValue, List points) { this.defaultValue = defaultValue; this.points = points; } public String getDefaultValue() { return defaultValue; } public void setDefaultValue(String defaultValue) { this.defaultValue = defaultValue; } public List getPoints() { return points; } public void setPoints(List points) { this.points = points; } // ---------------------------------------------------------------------------------------------------------------- // Transient objects // ---------------------------------------------------------------------------------------------------------------- private transient Map point2values = new HashMap<>(); @Override public Object calibrate(Object valueToCalibrate, IBindingResolver resolver, ValueTypeEnum expectedOutput) throws CalibrationException { // If the valueToCalibrate can become an integer number somehow, then calibrate, otherwise error long valueToUse = convertToLong(valueToCalibrate); if(point2values.isEmpty()) { for(EnumCalibrationPoint p : points) { point2values.put(p.getInput(), p.getValue()); } } String calibratedValue = point2values.getOrDefault(valueToUse, defaultValue); if(defaultValue == null && calibratedValue == null) { // Not found and no default: calibration failed throw new CalibrationException("Cannot calibrate " + valueToCalibrate + " using enumeration calibration: no correspondence found and no default value defined"); } else { return calibratedValue; } } public InvertedEnumCalibration buildInvertedEnum() { InvertedEnumCalibration toReturn = new InvertedEnumCalibration(); toReturn.setPoints(new ArrayList<>(points.size())); for(EnumCalibrationPoint point : points) { toReturn.getPoints().add(new InvertedEnumCalibrationPoint(point.getValue(), point.getInput())); } return toReturn; } } 10-100 package com.surenpi.jenkins.client.core; import com.surenpi.jenkins.client.BaseModel; /** * @author suren */ public class Cause extends BaseModel { private String userId; private String userName; private String shortDescription; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getShortDescription() { return shortDescription; } public void setShortDescription(String shortDescription) { this.shortDescription = shortDescription; } }CapitalismMobile/src_core/core/framework/audio/MusicManager.java package core.framework.audio; public class MusicManager { public MusicManager() { } } s20834/SORCER-multiFi /* /* * Copyright 2009 the original author or authors. * Copyright 2009 SorcerSoft.org. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package sorcer.service; import java.io.Serializable; /** * The Link interface allows path values of service contexts to be * linked to other service contexts using instances implementing this interface. * The interface provides for linking service contexts to persisted subcontexts. * Context links are references to an offset (path) in a context, which allows * the reuse of other existing service context objects. * * @author */ @SuppressWarnings("rawtypes") public interface Link extends Serializable { /** * Returns a name of this link. * * @return a link name */ public String getName(); /** * Assign a link name for its linked context. * * @param name * a name for this context link */ public void setName(String name); /** * Returns the path offset into this linked context. * * @return an offset of this link */ public String getOffset(); /** * Sets the offset in this linked context. If the offset itself is obtained * by traversing a link (meaning there is a redundant link), the offset is * recalculated and the link object is reset to point to the owning context * (removing the redundancy). * * @param offset * @throws ContextException */ public void setOffset(String offset) throws ContextException; /** * Assigns a link service context associated with this link. * * @param ctxt */ public void setContext(Context ctxt); /** * Returns the context associated with this link. */ public Context getContext() throws ContextException; /** * Returns true if the linked context associated with this link is enclosed * into the link, otherwise false. * * @return true if the linked context is enclosed in this link */ public boolean isLocal(); /** * Returns a boolean indicating whether the linked context is retrieved from * a persistent context storage into this link - true * indicating if the linked context is already fetched; false * otherwise. * * @return a boolean indicating if the linked context is already fetched */ public boolean isFetched(); /** * Assigns a boolean indicating whether the linked context is retrieved * from a persistent context storage into this link. * * @param state * true indicating if the linked context is * already fetched; false otherwise */ public void isFetched(boolean state); } /* * Copyright JiongBull 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.sgzcommon.logutil.jlog.util; import com.android.sgzcommon.logutil.jlog.constant.LogLevel; import com.android.sgzcommon.logutil.jlog.printer.Printer; import java.io.File; /** * 打印机工具类. */ public class PrinterUtils { /** 控制台打印的内容格式. */ private static final String PRINT_CONSOLE_FORMAT = "[(%1$s:%2$d)#%3$s]" + Printer.LINE_SEPARATOR + "%4$s"; /** 文件中保存的内容格式. */ private static final String PRINT_FILE_FORMAT = "[%1$s %2$s %3$s:%4$d]" + Printer.LINE_SEPARATOR + "%5$s" + Printer.LINE_SEPARATOR + Printer.LINE_SEPARATOR; private PrinterUtils() { } /** * 日志打印输出到控制台. * * @param level 级别 * @param tag 标签 * @param message 信息 */ public static void printConsole(LogLevel level, String tag, String message) { LogUtils.log(level, tag, message); } /** * 日志打印输出到文件. * * @param message 信息 */ public static void printFile(String message) { String dirPath = LogUtils.genDirPath(); String fileName = LogUtils.genFileName(); if (!FileUtils.isExist(dirPath + File.separator + fileName)) { message = SysUtils.genInfo() + message; } FileUtils.write(dirPath, fileName, message, false); } /** * 装饰打印到控制台的信息. * * @param message 信息 * @param element 对战元素 * @return 装饰后的信息 */ public static String decorateMsgForConsole(String message, StackTraceElement element) { String methodName = element.getMethodName(); int lineNumber = element.getLineNumber(); String fileName = element.getFileName(); return String.format(PRINT_CONSOLE_FORMAT, fileName, lineNumber, methodName, message); } /** * 装饰打印到文件的信息. * * @param level 级别 * @param message 信息 * @param element 堆栈元素 * @return 装饰后的信息 */ public static String decorateMsgForFile(LogLevel level, String message, StackTraceElement element) { String time = TimeUtils.getCurTime(); String fileName = element.getFileName(); int lineNum = element.getLineNumber(); return String.format(PRINT_FILE_FORMAT, time, level.getValue(), fileName, lineNum, message); } }package org.w3c.connectedcars; public enum Action { GET, SET, SUBSCRIBE, UNSUBSCRIBE } package com.github.pwittchen.reactivesensors.app; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.github.pwittchen.reactivesensors.R; import com.github.pwittchen.reactivesensors.library.ReactiveSensors; import io.reactivex.rxjava3.disposables.Disposable; public abstract class SensorActivity extends AppCompatActivity { protected int sensorType; protected String sensorName; private Disposable subscription; private SensorHelper sensorHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sensor_sample); final TextView tvSensor = (TextView) findViewById(R.id.sensor); final ReactiveSensors reactiveSensors = new ReactiveSensors(getApplicationContext()); sensorHelper = new SensorHelper(reactiveSensors, sensorType, sensorName, tvSensor); } @Override protected void onResume() { super.onResume(); subscription = sensorHelper.createSubscription(); } @Override protected void onPause() { super.onPause(); sensorHelper.safelyDispose(subscription); } } package probs2019; import java.io.File; import java.util.ArrayList; import java.util.HashSet; import java.util.Hashtable; import java.util.LinkedList; import java.util.Scanner; import java.util.Stack; import number.IsNumber; import utils.Mapping; import utils.Sort; import probs2019after1am.*; public class prob19part2 { public static void main(String[] args) { Scanner in; try { in = new Scanner(new File("in2019/prob2019in19.txt")); //in = new Scanner(new File("in2019/prob2019in19.txt.test")); int numTimes = 0; int count = 0; boolean part2 = true; String line = ""; Hashtable trail = new Hashtable(); ArrayList lines = new ArrayList(); int LIMIT = 20000; boolean table[][] = new boolean[LIMIT][LIMIT]; //dir: 0 up //1 right //2 down //3 left line = ""; while(in.hasNextLine()) { line += in.nextLine(); } String cmds[] = line.split(","); //pause on output, so I can process it... int FACTOR = 10000; long answer = -1; long dist=0; long distRangeMax = -1; int minj=0; int maxj=0; boolean hasBeam = false; LinkedList queue = new LinkedList(); int MAX_WAIT_FOR_BEAM = 100; int BLOCK_SIZE = 100; int oldMax = -1; for(int i=0; true; i++) { sopl(i + ": minj = " + minj + ", maxj = " + maxj + ", oldMax = " + oldMax); for(int j=minj; j BLOCK_SIZE) { queue.remove(); } if(queue.size() ==BLOCK_SIZE) { oldMax = queue.getFirst(); } if(minj + BLOCK_SIZE <= oldMax) { //619948 too low... int answerY = i-BLOCK_SIZE + 1; int answerX = minj; answer = FACTOR* answerX + answerY; break; } } sopl("Answer: " + answer); in.close(); } catch(Exception e) { e.printStackTrace(); } finally { } } public static long runProg(long x, long y, String line) { LinkedList inputQueue = new LinkedList(); inputQueue.add(x); inputQueue.add(y); String cmdsCopy[] = line.split(","); IntCode intCode = new IntCode(cmdsCopy, inputQueue); intCode.setPauseOnOutput(); long ret = intCode.runProg(); return ret; } public static void sop(Object a) { System.out.print(a.toString()); } public static void sopl(Object a) { System.out.println(a.toString()); } public static void sopl() { System.out.println(); } public static int pint(String s) { if (IsNumber.isNumber(s)) { return Integer.parseInt(s); } else { sop("Error: (" + s + " is not a number"); return -1; } } public static void exit() { exit(0); } public static void exit(int code) { sop("Exit with code " + code); System.exit(code); } } src/main/java/org/github/felipegutierrez/explore/akka/classic/remote/hello/RemoteActorJ.java package org.github.felipegutierrez.explore.akka.classic.remote.hello; import akka.actor.ActorRef; import akka.actor.ActorSystem; import com.typesafe.config.ConfigFactory; public class RemoteActorJ { public RemoteActorJ() { final ActorSystem remoteSystem = ActorSystem.create("RemoteSystem", ConfigFactory.load("remote/remoteActors.conf").getConfig("remoteSystem")); ActorRef remoteSimpleActor = remoteSystem.actorOf(SimpleActorJ.props(), "remoteSimpleActorJ"); remoteSimpleActor.tell(new SimpleMessage("Hello from REMOTE SimpleActorJ"), remoteSimpleActor); } // public static void main(String[] args) { public static void run(String[] args) { new RemoteActorJ(); } } package com.lls.seckill.dto; import com.lls.seckill.enums.SecKillStateEnum; import com.lls.seckill.model.SuccessRecord; /************************************ * Execution * @author liliangshan * @date 2019-03-22 ************************************/ public class Execution { private long secKillId; private int state; private SuccessRecord successRecord; private String message; public Execution(long secKillId, SecKillStateEnum state) { this.secKillId = secKillId; this.state = state.getState(); this.message = state.getMessage(); } public Execution(long secKillId, SecKillStateEnum state, SuccessRecord successRecord) { this.secKillId = secKillId; this.state = state.getState(); this.message = state.getMessage(); this.successRecord = successRecord; } public long getSecKillId() { return secKillId; } public void setSecKillId(long secKillId) { this.secKillId = secKillId; } public int getState() { return state; } public void setState(int state) { this.state = state; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public SuccessRecord getSuccessRecord() { return successRecord; } public void setSuccessRecord(SuccessRecord successRecord) { this.successRecord = successRecord; } } jbescos/el-3.0-support-2.2 /* * Copyright (c) 1997-2018 Oracle and/or its affiliates. All rights reserved. * Copyright 2004 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 javax.el; /** * Represents any of the exception conditions that can arise during * expression evaluation. * * @since JSP 2.1 */ public class ELException extends RuntimeException { //------------------------------------- /** * Creates an ELException with no detail message. */ public ELException () { super (); } //------------------------------------- /** * Creates an ELException with the provided detail message. * * @param pMessage the detail message */ public ELException (String pMessage) { super (pMessage); } //------------------------------------- /** * Creates an ELException with the given cause. * * @param pRootCause the originating cause of this exception */ public ELException (Throwable pRootCause) { super( pRootCause ); } //------------------------------------- /** * Creates an ELException with the given detail message and root cause. * * @param pMessage the detail message * @param pRootCause the originating cause of this exception */ public ELException (String pMessage, Throwable pRootCause) { super (pMessage, pRootCause); } } src/main/java/net/teamfruit/sushida/util/Timer.java10-100 package net.teamfruit.sushida.util; /** * A hires timer. This measures time in seconds as floating point values. * All Timers created are updated simultaneously by calling the static method * tick(). This ensures that within a single iteration of a game loop that * all timers are updated consistently with each other. * * @author cix_foo <> * @version $Revision$ * $Id$ */ public class Timer { // Timer resolution private static long resolution = 1000; // When the timer was started private long startTime; // The last time recorded by getTime() private long lastTime; // Whether the timer is paused private boolean paused; /** * Constructs a timer. The timer will be reset to 0.0 and resumed immediately. */ public Timer() { reset(); resume(); } /** * @return the time in seconds, as a float */ public float getTime() { if (!paused) { lastTime = currentTime() - startTime; } return (float) ((double) lastTime / (double) resolution); } /** * @return whether this timer is paused */ public boolean isPaused() { return paused; } /** * Pause the timer. Whilst paused the time will not change for this timer * when tick() is called. * * @see #resume() */ public void pause() { if (!paused) { lastTime = currentTime() - startTime; } paused = true; } /** * Reset the timer. Equivalent to set(0.0f); * * @see #set(float) */ public void reset() { set(0.0f); } /** * Resume the timer. * * @see #pause() */ public void resume() { if (paused) { startTime = currentTime() - lastTime; } paused = false; } /** * Set the time of this timer * * @param newTime the new time, in seconds */ public void set(float newTime) { long newTimeInTicks = (long) ((double) newTime * (double) resolution); startTime = currentTime() - newTimeInTicks; lastTime = newTimeInTicks; } /** * Get the next time update from the system's hires timer. * * @return time */ public static long currentTime() { return System.currentTimeMillis(); } /** * Debug output. */ public String toString() { return "Timer[Time=" + getTime() + ", Paused=" + paused + "]"; } }src/java/com/astoev/cave/survey/activity/dialog/ConfirmationDialog.java package com.astoev.cave.survey.activity.dialog; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import android.util.Log; import com.astoev.cave.survey.Constants; import com.astoev.cave.survey.R; import com.astoev.cave.survey.activity.UIUtilities; import java.io.Serializable; /** * * @author */ public class ConfirmationDialog extends DialogFragment { public static final String CONFIRM_DIALOG = "CONFIRM_DIALOG"; public static final String OPERATION = "operation"; public static final String MESSAGE = "message"; public static final String TITLE = "title"; private ConfirmationHandler confirmationHandler; /** * @see android.support.v4.app.DialogFragment#onCreateDialog(android.os.Bundle) */ @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceStateArg) { Bundle bundle = getArguments(); final Serializable operationFromBundle = bundle != null ? bundle.getSerializable(OPERATION) : null; final String message = bundle != null ? bundle.getString(MESSAGE) : null; final String title = bundle != null ? bundle.getString(TITLE) : null; final ConfirmationOperation operation; if (operationFromBundle != null && operationFromBundle instanceof ConfirmationOperation){ operation = (ConfirmationOperation)operationFromBundle; } else { operation = null; Log.e(Constants.LOG_TAG_UI, "Operation not supported:" + operationFromBundle); } AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(title); builder.setMessage(message); builder.setPositiveButton(R.string.button_yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // delete vector confirmationHandler.confirmOperation(operation); } }); builder.setNegativeButton(R.string.button_no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogArg, int whichArg) { // cancel ConfirmationDialog.this.getDialog().cancel(); } }); return builder.create(); } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { confirmationHandler = (ConfirmationHandler)activity; } catch (ClassCastException cce) { Log.e(Constants.LOG_TAG_UI, "Activity not an instance of ConfirmationHandler", cce); UIUtilities.showNotification(R.string.error); throw cce; } } } /* * Copyright 2000-2013 JetBrains s.r.o. * Copyright 2014-2014 AS3Boyan * Copyright 2014-2014 * * 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.intellij.plugins.haxe.ide.highlight; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.fileTypes.SyntaxHighlighter; import com.intellij.openapi.options.colors.AttributesDescriptor; import com.intellij.openapi.options.colors.ColorDescriptor; import com.intellij.openapi.options.colors.ColorSettingsPage; import icons.HaxeIcons; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.Map; public class HXMLColorSettingsPage implements ColorSettingsPage { private static final AttributesDescriptor[] DESCRIPTORS = new AttributesDescriptor[]{ new AttributesDescriptor("Key", HXMLSyntaxHighlighter.KEY), new AttributesDescriptor("Value", HXMLSyntaxHighlighter.VALUE), new AttributesDescriptor("Comment", HXMLSyntaxHighlighter.COMMENT), new AttributesDescriptor("Include", HXMLSyntaxHighlighter.INCLUDE), new AttributesDescriptor("ClassName", HXMLSyntaxHighlighter.CLASS_NAME), }; @Nullable @Override public Icon getIcon() { return HaxeIcons.Haxe_16; } @NotNull @Override public SyntaxHighlighter getHighlighter() { return new HXMLSyntaxHighlighter(); } @NotNull @Override public String getDemoText() { return "build-each2.hxml\n" + "\n" + "-main test.Test\n" + "--each\n" + "\n" + "-neko bin/Test.n\n" + "-cmd neko bin/Test.n\n" + "\n" + "# --next\n" + "# -swf bin/Test.swf\n" + "# -cmd open bin/Test.swf\n" + "\n" + "test.pack.ForceImportMe2016\n"; } @Nullable @Override public Map getAdditionalHighlightingTagToDescriptorMap() { return null; } @NotNull @Override public AttributesDescriptor[] getAttributeDescriptors() { return DESCRIPTORS; } @NotNull @Override public ColorDescriptor[] getColorDescriptors() { return ColorDescriptor.EMPTY_ARRAY; } @NotNull @Override public String getDisplayName() { return "HXML"; } } modules/authorization-manager/src/main/java/org/opencastproject/authorization/xacml/manager/impl/persistence/JpaAclDb.java /** * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * * The Apereo Foundation licenses this file to you under the Educational * Community 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://opensource.org/licenses/ecl2.txt * * 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.opencastproject.authorization.xacml.manager.impl.persistence; import static org.opencastproject.authorization.xacml.manager.impl.persistence.ManagedAclEntity.findByIdAndOrg; import static org.opencastproject.util.data.functions.Misc.chuck; import static org.opencastproject.util.persistence.PersistenceUtil.equip2; import static org.opencastproject.util.persistence.PersistenceUtil.persist; import org.opencastproject.authorization.xacml.manager.api.ManagedAcl; import org.opencastproject.authorization.xacml.manager.impl.AclDb; import org.opencastproject.security.api.AccessControlList; import org.opencastproject.security.api.Organization; import org.opencastproject.util.data.Function; import org.opencastproject.util.data.Monadics; import org.opencastproject.util.data.Option; import org.opencastproject.util.data.functions.Misc; import org.opencastproject.util.persistence.PersistenceEnv; import org.opencastproject.util.persistence.PersistenceEnv2; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.RollbackException; /** JPA based impl of an {@link org.opencastproject.authorization.xacml.manager.impl.AclDb}. */ public final class JpaAclDb implements AclDb { private final PersistenceEnv penv; private final PersistenceEnv2 penvf; public JpaAclDb(PersistenceEnv penv) { this.penv = penv; this.penvf = equip2(penv, uniqueConstraintViolationHandler); } @Override public List getAcls(Organization org) { return Misc.widen(Monadics.mlist(penv.tx(ManagedAclEntity.findByOrg(org.getId()))).value()); } @Override public Option getAcl(Organization org, long id) { return Misc.widen(penv.tx(findByIdAndOrg(org.getId(), id))); } @Override public boolean updateAcl(final ManagedAcl acl) { return penv.tx(new Function() { @Override public Boolean apply(final EntityManager em) { for (ManagedAclEntity e : ManagedAclEntity.findByIdAndOrg(acl.getOrganizationId(), acl.getId()).apply(em)) { final ManagedAclEntity updated = e.update(acl.getName(), acl.getAcl(), acl.getOrganizationId()); em.merge(updated); return true; } return false; } }); } @Override public Option createAcl(Organization org, AccessControlList acl, String name) { final ManagedAcl e = new ManagedAclEntity().update(name, acl, org.getId()); return penvf.tx(persist(e)).right().toOption(); } @Override public boolean deleteAcl(Organization org, long id) { return penv.tx(ManagedAclEntity.deleteByIdAndOrg(org.getId(), id)); } /** DB exception handler that takes care of unique constraint violation and rethrows any other exception. */ public static final Function uniqueConstraintViolationHandler = new Function() { @Override public Void apply(Exception e) { if (e instanceof RollbackException) { final Throwable cause = e.getCause(); String message = cause.getMessage().toLowerCase(); if (message.contains("unique") || message.contains("duplicate")) return null; } return chuck(e); } }; } kuli1/library package io.pillopl.library.lending.dailysheet.model; import io.pillopl.library.catalogue.BookId; import io.pillopl.library.lending.librarybranch.model.LibraryBranchId; import io.pillopl.library.lending.patron.model.PatronEvent; import io.pillopl.library.lending.patron.model.PatronId; import io.vavr.Tuple3; import io.vavr.collection.List; import io.vavr.collection.Stream; import lombok.NonNull; import lombok.Value; import org.springframework.context.event.EventListener; @Value public class HoldsToExpireSheet { @NonNull List> expiredHolds; @EventListener public Stream toStreamOfEvents() { return expiredHolds .toStream() .map(this::tupleToEvent); } public int count() { return expiredHolds.size(); } private PatronEvent.BookHoldExpired tupleToEvent(Tuple3 expiredHold) { return PatronEvent.BookHoldExpired.now(expiredHold._1, expiredHold._2, expiredHold._3); } } 0 package com.indianeagle.internal.dao.repository; import com.indianeagle.internal.dto.Employee; import com.indianeagle.internal.dto.Salary; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.util.List; /** * @author Praveen * @date 22/01/2020 */ @Repository public interface SalaryRepository extends JpaRepository { @Query("select emp from Employee emp ORDER BY emp.empId") List loadAllEmployees(); /** * method to load employee based on empID i.e * * @param * @return List */ @Query("from Employee emp where emp.empId=:empId") List loadEmployee(@Param("empId") String empID); /** * method to load Employees based on Department * * @param department * @return List */ @Query("select emp from Employee emp where emp.relieveDate IS NULL AND emp.department.department=:department") List loadEmployeesByDepartment(@Param("department") String department); /** * list of employees whose relieve date is null * and ordered by employee id * * @return List */ @Query("SELECT emp from Employee emp where emp.relieveDate IS NULL ORDER BY emp.empId") List loadActiveEmployees(); } package de.uulm.vs.autodetect.mds.framework.model.ipc; public class IPCException extends Exception { public IPCException(String string) { super(string); } private static final long serialVersionUID = -1051755687167921821L; } YY-ORG/yycloud /** * Project Name:liz-admin * File Name:SysBaseService.java * Package Name:com.gemii.lizcloud.api.admin.service * Date:Sep 28, 20164:08:03 PM * Copyright (c) 2016, chenxj All Rights Reserved. * */ package com.yy.cloud.api.basis.service; import java.util.List; import com.yy.cloud.common.data.otd.sysbase.AdminRegion; import com.yy.cloud.common.data.otd.sysbase.SysDic; /** * ClassName:SysBaseService
* Function: TODO ADD FUNCTION.
* Reason: TODO ADD REASON.
* Date: Sep 28, 2016 4:08:03 PM
* * @author chenxj * @version * @since JDK 1.8 * @see */ public interface SysBaseService { /** * getRegions:获取所有地理区域.
* * @return */ public List getRegionByStatus(Byte _status); /** * getAllSysdictionary: Retrieve all of the dictionaries
* * @return */ public List getAllSysdictionary(); /** * getSysdictionaryByOwner: Retrieve all of the _owner's discs.
* * @param _owner * @return */ public List getSysdictionaryByOwner(String _owner); /** * getSysdictionaryByOwnerAndField: Retrieve the dics with owner and field. *
* * @param _owner * @param _field * @return */ public List getSysdictionaryByOwnerAndField(String _owner, String _field); /** * getOneSysdictionary: Get someone of the dics..
* * @param _owner * @param _field * @param _code * @return */ public SysDic getOneSysdictionary(String _owner, String _field, String _code); } package com.leetcode; public class MirrorReflectionNovChallenge { public int mirrorReflection(int p, int q) { int reflections = p; int extension = q; while (reflections % 2 == 0 && extension % 2 == 0) { reflections /= 2; extension /= 2; } if (extension % 2 == 0 && reflections % 2 != 0) return 0; if (extension % 2 != 0 && reflections % 2 == 0) return 2; if (extension % 2 != 0 && reflections % 2 != 0) return 1; return -1; } } /* * Copyright © 2018-2019 Apple Inc. and the ServiceTalk project authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.servicetalk.http.api; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Spliterator; import java.util.stream.StreamSupport; import static io.servicetalk.http.api.HttpHeaderNames.AUTHORIZATION; import static io.servicetalk.http.api.HttpHeaderNames.HOST; import static java.util.Arrays.asList; import static java.util.Collections.addAll; import static java.util.Collections.singleton; import static java.util.Collections.singletonList; import static java.util.Spliterators.spliteratorUnknownSize; import static java.util.stream.Collectors.toList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; public abstract class AbstractHttpRequestMetaDataTest { @Rule public final ExpectedException expected = ExpectedException.none(); @Rule public final MockitoRule rule = MockitoJUnit.rule(); protected T fixture; private final Map> params = new LinkedHashMap<>(); protected abstract void createFixture(String uri); protected abstract void setFixtureQueryParams(Map> params); // https://tools.ietf.org/html/rfc7230#section-5.3.1 @Test public void testParseUriOriginForm() { createFixture("/some/path?foo=bar&abc=def&foo=baz"); assertNull(fixture.scheme()); assertNull(fixture.userInfo()); assertNull(fixture.host()); assertEquals(-1, fixture.port()); assertEquals("/some/path", fixture.path()); assertEquals("/some/path", fixture.rawPath()); assertEquals("foo=bar&abc=def&foo=baz", fixture.rawQuery()); assertEquals("/some/path?foo=bar&abc=def&foo=baz", fixture.requestTarget()); assertNull(fixture.effectiveHost()); assertEquals(-1, fixture.effectivePort()); // Host header provides effective host and port fixture.headers().set(HOST, "other.site.com:8080"); assertEquals("other.site.com", fixture.effectiveHost()); assertEquals(8080, fixture.effectivePort()); } // https://tools.ietf.org/html/rfc7230#section-5.3.2 @Test public void testParseHttpUriAbsoluteForm() { createFixture("http://my.site.com/some/path?foo=bar&abc=def&foo=baz"); assertEquals("http", fixture.scheme()); assertNull(fixture.userInfo()); assertEquals("my.site.com", fixture.host()); assertEquals(-1, fixture.port()); assertEquals("/some/path", fixture.path()); assertEquals("/some/path", fixture.rawPath()); assertEquals("foo=bar&abc=def&foo=baz", fixture.rawQuery()); assertEquals("http://my.site.com/some/path?foo=bar&abc=def&foo=baz", fixture.requestTarget()); assertEquals("my.site.com", fixture.effectiveHost()); assertEquals(-1, fixture.effectivePort()); // Host header ignored when request-target is absolute. fixture.headers().set(HOST, "other.site.com:8080"); assertEquals("my.site.com", fixture.effectiveHost()); assertEquals(-1, fixture.effectivePort()); } @Test public void testParseHttpsUriAbsoluteForm() { createFixture("https://jdoe@my.site.com/some/path?foo=bar&abc=def&foo=baz"); assertEquals("https", fixture.scheme()); assertEquals("jdoe", fixture.userInfo()); assertEquals("my.site.com", fixture.host()); assertEquals(-1, fixture.port()); assertEquals("/some/path", fixture.path()); assertEquals("/some/path", fixture.rawPath()); assertEquals("foo=bar&abc=def&foo=baz", fixture.rawQuery()); assertEquals("https://jdoe@my.site.com/some/path?foo=bar&abc=def&foo=baz", fixture.requestTarget()); assertEquals("my.site.com", fixture.effectiveHost()); assertEquals(-1, fixture.effectivePort()); // Host header ignored when request-target is absolute fixture.headers().set(HOST, "other.site.com:8080"); assertEquals("my.site.com", fixture.effectiveHost()); assertEquals(-1, fixture.port()); } // https://tools.ietf.org/html/rfc7230#section-5.3.3 @Test public void testParseHttpUriAuthorityForm() { createFixture("my.site.com:80"); assertNull(fixture.scheme()); assertNull(fixture.userInfo()); assertEquals("my.site.com", fixture.host()); assertEquals(80, fixture.port()); assertEquals("", fixture.path()); assertEquals("", fixture.rawPath()); assertEquals("", fixture.rawQuery()); assertEquals("my.site.com:80", fixture.requestTarget()); assertEquals("my.site.com", fixture.effectiveHost()); assertEquals(80, fixture.effectivePort()); // Host header ignored when request-target has authority form fixture.headers().set(HOST, "other.site.com:8080"); assertEquals("my.site.com", fixture.effectiveHost()); assertEquals(80, fixture.effectivePort()); } // https://tools.ietf.org/html/rfc7230#section-5.3.4 @Test public void testParseHttpUriAsteriskForm() { createFixture("*"); assertNull(fixture.scheme()); assertNull(fixture.userInfo()); assertNull(fixture.host()); assertEquals(-1, fixture.port()); assertEquals("", fixture.path()); assertEquals("", fixture.rawPath()); assertEquals("", fixture.rawQuery()); assertEquals("*", fixture.requestTarget()); assertNull(fixture.effectiveHost()); assertEquals(-1, fixture.effectivePort()); // Host header provides effective host and port fixture.headers().set(HOST, "other.site.com:8080"); assertEquals("other.site.com", fixture.effectiveHost()); assertEquals(8080, fixture.effectivePort()); } @Test public void testParseUriOriginFormWithHostHeader() { createFixture("/some/path?foo=bar&abc=def&foo=baz"); fixture.headers().set(HOST, "host.header.com"); assertNull(fixture.scheme()); assertNull(fixture.userInfo()); assertNull(fixture.host()); assertEquals(-1, fixture.port()); assertEquals("/some/path", fixture.path()); assertEquals("/some/path", fixture.rawPath()); assertEquals("foo=bar&abc=def&foo=baz", fixture.rawQuery()); assertEquals("/some/path?foo=bar&abc=def&foo=baz", fixture.requestTarget()); assertEquals("host.header.com", fixture.effectiveHost()); assertEquals(-1, fixture.effectivePort()); // Host header provides effective host and port fixture.headers().set(HOST, "other.site.com:8080"); assertEquals("other.site.com", fixture.effectiveHost()); assertEquals(8080, fixture.effectivePort()); } @Test public void testParseHttpUriAbsoluteFormWithHost() { createFixture("http://my.site.com/some/path?foo=bar&abc=def&foo=baz"); fixture.headers().set(HOST, "host.header.com"); assertEquals("http", fixture.scheme()); assertNull(fixture.userInfo()); assertEquals("my.site.com", fixture.host()); assertEquals(-1, fixture.port()); assertEquals("/some/path", fixture.path()); assertEquals("/some/path", fixture.rawPath()); assertEquals("foo=bar&abc=def&foo=baz", fixture.rawQuery()); assertEquals("http://my.site.com/some/path?foo=bar&abc=def&foo=baz", fixture.requestTarget()); assertEquals("my.site.com", fixture.effectiveHost()); assertEquals(-1, fixture.effectivePort()); // Host header ignored when request-target is absolute. fixture.headers().set(HOST, "other.site.com:8080"); assertEquals("my.site.com", fixture.effectiveHost()); assertEquals(-1, fixture.effectivePort()); } @Test public void testSetPathWithoutLeadingSlash() { createFixture("temp"); fixture.path("foo"); assertEquals("/foo", fixture.requestTarget()); } @Test public void testAppendSegmentsToPath() { createFixture("base/"); fixture.appendPathSegments("foo", "/$", "bar"); assertEquals("base/foo/%2F%24/bar", fixture.requestTarget()); } @Test public void testAppendSegmentsToPathWithQueryParam() { createFixture("base/"); fixture.appendPathSegments("foo", "/$", "bar"); assertEquals("base/foo/%2F%24/bar", fixture.requestTarget()); } @Test public void testAppendSegmentsToPathWithoutTrailingSlash() { createFixture("base?baz=123"); fixture.appendPathSegments("foo", "/$", "bar"); assertEquals("base/foo/%2F%24/bar?baz=123", fixture.requestTarget()); } @Test public void testAppendNoSegmentToPath() { createFixture("base/"); expected.expect(IllegalArgumentException.class); fixture.appendPathSegments(); } @Test public void testSetRawPathWithoutLeadingSlash() { createFixture("temp"); expected.expect(IllegalArgumentException.class); expected.expectMessage("Path must be empty or start with '/'"); fixture.rawPath("foo"); } @Test public void testReplacePathInAbsoluteForm() { createFixture("http://my.site.com/some/path?foo=bar&abc=def&foo=baz"); fixture.path("/new/$path$"); assertEquals("http://my.site.com/new/%24path%24?foo=bar&abc=def&foo=baz", fixture.requestTarget()); } @Test public void testSetEmptyPathInAbsoluteForm() { createFixture("http://my.site.com/some/path?foo=bar&abc=def&foo=baz"); fixture.path(""); assertEquals("http://my.site.com?foo=bar&abc=def&foo=baz", fixture.requestTarget()); } @Test public void testReplacePathInOriginForm() { createFixture("/some/path?foo=bar&abc=def&foo=baz"); fixture.path("/new/$path$"); assertEquals("/new/%24path%24?foo=bar&abc=def&foo=baz", fixture.requestTarget()); } @Test public void testSetEmptyPathInOriginForm() { createFixture("/some/path?foo=bar&abc=def&foo=baz"); fixture.path(""); assertEquals("?foo=bar&abc=def&foo=baz", fixture.requestTarget()); } @Test public void testReplaceExistingQuery() { createFixture("/some/path?foo=bar&abc=def&foo=baz"); fixture.rawQuery("new=query"); assertEquals("/some/path?new=query", fixture.requestTarget()); } @Test public void testSetRemoveExistingQuery() { createFixture("/some/path?foo=bar&abc=def&foo=baz"); fixture.rawQuery(""); assertEquals("/some/path", fixture.requestTarget()); } @Test public void testAddQuery() { createFixture("/some/path"); fixture.rawQuery("new=query"); assertEquals("/some/path?new=query", fixture.requestTarget()); } @Test public void testParseQuery() { createFixture("/some/path?foo=bar&abc=def&foo=baz"); assertEquals(asList("foo", "abc"), iteratorAsList(fixture.queryParametersKeys().iterator())); assertEquals("bar", fixture.queryParameter("foo")); assertEquals(asList("bar", "baz"), iteratorAsList(fixture.queryParametersIterator("foo"))); assertEquals("def", fixture.queryParameter("abc")); assertEquals(singletonList("def"), iteratorAsList(fixture.queryParametersIterator("abc"))); } @Test public void testParseEmptyAndEncodeQuery() { createFixture("/some/path"); fixture.addQueryParameter("foo", "bar"); assertEquals("/some/path?foo=bar", fixture.requestTarget()); } @Test public void testQueryDoesntChangeState() { createFixture("/some/path?foo=bar&abc=def&foo=baz"); fixture.queryParameters(); assertEquals("/some/path?foo=bar&abc=def&foo=baz", fixture.requestTarget()); } @Test public void testUpdateQueryParameters() { createFixture("/some/path?foo=bar&abc=def&foo=baz"); fixture.setQueryParameter("abc", "new"); assertEquals("/some/path?foo=bar&foo=baz&abc=new", fixture.requestTarget()); for (Iterator i = fixture.queryParametersIterator("foo"); i.hasNext();) { i.next(); i.remove(); } assertEquals("/some/path?abc=new", fixture.requestTarget()); fixture.addQueryParameters("foo", asList("bar", "baz")); assertEquals("/some/path?abc=new&foo=bar&foo=baz", fixture.requestTarget()); assertTrue(fixture.removeQueryParameters("foo")); assertEquals("/some/path?abc=new", fixture.requestTarget()); assertFalse(fixture.removeQueryParameters("foo")); fixture.addQueryParameters("foo", "bar", "baz"); assertEquals("/some/path?abc=new&foo=bar&foo=baz", fixture.requestTarget()); assertTrue(fixture.removeQueryParameters("foo", "baz")); assertEquals("/some/path?abc=new&foo=bar", fixture.requestTarget()); fixture.setQueryParameters("foo", singletonList("baz")); fixture.setQueryParameters("abc", "ghi", "jkl"); assertEquals("/some/path?abc=ghi&abc=jkl&foo=baz", fixture.requestTarget()); assertTrue(fixture.hasQueryParameter("foo")); assertTrue(fixture.hasQueryParameter("abc", "jkl")); assertEquals(fixture.queryParametersSize(), 3); for (Iterator> i = fixture.queryParameters().iterator(); i.hasNext();) { i.next(); i.remove(); } assertEquals("/some/path", fixture.requestTarget()); assertEquals(fixture.queryParametersSize(), 0); assertTrue(fixture.queryParametersKeys().isEmpty()); } @Test public void testSetRequestTargetAndReparse() { createFixture("/some/path?foo=bar&abc=def&foo=baz"); // parse it assertEquals("/some/path?foo=bar&abc=def&foo=baz", fixture.requestTarget()); assertEquals("/some/path", fixture.rawPath()); assertEquals("/some/path", fixture.path()); assertEquals("foo=bar&abc=def&foo=baz", fixture.rawQuery()); assertEquals(asList("bar", "baz"), iteratorAsList(fixture.queryParametersIterator("foo"))); assertEquals(singletonList("def"), iteratorAsList(fixture.queryParametersIterator("abc"))); // change it fixture.requestTarget("/new/%24path%24?another=bar"); // parse it again assertEquals("/new/%24path%24?another=bar", fixture.requestTarget()); assertEquals("/new/%24path%24", fixture.rawPath()); assertEquals("/new/$path$", fixture.path()); assertEquals("another=bar", fixture.rawQuery()); assertEquals(singletonList("bar"), iteratorAsList(fixture.queryParametersIterator("another"))); } @Test public void testSetPathAndReparse() { createFixture("/some/path?foo=bar&abc=def&foo=baz"); // parse it assertEquals("/some/path?foo=bar&abc=def&foo=baz", fixture.requestTarget()); assertEquals("/some/path", fixture.rawPath()); assertEquals("/some/path", fixture.path()); assertEquals("foo=bar&abc=def&foo=baz", fixture.rawQuery()); assertEquals(asList("bar", "baz"), iteratorAsList(fixture.queryParametersIterator("foo"))); assertEquals(singletonList("def"), iteratorAsList(fixture.queryParametersIterator("abc"))); // change it fixture.path("/new/$path$"); // parse it again assertEquals("/new/%24path%24?foo=bar&abc=def&foo=baz", fixture.requestTarget()); assertEquals("/new/%24path%24", fixture.rawPath()); assertEquals("/new/$path$", fixture.path()); assertEquals("foo=bar&abc=def&foo=baz", fixture.rawQuery()); assertEquals(asList("bar", "baz"), iteratorAsList(fixture.queryParametersIterator("foo"))); assertEquals(singletonList("def"), iteratorAsList(fixture.queryParametersIterator("abc"))); } @Test public void testSetQueryAndReparse() { createFixture("/some/path?foo=bar&abc=def&foo=baz"); // parse it assertEquals("/some/path?foo=bar&abc=def&foo=baz", fixture.requestTarget()); assertEquals("/some/path", fixture.rawPath()); assertEquals("/some/path", fixture.path()); assertEquals("foo=bar&abc=def&foo=baz", fixture.rawQuery()); assertEquals(asList("bar", "baz"), iteratorAsList(fixture.queryParametersIterator("foo"))); assertEquals(singletonList("def"), iteratorAsList(fixture.queryParametersIterator("abc"))); // change it fixture.rawQuery("abc=new"); // parse it again assertEquals("/some/path?abc=new", fixture.requestTarget()); assertEquals("/some/path", fixture.rawPath()); assertEquals("/some/path", fixture.path()); assertEquals("abc=new", fixture.rawQuery()); assertEquals(singleton("abc"), fixture.queryParametersKeys()); assertEquals(singletonList("new"), iteratorAsList(fixture.queryParametersIterator("abc"))); } @Test public void testEncodeToRequestTargetWithNoParams() { createFixture("/some/path"); setFixtureQueryParams(params); assertEquals("/some/path", fixture.requestTarget()); } @Test public void testEncodeToRequestTargetWithParam() { createFixture("/some/path"); params.put("foo", newList("bar", "baz")); setFixtureQueryParams(params); assertEquals("/some/path?foo=bar&foo=baz", fixture.requestTarget()); } @Test public void testEncodeToRequestTargetWithMultipleParams() { createFixture("/some/path"); params.put("foo", newList("bar", "baz")); params.put("abc", newList("123", "456")); setFixtureQueryParams(params); assertEquals("/some/path?foo=bar&foo=baz&abc=123&abc=456", fixture.requestTarget()); } @Test public void testEncodeToRequestTargetWithSpecialCharacters() { createFixture("/some/path"); params.put("pair", newList("key1=value1", "key2=value2")); setFixtureQueryParams(params); assertEquals("/some/path?pair=key1%3Dvalue1&pair=key2%3Dvalue2", fixture.requestTarget()); } @Test public void testEncodeToRequestTargetWithAbsoluteForm() { createFixture("http://my.site.com/some/path?foo=bar&abc=def&foo=baz"); params.put("foo", newList("new")); setFixtureQueryParams(params); assertEquals("http://my.site.com/some/path?foo=new", fixture.requestTarget()); assertEquals("my.site.com", fixture.effectiveHost()); assertEquals(-1, fixture.effectivePort()); } @Test public void testToString() { createFixture("/some/path?a=query"); fixture.headers().set(HOST, "some.site.com"); fixture.headers().set(AUTHORIZATION, "some auth info"); assertEquals("GET /some/path?a=query HTTP/1.1", fixture.toString()); } @Test public void testToStringWithPassFilter() { createFixture("/some/path?a=query"); fixture.headers().set(HOST, "some.site.com"); fixture.headers().set(AUTHORIZATION, "some auth info"); assertEquals("GET /some/path?a=query HTTP/1.1\n" + "DefaultHttpHeaders[authorization: some auth info\n" + "host: some.site.com]", fixture.toString((k, v) -> v)); } @Test public void testToStringWithRedactFilter() { createFixture("/some/path?a=query"); fixture.headers().set(HOST, "some.site.com"); fixture.headers().set(AUTHORIZATION, "some auth info"); assertEquals("GET /some/path?a=query HTTP/1.1\n" + "DefaultHttpHeaders[authorization: redacted\n" + "host: redacted]", fixture.toString((k, v) -> "redacted")); } @SuppressWarnings("unchecked") private static List newList(final T... elements) { final List list = new ArrayList<>(elements.length); addAll(list, elements); return list; } private static List iteratorAsList(final Iterator iterator) { return StreamSupport .stream(spliteratorUnknownSize(iterator, Spliterator.ORDERED), false) .collect(toList()); } } public class LineNumberException extends Exception {}// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.compute.generated; import com.azure.core.util.Context; import com.azure.resourcemanager.compute.fluent.models.RestorePointInner; import com.azure.resourcemanager.compute.models.ApiEntityReference; import java.util.Arrays; /** Samples for RestorePoints Create. */ public final class RestorePointsCreateSamples { /* * x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/stable/2022-03-01/ComputeRP/examples/restorePointExamples/RestorePoint_Copy_BetweenRegions.json */ /** * Sample code: Copy a restore point to a different region. * * @param azure The entry point for accessing resource management APIs in Azure. */ public static void copyARestorePointToADifferentRegion(com.azure.resourcemanager.AzureResourceManager azure) { azure .virtualMachines() .manager() .serviceClient() .getRestorePoints() .create( "myResourceGroup", "rpcName", "rpName", new RestorePointInner() .withSourceRestorePoint( new ApiEntityReference() .withId( "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/restorePointCollections/sourceRpcName/restorePoints/sourceRpName")), Context.NONE); } /* * x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/stable/2022-03-01/ComputeRP/examples/restorePointExamples/RestorePoint_Create.json */ /** * Sample code: Create a restore point. * * @param azure The entry point for accessing resource management APIs in Azure. */ public static void createARestorePoint(com.azure.resourcemanager.AzureResourceManager azure) { azure .virtualMachines() .manager() .serviceClient() .getRestorePoints() .create( "myResourceGroup", "rpcName", "rpName", new RestorePointInner() .withExcludeDisks( Arrays .asList( new ApiEntityReference() .withId( "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/disk123"))), Context.NONE); } } package com.krishagni.catissueplus.core.biospecimen.domain.factory; import com.krishagni.catissueplus.core.biospecimen.matching.ParticipantLookupLogic; public interface ParticipantLookupFactory { ParticipantLookupLogic getLookupLogic(); } package com.google.fleetengine.auth.token; import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; /** Custom authorization claims for task endpoint. */ public class TaskClaims implements FleetEngineTokenClaims { private static final String WILDCARD = "*"; static final String CLAIM_TASK_ID = "taskid"; private final ImmutableMap map; private final boolean isWildcardClaim; /** * Creates a task claim that works with any task. * * @return custom auth claim */ public static TaskClaims create() { return new TaskClaims(WILDCARD, true); } /** * Creates a task claim with an id. * * @param taskId id of the task id on the token scope * @return custom auth claim * @throws IllegalArgumentException when taskId is null or empty */ public static TaskClaims create(String taskId) { if (Strings.isNullOrEmpty(taskId)) { throw new IllegalArgumentException("taskId must have a value"); } return new TaskClaims(taskId, false); } private TaskClaims(String taskId, boolean isWildcard) { map = ImmutableMap.of(CLAIM_TASK_ID, taskId); isWildcardClaim = isWildcard; } /** {@inheritDoc} */ @Override public ImmutableMap toMap() { return map; } @Override public boolean isWildcard() { return isWildcardClaim; } } /* * Copyright 2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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.hillert.s1.plants.service.impl; import javax.validation.constraints.NotBlank; import com.univocity.parsers.annotations.Parsed; import com.univocity.parsers.annotations.Trim; public class CsvRow { @Trim @Parsed(index = 0) private Double latitude; @Trim @Parsed(index = 1) private Double longitude; @Trim @Parsed(index = 3) private String comments; @Trim @NotBlank @Parsed(index = 4) private String genus; @Trim @NotBlank @Parsed(index = 5) private String species; @Trim @Parsed(index = 6) private String imagePath; @Parsed(index = 8) private Boolean plantSignMissing; public Double getLatitude() { return latitude; } public void setLatitude(Double latitude) { this.latitude = latitude; } public Double getLongitude() { return longitude; } public void setLongitude(Double longitude) { this.longitude = longitude; } public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } public String getGenus() { return genus; } public void setGenus(String genus) { this.genus = genus; } public String getSpecies() { return species; } public void setSpecies(String species) { this.species = species; } public String getImagePath() { return imagePath; } public void setImagePath(String imagePath) { this.imagePath = imagePath; } public Boolean getPlantSignMissing() { return plantSignMissing != null ? plantSignMissing : false; } public void setPlantSignMissing(Boolean plantSignMissing) { this.plantSignMissing = plantSignMissing; } @Override public String toString() { return "CsvRow [Genus=" + genus + ", species=" + species +"]"; } } 0 package dev.vrremi.kurisucore.managers; import dev.vrremi.kurisucore.KurisuCore; import dev.vrremi.kurisucore.data.Rank; import dev.vrremi.kurisucore.data.Tag; import dev.vrremi.kurisucore.data.User; import dev.vrremi.kurisucore.utils.CC; import me.clip.placeholderapi.expansion.PlaceholderExpansion; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; public class PlaceholderAPIManager extends PlaceholderExpansion { @Override public @NotNull String getIdentifier() { return "kurisu"; } @Override public @NotNull String getAuthor() { return "VRRemi"; } @Override public @NotNull String getVersion() { return "1.0.0"; } @Override public boolean canRegister() { return true; } @Override public boolean persist() { return true; } @Override public String onRequest(OfflinePlayer offlinePlayer, @NotNull String params) { Player player = Bukkit.getPlayer(offlinePlayer.getUniqueId()); if (offlinePlayer.isOnline() && player != null) { User user = KurisuCore.getUserManager().getUser(player); if (user != null) { Rank rank = user.getHighestRank(); Tag tag = user.getTag(); if (params.equalsIgnoreCase("tag_display")) { return tag == null ? "" : tag.getTag(); } else if (params.equalsIgnoreCase("tag_name")) { return tag == null ? "" : tag.getName(); } else if (params.equalsIgnoreCase("rank_prefix")) { return rank == null ? "" : rank.getPrefix(); } else if (params.equalsIgnoreCase("rank_suffix")) { return rank == null ? "" : rank.getSuffix(); } else if (params.equalsIgnoreCase("rank_color")) { return rank == null ? "" : rank.getColor(); } else if (params.equalsIgnoreCase("rank_priority")) { return rank == null ? "" : CC.format(rank.getPriority()); } else if (params.equalsIgnoreCase("rank_name")) { return rank == null ? "" : rank.getName(); } } } return null; } } 0 /* * Copyright 2006-2011 The Virtual Laboratory for e-Science (VL-e) * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * For details, see the LICENCE.txt file location in the root directory of this * distribution or obtain the Apache Licence at the following location: * 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: http://www.vl-e.nl/ * See: LICENCE.txt (located in the root folder of this distribution). * --- * $Id: startVBrowser.java,v 1.8 2011-04-18 12:27:31 ptdeboer Exp $ * $Date: 2011-04-18 12:27:31 $ */ // source: package nl.uva.vlet.gui; import nl.uva.vlet.Global; import nl.uva.vlet.exception.VlException; import nl.uva.vlet.gui.dialog.ExceptionForm; import nl.uva.vlet.gui.vbrowser.BrowserController; import nl.uva.vlet.gui.vbrowser.VBrowserFactory; import nl.uva.vlet.gui.vbrowser.VBrowserInit; import nl.uva.vlet.gui.viewers.ViewerPlugin; import nl.uva.vlet.gui.viewers.ViewerRegistry; import nl.uva.vlet.vrl.VRL; /** * Simple VBrowser Start Class. */ public class startVBrowser { /** * Main * */ public static void main(String args[]) { try { Global.parseArguments(args); // does platform init! VBrowserInit.initPlatform(); VBrowserFactory factory=VBrowserFactory.getInstance(); // start browser(s) { int urls=0; if (args!=null) for (String arg:args) { Global.debugPrintf(startVBrowser.class,"arg=%s\n",arg); // assume that every non-option is a VRL: if (arg.startsWith("-")==false) { // urls specfied: urls++; factory.createBrowser(arg); } else { if (arg.compareTo("-noblock")==0) { BrowserController.setDummyMode(false); } else if (arg.compareTo("-notree")==0) { GuiSettings.setShowResourceTree(false); } } } // no urls specified, open default window: if (urls==0) { // get home LOCATION: Can also be gftp/srb/.... // BrowserController.performNewWindow(TermGlobal.getUserHomeLocation()); factory.createBrowser(UIGlobal.getVirtualRootLocation()); } } } catch (VlException e) { Global.errorPrintf(startVBrowser.class,"***Error: Exception:%s\n",e); Global.debugPrintStacktrace(e); ExceptionForm.show(e); } } /** Create VBrowser instance */ public static BrowserController createVBrowser(VRL vrl) { return VBrowserFactory.getInstance().createBrowser(vrl); } /** Register viewer */ public static void registerViewer(String clazzname) { ViewerRegistry.getRegistry().registerViewer(clazzname); } /** Register viewer class */ public static void registerViewer(Class clazz) { ViewerRegistry.getRegistry().registerViewer(clazz); } } package mb.pie.lang.test.returnTypes.tupleBoolString; import org.junit.jupiter.api.Test; import static mb.pie.lang.test.util.SimpleChecker.assertTaskOutputEquals; class TupleBoolStringTest { @Test void test() throws Exception { assertTaskOutputEquals(DaggertupleBoolStringComponent.class, new main_tupleBoolString.Output(false, "hey")); } } yifazhang/shop package com.zhangyifa.portal.service.impl; import com.zhangyifa.common.pojo.ShopResult; import com.zhangyifa.common.utils.HttpClientUtil; import com.zhangyifa.common.utils.JsonUtils; import com.zhangyifa.pojo.TbItemDesc; import com.zhangyifa.pojo.TbItemParamItem; import com.zhangyifa.portal.pojo.Item; import com.zhangyifa.portal.pojo.ItemInfo; import com.zhangyifa.portal.service.ItemService; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; /** * Created by zyf on 2017/9/27. */ @Service public class ItemServiceImpl implements ItemService { @Value("${ITEM_INFO_URL}") private String ITEM_INFO_URL; @Value("${ITEM_DESC_URL}") private String ITEM_DESC_URL; @Value("${ITEM_PARAM_URL}") private String ITEM_PARAM_URL; @Value("${REST_BASE_URL}") private String REST_BASE_URL; /** * 查询基本信息 * @param itemId * @return */ @Override public ItemInfo getItemById(Long itemId) { try { //使用rest服务查询 String json = HttpClientUtil.doGet(REST_BASE_URL + ITEM_INFO_URL + itemId); if (!StringUtils.isBlank(json)) { ShopResult result = ShopResult.formatToPojo(json, ItemInfo.class); if (result.getStatus() == 200) { ItemInfo item = (ItemInfo) result.getData(); return item; } } } catch (Exception e) { e.printStackTrace(); } return null; } /** * 查询详细信息 * @param itemId * @return */ @Override public String getItemDescById(Long itemId) { try { String json = HttpClientUtil.doGet(REST_BASE_URL + ITEM_DESC_URL + itemId); if (!StringUtils.isBlank(json)) { ShopResult result = ShopResult.formatToPojo(json, TbItemDesc.class); if (result.getStatus() == 200) { TbItemDesc itemDesc = (TbItemDesc) result.getData(); //取商品描述信息 String desc = itemDesc.getItemDesc(); return desc; } } } catch (Exception e) { e.printStackTrace(); } return null; } /** * 查询规格 * @param itemId * @return */ @Override public String getItemParam(Long itemId) { try { String json = HttpClientUtil.doGet(REST_BASE_URL + ITEM_PARAM_URL + itemId); //把json转化成java对象 if (!StringUtils.isBlank(json)) { ShopResult shopResult = ShopResult.formatToPojo(json, TbItemParamItem.class); if (shopResult.getStatus() == 200) { TbItemParamItem itemParamItem = (TbItemParamItem) shopResult.getData(); String paramData = itemParamItem.getParamData(); //生成html // 把规格参数json数据转换成java对象 List jsonList = JsonUtils.jsonToList(paramData, Map.class); StringBuffer sb = new StringBuffer(); sb.append("\n"); sb.append(" \n"); for(Map m1:jsonList) { sb.append(" \n"); sb.append(" \n"); sb.append(" \n"); List list2 = (List) m1.get("params"); for(Map m2:list2) { sb.append(" \n"); sb.append(" \n"); sb.append(" \n"); sb.append(" \n"); } } sb.append(" \n"); sb.append("
"+m1.get("group")+"
"+m2.get("k")+""+m2.get("v")+"
"); //返回html片段 return sb.toString(); } } } catch (Exception e) { e.printStackTrace(); } return ""; } } package de.ellpeck.actuallyadditions.common.recipe; import java.util.ArrayList; import java.util.List; import de.ellpeck.actuallyadditions.api.ActuallyAdditionsAPI; import de.ellpeck.actuallyadditions.api.recipe.EmpowererRecipe; import de.ellpeck.actuallyadditions.common.blocks.InitBlocks; import de.ellpeck.actuallyadditions.common.items.InitItems; import de.ellpeck.actuallyadditions.common.items.metalists.TheCrystals; import de.ellpeck.actuallyadditions.common.items.metalists.TheMiscItems; import de.ellpeck.actuallyadditions.common.util.RecipeUtil; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.Ingredient; import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.oredict.OreIngredient; public final class EmpowererHandler { public static final ArrayList MAIN_PAGE_RECIPES = new ArrayList<>(); public static EmpowererRecipe recipeEmpoweredCanolaSeed; public static void init() { addCrystalEmpowering(TheCrystals.REDSTONE, "dyeRed", Ingredient.fromItems(Items.NETHERBRICK), Ingredient.fromItems(Items.REDSTONE), Ingredient.fromItems(Items.BRICK)); addCrystalEmpowering(TheCrystals.LAPIS, "dyeCyan", Ingredient.fromItems(Items.PRISMARINE_SHARD), Ingredient.fromItems(Items.PRISMARINE_SHARD), Ingredient.fromItems(Items.PRISMARINE_SHARD)); addCrystalEmpowering(TheCrystals.DIAMOND, "dyeLightBlue", Ingredient.fromItems(Items.CLAY_BALL), Ingredient.fromItems(Items.CLAY_BALL), fromBlock(Blocks.CLAY)); addCrystalEmpowering(TheCrystals.IRON, "dyeGray", Ingredient.fromItems(Items.SNOWBALL), fromBlock(Blocks.STONE_BUTTON), fromBlock(Blocks.COBBLESTONE)); addCrystalEmpowering(TheCrystals.COAL, "dyeBlack", igd(new ItemStack(Items.COAL, 1, 1)), Ingredient.fromItems(Items.FLINT), fromBlock(Blocks.STONE)); List balls = OreDictionary.getOres("slimeball"); for (ItemStack ball : balls) { addCrystalEmpowering(TheCrystals.EMERALD, "dyeLime", igd(new ItemStack(Blocks.TALLGRASS, 1, 1)), igd(new ItemStack(Blocks.SAPLING)), igd(ball.copy())); } Ingredient seed = Ingredient.fromItems(InitItems.itemCanolaSeed); ActuallyAdditionsAPI.addEmpowererRecipe(Ingredient.fromStacks(new ItemStack(InitItems.itemMisc, 1, TheMiscItems.CRYSTALLIZED_CANOLA_SEED.ordinal())), new ItemStack(InitItems.itemMisc, 1, TheMiscItems.EMPOWERED_CANOLA_SEED.ordinal()), seed, seed, seed, seed, 1000, 30, new float[] { 1F, 91F / 255F, 76F / 255F }); recipeEmpoweredCanolaSeed = RecipeUtil.lastEmpowererRecipe(); } private static void addCrystalEmpowering(TheCrystals type, String dye, Ingredient modifier1, Ingredient modifier2, Ingredient modifier3) { float[] color = type.conversionColorParticles; ActuallyAdditionsAPI.addEmpowererRecipe(Ingredient.fromStacks(new ItemStack(InitItems.itemCrystal, 1, type.ordinal())), new ItemStack(InitItems.itemCrystalEmpowered, 1, type.ordinal()), new OreIngredient(dye), modifier1, modifier2, modifier3, 5000, 50, color); MAIN_PAGE_RECIPES.add(RecipeUtil.lastEmpowererRecipe()); ActuallyAdditionsAPI.addEmpowererRecipe(Ingredient.fromStacks(new ItemStack(InitBlocks.blockCrystal, 1, type.ordinal())), new ItemStack(InitBlocks.blockCrystalEmpowered, 1, type.ordinal()), new OreIngredient(dye), modifier1, modifier2, modifier3, 50000, 500, color); MAIN_PAGE_RECIPES.add(RecipeUtil.lastEmpowererRecipe()); } private static Ingredient igd(ItemStack s) { return Ingredient.fromStacks(s); } private static Ingredient fromBlock(Block b) { return Ingredient.fromItems(Item.getItemFromBlock(b)); } } 0 package Java8CompleteReference.ExploringSwing.TheSwingButtons.JTabbedPaneExample; import javax.swing.*; // Make the panels that will be added to the tabbed pane. class CitiesPanel extends JPanel { public CitiesPanel() { JButton b1 = new JButton("New York"); add(b1); JButton b2 = new JButton("London"); add(b2); JButton b3 = new JButton("Hong Kong"); add(b3); JButton b4 = new JButton("Tokyo"); add(b4); } } import java.util.*; import java.io.*; public class Apaxiaaans { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String input = br.readLine(); StringBuilder ans = new StringBuilder(); for(int i = 0; i < input.length() - 1; i++) { if(input.charAt(i) != input.charAt(i+1)) { ans.append(input.charAt(i)); } } ans.append(input.charAt(input.length() - 1)); System.out.println(ans.toString()); } } 1-10 /* * * * 2018-05-26 下午6:58 * * * Copyright (c) 2018, . All Rights Reserved, http://www.hankcs.com/ * This source is subject to Han He. Please contact Han He for more information. * */ package com.hankcs.book.ch02; import com.hankcs.hanlp.collection.AhoCorasick.AhoCorasickDoubleArrayTrie; import com.hankcs.hanlp.collection.trie.bintrie.BinTrie; import com.hankcs.hanlp.corpus.io.IOUtil; import com.hankcs.hanlp.dictionary.CoreDictionary; import java.io.IOException; import java.util.*; import static com.hankcs.book.ch02.NaiveDictionaryBasedSegmentation.evaluateSpeed; /** * 《自然语言处理入门》2.4 字典树 * 配套书籍:http://nlp.hankcs.com/book.php * 讨论答疑:https://bbs.hankcs.com/ * * @author hankcs * @see 《自然语言处理入门》 * @see 讨论答疑 */ public class BinTrieBasedSegmentation { public static void main(String[] args) throws IOException { // 加载词典 TreeMap dictionary = IOUtil.loadDictionary("data/dictionary/CoreNatureDictionary.mini.txt"); final BinTrie binTrie = new BinTrie(dictionary); Map binTrieMap = new Map() { @Override public int size() { return binTrie.size(); } @Override public boolean isEmpty() { return binTrie.size() == 0; } @Override public boolean containsKey(Object key) { return binTrie.containsKey((String) key); } @Override public boolean containsValue(Object value) { throw new UnsupportedOperationException(); } @Override public CoreDictionary.Attribute get(Object key) { return binTrie.get((String) key); } @Override public CoreDictionary.Attribute put(String key, CoreDictionary.Attribute value) { throw new UnsupportedOperationException(); } @Override public CoreDictionary.Attribute remove(Object key) { throw new UnsupportedOperationException(); } @Override public void putAll(Map m) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public Set keySet() { throw new UnsupportedOperationException(); } @Override public Collection values() { throw new UnsupportedOperationException(); } @Override public Set> entrySet() { throw new UnsupportedOperationException(); } }; String text = "江西鄱阳湖干枯,中国最大淡水湖变成大草原"; long start; double costTime; final int pressure = 10000; System.out.println("===朴素接口==="); System.out.println("完全切分"); start = System.currentTimeMillis(); for (int i = 0; i < pressure; ++i) { com.hankcs.book.ch02.NaiveDictionaryBasedSegmentation.segmentFully(text, binTrieMap); } costTime = (System.currentTimeMillis() - start) / (double) 1000; System.out.printf("%.2f万字/秒\n", text.length() * pressure / 10000 / costTime); evaluateSpeed(binTrieMap); System.out.println("===BinTrie接口==="); System.out.println("完全切分"); start = System.currentTimeMillis(); for (int i = 0; i < pressure; ++i) { segmentFully(text, binTrie); } costTime = (System.currentTimeMillis() - start) / (double) 1000; System.out.printf("%.2f万字/秒\n", text.length() * pressure / 10000 / costTime); System.out.println("正向最长"); start = System.currentTimeMillis(); for (int i = 0; i < pressure; ++i) { segmentForwardLongest(text, binTrie); } costTime = (System.currentTimeMillis() - start) / (double) 1000; System.out.printf("%.2f万字/秒\n", text.length() * pressure / 10000 / costTime); } /** * 基于BinTrie的完全切分式的中文分词算法 * * @param text 待分词的文本 * @param dictionary 词典 * @return 单词列表 */ public static List segmentFully(final String text, BinTrie dictionary) { final List wordList = new LinkedList(); dictionary.parseText(text, new AhoCorasickDoubleArrayTrie.IHit() { @Override public void hit(int begin, int end, CoreDictionary.Attribute value) { wordList.add(text.substring(begin, end)); } }); return wordList; } /** * 基于BinTrie的正向最长匹配的中文分词算法 * * @param text 待分词的文本 * @param dictionary 词典 * @return 单词列表 */ public static List segmentForwardLongest(final String text, BinTrie dictionary) { final List wordList = new LinkedList(); dictionary.parseLongestText(text, new AhoCorasickDoubleArrayTrie.IHit() { @Override public void hit(int begin, int end, CoreDictionary.Attribute value) { wordList.add(text.substring(begin, end)); } }); return wordList; } } Type-1/Mapwithme/app/src/main/java/com/example/d022omim/BaseLocationProvider.java package com.example.d022omim; import androidx.annotation.NonNull; abstract class BaseLocationProvider { @NonNull private final LocationFixChecker mLocationFixChecker; private boolean mActive; @NonNull LocationFixChecker getLocationFixChecker() { return mLocationFixChecker; } BaseLocationProvider(@NonNull LocationFixChecker locationFixChecker) { mLocationFixChecker = locationFixChecker; } protected abstract void start(); protected abstract void stop(); /** * Indicates whether this provider is providing location updates or not * @return true - if locations are actively coming from this provider, false - otherwise */ public final boolean isActive() { return mActive; } final void setActive(boolean active) { mActive = active; } } package pointinrectangle; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class Main { public static void main(String[] args) { try(BufferedReader bfr = new BufferedReader(new InputStreamReader(System.in))) { var coordinates = Arrays.stream(bfr.readLine().split("\\s+")).mapToInt(Integer::parseInt).toArray(); Rectangle rectangle = new Rectangle(new Point(coordinates[0], coordinates[1]), new Point(coordinates[2], coordinates[3])); var numberOfPointsToCheck = Integer.parseInt(bfr.readLine()); for (int i = 0; i < numberOfPointsToCheck; i++) { var pointCoordinates = Arrays.stream(bfr.readLine().split("\\s+")) .mapToInt(Integer::parseInt) .toArray(); System.out.println(rectangle.contains(new Point(pointCoordinates[0], pointCoordinates[1]))); } } catch (IOException e) { e.printStackTrace(); } } } package com.nano.candy.interpreter.i2.cni; 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.RUNTIME) public @interface NativeMethod { public String name(); public int argc() default 0; public int varArgsIndex() default -1; } /* * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree. */ package org.fcrepo.kernel.impl.cache; import static java.util.stream.Collectors.toList; import static org.apache.jena.vocabulary.RDF.type; import java.net.URI; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import org.fcrepo.config.FedoraPropsConfig; import org.fcrepo.kernel.api.RdfStream; import org.fcrepo.kernel.api.ReadOnlyTransaction; import org.fcrepo.kernel.api.cache.UserTypesCache; import org.fcrepo.kernel.api.identifiers.FedoraId; import org.apache.jena.graph.Triple; import org.springframework.stereotype.Component; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; /** * Default UserTypesCache implementation * * @author pwinckles */ @Component public class UserTypesCacheImpl implements UserTypesCache { private final Cache> globalCache; private final Map>> sessionCaches; public UserTypesCacheImpl(final FedoraPropsConfig config) { this.globalCache = Caffeine.newBuilder() .maximumSize(config.getUserTypesCacheSize()) .expireAfterAccess(config.getUserTypesCacheTimeout(), TimeUnit.MINUTES) .build(); this.sessionCaches = new ConcurrentHashMap<>(); } /** * {@inheritDoc} */ @Override public List getUserTypes(final FedoraId resourceId, final String sessionId, final Supplier rdfProvider) { if (isNotReadOnlySession(sessionId)) { final var sessionCache = getSessionCache(sessionId); return sessionCache.get(resourceId, k -> { return globalCache.get(resourceId, k2 -> { return extractRdfTypes(rdfProvider.get()); }); }); } else { return globalCache.get(resourceId, k -> { return extractRdfTypes(rdfProvider.get()); }); } } /** * {@inheritDoc} */ @Override public void cacheUserTypes(final FedoraId resourceId, final RdfStream rdf, final String sessionId) { if (isNotReadOnlySession(sessionId)) { getSessionCache(sessionId).put(resourceId, extractRdfTypes(rdf)); } } /** * {@inheritDoc} */ @Override public void cacheUserTypes(final FedoraId resourceId, final List userTypes, final String sessionId) { if (isNotReadOnlySession(sessionId)) { getSessionCache(sessionId).put(resourceId, userTypes); } } /** * {@inheritDoc} */ @Override public void mergeSessionCache(final String sessionId) { if (isNotReadOnlySession(sessionId)) { final var sessionCache = getSessionCache(sessionId); globalCache.putAll(sessionCache.asMap()); dropSessionCache(sessionId); } } /** * {@inheritDoc} */ @Override public void dropSessionCache(final String sessionId) { if (isNotReadOnlySession(sessionId)) { sessionCaches.remove(sessionId); } } private Cache> getSessionCache(final String sessionId) { return sessionCaches.computeIfAbsent(sessionId, k -> { return Caffeine.newBuilder() .maximumSize(1024) .build(); }); } private List extractRdfTypes(final RdfStream rdf) { return rdf.filter(t -> t.predicateMatches(type.asNode())) .map(Triple::getObject) .map(t -> URI.create(t.toString())) .collect(toList()); } private boolean isNotReadOnlySession(final String sessionId) { return !ReadOnlyTransaction.READ_ONLY_TX_ID.equals(sessionId); } } package bsoft.com.clipboard.config; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.core.Binding; import org.springframework.amqp.core.BindingBuilder; import org.springframework.amqp.core.FanoutExchange; import org.springframework.amqp.core.Queue; import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; import org.springframework.amqp.rabbit.core.RabbitAdmin; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.io.IOException; import java.util.concurrent.TimeoutException; @Slf4j @Configuration @Getter public class RabbitConfiguration { private final String hostName = "localhost"; private final String queueName = "topics"; private final String fanoutExchange = "fanoutExchange"; @Bean public CachingConnectionFactory connectionFactory() { return new CachingConnectionFactory(hostName); } @Bean public Channel channel(CachingConnectionFactory connectionFactory) { Channel channel = null; try { Connection connection = connectionFactory.getRabbitConnectionFactory().newConnection(); channel = connection.createChannel(); } catch (TimeoutException ex1) { log.error("Timeout: {}", ex1); } catch (IOException ex2) { log.error("IO exception: {}", ex2); } catch (Exception ex3) { log.error("Unknown exception: {}", ex3); } log.info("Channel created"); return channel; } @Bean public ConfigElements configElements() { return new ConfigElements(); } @Bean public RabbitAdmin amqpAdmin() { return new RabbitAdmin(connectionFactory()); } @Bean public RabbitTemplate rabbitTemplate() { return new RabbitTemplate(connectionFactory()); } @Bean public Queue financeQueue() { return new Queue("finance"); } @Bean public Queue newsQueue() { return new Queue("news"); } @Bean public Queue sportQueue() { return new Queue("sport"); } @Bean public FanoutExchange exchange() { return new FanoutExchange(fanoutExchange); } @Bean public Binding financeBinding(Queue financeQueue, FanoutExchange exchange) { return BindingBuilder.bind(financeQueue).to(exchange); } @Bean public Binding newsBinding(Queue newsQueue, FanoutExchange exchange) { return BindingBuilder.bind(newsQueue).to(exchange); } @Bean public Binding sportBinding(Queue sportQueue, FanoutExchange exchange) { return BindingBuilder.bind(sportQueue).to(exchange); } @Bean public String exchangeName() { return fanoutExchange; } /* @Bean public Queue topicQueue() { return new Queue(queueName); } @Bean public String rabbitHostName() { return hostName; } @Bean public String rabbitQueueName() { return queueName; } */ } import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; public class PythagoreanTriplet { private int a; private int b; private int c; public PythagoreanTriplet(final int a, final int b, final int c) { this.a = a; this.b = b; this.c = c; } public static TripletListBuilder makeTripletsList() { return new TripletListBuilder(); } public int calculateSum() { return this.a + this.b + this.c; } public long calculateProduct() { return this.a * this.b * this.c; } public boolean isPythagorean() { return this.a * this.a + this.b * this.b == this.c * this.c; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final PythagoreanTriplet other = (PythagoreanTriplet) obj; if (this.a != other.a) { return false; } if (this.b != other.b) { return false; } if (this.c != other.c) { return false; } return true; } public static class TripletListBuilder { private static final int MAX_FACTOR_DEFAULT_VALUE = 0; private static final int SUM_DEFAULT_VALUE = -1; private int maxFactor = MAX_FACTOR_DEFAULT_VALUE; private int minFactor = 1; private int sum = SUM_DEFAULT_VALUE; public TripletListBuilder() { } public TripletListBuilder withFactorsLessThanOrEqualTo( final int maxFactor) { this.maxFactor = maxFactor; return this; } public TripletListBuilder withFactorsGreaterThanOrEqualTo( final int minFactor) { this.minFactor = minFactor; return this; } public TripletListBuilder thatSumTo(final int sum) { this.sum = sum; return this; } public List build() { List triplets = new ArrayList<>(); if (this.maxFactor == MAX_FACTOR_DEFAULT_VALUE) { return triplets; } double sqrt; int floor; for (int n = minFactor; n < maxFactor; n++) { for (int m = n + 1; m < maxFactor; m++) { sqrt = Math.sqrt(n * n + m * m); floor = (int) Math.floor(sqrt); if (sqrt == floor) { triplets.add(new PythagoreanTriplet(n, m, floor)); } } } if (sum != SUM_DEFAULT_VALUE) { return triplets.stream() .filter(t -> t.calculateSum() == sum) .collect(Collectors.toList()); } return triplets; } } } 1-10 // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. /** * Metadata abstraction for Azure resource. */ package com.azure.spring.cloud.core.properties.resource; package com.mantuliu.retry.core.call.schedule; import com.mantuliu.retry.core.entity.RetryUnion; public interface ScheduleService { void scheduleRetry(RetryUnion retryUnion); } package uk.co.terminological.omop; import javax.annotation.Generated; import java.sql.Date; import java.sql.JDBCType; import java.sql.Timestamp; import uk.co.terminological.javapig.sqlloader.Column; import uk.co.terminological.javapig.sqlloader.Table; import uk.co.terminological.omop.ProcedureOccurrence; @Generated({"uk.co.terminological.javapig.JModelWriter"}) @Table(schema="", name="omop.dbo.procedure_occurrence") public interface ProcedureOccurrence { @Column(isNullable=false, isAutoIncrement=false, jdbcType=JDBCType.BIGINT, name="procedure_occurrence_id", length=19) public Long getProcedureOccurrenceId(); @Column(isNullable=false, isAutoIncrement=false, jdbcType=JDBCType.BIGINT, name="person_id", length=19) public Long getPersonId(); @Column(isNullable=false, isAutoIncrement=false, jdbcType=JDBCType.INTEGER, name="procedure_concept_id", length=10) public Integer getProcedureConceptId(); @Column(isNullable=true, isAutoIncrement=false, jdbcType=JDBCType.DATE, name="procedure_date", length=10) public Date getProcedureDate(); @Column(isNullable=false, isAutoIncrement=false, jdbcType=JDBCType.TIMESTAMP, name="procedure_datetime", length=27) public Timestamp getProcedureDatetime(); @Column(isNullable=false, isAutoIncrement=false, jdbcType=JDBCType.INTEGER, name="procedure_type_concept_id", length=10) public Integer getProcedureTypeConceptId(); @Column(isNullable=false, isAutoIncrement=false, jdbcType=JDBCType.INTEGER, name="modifier_concept_id", length=10) public Integer getModifierConceptId(); @Column(isNullable=true, isAutoIncrement=false, jdbcType=JDBCType.INTEGER, name="quantity", length=10) public Integer getQuantity(); @Column(isNullable=true, isAutoIncrement=false, jdbcType=JDBCType.BIGINT, name="provider_id", length=19) public Long getProviderId(); @Column(isNullable=true, isAutoIncrement=false, jdbcType=JDBCType.BIGINT, name="visit_occurrence_id", length=19) public Long getVisitOccurrenceId(); @Column(isNullable=true, isAutoIncrement=false, jdbcType=JDBCType.BIGINT, name="visit_detail_id", length=19) public Long getVisitDetailId(); @Column(isNullable=true, isAutoIncrement=false, jdbcType=JDBCType.VARCHAR, name="procedure_source_value", length=50) public String getProcedureSourceValue(); @Column(isNullable=false, isAutoIncrement=false, jdbcType=JDBCType.INTEGER, name="procedure_source_concept_id", length=10) public Integer getProcedureSourceConceptId(); @Column(isNullable=true, isAutoIncrement=false, jdbcType=JDBCType.VARCHAR, name="modifier_source_value", length=50) public String getModifierSourceValue(); } 1-10 /** * Copyright (C) 2013, 2014 SLUB Dresden & Avantgarde Labs 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.dswarm.controller.resources.job.test; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Map; import java.util.Set; import javax.ws.rs.client.Entity; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.junit.After; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.dswarm.controller.resources.job.test.utils.FiltersResourceTestUtils; import org.dswarm.controller.resources.job.test.utils.FunctionsResourceTestUtils; import org.dswarm.controller.resources.job.test.utils.MappingsResourceTestUtils; import org.dswarm.controller.resources.job.test.utils.ProjectsResourceTestUtils; import org.dswarm.controller.resources.job.test.utils.TransformationsResourceTestUtils; import org.dswarm.controller.resources.resource.test.utils.ConfigurationsResourceTestUtils; import org.dswarm.controller.resources.resource.test.utils.DataModelsResourceTestUtils; import org.dswarm.controller.resources.resource.test.utils.ResourcesResourceTestUtils; import org.dswarm.controller.resources.schema.test.utils.AttributePathsResourceTestUtils; import org.dswarm.controller.resources.schema.test.utils.AttributesResourceTestUtils; import org.dswarm.controller.resources.schema.test.utils.ClaszesResourceTestUtils; import org.dswarm.controller.resources.schema.test.utils.MappingAttributePathInstancesResourceTestUtils; import org.dswarm.controller.resources.schema.test.utils.SchemasResourceTestUtils; import org.dswarm.controller.resources.test.BasicResourceTest; import org.dswarm.persistence.model.job.Component; import org.dswarm.persistence.model.job.Filter; import org.dswarm.persistence.model.job.Function; import org.dswarm.persistence.model.job.Mapping; import org.dswarm.persistence.model.job.Project; import org.dswarm.persistence.model.job.Transformation; import org.dswarm.persistence.model.job.proxy.ProxyProject; import org.dswarm.persistence.model.resource.Configuration; import org.dswarm.persistence.model.resource.DataModel; import org.dswarm.persistence.model.resource.Resource; import org.dswarm.persistence.model.schema.Attribute; import org.dswarm.persistence.model.schema.AttributePath; import org.dswarm.persistence.model.schema.Clasz; import org.dswarm.persistence.model.schema.MappingAttributePathInstance; import org.dswarm.persistence.model.schema.Schema; import org.dswarm.persistence.service.job.ProjectService; import org.dswarm.persistence.service.job.test.utils.ProjectServiceTestUtils; public class ProjectRemoveMappingResourceTest extends BasicResourceTest { private static final Logger LOG = LoggerFactory .getLogger(ProjectRemoveMappingResourceTest.class); private final FunctionsResourceTestUtils functionsResourceTestUtils; private final TransformationsResourceTestUtils transformationsResourceTestUtils; private final AttributesResourceTestUtils attributesResourceTestUtils; private final AttributePathsResourceTestUtils attributePathsResourceTestUtils; private final ClaszesResourceTestUtils claszesResourceTestUtils; private final ResourcesResourceTestUtils resourcesResourceTestUtils; private final ConfigurationsResourceTestUtils configurationsResourceTestUtils; private final SchemasResourceTestUtils schemasResourceTestUtils; private final DataModelsResourceTestUtils dataModelsResourceTestUtils; private final MappingsResourceTestUtils mappingsResourceTestUtils; private final ProjectsResourceTestUtils projectsResourceTestUtils; private final MappingAttributePathInstancesResourceTestUtils mappingAttributePathInstancesResourceTestUtils; private final FiltersResourceTestUtils filterResourceTestUtils; final Map attributes = Maps.newHashMap(); final Map attributePaths = Maps.newLinkedHashMap(); final Map mappingAttributePathInstances = Maps.newLinkedHashMap(); private Project initiallyPersistedProject = null; public ProjectRemoveMappingResourceTest() { super(Project.class, ProjectService.class, "projects", "project_to_remove_mapping_from_with_dummy_IDs.json", new ProjectsResourceTestUtils()); functionsResourceTestUtils = new FunctionsResourceTestUtils(); attributesResourceTestUtils = new AttributesResourceTestUtils(); attributePathsResourceTestUtils = new AttributePathsResourceTestUtils(); transformationsResourceTestUtils = new TransformationsResourceTestUtils(); claszesResourceTestUtils = new ClaszesResourceTestUtils(); resourcesResourceTestUtils = new ResourcesResourceTestUtils(); configurationsResourceTestUtils = new ConfigurationsResourceTestUtils(); schemasResourceTestUtils = new SchemasResourceTestUtils(); dataModelsResourceTestUtils = new DataModelsResourceTestUtils(); mappingsResourceTestUtils = new MappingsResourceTestUtils(); projectsResourceTestUtils = new ProjectsResourceTestUtils(); mappingAttributePathInstancesResourceTestUtils = new MappingAttributePathInstancesResourceTestUtils(); filterResourceTestUtils = new FiltersResourceTestUtils(); } @Override public void prepare() throws Exception { super.prepare(); // persist project via API since dummy IDs need to be replaced with the ones used in database final Response response = target().request(MediaType.APPLICATION_JSON_TYPE).accept(MediaType.APPLICATION_JSON_TYPE) .post(Entity.json(objectJSONString)); Assert.assertEquals("201 Created was expected", 201, response.getStatus()); final String responseString = response.readEntity(String.class); Assert.assertNotNull("the response JSON shouldn't be null", responseString); initiallyPersistedProject = objectMapper.readValue(responseString, Project.class); Assert.assertNotNull("the response project shouldn't be null", initiallyPersistedProject); } /** * Simulate a user loading an already persisted project in front end, removing a mapping (that contains filters and functions) * and saving the updated project (by putting the whole project JSON).
*
* It is intended that the mapping is removed from the project only, i.e. the relation between the project and the mapping is * removed but the mapping itself and all of its parts (like functions and filters) are still present in the database (to be * used in other projects). * * @throws Exception */ @Test public void testPUTProjectWithRemovedMapping() throws Exception { // Start simulate user removing a mapping from the given project final String initiallyPersistedProjectJSONString = objectMapper.writeValueAsString(initiallyPersistedProject); final Project modifiedProject = objectMapper.readValue(initiallyPersistedProjectJSONString, Project.class); final Set persistedMappings = modifiedProject.getMappings(); final Set reducedMappings = Sets.newHashSet(); final String mappingToBeRemovedFromProjectName = "first+last-to-contributor"; Mapping mappingToBeRemovedFromProject = null; for (final Mapping mapping : persistedMappings) { // the mapping to be removed (by the user in front end) if (mapping.getName().equals(mappingToBeRemovedFromProjectName)) { mappingToBeRemovedFromProject = mapping; continue; } reducedMappings.add(mapping); } Assert.assertNotNull("could not find mapping to be removed \"" + mappingToBeRemovedFromProjectName + "\"", mappingToBeRemovedFromProject); // re-inject mappings modifiedProject.setMappings(reducedMappings); final String modifiedProjectJSONString = objectMapper.writeValueAsString(modifiedProject); // End simulate user removing a mapping from the given project // Start simulate user pushing button 'save project' in front end String idEncoded = null; try { idEncoded = URLEncoder.encode(initiallyPersistedProject.getId().toString(), "UTF-8"); } catch (final UnsupportedEncodingException e) { ProjectRemoveMappingResourceTest.LOG.debug("couldn't encode id", e); Assert.assertTrue(false); } final Response response = target(idEncoded).request(MediaType.APPLICATION_JSON_TYPE).accept(MediaType.APPLICATION_JSON_TYPE) .put(Entity.json(modifiedProjectJSONString)); // End simulate user pushing button 'save project' in front end // Start check response Assert.assertEquals("200 OK was expected", 200, response.getStatus()); final String responseString = response.readEntity(String.class); Assert.assertNotNull("the response JSON shouldn't be null", responseString); final Project updatedPersistedProject = objectMapper.readValue(responseString, Project.class); Assert.assertNotNull("the response project shouldn't be null", updatedPersistedProject); // make sure the project does not contain (the reference to) the mapping anymore projectsResourceTestUtils.compareObjects(modifiedProject, updatedPersistedProject); // End check response // Start check db // the mapping itself must still be present in database Assert.assertNotNull("mapping to be removed \"" + mappingToBeRemovedFromProjectName + "\" has no ID", mappingToBeRemovedFromProject.getId()); final Mapping persistedMappingToBeRemovedFromProject = mappingsResourceTestUtils.getObject(mappingToBeRemovedFromProject.getId()); mappingsResourceTestUtils.compareObjects(mappingToBeRemovedFromProject, persistedMappingToBeRemovedFromProject); } @After public void tearDown2() throws Exception { final DataModel inputDataModel = initiallyPersistedProject.getInputDataModel(); Resource inputDataResource = null; Configuration inputConfiguration = null; Schema inputSchema = null; final Map mappingAttributePathInstances = Maps.newHashMap(); final Map attributePaths = Maps.newHashMap(); final Map attributes = Maps.newHashMap(); final Map claszes = Maps.newHashMap(); final Map filter = Maps.newHashMap(); if (inputDataModel != null) { inputDataResource = inputDataModel.getDataResource(); inputConfiguration = inputDataModel.getConfiguration(); inputSchema = inputDataModel.getSchema(); if (inputSchema != null) { final Set inputAttributePaths = inputSchema.getUniqueAttributePaths(); if (inputAttributePaths != null) { for (final AttributePath inputAttributePath : inputAttributePaths) { attributePaths.put(inputAttributePath.getId(), inputAttributePath); final Set inputAttributePathAttributes = inputAttributePath.getAttributes(); if (inputAttributePathAttributes != null) { for (final Attribute inputAttributePathAttribute : inputAttributePathAttributes) { attributes.put(inputAttributePathAttribute.getId(), inputAttributePathAttribute); } } } } final Clasz recordClass = inputSchema.getRecordClass(); if (recordClass != null) { claszes.put(recordClass.getId(), recordClass); } } } final DataModel outputDataModel = initiallyPersistedProject.getOutputDataModel(); Schema outputSchema = null; if (outputDataModel != null) { outputSchema = outputDataModel.getSchema(); if (outputSchema != null) { final Set outputAttributePaths = outputSchema.getUniqueAttributePaths(); if (outputAttributePaths != null) { for (final AttributePath outputAttributePath : outputAttributePaths) { attributePaths.put(outputAttributePath.getId(), outputAttributePath); final Set outputAttributePathAttributes = outputAttributePath.getAttributes(); if (outputAttributePathAttributes != null) { for (final Attribute outputAttributePathAttribute : outputAttributePathAttributes) { attributes.put(outputAttributePathAttribute.getId(), outputAttributePathAttribute); } } } } final Clasz recordClass = outputSchema.getRecordClass(); if (recordClass != null) { claszes.put(recordClass.getId(), recordClass); } } } final Map mappings = Maps.newHashMap(); final Map functions = Maps.newHashMap(); Transformation transformation = null; final Set projectMappings = initiallyPersistedProject.getMappings(); if (projectMappings != null) { for (final Mapping projectMapping : projectMappings) { mappings.put(projectMapping.getId(), projectMapping); final Component transformationComponent = projectMapping.getTransformation(); if (transformationComponent != null) { final Function transformationComponentFunction = transformationComponent.getFunction(); if (transformationComponentFunction != null) { if (Transformation.class.isInstance(transformationComponentFunction)) { transformation = (Transformation) transformationComponentFunction; final Set components = transformation.getComponents(); for (final Component component : components) { final Function componentFunction = component.getFunction(); if (componentFunction != null) { functions.put(componentFunction.getId(), componentFunction); } } } else { functions.put(transformationComponentFunction.getId(), transformationComponentFunction); } } } final Set projectMappingInputAttributePaths = projectMapping.getInputAttributePaths(); if (projectMappingInputAttributePaths != null) { for (final MappingAttributePathInstance inputMappingAttributePathInstance : projectMappingInputAttributePaths) { mappingAttributePathInstances.put(inputMappingAttributePathInstance.getId(), inputMappingAttributePathInstance); final AttributePath inputAttributePath = inputMappingAttributePathInstance.getAttributePath(); if (inputAttributePath != null) { attributePaths.put(inputAttributePath.getId(), inputAttributePath); final Set inputAttributePathAttributes = inputAttributePath.getAttributes(); if (inputAttributePathAttributes != null) { for (final Attribute inputAttributePathAttribute : inputAttributePathAttributes) { attributes.put(inputAttributePathAttribute.getId(), inputAttributePathAttribute); } } } final Filter singleFilter = inputMappingAttributePathInstance.getFilter(); if (singleFilter != null) { filter.put(singleFilter.getId(), singleFilter); } } } final MappingAttributePathInstance projectMappingOutputMappingAttributePathInstance = projectMapping.getOutputAttributePath(); if (projectMappingOutputMappingAttributePathInstance != null) { mappingAttributePathInstances.put(projectMappingOutputMappingAttributePathInstance.getId(), projectMappingOutputMappingAttributePathInstance); final AttributePath projectMappingOutputAttributePath = projectMappingOutputMappingAttributePathInstance.getAttributePath(); if (projectMappingOutputAttributePath != null) { attributePaths.put(projectMappingOutputAttributePath.getId(), projectMappingOutputAttributePath); final Set inputAttributePathAttributes = projectMappingOutputAttributePath.getAttributes(); if (inputAttributePathAttributes != null) { for (final Attribute inputAttributePathAttribute : inputAttributePathAttributes) { attributes.put(inputAttributePathAttribute.getId(), inputAttributePathAttribute); } } } } } } final Set projectFunctions = initiallyPersistedProject.getFunctions(); if (projectFunctions != null) { for (final Function projectFunction : projectFunctions) { functions.put(projectFunction.getId(), projectFunction); } } cleanUpDB(initiallyPersistedProject); if (inputDataModel != null) { dataModelsResourceTestUtils.deleteObject(inputDataModel); } if (outputDataModel != null) { dataModelsResourceTestUtils.deleteObject(outputDataModel); } if (inputDataResource != null) { resourcesResourceTestUtils.deleteObject(inputDataResource); } if (inputConfiguration != null) { configurationsResourceTestUtils.deleteObject(inputConfiguration); } if (inputSchema != null) { schemasResourceTestUtils.deleteObject(inputSchema); } if (outputSchema != null) { schemasResourceTestUtils.deleteObject(outputSchema); } for (final Mapping mapping : mappings.values()) { mappingsResourceTestUtils.deleteObject(mapping); } for (final MappingAttributePathInstance mappingAttributePathInstance : mappingAttributePathInstances.values()) { mappingAttributePathInstancesResourceTestUtils.deleteObject(mappingAttributePathInstance); } for (final AttributePath attributePath : attributePaths.values()) { attributePathsResourceTestUtils.deleteObjectViaPersistenceServiceTestUtils(attributePath); } for (final Clasz clasz : claszes.values()) { claszesResourceTestUtils.deleteObjectViaPersistenceServiceTestUtils(clasz); } for (final Attribute attribute : attributes.values()) { attributesResourceTestUtils.deleteObjectViaPersistenceServiceTestUtils(attribute); } if (transformation != null) { transformationsResourceTestUtils.deleteObject(transformation); } for (final Function function : functions.values()) { functionsResourceTestUtils.deleteObject(function); } for (final Filter singleFilter : filter.values()) { filterResourceTestUtils.deleteObject(singleFilter); } } @Ignore @Test @Override public void testPOSTObjects() throws Exception { } @Ignore @Test @Override public void testGETObjects() throws Exception { } @Ignore @Test @Override public void testGETObject() throws Exception { } @Ignore @Test @Override public void testDELETEObject() throws Exception { } @Ignore @Test @Override public void testPUTObject() throws Exception { } } begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * 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. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|backup package|; end_package begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|assertFalse import|; end_import begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|assertTrue import|; end_import begin_import import|import name|java operator|. name|util operator|. name|ArrayList import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Collection import|; end_import begin_import import|import name|java operator|. name|util operator|. name|List import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|HBaseClassTestRule import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|HBaseTestingUtility import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|TableName import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|backup operator|. name|BackupInfo operator|. name|BackupState import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|backup operator|. name|impl operator|. name|BackupAdminImpl import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|backup operator|. name|impl operator|. name|BackupSystemTable import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|backup operator|. name|impl operator|. name|TableBackupClient import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|backup operator|. name|impl operator|. name|TableBackupClient operator|. name|Stage import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|client operator|. name|Admin import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|client operator|. name|ColumnFamilyDescriptorBuilder import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|client operator|. name|Connection import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|client operator|. name|ConnectionFactory import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|client operator|. name|Put import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|client operator|. name|Table import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|testclassification operator|. name|LargeTests import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|util operator|. name|Bytes import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|util operator|. name|ToolRunner import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Assert import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|ClassRule import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Test import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|experimental operator|. name|categories operator|. name|Category import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|runner operator|. name|RunWith import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|runners operator|. name|Parameterized import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|Logger import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|LoggerFactory import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hbase operator|. name|thirdparty operator|. name|com operator|. name|google operator|. name|common operator|. name|collect operator|. name|Lists import|; end_import begin_class annotation|@ name|Category argument_list|( name|LargeTests operator|. name|class argument_list|) annotation|@ name|RunWith argument_list|( name|Parameterized operator|. name|class argument_list|) specifier|public class|class name|TestIncrementalBackupWithFailures extends|extends name|TestBackupBase block|{ annotation|@ name|ClassRule specifier|public specifier|static specifier|final name|HBaseClassTestRule name|CLASS_RULE init|= name|HBaseClassTestRule operator|. name|forClass argument_list|( name|TestIncrementalBackupWithFailures operator|. name|class argument_list|) decl_stmt|; specifier|private specifier|static specifier|final name|Logger name|LOG init|= name|LoggerFactory operator|. name|getLogger argument_list|( name|TestIncrementalBackupWithFailures operator|. name|class argument_list|) decl_stmt|; annotation|@ name|Parameterized operator|. name|Parameters specifier|public specifier|static name|Collection argument_list|< name|Object index|[] argument_list|> name|data parameter_list|() block|{ name|provider operator|= literal|"multiwal" expr_stmt|; name|List argument_list|< name|Object index|[] argument_list|> name|params init|= operator|new name|ArrayList argument_list|< name|Object index|[] argument_list|> argument_list|() decl_stmt|; name|params operator|. name|add argument_list|( operator|new name|Object index|[] block|{ name|Boolean operator|. name|TRUE block|} argument_list|) expr_stmt|; return|return name|params return|; block|} specifier|public name|TestIncrementalBackupWithFailures parameter_list|( name|Boolean name|b parameter_list|) block|{ } comment|// implement all test cases in 1 test since incremental backup/restore has dependencies annotation|@ name|Test specifier|public name|void name|testIncBackupRestore parameter_list|() throws|throws name|Exception block|{ name|int name|ADD_ROWS init|= literal|99 decl_stmt|; comment|// #1 - create full backup for all tables name|LOG operator|. name|info argument_list|( literal|"create full backup image for all tables" argument_list|) expr_stmt|; name|List argument_list|< name|TableName argument_list|> name|tables init|= name|Lists operator|. name|newArrayList argument_list|( name|table1 argument_list|, name|table2 argument_list|) decl_stmt|; specifier|final name|byte index|[] name|fam3Name init|= name|Bytes operator|. name|toBytes argument_list|( literal|"f3" argument_list|) decl_stmt|; name|table1Desc operator|. name|setColumnFamily argument_list|( operator|new name|ColumnFamilyDescriptorBuilder operator|. name|ModifyableColumnFamilyDescriptor argument_list|( name|fam3Name argument_list|) argument_list|) expr_stmt|; name|HBaseTestingUtility operator|. name|modifyTableSync argument_list|( name|TEST_UTIL operator|. name|getAdmin argument_list|() argument_list|, name|table1Desc argument_list|) expr_stmt|; name|Connection name|conn init|= name|ConnectionFactory operator|. name|createConnection argument_list|( name|conf1 argument_list|) decl_stmt|; name|int name|NB_ROWS_FAM3 init|= literal|6 decl_stmt|; name|insertIntoTable argument_list|( name|conn argument_list|, name|table1 argument_list|, name|fam3Name argument_list|, literal|3 argument_list|, name|NB_ROWS_FAM3 argument_list|) operator|. name|close argument_list|() expr_stmt|; name|Admin name|admin init|= name|conn operator|. name|getAdmin argument_list|() decl_stmt|; name|BackupAdminImpl name|client init|= operator|new name|BackupAdminImpl argument_list|( name|conn argument_list|) decl_stmt|; name|BackupRequest name|request init|= name|createBackupRequest argument_list|( name|BackupType operator|. name|FULL argument_list|, name|tables argument_list|, name|BACKUP_ROOT_DIR argument_list|) decl_stmt|; name|String name|backupIdFull init|= name|client operator|. name|backupTables argument_list|( name|request argument_list|) decl_stmt|; name|assertTrue argument_list|( name|checkSucceeded argument_list|( name|backupIdFull argument_list|) argument_list|) expr_stmt|; comment|// #2 - insert some data to table name|Table name|t1 init|= name|insertIntoTable argument_list|( name|conn argument_list|, name|table1 argument_list|, name|famName argument_list|, literal|1 argument_list|, name|ADD_ROWS argument_list|) decl_stmt|; name|LOG operator|. name|debug argument_list|( literal|"writing " operator|+ name|ADD_ROWS operator|+ literal|" rows to " operator|+ name|table1 argument_list|) expr_stmt|; name|Assert operator|. name|assertEquals argument_list|( name|TEST_UTIL operator|. name|countRows argument_list|( name|t1 argument_list|) argument_list|, name|NB_ROWS_IN_BATCH operator|+ name|ADD_ROWS operator|+ name|NB_ROWS_FAM3 argument_list|) expr_stmt|; name|t1 operator|. name|close argument_list|() expr_stmt|; name|LOG operator|. name|debug argument_list|( literal|"written " operator|+ name|ADD_ROWS operator|+ literal|" rows to " operator|+ name|table1 argument_list|) expr_stmt|; name|Table name|t2 init|= name|conn operator|. name|getTable argument_list|( name|table2 argument_list|) decl_stmt|; name|Put name|p2 decl_stmt|; for|for control|( name|int name|i init|= literal|0 init|; name|i operator|< literal|5 condition|; name|i operator|++ control|) block|{ name|p2 operator|= operator|new name|Put argument_list|( name|Bytes operator|. name|toBytes argument_list|( literal|"row-t2" operator|+ name|i argument_list|) argument_list|) expr_stmt|; name|p2 operator|. name|addColumn argument_list|( name|famName argument_list|, name|qualName argument_list|, name|Bytes operator|. name|toBytes argument_list|( literal|"val" operator|+ name|i argument_list|) argument_list|) expr_stmt|; name|t2 operator|. name|put argument_list|( name|p2 argument_list|) expr_stmt|; block|} name|Assert operator|. name|assertEquals argument_list|( name|TEST_UTIL operator|. name|countRows argument_list|( name|t2 argument_list|) argument_list|, name|NB_ROWS_IN_BATCH operator|+ literal|5 argument_list|) expr_stmt|; name|t2 operator|. name|close argument_list|() expr_stmt|; name|LOG operator|. name|debug argument_list|( literal|"written " operator|+ literal|5 operator|+ literal|" rows to " operator|+ name|table2 argument_list|) expr_stmt|; comment|// #3 - incremental backup for multiple tables name|incrementalBackupWithFailures argument_list|() expr_stmt|; name|admin operator|. name|close argument_list|() expr_stmt|; name|conn operator|. name|close argument_list|() expr_stmt|; block|} specifier|private name|void name|incrementalBackupWithFailures parameter_list|() throws|throws name|Exception block|{ name|conf1 operator|. name|set argument_list|( name|TableBackupClient operator|. name|BACKUP_CLIENT_IMPL_CLASS argument_list|, name|IncrementalTableBackupClientForTest operator|. name|class operator|. name|getName argument_list|() argument_list|) expr_stmt|; name|int name|maxStage init|= name|Stage operator|. name|values argument_list|() operator|. name|length operator|- literal|1 decl_stmt|; comment|// Fail stages between 0 and 4 inclusive for|for control|( name|int name|stage init|= literal|0 init|; name|stage operator|<= name|maxStage condition|; name|stage operator|++ control|) block|{ name|LOG operator|. name|info argument_list|( literal|"Running stage " operator|+ name|stage argument_list|) expr_stmt|; name|runBackupAndFailAtStage argument_list|( name|stage argument_list|) expr_stmt|; block|} block|} specifier|private name|void name|runBackupAndFailAtStage parameter_list|( name|int name|stage parameter_list|) throws|throws name|Exception block|{ name|conf1 operator|. name|setInt argument_list|( name|FullTableBackupClientForTest operator|. name|BACKUP_TEST_MODE_STAGE argument_list|, name|stage argument_list|) expr_stmt|; try|try init|( name|BackupSystemTable name|table init|= operator|new name|BackupSystemTable argument_list|( name|TEST_UTIL operator|. name|getConnection argument_list|() argument_list|) init|) block|{ name|int name|before init|= name|table operator|. name|getBackupHistory argument_list|() operator|. name|size argument_list|() decl_stmt|; name|String index|[] name|args init|= operator|new name|String index|[] block|{ literal|"create" block|, literal|"incremental" block|, name|BACKUP_ROOT_DIR block|, literal|"-t" block|, name|table1 operator|. name|getNameAsString argument_list|() operator|+ literal|"," operator|+ name|table2 operator|. name|getNameAsString argument_list|() block|} decl_stmt|; comment|// Run backup name|int name|ret init|= name|ToolRunner operator|. name|run argument_list|( name|conf1 argument_list|, operator|new name|BackupDriver argument_list|() argument_list|, name|args argument_list|) decl_stmt|; name|assertFalse argument_list|( name|ret operator|== literal|0 argument_list|) expr_stmt|; name|List argument_list|< name|BackupInfo argument_list|> name|backups init|= name|table operator|. name|getBackupHistory argument_list|() decl_stmt|; name|int name|after init|= name|table operator|. name|getBackupHistory argument_list|() operator|. name|size argument_list|() decl_stmt|; name|assertTrue argument_list|( name|after operator|== name|before operator|+ literal|1 argument_list|) expr_stmt|; for|for control|( name|BackupInfo name|data range|: name|backups control|) block|{ if|if condition|( name|data operator|. name|getType argument_list|() operator|== name|BackupType operator|. name|FULL condition|) block|{ name|assertTrue argument_list|( name|data operator|. name|getState argument_list|() operator|== name|BackupState operator|. name|COMPLETE argument_list|) expr_stmt|; block|} else|else block|{ name|assertTrue argument_list|( name|data operator|. name|getState argument_list|() operator|== name|BackupState operator|. name|FAILED argument_list|) expr_stmt|; block|} block|} block|} block|} block|} end_class end_unit 10-100 package ca.carleton.gcrc.couch.submission; public class SubmissionConstants { final static public String PROP_ATTR_SUBMISSION_DB_NAME = "couchdb.submission.dbName"; final static public String PROP_ATTR_SUBMISSION_ENABLED = "couchdb.submission.enabled"; } src/main/java/dev/leons/ward/dto/UptimeDto.java package dev.leons.ward.dto; import lombok.Getter; import lombok.Setter; /** * UptimeDto is a values container for presenting uptime principal information * * @author * @version 1.0.0 */ @Getter @Setter public class UptimeDto { /** * Uptime days field */ private String days; /** * Uptime hours field */ private String hours; /** * Uptime minutes field */ private String minutes; /** * Uptime seconds field */ private String seconds; }package cuke4duke.internal.language; import cuke4duke.internal.JRuby; import org.jruby.RubyArray; import org.jruby.runtime.builtin.IRubyObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public abstract class AbstractProgrammingLanguage implements ProgrammingLanguage { protected final LanguageMixin languageMixin; private List stepDefinitions; private Map, Transformable> transforms; public AbstractProgrammingLanguage(LanguageMixin languageMixin) { this.languageMixin = languageMixin; } final public RubyArray step_matches(String step_name, String formatted_step_name) throws Throwable { return JRuby.newArray(step_match_list(step_name, formatted_step_name)); } public abstract void load_code_file(String file) throws Throwable; public final List step_match_list(String step_name, String formatted_step_name) throws Throwable { List matches = new ArrayList(); for (StepDefinition stepDefinition : stepDefinitions) { List arguments = stepDefinition.arguments_from(step_name); if (arguments != null) { matches.add(languageMixin.create_step_match(stepDefinition, step_name, formatted_step_name, arguments)); } } return matches; } protected void clearHooksAndStepDefinitions() { transforms = new HashMap, Transformable>(); stepDefinitions = new ArrayList(); } public final Map, Transformable> getTransforms() { return transforms; } public void addTransform(Class type, Transformable transform) { this.transforms.put(type, transform); } public void addBeforeHook(Hook before) { languageMixin.add_hook("before", before); } public void addStepDefinition(StepDefinition stepDefinition) { stepDefinitions.add(stepDefinition); } public void addAfterHook(Hook after) { languageMixin.add_hook("after", after); } protected abstract void begin_scenario(IRubyObject scenario) throws Throwable; public abstract void end_scenario() throws Throwable; public void availableStepDefinition(String regexp_source, String file_colon_line) { languageMixin.available_step_definition(regexp_source, file_colon_line); } public void invokedStepDefinition(String regexp_source, String file_colon_line) { languageMixin.invoked_step_definition(regexp_source, file_colon_line); } } // Copyright 2004-present Facebook. All Rights Reserved. package com.facebook.profilo.provider.mappingdensity; import android.util.Log; import com.facebook.profilo.core.BaseTraceProvider; import com.facebook.profilo.core.ProvidersRegistry; import com.facebook.profilo.ipc.TraceContext; import com.facebook.proguard.annotations.DoNotStrip; import java.io.File; @DoNotStrip public final class MappingDensityProvider extends BaseTraceProvider { public static final int PROVIDER_MAPPINGDENSITY = ProvidersRegistry.newProvider("mapping_density"); private boolean mEnabled; public MappingDensityProvider() { super("profilo_mappingdensity"); } @Override protected void enable() { mEnabled = true; } @Override protected void disable() { mEnabled = false; } @Override protected void onTraceStarted(TraceContext context, File extraDataFolder) { doDump(extraDataFolder, "start"); } @Override protected void onTraceEnded(TraceContext context, File extraDataFolder) { doDump(extraDataFolder, "end"); } @Override protected int getSupportedProviders() { return PROVIDER_MAPPINGDENSITY; } private static void doDump(File extraDataFolder, String dumpName) { extraDataFolder.mkdirs(); if (extraDataFolder.exists()) { dumpMappingDensities("^/data/(data|app)", extraDataFolder.getPath(), dumpName); } else { Log.w("Profilo/MappingDensity", "nonexistent extras directory: " + extraDataFolder.getPath()); } } private static native void dumpMappingDensities( String mapRegex, String extraDataFolderPath, String dumpName); @Override protected int getTracingProviders() { return mEnabled ? PROVIDER_MAPPINGDENSITY : 0; } } mobi.chouette.exchange.neptune/src/test/java/mobi/chouette/exchange/neptune/validation/Phase2StopAreaTests.java package mobi.chouette.exchange.neptune.validation; import mobi.chouette.exchange.validation.report.CheckPointReport.SEVERITY; import mobi.chouette.exchange.validation.report.ValidationReporter.RESULT; import org.testng.annotations.Test; public class Phase2StopAreaTests extends ValidationTests { @Test(groups = { "Phase 2 stop areas" }, description = "child of stoparea type is wrong") public void verifyTest_2_StopArea_1() throws Exception { verifyValidation( "2-NEPTUNE-StopArea-1.xml", "2-NEPTUNE-StopArea-1", SEVERITY.ERROR, RESULT.NOK); } @Test(groups = { "Phase 2 stop areas" }, description = "child of stoparea type is wrong (StopPlace)") public void verifyTest_2_StopArea_2() throws Exception { verifyValidation( "2-NEPTUNE-StopArea-2.xml", "2-NEPTUNE-StopArea-2", SEVERITY.ERROR, RESULT.NOK); } @Test(groups = { "Phase 2 stop areas" }, description = "child of stoparea type is wrong (CommercialStopPoint)") public void verifyTest_2_StopArea_3() throws Exception { verifyValidation( "2-NEPTUNE-StopArea-3.xml", "2-NEPTUNE-StopArea-3", SEVERITY.ERROR, RESULT.NOK); } @Test(groups = { "Phase 2 stop areas" }, description = "child of stoparea type is wrong (BoardingPosition)") public void verifyTest_2_StopArea_4() throws Exception { verifyValidation( "2-NEPTUNE-StopArea-4.xml", "2-NEPTUNE-StopArea-4", SEVERITY.ERROR, RESULT.NOK); } @Test(groups = { "Phase 2 stop areas" }, description = "Missing AreaCentroid (StopPlace)") public void verifyTest_2_StopArea_5_1() throws Exception { verifyValidation( "2-NEPTUNE-StopArea-5-1.xml", "2-NEPTUNE-StopArea-5", SEVERITY.ERROR, RESULT.NOK); } @Test(groups = { "Phase 2 stop areas" }, description = "Missing AreaCentroid (CommercialStopPoint)") public void verifyTest_2_StopArea_5_2() throws Exception { verifyValidation( "2-NEPTUNE-StopArea-5-2.xml", "2-NEPTUNE-StopArea-5", SEVERITY.ERROR, RESULT.NOK); } @Test(groups = { "Phase 2 stop areas" }, description = "Missing AreaCentroid (BoardingPosition)") public void verifyTest_2_StopArea_5_3() throws Exception { verifyValidation( "2-NEPTUNE-StopArea-5-3.xml", "2-NEPTUNE-StopArea-5", SEVERITY.ERROR, RESULT.NOK); } @Test(groups = { "Phase 2 stop areas" }, description = "cross references between stoparea and areacentroid") public void verifyTest_2_StopArea_6() throws Exception { verifyValidation( "2-NEPTUNE-StopArea-6.xml", "2-NEPTUNE-StopArea-6", SEVERITY.ERROR, RESULT.NOK); } } package com.rideaustin.assemblers; import java.util.Date; import java.util.Optional; import javax.inject.Inject; import org.springframework.core.env.Environment; import org.springframework.statemachine.ExtendedState; import org.springframework.statemachine.StateMachineContext; import org.springframework.statemachine.StateMachinePersist; import org.springframework.stereotype.Component; import com.rideaustin.Constants; import com.rideaustin.model.Address; import com.rideaustin.model.Document; import com.rideaustin.model.enums.DocumentType; import com.rideaustin.model.enums.RideStatus; import com.rideaustin.model.ride.ActiveDriver; import com.rideaustin.model.ride.Car; import com.rideaustin.model.ride.Ride; import com.rideaustin.model.user.Driver; import com.rideaustin.rest.model.HeadingDirection; import com.rideaustin.rest.model.Location; import com.rideaustin.rest.model.RideTrackingShareDto; import com.rideaustin.service.DocumentService; import com.rideaustin.service.model.Events; import com.rideaustin.service.model.States; import com.rideaustin.service.model.context.RideFlowContext; import com.rideaustin.service.user.CarTypesCache; import com.rideaustin.utils.DateUtils; import com.rideaustin.utils.dispatch.StateMachineUtils; import lombok.RequiredArgsConstructor; @Component @RequiredArgsConstructor(onConstructor = @__(@Inject)) public class RideTrackingShareDtoAssembler implements SingleSideAssembler { private final CarTypesCache carTypesCache; private final DocumentService documentService; private final StateMachinePersist contextAccess; private final Environment environment; @Override public RideTrackingShareDto toDto(Ride ride) { RideTrackingShareDto rideTrackingShareDto = new RideTrackingShareDto(); rideTrackingShareDto.setRideId(ride.getId()); rideTrackingShareDto.setCityId(ride.getCityId()); rideTrackingShareDto.setRiderId(ride.getRider().getId()); rideTrackingShareDto.setRiderFirstName(ride.getRider().getUser().getFirstname()); rideTrackingShareDto.setRiderLastName(ride.getRider().getUser().getLastname()); rideTrackingShareDto.setRiderPhoto(ride.getRider().getUser().getPhotoUrl()); rideTrackingShareDto.setRideCarCategory(ride.getRequestedCarType().getCarCategory()); ActiveDriver activeDriver = ride.getActiveDriver(); if (activeDriver != null) { Driver driver = activeDriver.getDriver(); rideTrackingShareDto.setDriverId(driver.getId()); rideTrackingShareDto.setDriverFirstName(driver.getUser().getFirstname()); rideTrackingShareDto.setDriverLastName(driver.getUser().getLastname()); String photoUrl = Optional.ofNullable(documentService.findAvatarDocument(driver, DocumentType.DRIVER_PHOTO)).map(Document::getDocumentUrl).orElse(""); rideTrackingShareDto.setDriverPhoto(photoUrl); rideTrackingShareDto.setDriverRating(driver.getRating()); Optional car = driver.getCars().stream().filter(Car::isSelected).findFirst(); rideTrackingShareDto.setDriverCar(car.orElse(null)); rideTrackingShareDto.setDriverCarTypes(car.map(c -> carTypesCache.fromBitMask(c.getCarCategoriesBitmask())).orElse(null)); rideTrackingShareDto.setDriverLicensePlate(car.map(Car::getLicense).orElse(null)); if (RideStatus.ACTIVE.equals(ride.getStatus())) { rideTrackingShareDto.setCurrentSpeed(activeDriver.getSpeed()); rideTrackingShareDto.setCurrentCourse(activeDriver.getCourse()); Double heading = activeDriver.getHeading(); rideTrackingShareDto.setCurrentHeading(heading); rideTrackingShareDto.setCurrentHeadingDirection(HeadingDirection.from(heading)); rideTrackingShareDto.setDriverLocation(new Location(activeDriver.getLatitude(), activeDriver.getLongitude())); } } rideTrackingShareDto.setStatus(ride.getStatus()); if (RideStatus.COMPLETED.equals(ride.getStatus())) { rideTrackingShareDto.setCompletedOn(Constants.DATETIME_FORMATTER.format(DateUtils.dateToInstant(ride.getCompletedOn()))); } StateMachineContext persistedContext = StateMachineUtils.getPersistedContext(environment, contextAccess, ride.getId()); Date startedOn = ride.getStartedOn(); if (persistedContext != null && startedOn == null) { ExtendedState extendedState = persistedContext.getExtendedState(); final RideFlowContext flowContext = StateMachineUtils.getFlowContext(extendedState); startedOn = flowContext.getStartedOn(); } Optional.ofNullable(startedOn).map(DateUtils::dateToInstant).map(Constants.DATETIME_FORMATTER::format).ifPresent(rideTrackingShareDto::setStartedOn); rideTrackingShareDto.setCreatedDate(Constants.DATETIME_FORMATTER.format(DateUtils.dateToInstant(ride.getCreatedDate()))); rideTrackingShareDto.setUpdatedDate(Constants.DATETIME_FORMATTER.format(DateUtils.dateToInstant(ride.getUpdatedDate()))); Optional.ofNullable(ride.getStart()).map(Address::getAddress).ifPresent(rideTrackingShareDto::setStartAddress); if (ride.getStartLocationLat() != null && ride.getStartLocationLong() != null) { rideTrackingShareDto.setStartLocation(new Location(ride.getStartLocationLat(), ride.getStartLocationLong())); } Optional.ofNullable(ride.getEnd()).map(Address::getAddress).ifPresent(rideTrackingShareDto::setEndAddress); if (ride.getEndLocationLat() != null && ride.getEndLocationLong() != null) { rideTrackingShareDto.setEndLocation(new Location(ride.getEndLocationLat(), ride.getEndLocationLong())); } return rideTrackingShareDto; } } package com.emall.service; import com.emall.dao.UserMapper; import com.emall.entity.User; import com.emall.utils.SnowflakeIdWorker; import com.emall.vo.PasswordVo; import com.emall.vo.UserUpdateVo; import org.apache.shiro.crypto.SecureRandomNumberGenerator; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import javax.annotation.Resource; import javax.validation.Valid; import static com.emall.shiro.ShiroEncrypt.shiroEncrypt; /** * 用户业务层 */ @Service public class UserService { @Resource UserMapper userMapper; @Resource SnowflakeIdWorker snowflakeIdWorker; /** * 根据用户名查询用户对象 * @param userName * @return User */ public User selectByUsername(String userName) { return userMapper.selectByUserName(userName); } /** * 注册验证 * @param user * @return Result */ public boolean registerValidate(User user) { String userName = user.getUserName(); String userPassword = user.getUserPassword(); Assert.isTrue(!userMapper.isExistByName(userName), "用户名已存在"); String salt = new SecureRandomNumberGenerator().nextBytes().toHex(); userPassword = shiroEncrypt(userPassword, salt); user.setUserId(String.valueOf(snowflakeIdWorker.nextId())); user.setUserPassword(userPassword); user.setUserSalt(salt); //设置为普通用户 user.setUserRole(0); return userMapper.insert(user) != 0; } /** * 用户信息修改 * @param userUpdateVo * @return */ public boolean userUpdate(@Valid UserUpdateVo userUpdateVo) { try { return userMapper.updateByUserId(userUpdateVo) != 0; } catch (Exception e) { return false; } } /** * 用户密码修改 * @param passwordVo * @return */ public boolean password(PasswordVo passwordVo) { return userMapper.pwdById(passwordVo) != 0; } } package com.bosssoft.learning.common; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @Description 日志注解 * @Date 2020/6/7 10:17 * @Author HetFrame */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) public @interface MyLogApi { public String action() default ""; public String desc() default ""; } fredxfred/pinotpinot-broker/src/main/java/com/linkedin/pinot/broker/routing/builder/RoutingTableBuilder.java /** * 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.linkedin.pinot.broker.routing.builder; import com.linkedin.pinot.broker.routing.RoutingTableLookupRequest; import com.linkedin.pinot.broker.routing.selector.SegmentSelector; import com.linkedin.pinot.common.config.TableConfig; import com.linkedin.pinot.common.metrics.BrokerMetrics; import java.util.List; import java.util.Map; import org.apache.commons.configuration.Configuration; import org.apache.helix.ZNRecord; import org.apache.helix.model.ExternalView; import org.apache.helix.model.InstanceConfig; import org.apache.helix.store.zk.ZkHelixPropertyStore; /** * Build routing tables based on ExternalView from Helix. */ public interface RoutingTableBuilder { /** * Initiate the routing table builder. */ void init(Configuration configuration, TableConfig tableConfig, ZkHelixPropertyStore propertyStore, BrokerMetrics brokerMetrics); /** * Compute routing tables (map from server to list of segments) that are used for query routing from ExternalView. *

Should be called whenever there is an ExternalView change. */ void computeOnExternalViewChange(String tableName, ExternalView externalView, List instanceConfigs); /** * Get the routing table based on the given lookup request and segment selector * * TODO: we need to consider relocating segment selector into the routing table builder instead of passing it * from outside. */ Map> getRoutingTable(RoutingTableLookupRequest request, SegmentSelector segmentSelector); /** * Get all pre-computed routing tables. */ List>> getRoutingTables(); } components/src/test/java/eu/internetofus/common/components/profile_manager/DiversityDataTest.java0 /* * ----------------------------------------------------------------------------- * * Copyright 2019 - 2022 UDT-IA, IIIA-CSIC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ----------------------------------------------------------------------------- */ package eu.internetofus.common.components.profile_manager; import eu.internetofus.common.components.StoreServices; import eu.internetofus.common.model.ModelTestCase; import io.vertx.core.Future; import io.vertx.core.Vertx; import io.vertx.junit5.VertxTestContext; import java.util.HashSet; /** * Test the {@link DiversityData}. * * @see DiversityData * * @author UDT-IA, IIIA-CSIC */ public class DiversityDataTest extends ModelTestCase { /** * {@inheritDoc} */ @Override public DiversityData createModelExample(final int index) { final var model = new DiversityData(); model.attributes = new HashSet<>(); model.attributes.add("gender"); model.attributes.add("occupation"); model.attributes.add("index of " + index); model.userIds = new HashSet<>(); model.userIds.add("User of " + index); model.userIds.add("User of " + index + 1); model.userIds.add("User of " + index + 2); return model; } /** * Create a valid diversity data. * * @param index of the example to create. * @param vertx event bus to use. * @param testContext context to test. * * @return the valid model. */ public Future createModelExample(final int index, final Vertx vertx, final VertxTestContext testContext) { final var model = new DiversityData(); model.attributes = new HashSet<>(); model.attributes.add("dateOfBirth.day"); model.attributes.add("dateOfBirth.month"); model.attributes.add("dateOfBirth.year"); model.attributes.add("gender"); model.attributes.add("locale"); model.attributes.add("nationality"); model.attributes.add("occupation"); model.attributes.add("materials.department"); model.attributes.add("materials.degree_programme"); model.attributes.add("materials.accommodation"); model.attributes.add("competences.c_food"); model.attributes.add("competences.c_eating"); model.attributes.add("competences.u_active"); model.attributes.add("competences.u_essay"); model.attributes.add("meanings.excitement"); model.attributes.add("meanings.promotion"); model.attributes.add("meanings.extraversion"); model.attributes.add("meanings.agreeableness"); model.userIds = new HashSet<>(); var future = Future.succeededFuture(model); for (var i = 0; i < 3; i++) { final var profileIndex = index + i; future = future .compose(chainModel -> StoreServices.storeProfileExample(profileIndex, vertx, testContext).map(profile -> { chainModel.userIds.add(profile.id); return chainModel; })); } return future; } } common/src/main/java/com/scottlogic/deg/common/profile/Rule.java package com.scottlogic.deg.common.profile; import com.scottlogic.deg.common.profile.constraints.Constraint; import java.util.Collection; public class Rule { public final RuleInformation ruleInformation; public final Collection constraints; public Rule(RuleInformation ruleInformation, Collection constraints) { this.ruleInformation = ruleInformation; this.constraints = constraints; } } import net.runelite.mapping.Export; import net.runelite.mapping.ObfuscatedName; import net.runelite.mapping.ObfuscatedSignature; @ObfuscatedName("dx") public abstract class class126 extends Node { @ObfuscatedName("nb") @ObfuscatedSignature(descriptor = "Ljz;") static Widget field1516; class126() { } @ObfuscatedName("c") @ObfuscatedSignature(descriptor = "(Lpi;I)V", garbageValue = "703192976") abstract void vmethod3019(Buffer var1); @ObfuscatedName("l") @ObfuscatedSignature(descriptor = "(Ley;I)V", garbageValue = "750335300") abstract void vmethod3020(ClanSettings var1); @ObfuscatedName("c") @ObfuscatedSignature(descriptor = "(II)Lfr;", garbageValue = "638570064") @Export("WorldMapElement_get") public static WorldMapElement WorldMapElement_get(int var0) { return ((var0 >= 0) && (var0 < WorldMapElement.WorldMapElement_cached.length)) && (WorldMapElement.WorldMapElement_cached[var0] != null) ? WorldMapElement.WorldMapElement_cached[var0] : new WorldMapElement(var0); } @ObfuscatedName("l") @ObfuscatedSignature(descriptor = "(Lkq;III)Lpt;", garbageValue = "856920976") @Export("SpriteBuffer_getSprite") public static SpritePixels SpriteBuffer_getSprite(AbstractArchive var0, int var1, int var2) { return !class125.method2744(var0, var1, var2) ? null : SpriteMask.method5322(); } @ObfuscatedName("l") @ObfuscatedSignature(descriptor = "(Ljava/lang/CharSequence;B)[B", garbageValue = "23") public static byte[] method2754(CharSequence var0) { int var1 = var0.length(); byte[] var2 = new byte[var1]; for (int var3 = 0; var3 < var1; ++var3) { char var4 = var0.charAt(var3); if (((var4 > 0) && (var4 < 128)) || ((var4 >= 160) && (var4 <= 255))) { var2[var3] = ((byte) (var4)); } else if (var4 == 8364) { var2[var3] = -128; } else if (var4 == 8218) { var2[var3] = -126; } else if (var4 == 402) { var2[var3] = -125; } else if (var4 == 8222) { var2[var3] = -124; } else if (var4 == 8230) { var2[var3] = -123; } else if (var4 == 8224) { var2[var3] = -122; } else if (var4 == 8225) { var2[var3] = -121; } else if (var4 == 710) { var2[var3] = -120; } else if (var4 == 8240) { var2[var3] = -119; } else if (var4 == 352) { var2[var3] = -118; } else if (var4 == 8249) { var2[var3] = -117; } else if (var4 == 338) { var2[var3] = -116; } else if (var4 == 381) { var2[var3] = -114; } else if (var4 == 8216) { var2[var3] = -111; } else if (var4 == 8217) { var2[var3] = -110; } else if (var4 == 8220) { var2[var3] = -109; } else if (var4 == 8221) { var2[var3] = -108; } else if (var4 == 8226) { var2[var3] = -107; } else if (var4 == 8211) { var2[var3] = -106; } else if (var4 == 8212) { var2[var3] = -105; } else if (var4 == 732) { var2[var3] = -104; } else if (var4 == 8482) { var2[var3] = -103; } else if (var4 == 353) { var2[var3] = -102; } else if (var4 == 8250) { var2[var3] = -101; } else if (var4 == 339) { var2[var3] = -100; } else if (var4 == 382) { var2[var3] = -98; } else if (var4 == 376) { var2[var3] = -97; } else { var2[var3] = 63; } } return var2; } @ObfuscatedName("e") @ObfuscatedSignature(descriptor = "(IZIZI)V", garbageValue = "223998791") @Export("sortWorldList") static void sortWorldList(int var0, boolean var1, int var2, boolean var3) { if (class33.World_worlds != null) { BoundaryObject.doWorldSorting(0, class33.World_worlds.length - 1, var0, var1, var2, var3); } } @ObfuscatedName("js") @ObfuscatedSignature(descriptor = "(I)Z", garbageValue = "350265873") @Export("getTapToDrop") static boolean getTapToDrop() { return Client.tapToDrop; } }lanaflonPerso/otus_java_2018_12 package ru.otus.login; import ru.otus.user.UserService; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; public class LoginServlet extends HttpServlet { private static final int EXPIRE_INTERVAL = 20; // seconds private final UserService userService; public LoginServlet(UserService userService) { this.userService = userService; } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { String name = request.getParameter("name"); String password = request.getParameter("password"); if (userService.authenticate(name, password)) { HttpSession session = request.getSession(); session.setMaxInactiveInterval(30); } else { response.setStatus(403); } } }/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public List rightSideView(TreeNode root) { List ans = new ArrayList<>(); if(root==null) return ans; List q = new ArrayList<>(); q.add(root); while(!q.isEmpty()){ List temp = new ArrayList<>(); ans.add(q.get(0).val); for(TreeNode node:q){ if(node.right!=null) temp.add(node.right); if(node.left!=null) temp.add(node.left); } q=temp; } return ans; } }1-10 import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class CalcMD5 { public static String stringMD5(String input) { try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); byte[] inputByteArray = input.getBytes(); messageDigest.update(inputByteArray); byte[] resultByteArray = messageDigest.digest(); System.out.println(resultByteArray); return byteArrayToHex(resultByteArray); } catch (NoSuchAlgorithmException e) { return null; } } public static String byteArrayToHex(byte[] byteArray) { final String hexDigits = "0123456789abcdef"; char[] resultCharArray = new char[byteArray.length * 2]; int index = 0; for (byte b : byteArray) { resultCharArray[index++] = hexDigits.toCharArray()[(b & 0xf0) >>> 4]; resultCharArray[index++] = hexDigits.toCharArray()[b & 0xf]; } return new String(resultCharArray); } public static Long stringMD5FirstHalfToLong(String input) { try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); byte[] inputByteArray = input.getBytes(); messageDigest.update(inputByteArray); byte[] resultByteArray = messageDigest.digest(); Long result = 0L; if (resultByteArray != null && (resultByteArray.length == 16)) { int i = 0; while (i < 8) { int j = 0xFF & resultByteArray[i]; long l = result << 8 | j; i++; result = l; } } return result; } catch (NoSuchAlgorithmException e) { return null; } } public static void main(String[] args) { String input = "android"; System.out.println(CalcMD5.stringMD5(input)); System.out.println(CalcMD5.stringMD5FirstHalfToLong(input)); } } 1-10 /* * Copyright (c) 2012-2018, . All Rights Reserved. * * This file is part of DDogleg (http://ddogleg.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ddogleg.nn.alg.searches; import org.ddogleg.nn.alg.KdTree; import org.ddogleg.nn.alg.KdTreeDistance; import org.ddogleg.nn.alg.KdTreeSearch1; /** * Standard algorithm for searching a {@link KdTree} for the nearest-neighbor of a search. This is the algorithm * which is typically described in books. At each node it examines distance of the two children and investigates * the closer child. After it reaches a leaf it steps back in the search and sees if the other child could produce * a better solution, if it can it is also investigated. The search stops when no more nodes can produce a better * result. * * @author */ public class KdTreeSearch1Standard

implements KdTreeSearch1

{ // the targeted tree private KdTree tree; // point being searched for private P target; // the maximum distance a neighbor is allowed to be private double maxDistanceSq = Double.MAX_VALUE; // the closest neighbor which has yet to be found private double bestDistanceSq; // the node which has been found to be the closest so far private KdTree.Node closest; KdTreeDistance

distance; public KdTreeSearch1Standard(KdTreeDistance

distance) { this.distance = distance; } @Override public void setTree( KdTree tree ) { this.tree = tree; } /** * Specifies the greatest distance it will search * * @param maxDistance Maximum distance (Euclidean squared) a closest point can be */ @Override public void setMaxDistance(double maxDistance ) { this.maxDistanceSq = maxDistance ; } /** * Finds the node which is closest to 'target' * * @param target A point * @return Closest node or null if none is within the minimum distance. */ @Override public KdTree.Node findNeighbor(P target) { if( tree.root == null ) return null; this.target = target; this.closest = null; this.bestDistanceSq = maxDistanceSq; stepClosest(tree.root); return closest; } @Override public double getDistance() { return bestDistanceSq; } /** * Recursive step for finding the closest point */ private void stepClosest(KdTree.Node node) { if( node == null ) return; if( node.isLeaf() ) { // a leaf can be empty. if( node.point != null ) { double distSq = distance.distance((P)node.point,target); if( distSq <= bestDistanceSq ) { if( closest == null || distSq < bestDistanceSq ) { closest = node; bestDistanceSq = distSq; } } } return; } else { double distSq = distance.distance((P)node.point,target); if( distSq <= bestDistanceSq ) { if( closest == null || distSq < bestDistanceSq ) { closest = node; bestDistanceSq = distSq; } } } // select the most promising branch to investigate first KdTree.Node nearer,further; double splitValue = distance.valueAt((P)node.point,node.split); double targetAtSplit = distance.valueAt(target,node.split); if( targetAtSplit <= splitValue ) { nearer = node.left; further = node.right; } else { nearer = node.right; further = node.left; } stepClosest(nearer); // See if it is possible for 'further' to contain a better node double dx = splitValue - targetAtSplit; double dx2 = dx*dx; if( dx2 <= bestDistanceSq ) { if( closest == null || dx2 < bestDistanceSq ) stepClosest(further); } } } jlopezmalla-stratio/spark0 package com.stratio.pf.sparkAT.coverage.streaminghdfsdynamic; import com.stratio.qa.cucumber.testng.CucumberRunner; import com.stratio.spark.tests.utils.BaseTest; import cucumber.api.CucumberOptions; import org.testng.annotations.Test; @CucumberOptions(features = { "src/test/resources/features/pf/coverage/streaming-hdfs-dynamic.feature" }) public class StreamingHDFSDynamicCoverage_IT extends BaseTest { public StreamingHDFSDynamicCoverage_IT() { } @Test(enabled = true, groups = {"DynamicCoverage"}) public void streamingHDFSDynamicCoverage() throws Exception { new CucumberRunner(this.getClass()).runCukes(); } } generated/java/com/github/helloiampau/janus/generated/ProtocolDelegate.java // AUTOGENERATED FILE - DO NOT MODIFY! // This file generated by Djinni from janus-client.djinni package com.github.helloiampau.janus.generated; import android.util.Log; import java.util.concurrent.atomic.AtomicBoolean; public abstract class ProtocolDelegate { private static String TAG = "pd java_native_janus_log"; public abstract void onReady(); public abstract void onClose(); public abstract void onError(JanusError error, Bundle context); public abstract void onEvent(JanusEvent event, Bundle context); public abstract void onHangup(String reason); private static final class CppProxy extends ProtocolDelegate { private final long nativeRef; private final AtomicBoolean destroyed = new AtomicBoolean(false); private CppProxy(long nativeRef) { Log.d(TAG, "CppProxy"); if (nativeRef == 0) throw new RuntimeException("nativeRef is zero"); this.nativeRef = nativeRef; } private native void nativeDestroy(long nativeRef); public void _djinni_private_destroy() { Log.d(TAG, "_djinni_private_destroy"); boolean destroyed = this.destroyed.getAndSet(true); if (!destroyed) nativeDestroy(this.nativeRef); } protected void finalize() throws java.lang.Throwable { Log.d(TAG, "finalize"); _djinni_private_destroy(); super.finalize(); } @Override public void onReady() { Log.d(TAG, "onReady"); assert !this.destroyed.get() : "trying to use a destroyed object"; native_onReady(this.nativeRef); } private native void native_onReady(long _nativeRef); @Override public void onClose() { Log.d(TAG, "onClose"); assert !this.destroyed.get() : "trying to use a destroyed object"; native_onClose(this.nativeRef); } private native void native_onClose(long _nativeRef); @Override public void onError(JanusError error, Bundle context) { Log.d(TAG, "onError"); assert !this.destroyed.get() : "trying to use a destroyed object"; native_onError(this.nativeRef, error, context); } private native void native_onError(long _nativeRef, JanusError error, Bundle context); @Override public void onEvent(JanusEvent event, Bundle context) { Log.d(TAG, "onEvent"); assert !this.destroyed.get() : "trying to use a destroyed object"; native_onEvent(this.nativeRef, event, context); } private native void native_onEvent(long _nativeRef, JanusEvent event, Bundle context); @Override public void onHangup(String reason) { Log.d(TAG, "onHangup"); assert !this.destroyed.get() : "trying to use a destroyed object"; native_onHangup(this.nativeRef, reason); } private native void native_onHangup(long _nativeRef, String reason); } } package com.ziroom.ziroomcustomer.ziroomapartment.activity; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import butterknife.Unbinder; import butterknife.internal.Utils; public class ZryuRentCardActivity$ViewHolder_ViewBinding implements Unbinder { protected T a; public ZryuRentCardActivity$ViewHolder_ViewBinding(T paramT, View paramView) { this.a = paramT; paramT.mTvName = ((TextView)Utils.findRequiredViewAsType(paramView, 2131690049, "field 'mTvName'", TextView.class)); paramT.mTvTime = ((TextView)Utils.findRequiredViewAsType(paramView, 2131689852, "field 'mTvTime'", TextView.class)); paramT.mTvNum = ((TextView)Utils.findRequiredViewAsType(paramView, 2131690003, "field 'mTvNum'", TextView.class)); paramT.mTvTitle = ((TextView)Utils.findRequiredViewAsType(paramView, 2131689541, "field 'mTvTitle'", TextView.class)); paramT.mTvSubTitle = ((TextView)Utils.findRequiredViewAsType(paramView, 2131694578, "field 'mTvSubTitle'", TextView.class)); paramT.mIv = ((ImageView)Utils.findRequiredViewAsType(paramView, 2131691574, "field 'mIv'", ImageView.class)); paramT.card_check = ((RelativeLayout)Utils.findRequiredViewAsType(paramView, 2131695387, "field 'card_check'", RelativeLayout.class)); } public void unbind() { ZryuRentCardActivity.ViewHolder localViewHolder = this.a; if (localViewHolder == null) { throw new IllegalStateException("Bindings already cleared."); } localViewHolder.mTvName = null; localViewHolder.mTvTime = null; localViewHolder.mTvNum = null; localViewHolder.mTvTitle = null; localViewHolder.mTvSubTitle = null; localViewHolder.mIv = null; localViewHolder.card_check = null; this.a = null; } } /* Location: /Users/gaoht/Downloads/zirom/classes3-dex2jar.jar!/com/ziroom/ziroomcustomer/ziroomapartment/activity/ZryuRentCardActivity$ViewHolder_ViewBinding.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */package me.kirantipov.mods.sync.client.render; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.render.RenderLayer; import net.minecraft.client.render.RenderPhase; import net.minecraft.client.render.VertexFormat; import net.minecraft.client.render.VertexFormats; import net.minecraft.util.Identifier; import net.minecraft.util.Util; import java.util.function.BiFunction; @Environment(EnvType.CLIENT) public final class CustomRenderLayer extends RenderLayer { private static final Shader ENTITY_TRANSLUCENT_PARTIALLY_TEXTURED_SHADER; private static final Shader VOXEL_SHADER; private static final RenderLayer VOXELS; private static final BiFunction ENTITY_TRANSLUCENT_PARTIALLY_TEXTURED; private CustomRenderLayer(String name, VertexFormat vertexFormat, VertexFormat.DrawMode drawMode, int expectedBufferSize, boolean hasCrumbling, boolean translucent, Runnable startAction, Runnable endAction) { super(name, vertexFormat, drawMode, expectedBufferSize, hasCrumbling, translucent, startAction, endAction); } public static RenderLayer getVoxels() { return VOXELS; } public static RenderLayer getEntityTranslucentPartiallyTextured(Identifier textureId, float cutoutY) { return getEntityTranslucentPartiallyTextured(textureId, cutoutY, true); } public static RenderLayer getEntityTranslucentPartiallyTextured(Identifier textureId, float cutoutY, boolean affectsOutline) { net.minecraft.client.render.Shader shader = CustomGameRenderer.getRenderTypeEntityTranslucentPartiallyTexturedShader(); shader.getUniformOrDefault("CutoutY").set(cutoutY); shader.getUniformOrDefault("ModelMat").set(MatrixStackStorage.getModelMatrixStack().peek().getModel()); return ENTITY_TRANSLUCENT_PARTIALLY_TEXTURED.apply(textureId, affectsOutline); } static { ENTITY_TRANSLUCENT_PARTIALLY_TEXTURED_SHADER = new Shader(CustomGameRenderer::getRenderTypeEntityTranslucentPartiallyTexturedShader); VOXEL_SHADER = new Shader(CustomGameRenderer::getRenderTypeVoxelShader); VOXELS = of("voxels", CustomVertexFormats.POSITION_COLOR_OVERLAY_LIGHT_NORMAL, VertexFormat.DrawMode.QUADS, 256, false, false, RenderLayer.MultiPhaseParameters.builder().shader(VOXEL_SHADER).transparency(NO_TRANSPARENCY).cull(DISABLE_CULLING).lightmap(ENABLE_LIGHTMAP).overlay(ENABLE_OVERLAY_COLOR).build(true)); ENTITY_TRANSLUCENT_PARTIALLY_TEXTURED = Util.memoize((id, outline) -> RenderLayer.of("entity_translucent_partially_textured", VertexFormats.POSITION_COLOR_TEXTURE_OVERLAY_LIGHT_NORMAL, VertexFormat.DrawMode.QUADS, 256, true, true, RenderLayer.MultiPhaseParameters.builder().shader(ENTITY_TRANSLUCENT_PARTIALLY_TEXTURED_SHADER).texture(new RenderPhase.Texture(id, false, false)).transparency(RenderLayer.TRANSLUCENT_TRANSPARENCY).cull(RenderLayer.DISABLE_CULLING).lightmap(RenderLayer.ENABLE_LIGHTMAP).overlay(RenderLayer.ENABLE_OVERLAY_COLOR).build(outline))); } }package io.left.rightmesh.libdtn.common.data.bundlev7.parser; import io.left.rightmesh.libcbor.CBOR; import io.left.rightmesh.libcbor.CborParser; import io.left.rightmesh.libdtn.common.data.ManifestBlock; import io.left.rightmesh.libdtn.common.utils.Log; /** * ManifestBlockParser parses the data-specific part of the ManifestBlock block. * * @author on 04/11/18. */ public class ManifestBlockParser { static CborParser getParser(ManifestBlock block, Log logger) { return CBOR.parser(); //todo } } TinghuanWang/source1-10 package cn.jsprun.struts.form; import org.apache.struts.action.ActionForm; public class PostsForm extends ActionForm { private static final long serialVersionUID = 1685250449032061435L; private int pid; private short fid = -1; private String filter = "normal"; public PostsForm() { } public PostsForm(Short fid) { this.fid = fid; } public Short getFid() { return fid; } public void setFid(Short fid) { this.fid = fid; } public Integer getPid() { return pid; } public void setPid(Integer pid) { this.pid = pid; } public String getFilter() { return filter; } public void setFilter(String filter) { this.filter = filter; } } package com.jayantkrish.jklol.experiments.wikitables; import java.util.List; import java.util.Set; import com.google.common.collect.ImmutableList; import com.google.common.collect.Sets; public class WikiTableMentionAnnotation { public static final String HEADING = "heading"; public static final String VALUE = "value"; public static final String NAME = "mentionAnnotation"; private final List mentions; private final List mentionTypes; private final List tokenStarts; private final List tokenEnds; public WikiTableMentionAnnotation(List mentions, List mentionTypes, List tokenStarts, List tokenEnds) { this.mentions = ImmutableList.copyOf(mentions); this.mentionTypes = ImmutableList.copyOf(mentionTypes); this.tokenStarts = ImmutableList.copyOf(tokenStarts); this.tokenEnds = ImmutableList.copyOf(tokenEnds); } public Set getMentionsWithType(String type) { Set things = Sets.newHashSet(); for (int i = 0; i < mentionTypes.size(); i++) { if (mentionTypes.get(i).equals(type)) { things.add(mentions.get(i)); } } return things; } public List getMentions() { return mentions; } public List getMentionTypes() { return mentionTypes; } public List getTokenStarts() { return tokenStarts; } public List getTokenEnds() { return tokenEnds; } } a878804506/water-vue-springbootflash-core/src/main/java/cn/enilu/flash/utils/water/OperateExcelUtil.java package cn.enilu.flash.utils.water; import cn.enilu.flash.bean.entity.water.WaterBill; import cn.enilu.flash.utils.HttpUtil; import jxl.SheetSettings; import jxl.Workbook; import jxl.format.Border; import jxl.format.BorderLineStyle; import jxl.write.*; import org.apache.commons.lang3.StringUtils; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.URLEncoder; public class OperateExcelUtil { /** * 生成excel * * @param waterBill 月度账单 * @param waterExcelRootPath 文件根目录位置 * @return */ public static String createExcelFile(WaterBill waterBill, String waterExcelRootPath) { String fileName = ""; try { // 第一种字体样式 WritableFont font1 = new WritableFont(WritableFont.createFont("黑体"), 12, WritableFont.BOLD); WritableCellFormat format1 = new WritableCellFormat(font1); format1.setBorder(Border.BOTTOM, BorderLineStyle.DOUBLE); format1.setAlignment(jxl.format.Alignment.CENTRE); // 把水平对齐方式指定为居中 format1.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE); // 把垂直对齐方式指定为居中 // 第二种字体样式 WritableFont font2 = new WritableFont(WritableFont.TIMES, 12); WritableCellFormat format2 = new WritableCellFormat(font2); format2.setAlignment(jxl.format.Alignment.CENTRE); // 把水平对齐方式指定为居中 // 第三种字体样式 WritableFont font3 = new WritableFont(WritableFont.createFont("黑体"), 10); WritableCellFormat format3 = new WritableCellFormat(font3); format3.setWrap(true);// 自动换行 format3.setBorder(Border.ALL, BorderLineStyle.THIN); format3.setAlignment(jxl.format.Alignment.CENTRE); // 把水平对齐方式指定为居中 format3.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE); // 把垂直对齐方式指定为居中 // 第四种字体样式 WritableFont font4 = new WritableFont(WritableFont.TIMES, 10); WritableCellFormat format4 = new WritableCellFormat(font4); format4.setWrap(true);// 自动换行 format4.setBorder(Border.ALL, BorderLineStyle.THIN); format4.setAlignment(jxl.format.Alignment.CENTRE); // 把水平对齐方式指定为居中 format4.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE); // 把垂直对齐方式指定为居中 // 第五种字体样式 WritableFont font5 = new WritableFont(WritableFont.TIMES, 9); WritableCellFormat format5 = new WritableCellFormat(font5); format5.setWrap(true);// 自动换行 format5.setBorder(Border.ALL, BorderLineStyle.THIN); format5.setAlignment(jxl.format.Alignment.CENTRE); // 把水平对齐方式指定为居中 format5.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE); // 把垂直对齐方式指定为居中 // 第六种字体样式 WritableFont font6 = new WritableFont(WritableFont.createFont("黑体"), 8); WritableCellFormat format6 = new WritableCellFormat(font6); format6.setBorder(Border.ALL, BorderLineStyle.THIN); format6.setAlignment(jxl.format.Alignment.CENTRE); // 把水平对齐方式指定为居中 format6.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE); // 把垂直对齐方式指定为居中 // 第七种字体样式 WritableFont font7 = new WritableFont(WritableFont.createFont("黑体"), 10); WritableCellFormat format7 = new WritableCellFormat(font7); format7.setBorder(Border.NONE, BorderLineStyle.THIN); format7.setAlignment(jxl.format.Alignment.CENTRE); // 把水平对齐方式指定为居中 format7.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE); // 把垂直对齐方式指定为居中 // 第八种字体样式 WritableFont font8 = new WritableFont(WritableFont.createFont("黑体"), 9); WritableCellFormat format8 = new WritableCellFormat(font8); format8.setBorder(Border.NONE, BorderLineStyle.THIN); format8.setAlignment(jxl.format.Alignment.CENTRE); // 把水平对齐方式指定为居中 format8.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE); // 把垂直对齐方式指定为居中 // 第九种字体样式 WritableFont font9 = new WritableFont(WritableFont.createFont("黑体"), 10, WritableFont.BOLD); WritableCellFormat format9 = new WritableCellFormat(font9); format9.setBorder(Border.ALL, BorderLineStyle.THIN); format9.setAlignment(jxl.format.Alignment.CENTRE); // 把水平对齐方式指定为居中 format9.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE); // 把垂直对齐方式指定为居中 // 第十种字体样式 WritableFont font10 = new WritableFont(WritableFont.createFont("黑体"), 8); WritableCellFormat format10 = new WritableCellFormat(font10); format10.setWrap(true);// 自动换行 format10.setBorder(Border.ALL, BorderLineStyle.THIN); format10.setAlignment(jxl.format.Alignment.CENTRE); // 把水平对齐方式指定为居中 format10.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE); // 把垂直对齐方式指定为居中 // 用户编号前面+“0” String cid = String.format("%04d", waterBill.getCid()); WritableWorkbook workbook = null; // 判断文件夹是否存在 String fullFilePath = waterExcelRootPath + System.getProperty("file.separator") + waterBill.getYear() + String.format("%02d", waterBill.getMonth()); File filePath = new File(fullFilePath); if (!filePath.exists() && !filePath.isDirectory()) { System.out.println("文件夹不存在"); filePath.mkdir(); } File file = null; // 判断用户是要单月开票还是连月(1-2月)开票 fileName = cid + "-" + waterBill.getCname() + "的" + waterBill.getYear() + "年" + (waterBill.getMonth() == 13 ? "1-2" : waterBill.getMonth()) + "月收据.xls"; file = new File(fullFilePath + System.getProperty("file.separator") + fileName); // 若文件不存在 if (!file.exists()) { file.getParentFile().mkdirs(); try { // 创建文件 System.out.println("文件不存在"); file.createNewFile(); } catch (Exception e) { e.printStackTrace(); } } workbook = Workbook.createWorkbook(file); // 把用户的名字作为工作表的第一页,参数0表示第一页 WritableSheet sheet = workbook.createSheet("这里是第一页", 0); // 合并第一行 sheet.mergeCells(0, 0, 12, 0); Label a = new Label(0, 0, "谷城县水利局紫金农水站水费收据", format1); sheet.addCell(a); // 合并第二行 sheet.mergeCells(0, 1, 12, 1); Label b = null; b = new Label(0, 1, waterBill.getYear() + "年" + (waterBill.getMonth() == 13 ? "1-2" : waterBill.getMonth()) + "月", format2); sheet.addCell(b); Label c = new Label(0, 2, "用户", format3); sheet.addCell(c); // 合并BC列 sheet.mergeCells(1, 2, 2, 2); Label d = new Label(1, 2, waterBill.getCname(), format9); sheet.addCell(d); Label e = new Label(3, 2, "住址", format3); sheet.addCell(e); // 合并E-L列 sheet.mergeCells(4, 2, 11, 2); Label f = new Label(4, 2, StringUtils.isEmpty(waterBill.getAddress()) ? "紫金" : waterBill.getAddress(), format3); sheet.addCell(f); Label g = new Label(12, 2, "备注", format4); sheet.addCell(g); // 合并A4 A5 sheet.mergeCells(0, 3, 0, 4); Label h = new Label(0, 3, "项目及类别", format3); sheet.addCell(h); // 合并B4 C4 sheet.mergeCells(1, 3, 2, 3); Label i = new Label(1, 3, "水表动态", format3); sheet.addCell(i); Label j = new Label(1, 4, "起码", format3); sheet.addCell(j); Label k = new Label(2, 4, "止码", format3); sheet.addCell(k); // 合并D4 D5 sheet.mergeCells(3, 3, 3, 4); Label l = new Label(3, 3, "用水量(立方米)", format5); sheet.addCell(l); // 合并E4 E5 sheet.mergeCells(4, 3, 4, 4); Label m = new Label(4, 3, "单价", format6); sheet.addCell(m); // 合并F4-L4 sheet.mergeCells(5, 3, 11, 3); Label n = new Label(5, 3, "金额", format3); sheet.addCell(n); Label n1 = new Label(5, 4, "万", format3); sheet.addCell(n1); Label n2 = new Label(6, 4, "千", format3); sheet.addCell(n2); Label n3 = new Label(7, 4, "百", format3); sheet.addCell(n3); Label n4 = new Label(8, 4, "十", format3); sheet.addCell(n4); Label n5 = new Label(9, 4, "元", format3); sheet.addCell(n5); Label n6 = new Label(10, 4, "角", format3); sheet.addCell(n6); Label n7 = new Label(11, 4, "分", format3); sheet.addCell(n7); Label o = new Label(0, 5, "计量水费", format6); sheet.addCell(o); Label p = new Label(1, 5, waterBill.getFirstNumber().toString(), format9); // 起码 sheet.addCell(p); Label q = new Label(2, 5, waterBill.getLastNumber().toString(), format9); // 止码 sheet.addCell(q); Label r = new Label(3, 5, waterBill.getWaterCount().toString(), format9); // 用水量 sheet.addCell(r); Label s = new Label(4, 5, waterBill.getPrice().toString(), format6); // 单价 sheet.addCell(s); Label t = new Label(5, 5, waterBill.getCharMeterageCost()[0] + "", format9); // 万 sheet.addCell(t); Label t1 = new Label(6, 5, waterBill.getCharMeterageCost()[1] + "", format9); // 千 sheet.addCell(t1); Label t2 = new Label(7, 5, waterBill.getCharMeterageCost()[2] + "", format9); // 百 sheet.addCell(t2); Label t3 = new Label(8, 5, waterBill.getCharMeterageCost()[3] + "", format9); // 十 sheet.addCell(t3); Label t4 = new Label(9, 5, waterBill.getCharMeterageCost()[4] + "", format9); // 元 sheet.addCell(t4); Label t5 = new Label(10, 5, waterBill.getCharMeterageCost()[6] + "", format9); // 角 sheet.addCell(t5); Label t6 = new Label(11, 5, waterBill.getCharMeterageCost()[7] + "", format9); // 分 sheet.addCell(t6); Label t7 = new Label(0, 6, "容量水费", format6); sheet.addCell(t7); Label t8 = new Label(1, 6, "", format9); // 空格 sheet.addCell(t8); Label t9 = new Label(2, 6, "", format9); sheet.addCell(t9); Label t0 = new Label(3, 6, "", format9); sheet.addCell(t0); Label t11 = new Label(4, 6, "", format9); sheet.addCell(t11); Label t12 = new Label(5, 6, waterBill.getCharCapacityCost()[0] + "", format9); sheet.addCell(t12); Label t13 = new Label(6, 6, waterBill.getCharCapacityCost()[1] + "", format9); sheet.addCell(t13); Label t14 = new Label(7, 6, waterBill.getCharCapacityCost()[2] + "", format9); sheet.addCell(t14); Label t15 = new Label(8, 6, waterBill.getCharCapacityCost()[3] + "", format9); // 拾 sheet.addCell(t15); Label t16 = new Label(9, 6, waterBill.getCharCapacityCost()[4] + "", format9); // 元 sheet.addCell(t16); Label t17 = new Label(10, 6, waterBill.getCharCapacityCost()[6] + "", format9); // 角 sheet.addCell(t17); Label t18 = new Label(11, 6, waterBill.getCharCapacityCost()[7] + "", format9); // 分 sheet.addCell(t18); Label v = new Label(0, 7, "合计大写", format6); sheet.addCell(v); // 合并B8-E8 sheet.mergeCells(1, 7, 4, 7); Label v1 = new Label(1, 7, waterBill.getCapitalization(), format9); sheet.addCell(v1); Label v2 = new Label(5, 7, waterBill.getCharWaterCost()[0] + "", format9); // 万 sheet.addCell(v2); Label v3 = new Label(6, 7, waterBill.getCharWaterCost()[1] + "", format9); // 千 sheet.addCell(v3); Label v4 = new Label(7, 7, waterBill.getCharWaterCost()[2] + "", format9); // 百 sheet.addCell(v4); Label v5 = new Label(8, 7, waterBill.getCharWaterCost()[3] + "", format9); // 十 sheet.addCell(v5); Label v6 = new Label(9, 7, waterBill.getCharWaterCost()[4] + "", format9); // 元 sheet.addCell(v6); Label v7 = new Label(10, 7, waterBill.getCharWaterCost()[6] + "", format9); // 角 sheet.addCell(v7); Label v8 = new Label(11, 7, waterBill.getCharWaterCost()[7] + "", format9); // 分 sheet.addCell(v8); // 合并备注单元格 sheet.mergeCells(12, 3, 12, 7); Label w = new Label(12, 3, "", format6); sheet.addCell(w); Label x = new Label(0, 8, "合计:", format7); sheet.addCell(x); Label y = new Label(2, 8, "复核:", format7); sheet.addCell(y); Label z = new Label(4, 8, "收款:", format7); sheet.addCell(z); // 合并K8L8 sheet.mergeCells(10, 8, 11, 8); Label z1 = new Label(10, 8, "开票:", format7); sheet.addCell(z1); Label num = new Label(12, 8, cid, format8); sheet.addCell(num); // 将第一行的高度设为200 sheet.setRowView(0, 435); sheet.setRowView(1, 435); // 第二行高度 sheet.setRowView(2, 435); // 第三行高度 sheet.setRowView(3, 435); sheet.setRowView(4, 435); sheet.setRowView(5, 435); sheet.setRowView(6, 435); sheet.setRowView(7, 435); sheet.setRowView(8, 435); // 将第一列的宽度设为30 sheet.setColumnView(0, 7); // A列 sheet.setColumnView(1, 5); // B列 sheet.setColumnView(2, 5); // C列 sheet.setColumnView(3, 5); // D列 sheet.setColumnView(4, 4); // E列 sheet.setColumnView(5, 3); sheet.setColumnView(6, 3); sheet.setColumnView(7, 3); sheet.setColumnView(8, 3); sheet.setColumnView(9, 3); sheet.setColumnView(10, 3); sheet.setColumnView(11, 3); // L列 sheet.setColumnView(12, 4); // M列 SheetSettings sheetSettings = sheet.getSettings(); // 获取原sheet的属性 sheetSettings.setLeftMargin(0.4); // 设置左边距 sheetSettings.setTopMargin(0.4); // 设置上边距 workbook.write(); workbook.close(); } catch (Exception e) { } return fileName; } public static void fileDownload( String waterExcelRootPath, String yearMonth, String excelFileName) throws Exception { HttpServletResponse response = HttpUtil.getResponse(); response.setCharacterEncoding("UTF-8"); // 第一步:设置响应类型 response.setContentType("application/force-download");// 应用程序强制下载 // 第二读取文件 InputStream in = new FileInputStream(waterExcelRootPath + yearMonth + System.getProperty("file.separator") + excelFileName); // 设置响应头,对文件进行url编码 excelFileName = URLEncoder.encode(excelFileName, "UTF-8"); response.setHeader("Content-Disposition", "attachment;filename=" + excelFileName); response.setContentLength(in.available()); // 第三步:老套路,开始copy OutputStream out = response.getOutputStream(); byte[] b = new byte[1024]; int len = 0; while ((len = in.read(b)) != -1) { out.write(b, 0, len); } out.flush(); out.close(); in.close(); } }/** * ********************************************************************** * *

DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER * *

Copyright 2008, 2010 Oracle and/or its affiliates. All rights reserved. * *

Use is subject to license terms. * *

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. You can also obtain a copy of the License at * http://odftoolkit.org/docs/license.txt * *

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.odftoolkit.odfxsltrunner; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Vector; /** * This application applies an XSLT style sheet to an ODF file. To run this application from the * command line without Ant, try: java -jar "[path/]odfxsltrunner.jar". */ public class Main { private static final String VERSION = "1.1.0"; /** Creates a new instance of Main */ public Main() {} /** @param aArgs the command line arguments */ public static void main(String[] aArgs) { String aStyleSheetName = null; String aInputName = null; String aOutputName = null; String aPath = "content.xml"; String aLogFileName = null; String aTransformerFactoryClass = null; int aInputMode = ODFXSLTRunner.INPUT_MODE_PACKAGE; int aOutputMode = ODFXSLTRunner.OUTPUT_MODE_COPY_INPUT_PACKAGE; Vector aParams = null; Vector aExtractFileNames = null; int nLogLevel = CommandLineLogger.ERROR; boolean bCommandLineValid = true; List aArgList = Arrays.asList(aArgs); Iterator aArgIter = aArgList.iterator(); while (aArgIter.hasNext() && bCommandLineValid) { String aArg = aArgIter.next(); if (aArg.equals("-f")) { if (aArgIter.hasNext()) aTransformerFactoryClass = aArgIter.next(); else bCommandLineValid = false; } else if (aArg.equals("-i")) { aInputMode = ODFXSLTRunner.INPUT_MODE_FILE; } else if (aArg.equals("-l")) { if (aArgIter.hasNext()) aLogFileName = aArgIter.next(); else bCommandLineValid = false; } else if (aArg.equals("-o")) { if (aOutputMode == ODFXSLTRunner.OUTPUT_MODE_COPY_INPUT_PACKAGE) aOutputMode = ODFXSLTRunner.OUTPUT_MODE_FILE; else bCommandLineValid = false; } else if (aArg.equals("-p")) { if (aArgIter.hasNext()) aPath = aArgIter.next(); else bCommandLineValid = false; } else if (aArg.equals("-r")) { if (aOutputMode == ODFXSLTRunner.OUTPUT_MODE_COPY_INPUT_PACKAGE) aOutputMode = ODFXSLTRunner.OUTPUT_MODE_REPLACE_INPUT_PACKAGE; else bCommandLineValid = false; } else if (aArg.equals("-t")) { if (aOutputMode == ODFXSLTRunner.OUTPUT_MODE_COPY_INPUT_PACKAGE) aOutputMode = ODFXSLTRunner.OUTPUT_MODE_TEMPLATE_PACKAGE; else bCommandLineValid = false; } else if (aArg.equals("-v")) { nLogLevel = CommandLineLogger.INFO; } else if (aArg.equals("-x")) { if (aArgIter.hasNext()) { if (aExtractFileNames == null) aExtractFileNames = new Vector(); aExtractFileNames.add(aArgIter.next()); } else bCommandLineValid = false; } else if (aArg.startsWith("-")) { System.out.print(aArg); System.out.println(": unknown option, use '-' for help"); bCommandLineValid = false; break; } else if (aStyleSheetName == null) { aStyleSheetName = aArg; } else if (aInputName == null) { aInputName = aArg; } else if (aOutputMode != ODFXSLTRunner.OUTPUT_MODE_REPLACE_INPUT_PACKAGE && aOutputName == null) { aOutputName = aArg; } else if (aArg.indexOf('=') != -1) { if (aParams == null) aParams = new Vector(); aParams.add(new XSLTCommandLineParameter(aArg)); } else { bCommandLineValid = false; break; } } if (aOutputMode == ODFXSLTRunner.OUTPUT_MODE_COPY_INPUT_PACKAGE && aOutputName == null) aOutputMode = ODFXSLTRunner.OUTPUT_MODE_STDOUT; // check usage bCommandLineValid = aInputName != null && aStyleSheetName != null; bCommandLineValid = bCommandLineValid && !(aOutputMode == ODFXSLTRunner.OUTPUT_MODE_REPLACE_INPUT_PACKAGE || aOutputMode == ODFXSLTRunner.OUTPUT_MODE_STDOUT) == (aOutputName != null); // print help if (!bCommandLineValid) { printUsage(); return; } PrintStream aLogStream = null; if (aLogFileName != null) { try { aLogStream = new PrintStream(aLogFileName); } catch (FileNotFoundException e) { System.err.println(e.getMessage()); } } boolean bError = false; try { ODFXSLTRunner aRunner = new ODFXSLTRunner(); Logger aLogger = new CommandLineLogger(aLogStream != null ? aLogStream : System.err, nLogLevel); bError = aRunner.runXSLT( aStyleSheetName, aParams, aInputName, aInputMode, aOutputName, aOutputMode, aPath, aTransformerFactoryClass, aExtractFileNames, aLogger); } catch (Exception e) { System.err.println(e.getMessage()); } // if( bError ) // System.err.println("transformation failed"); if (aLogStream != null) aLogStream.close(); } private static void printUsage() { System.out.print("odfxsltrunner v"); System.out.println(VERSION); System.out.println(); System.out.println( "usage: odfxsltrunner