text
stringlengths
10
2.72M
/** * Includes core classes for common tasks that can be used over all other packages. */ package edu.kit.pse.osip.core;
package com.tencent.mm.plugin.emoji.a.a; import com.tencent.mm.plugin.emoji.h.a; import com.tencent.mm.plugin.emoji.model.f; import com.tencent.mm.plugin.emoji.model.i; import com.tencent.mm.protocal.c.ts; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.ao; import com.tencent.mm.storage.emotion.EmojiGroupInfo; import java.util.ArrayList; import java.util.List; public final class d extends c { private final String TAG = "MicroMsg.emoji.EmojiListMineData"; public d(f fVar) { super(fVar); } public final synchronized void notifyDataSetChanged() { List<EmojiGroupInfo> cnt = i.aEA().igy.cnt(); boolean aFS = a.aFS(); this.mItemList = new ArrayList(); x.v("MicroMsg.emoji.EmojiListMineData", "============= refresh Data By DB"); for (EmojiGroupInfo cnc : cnt) { ts cnc2 = cnc.cnc(); f fVar = new f(cnc2); if (a.d(cnc2) && aFS) { this.iev.put(cnc2.rem, new ao(cnc2.rem)); } fVar.setStatus(9); this.mItemList.add(fVar); } } public final void clear() { super.clear(); } public final void aDF() { } }
package com.espendwise.manta.history; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Set; import org.springframework.beans.BeanUtils; import com.espendwise.manta.auth.Auth; import com.espendwise.manta.auth.AuthUser; import com.espendwise.manta.i18n.I18nUtil; import com.espendwise.manta.model.data.HistoryData; import com.espendwise.manta.model.data.HistoryObjectData; import com.espendwise.manta.model.data.HistorySecurityData; import com.espendwise.manta.util.Escaper; import com.espendwise.manta.util.RefCodeNames; import com.espendwise.manta.util.Utility; /** * This is the abstract base class for all classes that describe the details of a * history record. * * <p>Derived classes must: * <ul> * <li>Define {@link #getHistoryTypeCode() getHistoryTypeCode} to define the type code * for the history record they represent.</li> * <li>Define {@link #getShortDescription() getShortDescription} to define the * short description of the history record they represent.</li> * <li>Define {@link #getLongDescription() getLongDescription} to define the * long description of the history record they represent.</li> * <li>Define {@link #getInvolvedObjects() getInvolvedObjects} to define the * set of objects directly involved in the transaction this history object represents.</li> * <li>Override {@link #describeIntoHistoryData(Object...objects) * describeIntoHistoryData} to define how to represent the history record * in the database.</li> * </ul> * * <p>This class also provides some utility methods and constants that are * useful in manipulating history details. */ public abstract class HistoryRecord extends HistoryData implements java.io.Serializable { protected static String clobValueSeparator = ";;"; /** * Application context needed to generate the links in the long description */ private String _historyLinkBase; /** * The value returned by {@link #getHistoryTypeCode() getHistoryTypeCode} for a * create shopping control transaction. */ public static final String TYPE_CODE_CREATE_SHOPPING_CONTROL = "CreateShoppingControl"; /** * The value returned by {@link #getHistoryTypeCode() getHistoryTypeCode} for a * modify shopping control transaction. */ public static final String TYPE_CODE_MODIFY_SHOPPING_CONTROL = "ModifyShoppingControl"; /** * The value returned by {@link #getHistoryTypeCode() getHistoryTypeCode} for a * create user transaction. */ public static final String TYPE_CODE_CREATE_USER = "CreateUser"; /** * The value returned by {@link #getHistoryTypeCode() getHistoryTypeCode} for a * modify user transaction. */ public static final String TYPE_CODE_MODIFY_USER = "ModifyUser"; /** * The value returned by {@link #getHistoryTypeCode() getHistoryTypeCode} for a * update user groups transaction. */ public static final String TYPE_CODE_UPDATE_USER_GROUPS= "UpdateUserGroups"; /** * The value returned by {@link #getHistoryTypeCode() getHistoryTypeCode} for a * create punchout order message transaction. NOTE - this transaction is created in the * St.John application, not Manta. However, we display the history records for such * transactions here */ public static final String TYPE_CODE_CREATE_PUNCHOUT_ORDER_MESSAGE = "CreatePunchoutOrderMessage"; /** * The value returned by {@link #getHistoryTypeCode() getHistoryTypeCode} for a * create generic report transaction. */ public static final String TYPE_CODE_CREATE_GENERIC_REPORT = "CreateGenericReport"; /** * The value returned by {@link #getHistoryTypeCode() getHistoryTypeCode} for a * modify generic report transaction. NOTE - this transaction is created in the * St.John application, not Manta. However, we display the history records for such * transactions here */ public static final String TYPE_CODE_MODIFY_GENERIC_REPORT = "ModifyGenericReport"; //********* NOTE TO DEVELOPERS *************************************** // When you add new TYPE_CODE_* constants above, also add corresponding // entries to the _historyRecordMetaData HashMap in the static // initialization block below as well as to the HistoryController.populateFormReferenceData // method //******************************************************************** /** * A map of history type codes (TYPE_CODE_*) to meta-data information relating * that history record type. * The entries in the map are HistoryRecordMetaData objects (an inner class of * HistoryRecord). */ private static final transient Map<String, HistoryRecordMetaData> _historyRecordMetaData; //Static class initialization: static { _historyRecordMetaData = new HashMap<String, HistoryRecordMetaData>(); _historyRecordMetaData.put( TYPE_CODE_CREATE_SHOPPING_CONTROL, new HistoryRecordMetaData(CreateShoppingControlHistoryRecord.class)); _historyRecordMetaData.put( TYPE_CODE_MODIFY_SHOPPING_CONTROL, new HistoryRecordMetaData(ModifyShoppingControlHistoryRecord.class)); _historyRecordMetaData.put( TYPE_CODE_CREATE_USER, new HistoryRecordMetaData(CreateUserHistoryRecord.class)); _historyRecordMetaData.put( TYPE_CODE_MODIFY_USER, new HistoryRecordMetaData(ModifyUserHistoryRecord.class)); _historyRecordMetaData.put( TYPE_CODE_UPDATE_USER_GROUPS, new HistoryRecordMetaData(UpdateUserGroupsHistoryRecord.class)); _historyRecordMetaData.put( TYPE_CODE_CREATE_PUNCHOUT_ORDER_MESSAGE, new HistoryRecordMetaData(CreatePunchoutOrderMessageHistoryRecord.class)); _historyRecordMetaData.put( TYPE_CODE_CREATE_GENERIC_REPORT, new HistoryRecordMetaData(CreateGenericReportHistoryRecord.class)); _historyRecordMetaData.put( TYPE_CODE_MODIFY_GENERIC_REPORT, new HistoryRecordMetaData(ModifyGenericReportHistoryRecord.class)); } public HistoryRecord() { super(); } public String getHistoryLinkBase() { return _historyLinkBase; } public void setHistoryLinkBase(String historyLinkBase) { _historyLinkBase = historyLinkBase; } /** * Return the history type code for the history record that this * class represents. Derived classes must override this method. * @return the history type code. */ public abstract String getHistoryTypeCode(); /** * Return the short description of the history record that this * class represents. Derived classes must override this method. * @return the history type key. */ public abstract String getShortDescription(); /** * Return the long description of history record that this * class represents. Derived classes must override this method. * @return the history description key. */ public abstract String getLongDescription(); /** * Return the long description of history record that this * class represents as HTML. Derived classes must override this method. * @return the history description key. */ public abstract String getLongDescriptionAsHtml(); /** * Return a set of <code>HistoryObjectData</code> instances describing the objects * involved in the history record that this instance represents. * Derived classes must override this method. * @return the set of involved objects. */ public abstract Set<HistoryObjectData> getInvolvedObjects(Object... objects); /** * Return a set of <code>HistorySecurityData</code> instances describing the business entities * that should have access to this history record. * Derived classes must override this method. * @return the set of security objects. */ public abstract Set<HistorySecurityData> getSecurityObjects(Object... objects); /** * Create a history data from information related to some specific * business activity. * @param objects objects containing the information necessary to populate the * history record. * @return a HistoryData object. */ public HistoryData describeIntoHistoryData(Object... objects) { HistoryData historyData = new HistoryData(); describeIntoHistoryData(historyData, objects); return historyData; } /** * Populate a history data from information related to some specific * business activity. Derived classes should call the corresponding method * on their superclass, to make sure information populated there is populated * for those methods as well * @param objects objects containing the information necessary to populate the * history record. * @return a HistoryData object. */ public void describeIntoHistoryData(HistoryData historyData, Object... objects) { AuthUser authUser = Auth.getAuthUser(); Date date = new Date(); historyData.setHistoryTypeCd(getHistoryTypeCode()); historyData.setUserId(authUser.getUsername()); historyData.setActivityDate(date); } /** * Populate the fields of this object with information contained in a * history data object. Derived classes should call the corresponding method * on their superclass, to make sure information populated there is populated * for those methods as well * A runtime exception is thrown if the transaction type represented by * the history record doesn't match the transaction type represented by this object. * * @param history the history data object that will be used as the * information source. A runtime exception is thrown if this is null. */ public final void populateFromHistoryData(HistoryData history) { if (history == null) { throw new IllegalArgumentException("HistoryRecorder.populateFromHistoryData: history data must not be null."); } if (!getHistoryTypeCode().equals(history.getHistoryTypeCd())) { throw new IllegalArgumentException( "HistoryRecorder.populateFromHistoryData: expected a history record of type " + getHistoryTypeCode() + " but got a record of type " + history.getHistoryTypeCd() + "."); } //populate this object from the HistoryData passed in BeanUtils.copyProperties(history, this); } /** * Return the meta-data information corresponding to the * specified history record type code. * * @param historyTypeCode the history record type code * @return the history record meta data object. */ private static final HistoryRecordMetaData getHistoryRecordMetaData(String historyTypeCode) { if (!Utility.isSet(historyTypeCode)) { throw new IllegalArgumentException("HistoryRecord.getHistoryRecordMetaData: historyTypeCode must be specified."); } HistoryRecordMetaData metaData = _historyRecordMetaData.get(historyTypeCode); if (metaData == null) { throw new RuntimeException("HistoryRecord.getHistoryRecordMetaData: unexpected type code '" + historyTypeCode + "'."); } return metaData; } /** * Return an instance of the history record subclass that represents * transactions of the specified type. The instance is constructed * using the type's zero-argument constructor. A runtime exception * is thrown if the specified history type code is null, if * there's no class registered to correspond to the specified type code, * or if the registered class isn't a subclass of HistoryRecord. * * @param historyTypeCode the history type code * @return the HistoryRecord subclass instance. */ public static final HistoryRecord getInstance(String historyTypeCode) { Class clazz = getHistoryRecordMetaData(historyTypeCode).getHistoryRecordSubclass(); if (clazz == null) { throw new RuntimeException("HistoryRecord.getInstance: unexpected type code '" + historyTypeCode + "'."); } HistoryRecord instance = null; try { instance = (HistoryRecord) clazz.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } return instance; } public String getHistoryLink(String id, String objectType) { String returnValue = null; boolean includeLink = Utility.isSet(getHistoryLinkBase()); if (includeLink && (RefCodeNames.HISTORY_OBJECT_TYPE_CD.ITEM.equals(objectType) || RefCodeNames.HISTORY_OBJECT_TYPE_CD.SHOPPING_CONTROL.equals(objectType) || RefCodeNames.HISTORY_OBJECT_TYPE_CD.USER.equals(objectType) || RefCodeNames.HISTORY_OBJECT_TYPE_CD.GROUP.equals(objectType) || RefCodeNames.HISTORY_OBJECT_TYPE_CD.GENERIC_REPORT.equals(objectType))) { StringBuffer buff = new StringBuffer(50); buff.append("<a href='"); buff.append(getHistoryLinkBase()); buff.append("/history/filter?objectId="); buff.append(id); buff.append("&objectType="); buff.append(objectType); buff.append("' target='_self'>"); buff.append(id); buff.append("</a>"); returnValue = buff.toString(); } else { returnValue = id; } return returnValue; } /** * Method to escape any non-html markup in the history record long description * @param value - the history record long description, possibly containing html markup * @return - a string in which all non-html markup has been escaped for rendering on an html page * Note - the only markup currently in use in the long description is anchor tags (<a>, </a>) and break tags (<br>). * If additional markup is used then this method will need to be updated accordingly. */ public String htmlEscape(String value) { String returnValue = null; int beginStartAnchor = value.indexOf("<a "); int beginStartBreak = value.indexOf("<br>"); //if the value contains no html markup, escape all of it if (beginStartAnchor < 0 && beginStartBreak < 0) { returnValue = Escaper.htmlEscape(value); } //otherwise, escape the non-html markup else { boolean isAnchor = (beginStartAnchor >= 0 && (beginStartBreak < 0 || beginStartAnchor < beginStartBreak)); boolean isBreak = (beginStartBreak >= 0 && (beginStartAnchor < 0 || beginStartBreak < beginStartAnchor)); //if an anchor tag is the next markup handle it //escape everything up to the start of the link tag, the link text, and recursively call this method on //everything after the end of the link tag if (isAnchor) { //extract everything up to the start of the anchor tag so that any > in the text doesn't cause an issue String subString = value.substring(0, beginStartAnchor); value = value.substring(beginStartAnchor); int endStartAnchor = value.indexOf(">"); int beginEndAnchor = value.indexOf("</a"); int endEndAnchor = beginEndAnchor + 3; returnValue = Escaper.htmlEscape(subString) + value.substring(0, endStartAnchor + 1) + Escaper.htmlEscape(value.substring(endStartAnchor + 1, beginEndAnchor)) + value.substring(beginEndAnchor, endEndAnchor + 1) + htmlEscape(value.substring(endEndAnchor + 1)); } //if a break tag is the next markup handle it //escape everything up to the start of the break tag, and recursively call this method on //everything after the end of the break tag if (isBreak) { //extract everything up to the start of the break tag so that any > in the text doesn't cause an issue String subString = value.substring(0, beginStartBreak); value = value.substring(beginStartBreak); int endStartBreak = value.indexOf(">"); returnValue = Escaper.htmlEscape(subString) + value.substring(0, endStartBreak + 1) + htmlEscape(value.substring(endStartBreak + 1)); } } return returnValue; } /** * Represent a variety of meta-data information about a history record. The * information this represents for each history record type is: * <ul> * <li>historyRecordSubclass: The subclass of HistoryRecord that represents details for that * type of history record.</li> * </ul> */ private static class HistoryRecordMetaData { private Class historyRecordSubclass; HistoryRecordMetaData(Class historyRecordSubclass) { super(); if (historyRecordSubclass == null) { throw new IllegalArgumentException("HistoryRecordMetaData: The history record subclass must not be null."); } this.historyRecordSubclass = historyRecordSubclass; } public Class getHistoryRecordSubclass() { return historyRecordSubclass; } } protected String getLabelAndValue(String attribute, boolean includeComma, Locale locale, String labelKey){ String returnValue = ""; if (Utility.isSet(attribute)) { if (includeComma) { returnValue += ", "; } includeComma = true; returnValue += I18nUtil.getMessage(locale, labelKey); returnValue += ": "; returnValue+= attribute; } return returnValue; } }
package Lock; import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; class MyCache{ // 可见性保证:volatile private volatile Map<String, Object> map= new HashMap<>(); //private Lock lock = new ReentrantLock(); private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock(); public void put(String key , String value){ rwLock.writeLock().lock(); try{ System.out.println(Thread.currentThread().getName()+"\t 正在写入:" + key); map.put(key,value); try{ Thread.sleep(1000); }catch (Exception e){ e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"\t 写入完成"); }catch (Exception e){ e.printStackTrace(); }finally { rwLock.writeLock().unlock(); } } public void get(String key){ rwLock.readLock().lock(); try{ System.out.println(Thread.currentThread().getName()+"\t 正在读取:" + key); Object result = map.get(key); try{ Thread.sleep(1000); }catch (Exception e){ e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"\t 读取完成"); }catch (Exception e){ e.printStackTrace(); }finally { rwLock.readLock().unlock(); } } } public class ReadWriteLockDemo { /* 多个线程同时读一个资源类没有问题,但是为了满足并发性,我们对读取有了更高的要求。 (1)读-读可以共存 (2)写-写不可以共存 (3)写-读也是不可以的(就是有些线程去写,那就不能共存) 所谓的共存,就和前面说的加锁是一个意思。其实整个多线程很多关键词, synchronized, lock(ReentrantLock)他们实现的都是一个概念, 这段代码如果要执行,那么只能由一个线程去执行,他执行完了,其他线程才能上,不然都给我等着 这个其实就是所说的原子性!!! 所以为什么volatile没有原子性,之前的代码验证,20个线程,每个线程做累加。最后小于2w, 这显然是因为number++ 这个是线程不安全的,number++其实底层字节码可以分成三个指令,getfield,iadd,putfield 线程1得到原来为1,然后自己加1,准备把1写回内存的时候,被打断了,然后线程二同样加1,然后线程1又执行写会主内存, 现在主内存number是1,还没来得及通知线程二现在的值是1了,线程二又写回,所以number还是1。 所以AtomicInteger就避免了number++出现的问题,你要加,就得给我把这个加的命令都执行完,其他线程才能再使用。 */ public static void main(String[] args) { MyCache myCache = new MyCache(); // 10个线程来写 for(int i=0; i<10;i++){ int temp = i; new Thread(() -> { myCache.put(temp+"",temp+""); },String.valueOf(i)).start(); } // 10个线程来读 for(int i=0; i<10;i++){ int temp = i; new Thread(() -> { myCache.get(temp+""); },String.valueOf(i)).start(); } } }
/* * 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 tsp; import java.io.File; import java.util.ArrayList; /** * Esta clase guarda toda la información obtenida del archivo .tsp * @author JavierAros */ public class FileTSP { private String name; private String type; private String comment; private String dimension; private String edgeWeightType; private String edgeWeightFormat; private String displayDataType; private int[][] edgEweighTsection; private ArrayList<Nodo> displayDataSelection; /** * Constructor para guardar la informacion * @param archivo El parámetro archivo es el fichero .tsp */ public FileTSP(File archivo){ //sugerencia StringTokenizer } }
package org.rebioma.client.services; public enum StatisticType { TYPE_DATA_MANAGER(1, "data_manager"), TYPE_DATA_PROVIDER_INSTITUTION(2, "institution"), TYPE_COLLECTION_CODE(3, "collection_code"), TYPE_YEAR_COLLECTED( 4, "year_collected"); private int i; private String s; /** * * @param i * - integer representation of the statistic type * @param s * - string representation of the statistic type */ StatisticType(int i, String s) { this.i = i; this.s = s; } public int asInt() { return i; } public String asString() { return s; } public static StatisticType asEnum(int i){ for(StatisticType s: values()){ if(s.i == i){ return s; } } return null; } public static StatisticType asEnum(String s){ for(StatisticType stat: values()){ if(stat.s.equalsIgnoreCase(s)){ return stat; } } return null; } }
package in.ac.iiitd.kunal.expresso; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import java.util.List; public class Show extends AppCompatActivity { TextView Data; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_show); Data=(TextView)findViewById(R.id.display); DatabaseHandler db = new DatabaseHandler(this); List<Information> contacts = db.getAllInfo(); String data=""; for (Information cn : contacts) { data = data + "Id: " + cn.getId() + " ,Name: " + cn.getName() + " ,Phone: " + cn.getPhone_number() + " ,College Name: " + cn.getCollege_name() + " ,College Id: " + cn.getCollege_id() + " ,DOB: " + cn.getDob() + "\n"; } Data.setText(data); } }
package org.inftel.anmap.async; import java.io.IOException; import java.net.ConnectException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.channels.ClosedSelectorException; import java.nio.channels.DatagramChannel; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.nio.charset.Charset; import java.util.Iterator; import android.app.Activity; import android.os.AsyncTask; import android.util.Log; public class AsyncPortScan extends AsyncTask<Void, Object, Void> { private final String TAG = "AsyncPortscan"; private static final int TIMEOUT_SELECT = 300; private static long TIMEOUT_CONNECT = 1000 * 1000000; // ns private static final long TIMEOUT_RW = 3 * 1000 * 1000000; // ns private static final String E_REFUSED = "Connection refused"; private static final String E_TIMEOUT = "The operation timed out"; private static final String[] PROBES = new String[] { "", "\r\n\r\n", "GET / HTTP/1.0\r\n\r\n" }; private static final int MAX_READ = 8 * 1024; private static final int WRITE_PASS = PROBES.length; private static final long WRITE_COOLDOWN = 200 * 1000000; // ns private int rate; private boolean select = true; private Selector selector; protected String ipAddr = null; protected int port_start = 0; protected int port_end = 1000; protected int nb_port = 0; // private boolean getBanner = false; private ByteBuffer byteBuffer = ByteBuffer.allocate(MAX_READ); private Charset charset = Charset.forName("UTF-8"); public final static int OPEN = 0; public final static int CLOSED = 1; public final static int FILTERED = -1; public final static int UNREACHABLE = -2; public final static int TIMEOUT = -3; protected AsyncPortScan(Activity activity, String host, int _rate) { ipAddr = host; rate = _rate; TIMEOUT_CONNECT = rate * 1000000; // ms to ns } @Override protected Void doInBackground(Void... params) { try { int step = 11; InetAddress ina = InetAddress.getByName(ipAddr); if (nb_port > step) { for (int i = port_start; i <= port_end - step; i += step + 1) { Log.d(getClass().getSimpleName(), "for" + i); if (select) { Log.d(getClass().getSimpleName(), "if " + i); start(ina, i, i + ((i + step <= port_end - step) ? step : port_end - i)); } } } else { start(ina, port_start, port_end); } } catch (UnknownHostException e) { Log.e(TAG, e.getMessage()); publishProgress(0, UNREACHABLE, null); } return null; } private void start(final InetAddress ina, final int PORT_START, final int PORT_END) { Log.d(getClass().getSimpleName(), "PORT_START: " + PORT_START + " PORT_END: " + PORT_END); select = true; try { selector = Selector.open(); for (int j = PORT_START; j <= PORT_END; j++) { connectSocket(ina, j); } while (select && selector.keys().size() > 0) { if (selector.select(TIMEOUT_SELECT) > 0) { // Al menos un // channel tiene que // estar ready synchronized (selector.selectedKeys()) { Iterator<SelectionKey> iterator = selector.selectedKeys().iterator(); while (iterator.hasNext()) { SelectionKey key = (SelectionKey) iterator.next(); try { if (!key.isValid()) { continue; } // States final Data data = (Data) key.attachment();// Data // asociado // al // socket // (Data{puerto,estado...}) if (key.isConnectable()) { if (((SocketChannel) key.channel()).finishConnect()) { finishKey(key, OPEN); } } else if (key.isReadable()) { try { byteBuffer.clear(); final int numRead = ((SocketChannel) key.channel()) .read(byteBuffer); if (numRead > 0) { String banner = new String(byteBuffer.array()) .substring(0, numRead).trim(); finishKey(key, OPEN, banner); } else { key.interestOps(SelectionKey.OP_WRITE); } } catch (IOException e) { Log.e(TAG, e.getMessage()); } } else if (key.isWritable()) { key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); if (System.nanoTime() - data.start > WRITE_COOLDOWN) { if (data.pass < WRITE_PASS) { final ByteBuffer bytedata = charset .encode(PROBES[data.pass]); final SocketChannel sock = (SocketChannel) key .channel(); while (bytedata.hasRemaining()) { sock.write(bytedata); } bytedata.clear(); data.start = System.nanoTime(); data.pass++; } else { finishKey(key, OPEN); } } } } catch (ConnectException e) { if (e.getMessage().equals(E_REFUSED)) { finishKey(key, CLOSED); } else if (e.getMessage().equals(E_TIMEOUT)) { finishKey(key, FILTERED); } else { Log.e(TAG, e.getMessage()); e.printStackTrace(); finishKey(key, FILTERED); } } catch (Exception e) { try { Log.e(TAG, e.getMessage()); } catch (java.lang.NullPointerException e1) { e1.printStackTrace(); } finally { e.printStackTrace(); finishKey(key, FILTERED); } } finally { iterator.remove(); } } } } else { final long now = System.nanoTime(); final Iterator<SelectionKey> iterator = selector.keys().iterator(); while (iterator.hasNext()) { final SelectionKey key = (SelectionKey) iterator.next(); final Data data = (Data) key.attachment(); if (data.state == OPEN && now - data.start > TIMEOUT_RW) { Log.e(TAG, "TIMEOUT=" + data.port); finishKey(key, TIMEOUT); } else if (data.state != OPEN && now - data.start > TIMEOUT_CONNECT) { finishKey(key, TIMEOUT); } } } } } catch (IOException e) { Log.e(TAG, e.getMessage()); } finally { closeSelector(); } } private void connectSocket(InetAddress ina, int port) { try { SocketChannel socket = SocketChannel.open(); socket.configureBlocking(false); socket.connect(new InetSocketAddress(ina, port)); Data data = new Data(); data.port = port; data.start = System.nanoTime(); socket.register(selector, SelectionKey.OP_CONNECT, data); } catch (IOException e) { Log.e(TAG, e.getMessage()); } } @Override protected void onCancelled() { select = false; } private void closeSelector() { try { if (selector.isOpen()) { synchronized (selector.keys()) { Iterator<SelectionKey> iterator = selector.keys().iterator(); while (iterator.hasNext()) { finishKey((SelectionKey) iterator.next(), FILTERED); } selector.close(); } } } catch (IOException e) { Log.e(TAG, e.getMessage()); } catch (ClosedSelectorException e) { if (e.getMessage() != null) { Log.e(TAG, e.getMessage()); } } } private void finishKey(SelectionKey key, int state) { finishKey(key, state, null); } private void finishKey(SelectionKey key, int state, String banner) { synchronized (key) { if (key == null || !key.isValid()) { return; } closeChannel(key.channel()); Data data = (Data) key.attachment(); publishProgress(data.port, state, banner); key.attach(null); key.cancel(); key = null; } } private void closeChannel(SelectableChannel channel) { if (channel instanceof SocketChannel) { Socket socket = ((SocketChannel) channel).socket(); try { if (!socket.isInputShutdown()) socket.shutdownInput(); } catch (IOException ex) { } try { if (!socket.isOutputShutdown()) socket.shutdownOutput(); } catch (IOException ex) { } try { socket.close(); } catch (IOException ex) { } } try { channel.close(); } catch (IOException ex) { } } // Port private object private static class Data { protected int state = FILTERED; protected int port; protected long start; protected int pass = 0; } }
package ru.sprikut.sd.refactoring.servlet; import ru.sprikut.sd.refactoring.database.Database; import ru.sprikut.sd.refactoring.product.Product; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author sprikut */ public class AddProductServlet extends HttpServlet { private final Database<Product> database; public AddProductServlet(Database<Product> database) { this.database = database; } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String name = request.getParameter("name"); long price = Long.parseLong(request.getParameter("price")); database.insert(new Product(name, price)); response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println("OK"); } }
package com.bearsonsoftware.list.actions; import android.content.Context; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import com.bearsonsoftware.list.R; import com.bearsonsoftware.list.database.NoteListManager; import com.bearsonsoftware.list.datatypes.NoteList; import com.bearsonsoftware.list.ui.NoteListAdapter; /** * Creates note list entry in database, removes edittext and replaces it with a * row for the created note list */ public class SaveNoteList { public static void save(View view, NoteListAdapter adapter, NoteListManager noteListManager){ //clear focus from item that will no longer exist view.clearFocus(); NoteList noteList; EditText mEdit = (EditText) view.findViewById(R.id.noteListEditText); String name = mEdit.getText().toString(); noteList = noteListManager.createNoteList(name); adapter.add(0, noteList); //remove the edittext row - currently at position 1 NoteList toDelete = adapter.getItem(1); adapter.remove(toDelete); //hide keyboard InputMethodManager imm = (InputMethodManager)view.getContext().getSystemService( Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(mEdit.getWindowToken(), 0); } }
package com.stark.design23.bridge; /** * Created by Stark on 2018/1/17. * 具有展示数据和修改数据功能的产品 */ public class Product { private DataBase dataBase; public Product(DataBase dataBase) { this.dataBase = dataBase; } public String display() { return dataBase.read(); } public void update(String msg) { //先存储写数据 dataBase.write(msg); } }
package com.binary.mindset.tasklistmanagement.service.impl; import com.binary.mindset.tasklistmanagement.crud.entity.TaskEntity; import com.binary.mindset.tasklistmanagement.crud.repository.TaskRepository; import com.binary.mindset.tasklistmanagement.model.Task; import com.binary.mindset.tasklistmanagement.service.TaskService; import ma.glasnost.orika.MapperFacade; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.zalando.problem.Problem; import org.zalando.problem.Status; import java.util.List; import java.util.Optional; @Service public class TaskServiceImpl implements TaskService { private final TaskRepository taskRepository; private final MapperFacade mapperFacade; @Autowired public TaskServiceImpl(final TaskRepository taskRepository, final MapperFacade mapperFacade) { this.taskRepository = taskRepository; this.mapperFacade = mapperFacade; } @Override public List<Task> findAllByProject(Integer projectId) { Iterable<TaskEntity> tasks = taskRepository.findAllByProjectId(projectId); return mapperFacade.mapAsList(tasks, Task.class); } @Override public Task findByTaskIdAndProjectId(Integer taskId, Integer projectId) { Optional<TaskEntity> task = taskRepository.findByIdAndProjectId(taskId, projectId); return task.map(tsk -> mapperFacade.map(tsk, Task.class)) .orElseThrow(() -> Problem.valueOf(Status.NOT_FOUND, "Task not found")); } @Override public void deleteAllByProjectId(Integer projectId) { taskRepository.deleteAllByProjectId(projectId); } @Override public void deleteById(Integer taskId) { taskRepository.deleteById(taskId); } @Override public void deleteByIdAndProjectId(Integer taskId, Integer projectId) { taskRepository.deleteByIdAndProjectId(taskId, projectId); } }
package edu.mum.cs.cs544.exercises.f; import java.util.ArrayList; import java.util.List; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; @Entity public class Department { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String name; @OneToMany(mappedBy = "dept") private List<Employee> employees = new ArrayList<Employee>(); // Default Constructor public Department() { } public Department(String name) { this.name = name; } public void addEmployee(Employee employee) { employee.setDept(this); this.employees.add(employee); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Employee> getEmployees() { return employees; } public void setEmployees(List<Employee> employees) { this.employees = employees; } }
package cz.uhk.restaurace.service; import java.util.List; import cz.uhk.restaurace.model.CustomerOrder; public interface CustomerOrderService { public void addOrder(CustomerOrder customerOrder); public void updateOrder(CustomerOrder customerOrder); /** * Get all customers orders * @param username * @return */ public List<CustomerOrder> getUserOrdersByUsername(String username); public CustomerOrder getOrderById(int id); public void removeOrder(int id); /** * Just create empty cart * @return */ public CustomerOrder createCart(); /** * Get new customer orders of registered users * @return */ public List<CustomerOrder> getUnprocessedRegisteredCustomerOrders(); /** * Get new customer orders of unregistered users * @return */ public List<CustomerOrder> getUnprocessedNotregisteredCustomerOrders(); }
package com.example.pos; import java.util.ArrayList; import java.util.HashMap; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.GridView; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.AdapterView.OnItemClickListener; public class Modifiers extends Activity{ private ArrayList<HashMap<String, String>> sampleArrayList; private SimpleAdapter sampleListAdapter; private ListView listView; private GridView gridView; Button keyboardbtn; static final String[] numbers = new String[] { "More Salt", "Less Salt","No Salt", "More Spicy", "Less Spicy", "More Sugar", "Less Sugar", "No Sugar", "More Sour", "Less Sour", "No Sour", "More Pepper", "Less Pepper", "No Pepper"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.modifier); listView=(ListView)findViewById(R.id.listView1); gridView=(GridView)findViewById(R.id.gridview); keyboardbtn=(Button)findViewById(R.id.keyboardbtn); ArrayAdapter<String> adapter = new ArrayAdapter<>(Modifiers.this, R.layout.griditem, R.id.textView1, numbers); gridView.setAdapter(adapter); gridView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String name = getResources().getResourceEntryName(position); Log.d("nameeeeeeeeeeeeeeeeeeee",name); sampleArrayList=new ArrayList<HashMap<String, String>>(); for (int i=0;i<10;i++) { HashMap<String, String> sampleObjectMap= new HashMap<String, String>(); sampleObjectMap.put("value1", "SI"+i); sampleObjectMap.put("value2", ""+i); sampleObjectMap.put("value3", "price"+i); sampleArrayList.add(sampleObjectMap); } sampleListAdapter= new SimpleAdapter( Modifiers.this, sampleArrayList, R.layout.modifierlistitem, new String[] { "value1", "value2" , "value3"}, new int[] { R.id.textView1, R.id.textView2, R.id.textView3}); listView.setAdapter(sampleListAdapter); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { view.setSelected(true); } }); } }); } }
package com.android.yinwear.ui.app; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Message; import android.preference.PreferenceManager; import android.text.Editable; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.android.volley.Request; import com.android.yinwear.R; import com.android.yinwear.YINApplication; import com.android.yinwear.core.controller.CoreController; import com.android.yinwear.core.network.model.request.NetRequest; import com.android.yinwear.core.network.model.response.BaseResponse; import com.android.yinwear.core.network.model.response.LoginResp; import com.android.yinwear.core.network.model.response.UsersResp; import com.android.yinwear.core.utils.Constants; import com.android.yinwear.core.utils.Utility; public class LoginActivity extends BaseActivity implements View.OnClickListener { private static final String TAG = "SplashActivity"; private String mRestCallbackId; private UsersResp mUserResponse; private String mAuthToken; private String mYINAccountId; private EditText edtUserName; private EditText edtPassword; private Button btnLogin; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.activity_login); edtUserName = findViewById(R.id.edt_account_id); edtPassword = findViewById(R.id.edt_password); btnLogin = findViewById(R.id.btn_login); btnLogin.setOnClickListener(this); } @Override protected void onResume() { super.onResume(); mRestCallbackId = mCoreController.registerCallback(mHandler); } @Override protected void onPause() { super.onPause(); mCoreController.removeCallback(mRestCallbackId); } private void launchUserActivity() { setProgressBarIndeterminateVisibility(false); Intent intentToUsers = new Intent(LoginActivity.this, HomeActivity.class); intentToUsers.putExtra("user_resp", mUserResponse); startActivity(intentToUsers); finish(); } private void processLoginRequest() { setProgressBarIndeterminateVisibility(true); CoreController coreController = ((YINApplication) this.getApplication()).getCoreController(); Bundle reqParam = new Bundle(); Editable userName = edtUserName.getText(); Editable password = edtPassword.getText(); if (TextUtils.isEmpty(userName)) { Toast.makeText(this, "Please Enter Username", Toast.LENGTH_SHORT).show(); return; } if (TextUtils.isEmpty(password)) { Toast.makeText(this, "Please Enter Password", Toast.LENGTH_SHORT).show(); return; } reqParam.putString("username", userName.toString()); reqParam.putString("password", password.toString()); NetRequest loginRequest = new NetRequest(Constants.REQUEST.LOGIN_REQUEST, Request.Method.POST, Constants.URL.LOGIN, reqParam); coreController.addRequest(Constants.NETWORK_REQUEST, loginRequest, false); } private void processUsersRequest() { CoreController coreController = ((YINApplication) this.getApplication()).getCoreController(); Bundle reqParam = new Bundle(); reqParam.putString("authentication_token", mAuthToken); NetRequest userRequest = new NetRequest(Constants.REQUEST.USER_REQUEST, Request.Method.POST, Constants.URL.USERS, reqParam); coreController.addRequest(Constants.NETWORK_REQUEST, userRequest, true); } private void processDevicesRequest() { CoreController coreController = ((YINApplication) this.getApplication()).getCoreController(); Bundle reqParam = new Bundle(); reqParam.putString("authentication_token", mAuthToken); NetRequest deviceRequest = new NetRequest(Constants.REQUEST.DEVICE_REQUEST, Request.Method.POST, Constants.URL.DEVICES, reqParam); coreController.addRequest(Constants.NETWORK_REQUEST, deviceRequest, true); } @Override protected boolean handleMessage1(Message msg) { switch (msg.what) { case Constants.REQUEST.LOGIN_REQUEST: { BaseResponse baseResponse = (BaseResponse) msg.obj; if (baseResponse.getResponseCode() == 200) { LoginResp loginResp = (LoginResp) Utility.getDataObj(baseResponse.getResponse().toString(), LoginResp.class); Log.d(TAG, "LOGIN SUCCESSFUL"); SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor editor = sharedPref.edit(); editor.putString(Constants.PREFERENCE.AUTH_TOKEN, loginResp.getAuthToken()); editor.putBoolean(Constants.PREFERENCE.IS_LOGGED_IN, true); mAuthToken = loginResp.getAuthToken(); editor.apply(); processDevicesRequest(); } else { Toast.makeText(this, baseResponse.getResponse().toString(), Toast.LENGTH_LONG).show(); } } return true; case Constants.REQUEST.DEVICE_REQUEST: { processUsersRequest(); } return true; case Constants.REQUEST.USER_REQUEST: { BaseResponse baseResponse = (BaseResponse) msg.obj; String responseString = baseResponse.getResponse().toString(); if (baseResponse.getResponseCode() == 200) { mUserResponse = (UsersResp) Utility.getDataObj(responseString, UsersResp.class); launchUserActivity(); } else { SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor editor = sharedPref.edit(); editor.remove(Constants.PREFERENCE.AUTH_TOKEN); editor.remove(Constants.PREFERENCE.IS_LOGGED_IN); editor.apply(); processLoginRequest(); Toast.makeText(this, responseString, Toast.LENGTH_LONG).show(); } } return true; } return super.handleMessage1(msg); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_login: processLoginRequest(); break; } } }
package interfaces; import java.sql.Timestamp; import entities.User; public interface Activity { public int getId(); public void setId(int id); public Object getParent(); public void setParent(Object parent); public User getUser(); public void setUser(User user); public String getMessage(); public void setMessage(String message); public Timestamp getPosted(); public void setPosted(Timestamp posted); public Timestamp getLastUpdate(); public void setLastUpdate(Timestamp lastUpdate); public User getLastUpdateUser(); public void setLastUpdateUser(User lastUpdateUser); public Boolean getModeratorHide(); public void setModeratorHide(Boolean moderatorHide); public User getHidingModerator(); public void setHidingModerator(User hidingModerator); }
package com.sbadc.survivalera.adapters; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.viewpager.widget.PagerAdapter; import com.sbadc.survivalera.R; import com.sbadc.survivalera.models.ScreenItem; import java.util.List; public class IntroViewPagerAdapter extends PagerAdapter { Context context; List<ScreenItem> screenItemList; public IntroViewPagerAdapter(Context context, List<ScreenItem> screenItemList) { this.context = context; this.screenItemList = screenItemList; } @NonNull @Override public Object instantiateItem(@NonNull ViewGroup container, int position){ LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View layoutScreen = inflater.inflate(R.layout.slider_screen,null); ImageView imgSlider = layoutScreen.findViewById(R.id.img_intro); TextView tittle = layoutScreen.findViewById(R.id.tv_tittle); TextView description = layoutScreen.findViewById(R.id.tv_desc); tittle.setText(screenItemList.get(position).getTittle()); description.setText(screenItemList.get(position).getDescription()); imgSlider.setImageResource(screenItemList.get(position).getScreenimg()); container.addView(layoutScreen); return layoutScreen; } @Override public int getCount(){ return screenItemList.size(); } @Override public boolean isViewFromObject(@NonNull View view, @NonNull Object o){ return view == o; } @Override public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object){ container.removeView((View) object); } }
package univ.lorraine.notes.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import univ.lorraine.notes.model.*; import univ.lorraine.notes.repository.TypeRepository; import java.util.List; @Service public class TypeService implements ITypeService { @Autowired private TypeRepository typeRepository; @Autowired private JeuService jeuService; @Override public List<Type> findAll() { return (List<Type>) typeRepository.findAll(); } @Override public Type save(Type type) { return (Type) typeRepository.save(type);} @Override public Type findById(int id) { return (Type) typeRepository.findById((long)id).orElseThrow(() -> new IllegalArgumentException("Invalid type Id:" + id)); } @Override public void delete(Type type){ for (Jeu jeu:type.getJeux()) { jeu.setType(null); jeuService.save(jeu); } typeRepository.delete(type); } }
package com.tencent.mm.ar; import com.tencent.mm.bt.h.d; class r$1 implements d { r$1() { } public final String[] xb() { return n.diD; } }
/* * 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 projetobd.bean; /** * * @author sampa */ public class Localidade { private String CNPJ; private String NomedaInstituicao; private String Email; private String CEP; private int Numero; public Localidade (){ } public Localidade ( String CNPJ, String NomedaInstituicao, String Email, String CEP, int Numero ){ this.CNPJ = CNPJ; this.NomedaInstituicao = NomedaInstituicao ; this.Email = Email; this.CEP = CEP; this.Numero = Numero; } public String getCNPJ() { return CNPJ; } public void setCNPJ(String CNPJ) { this.CNPJ = CNPJ; } public String getNomedaInstituicao() { return NomedaInstituicao; } public void setNomedaInstituicao(String NomedaInstituicao) { this.NomedaInstituicao = NomedaInstituicao; } public String getEmail() { return Email; } public void setEmail(String Email) { this.Email = Email; } public String getCEP() { return CEP; } public void setCEP(String CEP) { this.CEP = CEP; } public int getNumero() { return Numero; } public void setNumero(int Numero) { this.Numero = Numero; } }
package solution; import java.util.ArrayList; import java.util.List; /** * User: jieyu * Date: 12/11/16. */ public class RestoreIPAddresses93 { public List<String> restoreIpAddresses(String s) { List<String> res = new ArrayList<>(); if (s.length() > 12 || s.length() < 4) return res; search(s, 0, 1, res, new StringBuilder()); return res; } private void search(String s, int start, int level, List<String> res, StringBuilder ip) { if (level == 4) { if ((s.charAt(start) == '0' && start == s.length() - 1) || (s.charAt(start) != '0' && Integer.parseInt(s.substring(start, s.length())) <= 255)) { StringBuilder sb = new StringBuilder(ip.toString()); sb.append("."); sb.append(s.substring(start, s.length())); res.add(sb.toString()); } } else { int n = 0; if (start + 3 > s.length()) { if (s.charAt(start) == '0') n = 1; else n = 2; } else { if (s.charAt(start) == '0') n = 1; else if (Integer.parseInt(s.substring(start, start + 3)) <= 255) n = 3; else n = 2; } for (int i = 1; i + start <= s.length() && i <= n; ++i) { if (s.length() - (start + i) <= (4 - level) * 3 && s.length() - (start + i) >= (4 - level)) { StringBuilder sb = new StringBuilder(ip.toString()); if (level != 1) sb.append("."); sb.append(s.substring(start, start + i)); search(s, start + i, level + 1, res, sb); } } } } }
package com.spower.basesystem.attach.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.spower.basesystem.attach.command.AttachInfo; /* * FileName: IActionBean.java * Description: * Company: 南宁超创信息工程有限公司 * Copyright: ChaoChuang (c) 2006 * History: 2006-10-19 (Jyb) 1.0 Create */ /** * @author Jyb * @version 1.0, 2006-10-19 */ public interface IAction { /** 具体操作 * @param request HttpServletRequest * @param response HttpServletResponse * @param info AttachInfo * @return String */ String doAction(HttpServletRequest request, HttpServletResponse response, AttachInfo info); }
package zm.gov.moh.common; public class OpenmrsConfig { //Vitals public static final String CONCEPT_UUID_RESPIRATORY_RATE = "5242AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; public static final String CONCEPT_UUID_SYSTOLIC_BLOOD_PRESSURE = "5085AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; public static final String CONCEPT_UUID_DIASTOLIC_BLOOD_PRESSURE = "5086AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; public static final String CONCEPT_UUID_PULSE = "5087AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; public static final String CONCEPT_UUID_TEMPERATURE = "5088AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; public static final String CONCEPT_UUID_WEIGHT = "5089AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; public static final String CONCEPT_UUID_HEIGHT = "5090AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; public static final String CONCEPT_UUID_BLOOD_OXYGEN_SATURATION = "5092AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; //Encounter types public static final String ENCOUNTER_TYPE_UUID_VITALS = "67a71486-1a54-468f-ac3e-7091a9a79584"; //Visit types public static final String VISIT_TYPE_UUID_FACILITY_VISIT = "7b0f5697-27e3-40c4-8bae-f4049abfb4ed"; //Location tags public static final String LOCATION_TAG_UUID_DISTRICT = "332f8bdb-7a2d-4063-9c76-cbb4a969fb8d"; public static final String LOCATION_TAG_UUID_PROVINCE ="4bd0baf0-40eb-4209-bc6b-1080f3b34b41"; //Person Attribute types public static final String PERSON_ATTRIBUTE_TYPE = "0dc3daad-1ff2-4e6e-934f-e675a092a3ed"; public static final String PERSON_ATTRIBUTE_TYPE_NRC="ef5935b5-b96f-4d00-8429-46c0c3267c3a"; public static final String PERSON_ATTRIBUTE_TYPE_PHONE="c7e0a063-c20a-4e83-b461-0db6d79d2388"; // Provider Attributes public static final String PROVIDER_ATTRIBUTE_TYPE_PHONE = "0ec123b7-2826-41d6-a21e-b019350f78d7"; public static final String PROVIDER_ATTRIBUTE_TYPE_HOME_FACILITY = "c34fac13-9c48-4f29-beb1-04c8d0a86754"; public static final String CCPIZ_IDENTIFIER_TYPE = "852a0bd1-d283-48b1-b72e-e7af0b4b6ce7"; // Person attribute Type public static final String PHONE_NUMBER_ATTRIBUTE = "14d4f066-15f5-102d-96e4-000c29c2a5d7"; }
package com.github.jerrysearch.tns.console.task; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import com.github.jerrysearch.tns.protocol.rpc.TCNode; public class BaseClusterListTask { private static final List<TCNode> list = new ArrayList<TCNode>(); protected static synchronized void updateAll(List<TCNode> dst) { list.clear(); list.addAll(dst); } protected static synchronized TCNode selectOne() { int size = list.size(); int index = ThreadLocalRandom.current().nextInt(size); return list.get(index); } protected static synchronized List<TCNode> getAll() { List<TCNode> dst = new LinkedList<TCNode>(); dst.addAll(list); return dst; } }
package br.edu.ifam.saf.login; import br.edu.ifam.saf.api.data.LoginData; import br.edu.ifam.saf.mvp.BasePresenter; import br.edu.ifam.saf.mvp.LoadingView; interface LoginContract { interface View extends LoadingView { void mostrarMensagem(String message); } interface Presenter extends BasePresenter { void login(LoginData loginData); } }
import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; /** * Created by egalperi on 6/18/15. */ public class TWAwesomeBufferedReader extends BufferedReader { public TWAwesomeBufferedReader(Reader in) { super(in); } @Override public String readLine() { try{ return super.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } }
package br.bispojr.mastermind.jogo.viewer; import br.bispojr.mastermind.configuracao.ConfiguracaoControle; import br.bispojr.mastermind.jogo.models.ResultadoModel; import br.bispojr.mastermind.util.ImagePanel; import br.bispojr.mastermind.util.UpdateLabels; import javax.swing.*; import java.io.IOException; import java.util.ArrayList; import java.util.List; public final class ResultadoViewer extends JComponent implements UpdateLabels { private ImagePanel preta; private ImagePanel branca; public ResultadoViewer(List<Integer> bolinhas) throws IOException { setLayout(null); setSize(74, 27); preta = new ImagePanel("/jogo/preta.png"); branca = new ImagePanel("/jogo/branca.png"); preta.setSize(18, 18); preta.setLocation(5, 4); branca.setSize(18, 18); branca.setLocation(5, 4); adicionaResposta(bolinhas); setToolTipText(setToll()); } public String setToll() { String corCorreta = ConfiguracaoControle.bundleMesagens.getString("msgToll_CorCorreta"); String corCorretaPcorreta = ConfiguracaoControle.bundleMesagens.getString("msgToll_CorPCorreta"); return "<html>" + corCorreta + (corp + corb) + "<br>" + corCorretaPcorreta + corp; } int corb = 0; int corp = 0; ImagePanel criaBolinha(int cor, int x, int y) throws IOException { ImagePanel b = null; if (cor == 0) { b = new ImagePanel("/jogo/preta.png"); corp += 1; } if (cor == 1) { b = new ImagePanel("/jogo/branca.png"); corb += 1; } b.setSize(18, 18); b.setLocation(5 + x, y + 5); return b; } public void adicionaResposta(List<Integer> bolinhas) throws IOException { int p = 0; int b = 0; for (int i = 0; i < bolinhas.size(); i++) { if (((Integer)bolinhas.get(i)).equals(Integer.valueOf(ResultadoModel.BOLA_BRANCA))) { if (i == 0) { add(criaBolinha(1, 0, 0)); } else { add(criaBolinha(1, 17 * i, 0)); } b++; } if (((Integer)bolinhas.get(i)).equals(Integer.valueOf(ResultadoModel.BOLA_PRETA))) { ImagePanel t = preta; if (i == 0) { add(criaBolinha(0, 0, 0)); } else { add(criaBolinha(0, 17 * i, 0)); } p++; } } } public static void main(String[] a) throws IOException { JFrame j = new JFrame(); j.setSize(500, 600); j.setLayout(null); ArrayList<Integer> lista = new ArrayList(); lista.add(Integer.valueOf(0)); lista.add(Integer.valueOf(0)); lista.add(Integer.valueOf(1)); lista.add(Integer.valueOf(1)); ResultadoViewer p = new ResultadoViewer(lista); j.getContentPane().add(p); j.setDefaultCloseOperation(3); j.setVisible(true); } public void updateLabels() { setToolTipText(setToll()); } public String getTextosLabels() { throw new UnsupportedOperationException("Not supported yet."); } }
package list; import java.util.Iterator; import java.util.LinkedList; public class LinkedListJDK { public static void main(String[] args){ Employee employee = new Employee("John", "Doe", 4567); Employee employee2 = new Employee("Mary", "Smith", 22); Employee employee3 = new Employee("Jane", "Jones", 123); Employee employee4 = new Employee("Mike", "Wilson", 3245); Employee employee5 = new Employee("Bill", "End", 66); LinkedList<Employee> list = new LinkedList<>(); list.addFirst(employee); list.addFirst(employee2); list.addFirst(employee3); list.addFirst(employee4); // 마지막에 추가됨. addLast로 해도 동일 list.add(employee5); // 첫 node 제거 list.removeFirst(); // 마지막 node 제거 list.removeLast(); Iterator iter = list.iterator(); System.out.print("HEAD -> "); while(iter.hasNext()){ System.out.print(iter.next()); System.out.print(" <-> "); } System.out.println("null"); // for(Employee employees : list){ // System.out.println(employees); // } } }
package be.spring.app.utils; import be.spring.app.model.Account; import be.spring.app.model.Match; import be.spring.app.model.Team; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.Locale; import java.util.Map; /** * Created by u0090265 on 8/30/14. */ @Component public class HtmlHelper { private static final String EDIT = "glyphicon glyphicon-edit edit"; private static final String DELETE = "glyphicon glyphicon-trash delete"; private static final String MAP = "glyphicon glyphicon-map-marker"; private static final String DOODLE = "glyphicon glyphicon-th-list"; private static final String MOTM = "glyphicon glyphicon-user"; private static final String OK = "glyphicon glyphicon-ok green presence"; private static final String REMOVE = "glyphicon glyphicon-remove red presence"; private static final String DETAILS = "glyphicon glyphicon-eye-open"; private static final String DELETE_CLASS = "delete"; private static final String PRESENCE_CLASS = "presence"; private static final String PRESENCE_BOX = "presenceBox"; private static final String MAP_CLASS = "map"; private static final String DETAILS_CLASS = "details"; private static final String DOODLE_CLASS = "doodle"; private static final String MOTM_CLASS = "motm"; private static final String EMPTY = ""; private static final String HTML_ACTIONS = "htmlActions"; private static final String PRESENCE_ACTIONS = "presenceActions"; @Autowired private MessageSource messageSource; private static String getBtn(String aClazz, String clazz, String url) { return String.format ("<a href='%s' data-toggle='tooltip' data-placement='top' class='btn btn-default %s'><span class='%s' aria-hidden=\"true\"></span></a>", url, aClazz, clazz); } private static String getBtn(String aClazz, String clazz, String url, String title) { return String.format ("<a href='%s' title='%s' data-toggle='tooltip' data-placement='top' class='btn btn-default %s'><span class='%s' aria-hidden=\"true\"></span></a>", url, title, aClazz, clazz); } private static String wrapIntoBtnGroup(String s) { return "<div class=\"btn-group\">" + s + "</div>"; } public Map<String, String> getMatchesAdditions(Match match, Account account, Locale locale) { Map<String, String> r = new HashMap<>(); if (account != null) { r.put(PRESENCE_ACTIONS, getPresenceBtns(match, account)); } return r; } public String getPresenceBtns(Match match, Account account) { /** return match.getMatchDoodle().isPresent(account) ? getDoodleBtns(PRESENCE_CLASS, OK, String.format("/doodle/changeMatchDoodle.json?matchId=%s&present=false", match.getId())) : getDoodleBtns(PRESENCE_CLASS, REMOVE, String.format("/doodle/changeMatchDoodle.json?matchId=%s&present=true", match.getId())); **/ return null; } private String getDoodleBtns(String aClazz, String clazz, String url) { StringBuilder stringBuilder = new StringBuilder().append(getBtn(aClazz, clazz, url)); stringBuilder.append(clazz.equals(OK) ? getCheckBox(true, PRESENCE_BOX) : getCheckBox(false, PRESENCE_BOX)); return stringBuilder.toString(); } private String getCheckBox(boolean checked, String name) { return "<input type=\"checkbox\" style=\"display:none\"" + (checked ? "checked" : "") + "name=\"" + name + "\">"; } public Map<String, String> getMatchesButtons(Match match, boolean isAdmin, Locale locale) { Map<String, String> m = new HashMap<>(); StringBuilder btns = new StringBuilder(); if (isAdmin) { btns.append(getBtn(EMPTY, EDIT, String.format("changeMatch.html?matchId=%s", match.getId()), messageSource.getMessage("title.changeMatchResult", null, locale))) .append(getBtn(DELETE_CLASS, DELETE, String.format("deleteMatch.html?matchId=%s", match.getId()), messageSource.getMessage("title.deleteMatch", null, locale))); } String googleLink = match.getHomeTeam().getAddress().getGoogleLink(); if (googleLink != null) btns.append(getBtn(MAP_CLASS, MAP, googleLink, messageSource.getMessage("title.matchLocation", null, locale))); if (!match.getGoals().isEmpty()) btns.append(getBtn(DETAILS_CLASS, DETAILS, "details" + match.getId(), messageSource.getMessage("title" + ".matchDetails", null, locale))); btns.append(getBtn(DOODLE_CLASS, DOODLE, String.format("getDoodle.html?matchId=%s", match.getId()), messageSource.getMessage("title.matchDoodle", null, locale))); if (match.getMotmPoll() != null) { btns.append(getBtn(MOTM_CLASS, MOTM, "motm" + match.getId().toString(), messageSource.getMessage("title" + ".manOfTheMatchPoll", null, locale))); } m.put(HTML_ACTIONS, btns.toString().isEmpty() ? messageSource.getMessage("text.noActions", null, locale) : wrapIntoBtnGroup(btns.toString())); return m; } public Map getTeamButtons(Team team, boolean isAdmin, Locale locale) { Map<String, String> m = new HashMap<>(); StringBuilder btns = new StringBuilder(); if (team.getAddress().getGoogleLink() != null) btns.append(getBtn(MAP_CLASS, MAP, "#", messageSource.getMessage("title.teamLocation", null, locale))); if (isAdmin) { btns.append(getBtn(EMPTY, EDIT, String.format("editTeam.html?teamId=%s", team.getId()), messageSource .getMessage("title.editTeam", null, locale))) .append(getBtn(DELETE_CLASS, DELETE, String.format("deleteTeam.html?teamId=%s", team.getId()), messageSource.getMessage("title.deleteTeam", null, locale))); } m.put(HTML_ACTIONS, btns.toString().isEmpty() ? messageSource.getMessage("text.noActions", null, locale) : wrapIntoBtnGroup(btns.toString())); return m; } }
package chapter06; public class Exercise06_28 { public static void main(String[] args) { System.out.printf("%-4s%-4s\n","p","2^p-1"); System.out.println("---------------"); for (int i = 0; i <= 31; i++) { if (isMersennePrime(i)) { System.out.printf("%-4d%-4d\n",i,(int)(Math.pow(2, i)-1)); } } } public static boolean isMersennePrime(int number) { if (isPrime(number) && isPrime((int)(Math.pow(2, number)-1))) { return true; } return false; } public static boolean isPrime(int number) { if (number < 2) return false; for (int i = 2; i < number; i++) { if (number % i == 0) return false; } return true; } }
package com.dustin.controller.item; import com.dustin.dao.object.Items; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.ArrayList; import java.util.List; /** * <p> Description: </p> * * @author Wangsw * @date 2017/11/24下午 02:51 * @Version 1.0.0 */ public class NonAnnotationItemController implements Controller { public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { //调用service查找 数据库,查询商品列表,这里使用静态数据模拟 List<Items> itemsList = new ArrayList<Items>(); //向list中填充静态数据 Items items_1 = new Items(); items_1.setName("联想笔记本"); items_1.setPrice(6000f); items_1.setDetail("ThinkPad T430 联想笔记本电脑!"); Items items_2 = new Items(); items_2.setName("苹果手机"); items_2.setPrice(5000f); items_2.setDetail("iphone6苹果手机!"); itemsList.add(items_1); itemsList.add(items_2); //返回ModelAndView ModelAndView modelAndView = new ModelAndView(); //相当 于request的setAttribut,在jsp页面中通过itemsList取数据 modelAndView.addObject("itemsList", itemsList); //指定视图 modelAndView.setViewName("/WEB-INF/jsp/items/itemsList.jsp"); return modelAndView; } }
/* * 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 data.db; import data.core.api.ApiData; import data.core.api.ApiDatabase; import java.util.HashMap; /** * * @author Ryno */ public class DBPerson_class extends ApiDatabase{ //-------------------------------------------------------------------------- //properties //-------------------------------------------------------------------------- public DBPerson_class(){ key = "pec_id"; table = "person_class"; fields = new HashMap <> (); fields.put("pec_id", new Object[]{"id", "null", ApiData.INT}); fields.put("pec_ref_person", new Object[]{"student", "null", ApiData.INT}); fields.put("pec_ref_class", new Object[]{"class", "null", ApiData.INT}); fields.put("pec_type", new Object[]{"type", "", ApiData.INT}); } //-------------------------------------------------------------------------- public String[] pec_type = { "-- Not Selected --", //0 "student", //1 "teacher", //2 }; //-------------------------------------------------------------------------- }
package task105_106; import java.util.ArrayList; import java.util.List; /** * @author Igor */ public class Main103 { public static void main(String[] args) { List<Element> elements = Element.get("11,18,19,20,22,25"); int maxNextSum = getMaxNextSum(elements); elements.add(new Element(26)); List<Set> sets = Set.getSets(elements); Subsets subsets = new Subsets(sets, elements); List<Element> minElements = null; int minSum = Integer.MAX_VALUE; Element e0 = elements.get(0); Element e1 = elements.get(1); Element e2 = elements.get(2); Element e3 = elements.get(3); Element e4 = elements.get(4); Element e5 = elements.get(5); Element e6 = elements.get(6); e0.value = 20; for (;; e0.value++) { resetElements(elements, 0); if (getSum(elements) > maxNextSum) break; for (e1.value = e0.value + 1;; e1.value++) { resetElements(elements, 1); if (getSum(elements) > maxNextSum) break; for (e2.value = e1.value + 1; ; e2.value++) { resetElements(elements, 2); if (getSum(elements) > maxNextSum) break; for (e3.value = e2.value + 1; ; e3.value++) { resetElements(elements, 3); if (getSum(elements) > maxNextSum) break; for (e4.value = e3.value + 1; ; e4.value++) { resetElements(elements, 4); if (getSum(elements) > maxNextSum) break; for (e5.value = e4.value + 1;; e5.value++) { resetElements(elements, 5); if (getSum(elements) > maxNextSum) break; for (e6.value = e5.value + 1; ; e6.value++) { resetElements(elements, 6); if (getSum(elements) > maxNextSum) break; else { if (subsets.isSpecial()) { int sum = subsets.getSpecialSum(); if (minSum > sum) { minSum = subsets.getSpecialSum(); minElements = copyElements(subsets.elements); } } } } } } } } } } System.out.println(minSum); System.out.println(minElements); } private static List<Element> copyElements (List<Element> elements) { List<Element> newElements = new ArrayList<>(); for (Element element : elements) { newElements.add(new Element(element.value)); } return newElements; } private static void resetElements(List<Element> elements, int index) { int value = elements.get(index).value + 1; for (int i = index + 1; i < elements.size(); i++) { elements.get(i).value = value++; } } private static int getMaxNextSum(List<Element> elements) { List<Element> newElements = new ArrayList<>(); int b = 20; newElements.add(new Element(b)); for (Element newElement : elements) { newElements.add(new Element(newElement.value + b)); } return getSum(newElements); } private static int getSum(List<Element> elements) { int sum = 0; for (Element element : elements) { sum += element.value; } return sum; } }
package com.jim.multipos.ui.customer_debt.di; import android.content.Context; import android.support.v7.app.AppCompatActivity; import com.jim.multipos.config.scope.PerActivity; import com.jim.multipos.config.scope.PerFragment; import com.jim.multipos.core.BaseActivityModule; import com.jim.multipos.ui.customer_debt.CustomerDebtActivity; import com.jim.multipos.ui.customer_debt.CustomerDebtActivityPresenter; import com.jim.multipos.ui.customer_debt.CustomerDebtActivityPresenterImpl; import com.jim.multipos.ui.customer_debt.CustomerDebtActivityView; import com.jim.multipos.ui.customer_debt.connection.CustomerDebtConnection; import com.jim.multipos.ui.customer_debt.view.CustomerDebtListFragment; import com.jim.multipos.ui.customer_debt.view.CustomerDebtListFragmentModule; import com.jim.multipos.ui.customer_debt.view.CustomerListFragment; import com.jim.multipos.ui.customer_debt.view.CustomerListFragmentModule; import dagger.Binds; import dagger.Module; import dagger.Provides; import dagger.android.ContributesAndroidInjector; /** * Created by Sirojiddin on 30.11.2017. */ @Module(includes = BaseActivityModule.class) public abstract class CustomerDebtActivityModule { @Binds @PerActivity abstract AppCompatActivity provideCustomerDebtActivity(CustomerDebtActivity customerDebtActivity); @Binds @PerActivity abstract CustomerDebtActivityPresenter provideCustomerDebtActivityPresenter(CustomerDebtActivityPresenterImpl customerDebtPresenter); @Binds @PerActivity abstract CustomerDebtActivityView provideCustomerDebtActivityView(CustomerDebtActivity customerDebtActivity); @PerFragment @ContributesAndroidInjector(modules = CustomerListFragmentModule.class) abstract CustomerListFragment provideCustomerListFragmentInjector(); @PerFragment @ContributesAndroidInjector(modules = CustomerDebtListFragmentModule.class) abstract CustomerDebtListFragment provideCustomerDebtListFragmentInjector(); @PerActivity @Provides static CustomerDebtConnection provideCustomerDebtConnection(Context context){ return new CustomerDebtConnection(context); } }
package com.smxknife.java2.io.input; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.PushbackInputStream; /** * @author smxknife * 2018/11/19 */ public class PushbackInputStreamDemo { public static void main(String[] args) throws IOException { String url = "www.baidu.com"; PushbackInputStream pushbackInputStream = new PushbackInputStream(new ByteArrayInputStream(url.getBytes())); int read = 0; System.out.println(pushbackInputStream.available()); while ((read = pushbackInputStream.read()) != -1) { if ('.' == (char) read) { pushbackInputStream.unread(read); read = pushbackInputStream.read(); System.out.println("回退 " + (char) read); } else System.out.println((char) read); } System.out.println(pushbackInputStream); } }
package com.nikvay.saipooja_patient.view.activity; import android.content.Intent; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.RelativeLayout; import android.widget.TextView; import com.google.gson.Gson; import com.nikvay.saipooja_patient.MainActivity; import com.nikvay.saipooja_patient.R; import com.nikvay.saipooja_patient.apiCallCommen.ApiClient; import com.nikvay.saipooja_patient.apiCallCommen.ApiInterface; import com.nikvay.saipooja_patient.model.PatientModel; import com.nikvay.saipooja_patient.model.SuccessModel; import com.nikvay.saipooja_patient.utils.AppointmentDialog; import com.nikvay.saipooja_patient.utils.ErrorMessageDialog; import com.nikvay.saipooja_patient.utils.NetworkUtils; import com.nikvay.saipooja_patient.utils.SharedUtils; import com.nikvay.saipooja_patient.utils.SuccessMessageDialog; import java.util.ArrayList; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class LoginActivity extends AppCompatActivity { EditText textPassword,textEmail; Button btn_login; TextView txtCreateAc; private ErrorMessageDialog errorMessageDialog; private SuccessMessageDialog successMessageDialog; AppointmentDialog appointmentDialog; String TAG = getClass().getSimpleName(),device_token; String is_login; ApiInterface apiInterface; RelativeLayout ll_relative_login; ArrayList<PatientModel> patientModelArrayList = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); find_ALL_ID(); event(); } private void find_ALL_ID() { textPassword = findViewById(R.id.password); textEmail = findViewById(R.id.email); btn_login = findViewById(R.id.btn_login); txtCreateAc = findViewById(R.id.txtCreateAc); ll_relative_login = findViewById(R.id.ll_relative_login); apiInterface = ApiClient.getClient().create(ApiInterface.class); device_token = SharedUtils.getDeviceToken(LoginActivity.this); errorMessageDialog = new ErrorMessageDialog(LoginActivity.this); successMessageDialog = new SuccessMessageDialog(LoginActivity.this); appointmentDialog = new AppointmentDialog(LoginActivity.this); } private void event() { txtCreateAc.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(LoginActivity.this,RegistrationActivity.class); startActivity(intent); } }); btn_login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String email=textEmail.getText().toString().trim(); String password=textPassword.getText().toString().trim(); if(email.equalsIgnoreCase("")) { errorMessageDialog.showDialog("Email ID Can't Be Empty"); // SnackbarCommon.displayValidation(v,"Email ID Can't Be Empty"); } else if(!android.util.Patterns.EMAIL_ADDRESS.matcher(textEmail.getText().toString()).matches()) { errorMessageDialog.showDialog("Enter valid Email"); // SnackbarCommon.displayValidation(v,"Enter valid Email"); } else if(password.equalsIgnoreCase("")) { errorMessageDialog.showDialog("Password Can't Be Empty"); //SnackbarCommon.displayValidation(v,"Password Can't Be Empty"); } else if(password.length()>15||password.length()<5) { errorMessageDialog.showDialog("Password Length Between 5 to 15"); //SnackbarCommon.displayValidation(v,"Password Length Between 5 to 15"); } else { if (NetworkUtils.isNetworkAvailable(LoginActivity.this)) callLogin(email,password); else NetworkUtils.isNetworkNotAvailable(LoginActivity.this); } } }); } private void callLogin(String email, String password) { Call<SuccessModel> call = apiInterface.loginCall(email, password,device_token); call.enqueue(new Callback<SuccessModel>() { @Override public void onResponse(Call<SuccessModel> call, Response<SuccessModel> response) { String str_response = new Gson().toJson(response.body()); Log.e("" + TAG, "Response >>>>" + str_response); try { if (response.isSuccessful()) { SuccessModel successModel = response.body(); String message = null, code = null; if (successModel != null) { message = successModel.getMsg(); code = successModel.getError_code(); if (code.equalsIgnoreCase("1")) { patientModelArrayList = successModel.getPatientModelArrayList(); SharedUtils.putSharedUtils(LoginActivity.this); SharedUtils.addUserUtils(LoginActivity.this,patientModelArrayList); loginIntent(); appointmentDialog.showDialog("Login Successfully"); } else { errorMessageDialog.showDialog("User Not Registered"); } } } } catch (Exception e) { e.printStackTrace(); } } @Override public void onFailure(Call<SuccessModel> call, Throwable t) { errorMessageDialog.showDialog(t.getMessage()); } }); } private void loginIntent() { Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { Intent intent=new Intent(LoginActivity.this, MainActivity.class); startActivity(intent); finish(); } },1000); } }
package br.usp.memoriavirtual.modelo.entidades.bempatrimonial; import java.io.Serializable; import java.sql.Date; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.SequenceGenerator; import javax.xml.bind.annotation.XmlTransient; @Entity @SequenceGenerator(name = "REVISAO_ID", sequenceName = "REVISAO_SEQ", allocationSize = 1) public class Revisao implements Serializable{ private static final long serialVersionUID = 3733542902798023334L; @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "REVISAO_ID") private Long id; @ManyToOne(fetch=FetchType.EAGER) private BemPatrimonial bemPatrimonial; private Date dataRevisao; private String anotacao; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Date getDataRevisao() { return dataRevisao; } public void setDataRevisao(Date dataRevisao) { this.dataRevisao = dataRevisao; } public String getAnotacao() { return anotacao; } public void setAnotacao(String anotacao) { this.anotacao = anotacao; } @XmlTransient public BemPatrimonial getBemPatrimonial() { return bemPatrimonial; } public void setBemPatrimonial(BemPatrimonial bemPatrimonial) { this.bemPatrimonial = bemPatrimonial; } }
package com.malf.test; import com.malf.pojo.Category; import com.malf.pojo.Product; import com.malf.service.ProductService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @author malf * @description TODO * @project how2jStudy * @since 2020/10/27 */ public class SpringTest { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext( new String[]{"applicationContext.xml"}); ProductService service = (ProductService) context.getBean("service"); service.doSomeService(); // Product product = (Product) context.getBean("product"); // System.out.println(product.getName()); // System.out.println(product.getCategory().getName()); // Category category = (Category) context.getBean("category"); // System.out.println(category.getName()); } }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.cmsfacades.common.service.impl; import de.hybris.platform.cmsfacades.common.service.SearchResultConverter; import de.hybris.platform.core.model.ItemModel; import de.hybris.platform.servicelayer.search.SearchResult; import de.hybris.platform.servicelayer.search.impl.SearchResultImpl; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.function.Function; import java.util.stream.Collectors; /** * Default implementation of {@link SearchResultConverter} */ public class DefaultSearchResultConverter implements SearchResultConverter { @Override public <S extends ItemModel, T> SearchResult<T> convert(final SearchResult<S> modelSearchResult, final Function<S, T> convertFunction) { SearchResult<T> dataSearchResult; if (Objects.nonNull(modelSearchResult)) { final List<T> dataList = modelSearchResult.getResult().stream().map(model -> convertFunction.apply(model)) .collect(Collectors.toList()); dataSearchResult = new SearchResultImpl<>(dataList, modelSearchResult.getTotalCount(), modelSearchResult.getRequestedCount(), modelSearchResult.getRequestedStart()); } else { dataSearchResult = new SearchResultImpl<>(Collections.emptyList(), 0, 0, 0); } return dataSearchResult; } }
package tree; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.Stack; public class PreOrder { List<Integer> list = new ArrayList<>(); private List<Integer> preOrder1(TreeNode root){ if(root == null){ return null; } list.add(root.val); preOrder1(root.left); preOrder1(root.right); return list; } private List<Integer> preOrder2(TreeNode root){ Stack<TreeNode> stack = new Stack<>(); stack.add(root); while (!stack.isEmpty()){ TreeNode tmp = stack.pop(); list.add(tmp.val); if(tmp.right != null) { stack.add(tmp.right); } if(tmp.left != null){ stack.add(tmp.left); } } return list; } @Test public void testPreOrder(){ TreeNode root = new TreeNode(2); root.left = new TreeNode(3); root.right = new TreeNode(4); root.left.left = null; root.left.right = new TreeNode(5); root.right.left = new TreeNode(1); root.right.right = new TreeNode(0); List<Integer> list = new ArrayList<>(); list = preOrder2(root); System.out.println(list.toString()); } }
package jp.noxi.collection; import javax.annotation.Nonnull; final class InstanceOfCollection<TResult, TSource> extends LinqCollection<TResult> { final LinqCollection<TSource> mSource; final Class<TResult> mFilter; InstanceOfCollection(@Nonnull Iterable<TSource> source, @Nonnull Class<TResult> filter) { mSource = source instanceof LinqCollection ? (LinqCollection<TSource>) source : new LinqCollection<TSource>(source); mFilter = filter; } @Override @SuppressWarnings("unchecked") public boolean hasNext() { if (!mSource.hasNext()) return false; final LinqCollection collection = mInner == null ? null : mInner.get(); do { TSource source = mSource.next(); if (!mFilter.isInstance(source)) continue; if (collection == null || collection.hasNext(source)) { setElement((TResult) source); return true; } } while (mSource.hasNext()); return false; } @Override protected int getIndex() { return mSource.getIndex(); } @Override protected void reset() { mSource.reset(); mElement = null; mHasElement = false; } }
package com.tencent.mm.pluginsdk.ui.d; import android.content.Context; import android.net.Uri; import android.os.Bundle; import com.tencent.mm.R; import com.tencent.mm.kernel.g; import com.tencent.mm.plugin.downloader.model.FileDownloadTaskInfo; import com.tencent.mm.plugin.downloader.model.d; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.pluginsdk.model.app.p; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.e; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.aa.a; import com.tencent.mm.ui.base.s; import java.io.File; public final class q { public static boolean vq() { boolean z = true; if (g.Eg().Dx()) { boolean z2; if (bi.fU(ad.getContext()) || e.bxk == 1 || bi.getInt(com.tencent.mm.k.g.AT().getValue("ShowWeixinPBIntro"), 0) != 0 || p.r(ad.getContext(), "com.tencent.pb")) { z2 = false; } else { z2 = true; } if (z2) { int a = bi.a((Integer) g.Ei().DT().get(a.sPC, null), 3); x.v("MicroMsg.WxPhoneBookHelper", "needDisplayWxPBMenuItem, counter = %d", new Object[]{Integer.valueOf(a)}); if (a <= 0) { return false; } g.Ei().DT().set(352257, Integer.valueOf(a - 1)); return true; } String str = "MicroMsg.WxPhoneBookHelper"; String str2 = "%b, %b, %b, %b"; Object[] objArr = new Object[4]; objArr[0] = Boolean.valueOf(bi.fU(ad.getContext())); if (e.bxk != 1) { z2 = true; } else { z2 = false; } objArr[1] = Boolean.valueOf(z2); if (bi.getInt(com.tencent.mm.k.g.AT().getValue("ShowWeixinPBIntro"), 0) == 0) { z2 = true; } else { z2 = false; } objArr[2] = Boolean.valueOf(z2); if (p.r(ad.getContext(), "com.tencent.pb")) { z = false; } objArr[3] = Boolean.valueOf(z); x.d(str, str2, objArr); return false; } x.e("MicroMsg.WxPhoneBookHelper", "needDisplayWxPBMenuItem, account not ready"); return false; } public static void f(Context context, Bundle bundle) { int i = bundle != null ? bundle.getInt("fromScene") : 0; h.mEJ.h(11621, new Object[]{Integer.valueOf(i), Integer.valueOf(0)}); FileDownloadTaskInfo yP = d.aCU().yP("http://dianhua.qq.com/cgi-bin/cloudgrptemplate?t=dianhuaben_download&channel=100008"); if (yP == null || yP.status != 3) { s.makeText(context, context.getString(R.l.chatting_phone_downloading_wxpb), 2000).show(); com.tencent.mm.plugin.downloader.model.e.a aVar = new com.tencent.mm.plugin.downloader.model.e.a(); aVar.yQ("http://dianhua.qq.com/cgi-bin/cloudgrptemplate?t=dianhuaben_download&channel=100008"); aVar.yS(context.getString(R.l.chatting_phone_wxpb)); aVar.ox(1); aVar.ef(true); d.aCU().a(aVar.ick); return; } x.i("MicroMsg.WxPhoneBookHelper", "weixin phonebook already download successfully, install directly"); if (com.tencent.mm.a.e.cn(yP.path)) { com.tencent.mm.pluginsdk.model.app.q.g(context, Uri.fromFile(new File(yP.path))); } } }
package com.mineskies.skyblock.command; import com.mineskies.skyblock.Constants; import com.mineskies.skyblock.SkyBlock; import com.mineskies.skyblock.camera.Camera; import com.mineskies.skyblock.camera.Scene; import com.sk89q.worldedit.bukkit.BukkitAdapter; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldguard.WorldGuard; import com.sk89q.worldguard.protection.managers.RegionManager; import com.sk89q.worldguard.protection.regions.ProtectedRegion; import com.sk89q.worldguard.protection.regions.RegionContainer; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.ArmorStand; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; public class TutorialCommand implements CommandExecutor { @Override public boolean onCommand(CommandSender commandSender, Command command, String s, String[] strings) { if (commandSender instanceof Player) { Player player = (Player) commandSender; Location location = player.getLocation(); World defaultWorld = Bukkit.getWorld(Constants.DEFAULT_WORLD); RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer(); RegionManager manager = container.get(BukkitAdapter.adapt(defaultWorld)); ProtectedRegion region = manager.getRegion("spawn"); boolean atSpawn = region.contains(location.getBlockX(), location.getBlockY(), location.getBlockZ()); if (player.getWorld() == defaultWorld && atSpawn) { //--- Setup camera. /* Camera camera = new Camera(player); camera.addScene(new Scene(Constants.TUTORIAL_1, 10, "&9&lMINESKIES", "&fEnter the portal to begin.")); camera.addScene(new Scene(Constants.TUTORIAL_2, Constants.TUTORIAL_2_CHUNK, 5, "&aIsland", "&fChoose your starting island.")); camera.addScene(new Scene(Constants.TUTORIAL_3, Constants.TUTORIAL_3_CHUNK, 5, "&aIsland", "&fChoose your starting island.")); camera.addScene(new Scene(Constants.TUTORIAL_4,5, "&aIsland", "&fChoose your starting island.")); camera.addScene(new Scene(Constants.TUTORIAL_5, Constants.TUTORIAL_5_CHUNK,5, "&cNether", "&fProgress to the nether.")); camera.addScene(new Scene(Constants.TUTORIAL_6, Constants.TUTORIAL_6_CHUNK,5, "&5End", "&fProgress to the end.")); //--- Start tutorial. camera.start();*/ player.sendMessage(ChatColor.LIGHT_PURPLE + "[Tutorial] Disabled for now, we are working on a fix!"); } else { player.sendMessage(ChatColor.LIGHT_PURPLE + "[Tutorial] You need to be at spawn in order to start the tutorial! /spawn"); } } return true; } }
package com.rsm.yuri.projecttaxilivre.profile; import android.location.Location; import android.net.Uri; import com.rsm.yuri.projecttaxilivre.profile.events.ProfileEvent; /** * Created by yuri_ on 02/01/2018. */ public interface ProfilePresenter { void onCreate(); void onDestroy(); void uploadPhoto(Uri selectedImageUri); void onEventMainThread(ProfileEvent event); void retrieveDataUser(); }
package Unidade3; import java.util.Set; import java.util.TreeSet; public class TesteCompilaGenerics { //a) Errado porque esta add String Builder onde deve ser do tp String //Set<String> strSet = new HashSet<String>(); //strSet.add(new StringBuilder("hello")); //b) Correto Set<? extends Float> s = new TreeSet<Float>(); //c) Errado porque não trata objeto, esta tratando tipo primitivo int //LinkedList<int> list = new LinkedList<int>(); // lista encadeada }
import java.io.*; public class FileHandlingFour { public static void main(String[] args){ File file = new File("FileHandlingOne.txt"); if(file.exists()){ System.out.println("File name : " + file.getName()); System.out.println("File location : " + file.getAbsolutePath()); System.out.println("Readable : " + file.canRead()); System.out.println("Writeable : " + file.canWrite()); System.out.println("Size : " + file.length()); } } }
import java.util.Scanner; public class TriangleArea { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int pointAx = scanner.nextInt(); int pointAy = scanner.nextInt(); int pointBx = scanner.nextInt(); int pointBy = scanner.nextInt(); int pointCx = scanner.nextInt(); int pointCy = scanner.nextInt(); int triangleArea = triangleArea(pointAx, pointAy, pointBx,pointBy,pointCx,pointCy); System.out.println(triangleArea); } private static int triangleArea(int pointAx, int pointAy, int pointBx, int pointBy, int pointCx, int pointCy) { return Math.abs(pointAx*(pointBy-pointCy)+ pointBx*(pointCy-pointAy)+pointCx*(pointAy-pointBy))/2; } }
package com.tencent.mm.plugin.profile.ui; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import com.tencent.mm.g.a.rn; import com.tencent.mm.plugin.profile.ui.NormalUserFooterPreference.a; class NormalUserFooterPreference$a$2 implements OnClickListener { final /* synthetic */ a lXy; NormalUserFooterPreference$a$2(a aVar) { this.lXy = aVar; } public final void onClick(DialogInterface dialogInterface, int i) { rn rnVar = new rn(); rnVar.ccn.ccq = true; com.tencent.mm.sdk.b.a.sFg.m(rnVar); this.lXy.bnD(); dialogInterface.dismiss(); } }
package com.tencent.mm.plugin.fav.ui.detail; import android.app.Dialog; import com.tencent.mm.plugin.fav.ui.detail.FavoriteFileDetailUI.13.2; class FavoriteFileDetailUI$13$2$1 implements Runnable { final /* synthetic */ Dialog iYD; final /* synthetic */ 2 jcF; FavoriteFileDetailUI$13$2$1(2 2, Dialog dialog) { this.jcF = 2; this.iYD = dialog; } public final void run() { this.iYD.dismiss(); } }
package uk.ac.ed.inf.aqmaps.pathfinding.heuristics; import uk.ac.ed.inf.aqmaps.pathfinding.SearchNode; import uk.ac.ed.inf.aqmaps.pathfinding.goals.PathfindingGoal; /** * The simplest heuristic, uses the euclidian distance between the node and its goal as the value of its heuristic. */ public class StraightLineDistance implements PathfindingHeuristic{ /** * Initializes a new instance of the straight line heuristic with a relaxation factor of 1 (i.e. no relaxation) */ public StraightLineDistance(){ } /** * Initializes a new instance of the straight line heuristic with the given relaxation factor. Some pathfinding algorithms such as Astar will run much faster * with a relaxed heuristic, but the relaxed solution might not be optimal (path cost <= relaxationFactor * optimal path cost) * @param relaxationFactor */ public StraightLineDistance(double relaxationFactor){ assert relaxationFactor >= 1; this.relaxationFactor = relaxationFactor; } /** * Returns the straight line distance between the nodes multiplied by the relaxation factor */ @Override public <T extends SearchNode<T>> double heuristic(T a, PathfindingGoal b) { return a.getCoordinates().distance(b.getCoordinates()) * relaxationFactor; } /** * The value by which euclidian distance is multiplied to give the final heuristic value */ private double relaxationFactor = 1; }
package com.duanxr.yith.easy; import java.util.HashMap; import java.util.Map; /** * @author 段然 2021/3/8 */ public class TwoSumIIInputArrayIsSorted { /** * Given an array of integers numbers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. * * Return the indices of the two numbers (1-indexed) as an integer array answer of size 2, where 1 <= answer[0] < answer[1] <= numbers.length. * * You may assume that each input would have exactly one solution and you may not use the same element twice. * *   * * Example 1: * * Input: numbers = [2,7,11,15], target = 9 * Output: [1,2] * Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2. * Example 2: * * Input: numbers = [2,3,4], target = 6 * Output: [1,3] * Example 3: * * Input: numbers = [-1,0], target = -1 * Output: [1,2] *   * * Constraints: * * 2 <= numbers.length <= 3 * 104 * -1000 <= numbers[i] <= 1000 * numbers is sorted in increasing order. * -1000 <= target <= 1000 * Only one valid answer exists. * * 给定一个已按照 升序排列  的整数数组 numbers ,请你从数组中找出两个数满足相加之和等于目标数 target 。 * * 函数应该以长度为 2 的整数数组的形式返回这两个数的下标值。numbers 的下标 从 1 开始计数 ,所以答案数组应当满足 1 <= answer[0] < answer[1] <= numbers.length 。 * * 你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。 * *   * 示例 1: * * 输入:numbers = [2,7,11,15], target = 9 * 输出:[1,2] * 解释:2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。 * 示例 2: * * 输入:numbers = [2,3,4], target = 6 * 输出:[1,3] * 示例 3: * * 输入:numbers = [-1,0], target = -1 * 输出:[1,2] *   * * 提示: * * 2 <= numbers.length <= 3 * 104 * -1000 <= numbers[i] <= 1000 * numbers 按 递增顺序 排列 * -1000 <= target <= 1000 * 仅存在一个有效答案 * */ class Solution { public int[] twoSum(int[] numbers, int target) { Map<Integer, Integer> map = new HashMap<>(numbers.length / 2); for (int i = 0; i < numbers.length; i++) { if (map.containsKey(target - numbers[i])) { int[] r = new int[2]; r[0] = map.get(target - numbers[i]) + 1; r[1] = i + 1; return r; } map.put(numbers[i], i); } return null; } } }
package com.metacube.restful.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.metacube.restful.enums.StatusEnums; import com.metacube.restful.model.Advertisement; import com.metacube.restful.model.CategoryAdvertsiement; /** * AdvertisementDao class gets the connection with database and performs the operations on database(add, put, post, delete) * @author admin * */ public class AdvertisementDao { private Connection connection=ConnectionToDB.getConnection(); /** * addAdvertisement method add the advertisement in the database (id is primary key and category_id is foreign key) * @param advertisement * @return status inserted if advertisement is inserted * @throws SQLException if category id doesn't exists */ public StatusEnums addAvertisement(Advertisement advertisement) throws SQLException { try { //execute the query PreparedStatement preparedStatement = connection.prepareStatement(Query.insertAdvertisement); preparedStatement.setInt(1, advertisement.getId()); preparedStatement.setString(2, advertisement.getName()); preparedStatement.setString(3, advertisement.getDescription()); preparedStatement.setInt(4, advertisement.getCategory_id()); if(preparedStatement.executeUpdate()>0) { return StatusEnums.INSERTED; } } catch (SQLException e) { throw e; } return StatusEnums.NOTINSERTED; } /** * deleteAdvertisement method deletes the advertisement of the given id * @param advertisementID * @return status DELETED if advertisement is deleted */ public StatusEnums deleteAdvertisement(int advertisementID) { try { //executes the query PreparedStatement preparedStatement = connection.prepareStatement(Query.deleteAdvertisement); preparedStatement.setInt(1, advertisementID); if(preparedStatement.executeUpdate()>0) { return StatusEnums.DELETED; } } catch (SQLException e) { e.printStackTrace(); } return StatusEnums.NOTDELETED; } /** * getAllAdvertisement method returns the list of advertisement available in the database * @return the list of advertisement */ public List<Advertisement> getAllAdvertisement() { List<Advertisement> advertisementList = new ArrayList<Advertisement>(); try { //executes the query PreparedStatement preparedStatement = connection.prepareStatement(Query.getAllAdvertisement); ResultSet resultSet = preparedStatement.executeQuery(); //stores the result into list while(resultSet.next()) { Advertisement advertisement = new Advertisement(resultSet.getInt("id"), resultSet.getString("title"), resultSet.getString("description"), resultSet.getInt("category_id")); advertisementList.add(advertisement); } } catch (SQLException e) { e.printStackTrace(); } return advertisementList; } /** * getAdvertisementBycategoryID method finds the list of advertisement related to given category id * @param categoryID * @return the object CategoryAdvertisement which contains the category and list if advertsiement */ public CategoryAdvertsiement getAdvertisementBycategoryID(int categoryID) { List<Advertisement> advertisementList = new ArrayList<Advertisement>(); Advertisement advertisement = null; CategoryAdvertsiement categoryAdvertisement = null; try { //executes the query PreparedStatement preparedStatement = connection.prepareStatement(Query.getAdvertisementByCategoryID); preparedStatement.setInt(1, categoryID); ResultSet resultSet = preparedStatement.executeQuery(); //stores the result into list while(resultSet.next()) { advertisement = new Advertisement(resultSet.getInt("id"), resultSet.getString("title"), resultSet.getString("description"), resultSet.getInt("category_id")); advertisementList.add(advertisement); } categoryAdvertisement = new CategoryAdvertsiement(categoryID,advertisementList); } catch (SQLException e) { e.printStackTrace(); } return categoryAdvertisement; } /** * updateName update the name of the advertisement of given id of the advertisement * @param id * @param name * @return status updated if name is updated */ public StatusEnums updateName(int id, String name) { try { //executes the query PreparedStatement preparedStatement = connection.prepareStatement(Query.updateAdvertisementName); preparedStatement.setString(1, name); preparedStatement.setInt(2, id); if(preparedStatement.executeUpdate()>0) { return StatusEnums.UPDATED; } } catch (SQLException e) { e.printStackTrace(); } return StatusEnums.NOTUPDATED; } }
package com.asd.common.shiro.sessionid; import org.apache.shiro.session.Session; import org.apache.shiro.session.mgt.eis.SessionIdGenerator; import java.io.Serializable; import java.util.UUID; public class JavaUuidSessionIdGenerator implements SessionIdGenerator{ /** * Ignores the method argument and simply returns * {@code UUID}.{@link UUID#randomUUID() randomUUID()}.{@code toString()}. * * @param session the {@link Session} instance to which the ID will be applied. * @return the String value of the JDK's next {@link UUID#randomUUID() randomUUID()}. */ public Serializable generateId(Session session) { return UUID.randomUUID().toString(); } }
package com.services.rabbitmq.common; import com.services.utils.encrypt.Base64; public class Consts { /** * 默认队列名 */ public static String default_queue_name = Base64.encode("default_queueName".getBytes()); /** * 默认队列名 */ public static String default_queue_name_routing_key = Base64.encode("default_queueName_routing_key".getBytes()); /** * 默认队列名 */ public static String default_queue_name_subscribe = Base64.encode("default_queueName_subscribe".getBytes()); /** * 默认队列名 */ public static String default_queue_name_topic = Base64.encode("default_queueName_topic".getBytes()); }
package com.gmail.khanhit100896.foody.main; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import com.gmail.khanhit100896.foody.R; /** * A simple {@link Fragment} subclass. */ public class CheckGpsFragment extends Fragment { protected Button btn_thu_lai; public CheckGpsFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_check_gps, container, false); this.btn_thu_lai = view.findViewById(R.id.btn_thu_lai); this.btn_thu_lai.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { resetActivity(getActivity()); } }); return view; } private void resetActivity(Activity activity){ activity.recreate(); } }
import java.util.ArrayList; import java.util.List; public class TesteFuncionario { public static void main(String[] args) { Funcionario funcionario1 = new Funcionario("ana", 15); Funcionario funcionario2 = new Funcionario("rose", 16); Funcionario funcionario3 = new Funcionario("tati", 17); Funcionario funcionario4 = new Funcionario("dani", 18); List<Funcionario> listaFuncionario = new ArrayList<>(); listaFuncionario.add(funcionario1); listaFuncionario.add(funcionario2); listaFuncionario.add(funcionario3); listaFuncionario.add(funcionario4); Funcionario funcionario5 = new Funcionario("jaque", 15); if (listaFuncionario.contains(funcionario5)){ System.out.println("A funcionaria " + funcionario5.getNomeFuncionario() + " está na lista"); } else { System.out.println("A funcionaria " + funcionario5.getNomeFuncionario() + " não está na lista"); } } }
package com.pineapple.mobilecraft.tumcca.fragment; import android.app.Activity; import android.content.*; import android.graphics.Bitmap; import android.os.Bundle; import android.os.IBinder; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import com.etsy.android.grid.StaggeredGridView; import com.lsjwzh.widget.materialloadingprogressbar.CircleProgressBar; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.display.HalfRoundedBitmapDisplayer; import com.pineapple.mobilecraft.R; import com.pineapple.mobilecraft.TumccaApplication; import com.pineapple.mobilecraft.tumcca.activity.UserActivity; import com.pineapple.mobilecraft.tumcca.activity.WorkDetailActivity; import com.pineapple.mobilecraft.tumcca.adapter.WorkAdapter; import com.pineapple.mobilecraft.tumcca.data.Profile; import com.pineapple.mobilecraft.tumcca.data.WorksInfo; import com.pineapple.mobilecraft.tumcca.manager.UserManager; import com.pineapple.mobilecraft.tumcca.mediator.IWorksList; import com.pineapple.mobilecraft.tumcca.service.TumccaService; import com.pineapple.mobilecraft.util.logic.Util; import org.json.JSONArray; import org.json.JSONException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Created by yihao on 15/6/4. */ public class WorkListFragment extends Fragment implements IWorksList { public static final int MODE_LV_DRAG = 0; public static final int MODE_LV_FIXED = 1; static final int CORNER_RADIUS = 1; List<WorksInfo> mWorksInfoList = new ArrayList<WorksInfo>(); int mCurrentPage = 1; int mListViewMode = MODE_LV_DRAG; boolean mIsEnd = false; Activity mContext; WorkAdapter mAdapter; DisplayImageOptions mImageOptionsWorks; ImageLoader mImageLoader; boolean mScrollingIdle = false; HashMap<Integer, Profile> mMapProfile; TumccaService mService; WorkListLoader mWorksLoader = null; CircleProgressBar mProgressBar; SwipeRefreshLayout mSwipeRefreshLayout; BroadcastReceiver mReceiver; StaggeredGridView mListView; View mFooterProgressView; public void setListViewMode(int mode) { if (mode >= MODE_LV_DRAG && mode <= MODE_LV_FIXED) { mListViewMode = mode; } } public static interface WorkListLoader { /** * 获取初始数据 * * @return */ public List<WorksInfo> getInitialWorks(); /** * 取得数据后,要调用{@link #addWorksHead} */ public void loadHeadWorks(); /** * 取得数据后,要调用{@link #addWorksTail} */ public void loadTailWorks(final int page); } public WorkListFragment() { mMapProfile = new HashMap<Integer, Profile>(); mImageOptionsWorks = new DisplayImageOptions.Builder() .displayer(new HalfRoundedBitmapDisplayer(Util.dip2px(TumccaApplication.applicationContext, CORNER_RADIUS))).cacheOnDisk(true).bitmapConfig(Bitmap.Config.RGB_565) .build(); mImageLoader = ImageLoader.getInstance(); } public void setWorksLoader(WorkListLoader workListLoader) { mWorksLoader = workListLoader; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mContext = getActivity(); mAdapter = new WorkAdapter(mContext); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Context context = getActivity().getApplicationContext(); context.bindService(new Intent(context, TumccaService.class), new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { mService = ((TumccaService.LocalService) service).getService(); } @Override public void onServiceDisconnected(ComponentName name) { } }, Context.BIND_AUTO_CREATE); } @Override public void onAttach(Activity activity) { super.onAttach(activity); activity.registerReceiver(mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int id = intent.getIntExtra("id", -1); removeWork(id); } }, new IntentFilter("remove_work")); } @Override public void onDetach() { super.onDetach(); getActivity().unregisterReceiver(mReceiver); } private void removeWork(int id) { for (WorksInfo worksInfo : mWorksInfoList) { if (worksInfo.id == id) { mWorksInfoList.remove(worksInfo); break; } } } @Override public void onResume() { super.onResume(); setupProgressBar(); mAdapter.notifyDataSetChanged(); } /** * 将数据添加到底部,需要在主线程中调用 * 将数据添加到头部 * * @param worksInfoList */ @Override public int addWorksHead(final List<WorksInfo> worksInfoList) { int currentLength = mWorksInfoList.size(); mContext.runOnUiThread(new Runnable() { @Override public void run() { if (mWorksInfoList.size() > 0) { int topId = mWorksInfoList.get(0).id; int index = worksInfoList.size(); for (int i = 0; i < worksInfoList.size(); i++) { if (topId == worksInfoList.get(i).id) { index = i; break; } } if (worksInfoList.subList(0, index).size() != 0) { mWorksInfoList.addAll(0, worksInfoList.subList(0, index)); } } else { mWorksInfoList.addAll(worksInfoList); } mProgressBar.setVisibility(View.GONE); mSwipeRefreshLayout.setVisibility(View.VISIBLE); mAdapter.setWorks(mWorksInfoList); mAdapter.notifyDataSetChanged(); } }); parseWorks(mWorksInfoList); mContext.runOnUiThread(new Runnable() { @Override public void run() { mAdapter.setWorks(mWorksInfoList); mAdapter.notifyDataSetChanged(); } }); return (mWorksInfoList.size() - currentLength); } /** * 将数据添加到底部,需要在主线程中调用 * * @param worksInfoList */ @Override public int addWorksTail(final List<WorksInfo> worksInfoList) { Log.v(TumccaApplication.TAG, "WorkListFragment addWorksTail"); if(worksInfoList!=null&&worksInfoList.size()!=0){ mContext.runOnUiThread(new Runnable() { @Override public void run() { mWorksInfoList.addAll(worksInfoList); mAdapter.setWorks(mWorksInfoList); mAdapter.notifyDataSetChanged(); } }); parseWorks(mWorksInfoList); mContext.runOnUiThread(new Runnable() { @Override public void run() { mAdapter.setWorks(mWorksInfoList); mAdapter.notifyDataSetChanged(); } }); return worksInfoList.size(); } else{ setEnd(true); return 0; } } /** * 将数据添加到底部,需要在主线程中调用 * 清空数据 */ public void clearWorks() { mIsEnd = false; mContext.runOnUiThread(new Runnable() { @Override public void run() { mWorksInfoList.clear(); mAdapter.notifyDataSetChanged(); if (null != mWorksLoader) { mProgressBar.setVisibility(View.VISIBLE); mWorksLoader.loadHeadWorks(); } } }); } @Override public void addWorksListView(View view) { mListView = (StaggeredGridView) view; mFooterProgressView = mContext.getLayoutInflater().inflate(R.layout.progressbar, null); mListView.addFooterView(mFooterProgressView); mListView.setAdapter(mAdapter); mListView.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { switch (scrollState) { case AbsListView.OnScrollListener.SCROLL_STATE_IDLE: mImageLoader.resume(); mScrollingIdle = true; break; case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL: mImageLoader.pause(); mScrollingIdle = false; break; case AbsListView.OnScrollListener.SCROLL_STATE_FLING: mScrollingIdle = false; break; } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { Log.v(TumccaApplication.TAG, "onScroll " + visibleItemCount + " " + firstVisibleItem + " " + totalItemCount); if (visibleItemCount + firstVisibleItem == totalItemCount && !mIsEnd) { if (null != mWorksLoader) { mScrollingIdle = false; Log.v(TumccaApplication.TAG, "loadTailWorks"); mWorksLoader.loadTailWorks(++mCurrentPage); } } } }); if (null != mWorksLoader) { final List<WorksInfo> worksInfoList = mWorksLoader.getInitialWorks(); if (null != worksInfoList) { mContext.runOnUiThread(new Runnable() { @Override public void run() { mWorksInfoList.clear(); mWorksInfoList.addAll(worksInfoList); mAdapter.setWorks(mWorksInfoList); mAdapter.notifyDataSetChanged(); } }); } } } @Override public void openWorks(WorksInfo calligraphy) { WorkDetailActivity.startActivity(calligraphy, mContext); } @Override public void openAuthor(int authorId) { UserActivity.startActivity(mContext, authorId); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if(null!=savedInstanceState){ restoreState(savedInstanceState); } View view = inflater.inflate(R.layout.fragment_work_list, container, false); mProgressBar = (CircleProgressBar) view.findViewById(R.id.progressBar); StaggeredGridView listView = (StaggeredGridView) view.findViewById(R.id.list); addWorksListView(listView); mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container); mSwipeRefreshLayout.setColorSchemeResources(R.color.button_normal_red); mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { if (null != mWorksLoader) { mWorksLoader.loadHeadWorks(); } mSwipeRefreshLayout.setRefreshing(false); } }); setupProgressBar(); return view; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); //outState.putInt("parentWidth", mParentWidth); //缓存Works列表 JSONArray worksArray = new JSONArray(); for(WorksInfo worksInfo:mWorksInfoList){ worksArray.put(WorksInfo.toJSON(worksInfo)); } outState.putString("works", worksArray.toString()); //缓存当前页 outState.putInt("currentPage", mCurrentPage); //缓存是否到底 outState.getBoolean("isEnd", mIsEnd); } @Override public void onViewStateRestored(Bundle savedInstanceState) { super.onViewStateRestored(savedInstanceState); if(null!=savedInstanceState){ restoreState(savedInstanceState); } // if (null != savedInstanceState) { // try { // mWorksInfoList.reload(); // JSONArray worksArray = new JSONArray(savedInstanceState.getString("works")); // for(int i=0; i<worksArray.length(); i++){ // WorksInfo worksInfo = WorksInfo.fromJSON(worksArray.getJSONObject(i)); // mWorksInfoList.add(worksInfo); // } // } catch (JSONException e) { // e.printStackTrace(); // } // // mCurrentPage = savedInstanceState.getInt("currentPage"); // // mIsEnd = savedInstanceState.getBoolean("isEnd"); // } } private void restoreState(Bundle savedInstanceState){ Log.v(TumccaApplication.TAG, "restoreState"); try { mWorksInfoList.clear(); JSONArray worksArray = new JSONArray(savedInstanceState.getString("works")); for(int i=0; i<worksArray.length(); i++){ WorksInfo worksInfo = WorksInfo.fromJSON(worksArray.getJSONObject(i)); mWorksInfoList.add(worksInfo); } } catch (JSONException e) { e.printStackTrace(); } mCurrentPage = savedInstanceState.getInt("currentPage"); mIsEnd = savedInstanceState.getBoolean("isEnd"); } private void setupProgressBar() { mProgressBar.setShowArrow(true); if (null != mWorksLoader && mWorksLoader.getInitialWorks() == null && mWorksInfoList.size() == 0) { mWorksLoader.loadHeadWorks(); } else { mProgressBar.setVisibility(View.GONE); mSwipeRefreshLayout.setVisibility(View.VISIBLE); } } private void parseWorks(final List<WorksInfo> worksInfoList) { if (null != worksInfoList) { for (int i = 0; i < worksInfoList.size(); i++) { if (!mMapProfile.containsKey(worksInfoList.get(i).author)) { Profile profile = UserManager.getInstance().getUserProfile(worksInfoList.get(i).author); worksInfoList.get(i).profile = profile; mMapProfile.put(worksInfoList.get(i).author, profile); } else { worksInfoList.get(i).profile = mMapProfile.get(worksInfoList.get(i).author); } } } } private void setEnd(boolean isEnd) { mIsEnd = isEnd; if (mIsEnd) { mContext.runOnUiThread(new Runnable() { @Override public void run() { mListView.removeFooterView(mFooterProgressView); } }); } } // public void applyListviewHeightWithChild(){ // int listViewHeightLeft = 0; // int listViewHeightRight = 0; // int adaptCount = mAdapter.getCount(); // for(int i=0;i<adaptCount;i=i+2){ // View viewLeft = mAdapter.getView(i, null, null); // viewLeft.measure(0,0); // listViewHeightLeft += viewLeft.getMeasuredHeight(); // Log.v(TumccaApplication.TAG, "BaseListFragment:applyListviewHeightWithChild:HeightLeft=" + listViewHeightLeft); // // if((i+1)<mAdapter.getCount()){ // View viewRight = mAdapter.getView(i, null, null); // viewRight.measure(0,0); // listViewHeightRight += viewRight.getMeasuredHeight(); // Log.v(TumccaApplication.TAG, "BaseListFragment:applyListviewHeightWithChild:HeightRight=" + listViewHeightLeft); // } // } // ViewGroup.LayoutParams layoutParams = this.mListView.getLayoutParams(); // layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT; // // //int expandSpec = View.MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, View.MeasureSpec.AT_MOST); // //super.onMeasure(widthMeasureSpec, expandSpec); // layoutParams.height = Math.max(listViewHeightLeft, listViewHeightRight); // mListView.setLayoutParams(layoutParams); // } }
package com.ha.cn.service.impl; import com.baomidou.mybatisplus.service.impl.ServiceImpl; import com.ha.cn.dao.CustomerTypeMapper; import com.ha.cn.dao.UserMapper; import com.ha.cn.model.CustomerType; import com.ha.cn.model.Users; import com.ha.cn.model.UsersPage; import com.ha.cn.service.ICustomerTypeService; import com.ha.cn.service.IUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * @program: wisdomside * @description: CustomerTypeServiceImpl * @author: zan.Kang * @crate: 2018-04-06 16:54 **/ @Service public class CustomerTypeServiceImpl extends ServiceImpl<CustomerTypeMapper,CustomerType> implements ICustomerTypeService { }
package pwr.chrzescijanek.filip.gifa.core.function.rgb.mean; import org.opencv.core.Mat; import pwr.chrzescijanek.filip.gifa.core.function.EvaluationFunction; import static pwr.chrzescijanek.filip.gifa.core.util.FunctionUtils.calculateMeans; /** * Provides method to calculate green mean. */ public final class MeanGreen implements EvaluationFunction { /** * Default constructor. */ public MeanGreen() {} @Override public double[] evaluate(final Mat[] images) { return calculateMeans(images, 1); } }
package com.github.vboiko.dropwizard.docs.core; import com.google.common.base.CharMatcher; import com.google.common.base.Preconditions; import com.github.vboiko.dropwizard.docs.model.PageInfo; import org.reflections.Reflections; import org.reflections.scanners.ResourcesScanner; import java.io.IOException; import java.util.Set; import io.dropwizard.Application; public class ContentCrawler { private static final CharMatcher SLASHES = CharMatcher.is('/'); private final String contentDir; private final ContentStore contentStore; private final ContentParser contentParser; public ContentCrawler(String contentDir, ContentStore contentStore, Class<? extends Application> appClass) { Preconditions.checkArgument(contentDir.startsWith("/"), "%s is not an absolute path", contentDir); Preconditions.checkArgument(!"/".equals(contentDir), "%s is the classpath root", contentDir); this.contentDir = SLASHES.trimLeadingFrom(contentDir); this.contentStore = contentStore; this.contentParser = new ContentParser(appClass); } public void crawl() throws IOException { Reflections reflections = new Reflections(contentDir, new ResourcesScanner()); Set<String> resourceList = reflections.getResources(str -> true); Set<PageInfo> pageInfos = contentParser.parse(resourceList); pageInfos .stream() .forEach(pageInfo -> contentStore.put(pageInfo.getPermalink(), pageInfo)); } }
package pl.webartists.sms2clipboard.plugins; import java.util.Iterator; import java.util.Map; import org.apache.cordova.api.CallbackContext; import org.apache.cordova.api.CordovaPlugin; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.util.Log; public class Settings extends CordovaPlugin { private String TAG = this.getClass().getName(); SharedPreferences settings; @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { Context context = cordova.getActivity().getApplicationContext(); settings = context.getSharedPreferences("settings", context.MODE_PRIVATE); Log.i(TAG, action); if (action.equals("getAll")) { getAll(callbackContext); return true; } if (action.equals("setAll")) { Log.i(TAG, args.getJSONObject(0).toString()); setAll(callbackContext, args.getJSONObject(0)); return true; } return false; } private void getAll( CallbackContext callbackContext ) { Log.d(TAG, this.toString()); try { JSONObject settingsJson = new JSONObject(settings.getAll()); Log.i( TAG, settingsJson.toString() ); callbackContext.success(settingsJson); } catch( Exception exception ) { Log.e(TAG, "exception", exception); callbackContext.error( exception.getMessage() ); } } private void setAll( CallbackContext callbackContext, JSONObject settingsJson ) { Log.i(TAG, settingsJson.toString()); try { Editor settingsEditor = settings.edit(); Iterator<?> iterator = settingsJson.keys(); while( iterator.hasNext() ) { String key = (String)iterator.next(); Object value = settingsJson.get(key); Log.i(TAG , "Settings update: " + key + " = " + value.toString()); Log.i(TAG, "isBoolean?"); if( value instanceof Boolean) { Log.i(TAG, "yes it is boolean"); settingsEditor.putBoolean(key, (Boolean)value); } Log.i(TAG, "isString?"); if( value instanceof String) { Log.i(TAG, "yes it is string"); settingsEditor.putString(key, (String)value); } Log.i(TAG, "isInt?"); if( value instanceof Integer) { Log.i(TAG, "yes it is int"); settingsEditor.putInt(key, (Integer)value); } } settingsEditor.commit(); callbackContext.success(settingsJson); } catch( Exception exception ) { Log.e(TAG, "exception", exception); callbackContext.error( exception.getMessage() ); } } }
package com.bandtec.alprime; import com.bandtec.alprime.imoveis.Aluguel; import com.bandtec.alprime.imoveis.Imovel; import java.util.ArrayList; import java.util.List; import java.util.Objects; public class Cliente { private Integer idCliente; private String nome; private String email; private String senha; private List<Imovel> listaImoveis; public Cliente(Integer idCliente, String nome, String email, String senha, String tipo) { this.listaImoveis = new ArrayList<>(); this.idCliente = idCliente; this.nome = nome; this.email = email; this.senha = senha; } public String adquirirImovel(Imovel imovel) { listaImoveis.add(imovel); return "Imovel adicionado com sucesso"; } public String calcularImpostoTotal() { Double total = 0.0; for (Imovel imovel : listaImoveis) { total += imovel.calcularImposto(); } return "Você deve pagar ao governo " + total + " reais"; } public String calcularAluguelTotal() { Double total = 0.0; for (Imovel imovel : listaImoveis) { if (imovel instanceof Aluguel) { total += ((Aluguel) imovel).calcularPrecoAluguel(); } } return "Você deve todo mês de aluguel " + total + " reais"; } @Override public String toString() { return "Cliente{" + "idCliente=" + idCliente + ", nome='" + nome + '\'' + ", email='" + email + '\'' + ", senha='" + senha + '\'' + ", Lista de imoveis='" + listaImoveis + '\'' + '}'; } public Integer getIdCliente() { return idCliente; } public void setIdCliente(Integer idCliente) { this.idCliente = idCliente; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getSenha() { return senha; } public void setSenha(String senha) { this.senha = senha; } public List<Imovel> getListaImoveis() { return listaImoveis; } public void setListaImoveis(List<Imovel> listaImoveis) { this.listaImoveis = listaImoveis; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Cliente cliente = (Cliente) o; return Objects.equals(idCliente, cliente.idCliente) && Objects.equals(nome, cliente.nome) && Objects.equals(email, cliente.email) && Objects.equals(senha, cliente.senha); } @Override public int hashCode() { return Objects.hash(idCliente, nome, email, senha); } }
package com.thomaster.ourcloud.repositories.file; import com.thomaster.ourcloud.model.user.OCUser; import org.hibernate.annotations.Type; import javax.persistence.*; import java.util.Objects; @Entity @Inheritance(strategy=InheritanceType.SINGLE_TABLE) abstract class PersistentFileSystemElement { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Type(type = "com.thomaster.ourcloud.repositories.file.LTreeType") @Column(columnDefinition="ltree") private String relativePath; private String originalName; @ManyToOne(fetch = FetchType.EAGER) private OCUser owner; private String parentFolderPath; private long fileSize; PersistentFileSystemElement() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getRelativePath() { return relativePath; } public void setRelativePath(String relativePath) { this.relativePath = relativePath; } public String getOriginalName() { return originalName; } public void setOriginalName(String originalName) { this.originalName = originalName; } public OCUser getOwner() { return owner; } public void setOwner(OCUser owner) { this.owner = owner; } public String getParentFolderPath() { return parentFolderPath; } public void setParentFolderPath(String parentFolderPath) { this.parentFolderPath = parentFolderPath; } public long getFileSize() { return fileSize; } public void setFileSize(long fileSize) { this.fileSize = fileSize; } @Override public String toString() { return "FileSystemElement{" + "originalName='" + originalName + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PersistentFileSystemElement that = (PersistentFileSystemElement) o; return relativePath.equals(that.relativePath); } @Override public int hashCode() { return Objects.hash(relativePath); } }
package ch2.sub2.applefilter; public class AppleHeavyWeightPredicate implements ApplePredicate{ @Override public boolean test(Apple apple) { return apple.getWight() > 150; } }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2011.12.21 at 11:35:30 AM MSK // package com.espendwise.tools.gencode.dbxml; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.namespace.QName; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the generated package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { private final static QName _Database_QNAME = new QName("", "database"); /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: generated * */ public ObjectFactory() { } /** * Create an instance of {@link FKeyRef } * */ public FKeyRef createFKeyRef() { return new FKeyRef(); } /** * Create an instance of {@link FKey } * */ public FKey createFKey() { return new FKey(); } /** * Create an instance of {@link ColumnRef } * */ public ColumnRef createColumnRef() { return new ColumnRef(); } /** * Create an instance of {@link Column } * */ public Column createColumn() { return new Column(); } /** * Create an instance of {@link Table } * */ public Table createTable() { return new Table(); } /** * Create an instance of {@link Sequence } * */ public Sequence createSequence() { return new Sequence(); } /** * Create an instance of {@link Index } * */ public Index createIndex() { return new Index(); } /** * Create an instance of {@link Database } * */ public Database createDatabase() { return new Database(); } /** * Create an instance of {@link PrimaryKey } * */ public PrimaryKey createPrimaryKey() { return new PrimaryKey(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link Database }{@code >}} * */ @XmlElementDecl(namespace = "", name = "database") public JAXBElement<Database> createDatabase(Database value) { return new JAXBElement<Database>(_Database_QNAME, Database.class, null, value); } }
package com.jiuzhe.app.hotel.control; import com.jiuzhe.app.hotel.constants.CommonConstant; import com.jiuzhe.app.hotel.dto.FeedbackDto; import com.jiuzhe.app.hotel.dto.OrderScoreDto; import com.jiuzhe.app.hotel.dto.ResponseBase; import com.jiuzhe.app.hotel.service.FeedbackService; import io.swagger.annotations.ApiParam; import org.bouncycastle.crypto.tls.MACAlgorithm; import org.springframework.beans.factory.annotation.Autowired; 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 java.util.List; import java.util.Map; /** * @Description:用户反馈control */ @RestController @RequestMapping("/userfeedback") public class FeedbackControl { @Autowired private FeedbackService feedbackService; @PostMapping public ResponseBase<Map<String, String>> saveUserFeedback( @ApiParam(name = "feedback", value = "反馈数据") @RequestBody() FeedbackDto dto ) { ResponseBase<Map<String, String>> res = new ResponseBase<>(); int result = feedbackService.saveFeedback(dto); res.setStatus(result); if (CommonConstant.SUCCESS != result) { res.setMessage(CommonConstant.FAILED); } return res; } /** * @Description:获取门店下面的订单评分 * @author: 郑鹏宇 * @date 2018/8/29/029 */ @PostMapping("/orderscore") public ResponseBase getOrderScoreByStoreId(@RequestBody Map<String, String> map) { ResponseBase responseBase = new ResponseBase(); String storeId = map.get("storeId"); try { List<OrderScoreDto> dtos = feedbackService.getOrderScoreByStoreId(storeId); responseBase.setStatus(CommonConstant.SUCCESS); responseBase.setData(dtos); } catch (Exception e) { responseBase.setStatus(CommonConstant.FAIL); } return responseBase; } /** * @Description:获取房间评分 * @author: 郑鹏宇 * @date 2018/8/29/029 */ @PostMapping("/skuscore") public ResponseBase getSkuScoreByStoreId(@RequestBody Map<String, String> map) { ResponseBase responseBase = new ResponseBase(); String storeId = map.get("storeId"); try { List<OrderScoreDto> dtos = feedbackService.getSkuScoreByStoreId(storeId); responseBase.setStatus(CommonConstant.SUCCESS); responseBase.setData(dtos); } catch (Exception e) { responseBase.setStatus(CommonConstant.FAIL); } return responseBase; } }
package com.android.medicaladvisor.categories; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import android.widget.Toast; import com.android.medicaladvisor.Injection; import com.android.medicaladvisor.R; import com.android.medicaladvisor.backend.RetrievingRepository; import com.android.medicaladvisor.initialsymptoms.InitialSymptomScreen; import com.android.medicaladvisor.models.Category; import java.util.ArrayList; import androidx.appcompat.app.AppCompatActivity; public class SelectCategoryScreen extends AppCompatActivity implements RetrievingRepository.RetrievingRepositoryCallback<Category> { private CategoriesPresenter presenter; private Button nextButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_categories); nextButton = findViewById(R.id.next_button); SharedPreferences sharedPreferences = getSharedPreferences(getString(R.string.app_name), Context.MODE_PRIVATE); presenter = new CategoriesPresenter(Injection.provideCategoriesRepository(), Injection.provideDiagnosisSharedPref(sharedPreferences)); presenter.retrieveCategories(this); } private void initializeCategoriesSpinner(final ArrayList<Category> categories) { ArrayAdapter<String> categoriesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_expandable_list_item_1); for (Category category : categories) { categoriesAdapter.add(category.getName()); } Spinner categoriesSpinner = findViewById(R.id.categories_spinner); categoriesSpinner.setAdapter(categoriesAdapter); categoriesSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { Category selectedCategory = categories.get(position); presenter.setDiagnosisCategory(selectedCategory); nextButton.setEnabled(true); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } public void onBackClicked(View view) { onBackPressed(); } public void onNextClicked(View view) { startActivity(new Intent(this, InitialSymptomScreen.class)); } @Override public void onRetrievingDataSuccessfully(ArrayList<Category> list) { initializeCategoriesSpinner(list); } @Override public void onRetrievingDataFailed(String errmsg) { Toast.makeText(this, errmsg, Toast.LENGTH_LONG).show(); } }
class Solution { public int findMaxLength(int[] nums) { //a counter : when 0, counter -1 ; when 1, counter + 1 // when the counter exists in map, the subarray between the map.get(counter) and i has same number of 0 and 1 //map.put(counter, i) HashMap<Integer, Integer> map = new HashMap<>(); map.put(0, -1); int counter = 0; int maxLength = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] == 0) counter--; else counter++; if (map.containsKey(counter)) { maxLength = Math.max(maxLength, i - map.get(counter)); } else { map.put(counter, i); } } return maxLength; } }
package pl.dostrzegaj.soft.flicloader; import java.util.Scanner; import org.scribe.model.Token; import org.scribe.model.Verifier; import com.flickr4java.flickr.Flickr; import com.flickr4java.flickr.FlickrException; import com.flickr4java.flickr.REST; import com.flickr4java.flickr.auth.Auth; import com.flickr4java.flickr.auth.AuthInterface; import com.flickr4java.flickr.auth.Permission; import com.google.common.base.Throwables; class FlickrAuthImpl implements AuthWrapper { private Flickr f; public FlickrAuthImpl(String apiKey, String secret) { f = new Flickr(apiKey, secret, new REST()); } @Override public UserAccount authorise(String token, String tokenSecret) { AuthInterface authInterface = f.getAuthInterface(); Token requestToken = new Token(token, tokenSecret); try { Auth auth = authInterface.checkToken(requestToken); System.out.println("Authentication success"); return new FlickrAccountImpl(f,auth); } catch (FlickrException e) { throw Throwables.propagate(e); } } @Override public Token authoriseNewToken() { AuthInterface authInterface = f.getAuthInterface(); Token token = authInterface.getRequestToken(); String authorizationUrl = authInterface.getAuthorizationUrl(token, Permission.WRITE); System.out.println("Follow this URL to authorise yourself on Flickr"); System.out.println(authorizationUrl); System.out.println("Paste in the token it gives you:"); System.out.print(">>"); try (Scanner scanner = new Scanner(System.in)) { String tokenKey = scanner.nextLine(); Token accessToken = authInterface.getAccessToken(token, new Verifier(tokenKey)); return accessToken; } } }
package país; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.List; import java.util.ArrayList; public class PaísDBRepository implements PaísRepository { private Connection getConnection() { String url = "url aqui"; String user = "usuario"; String password = "senha"; try { Connection conn = DriverManager.getConnection(url, user, password); return conn; } catch (Exception e) { e.printStackTrace(); return null; } } @Override public boolean save(País país) { try { Connection conn = getConnection(); String sql = "INSERT INTO país (id, nome, continente, população) VALUES (?,?,?,?)"; PreparedStatement pstm = conn.prepareStatement(sql); pstm.setInt(1, país.getId()); pstm.setString(2, país.getNome()); pstm.setString(3, país.getContinente()); pstm.setInt(4, país.getPopulação()); pstm.executeUpdate(); conn.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } } @Override public boolean update(País país) { try { String sql = "UPDATE produto SET nome=?, continente=?, população=? WHERE id=?"; Connection conn = getConnection(); PreparedStatement pstm = conn.prepareStatement(sql); pstm.setString(1, país.getNome()); pstm.setString(2, país.getContinente()); pstm.setInt(3, país.getPopulação()); pstm.setInt(4, país.getId()); int rowsUpdated = pstm.executeUpdate(); if (rowsUpdated > 0) { System.out.println("Um país existente foi atualizado com sucesso"); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } @Override public boolean delete(País país) { try { Connection conn = getConnection(); String sql = "DELETE FROM país WHERE id=?"; PreparedStatement pstm = conn.prepareStatement(sql); pstm.setInt(1, país.getId()); pstm.executeUpdate(); conn.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } } @Override public País get(int id) { try { País resposta = new País(); Connection conn = getConnection(); String sql = "SELECT * FROM país WHERE id=?"; PreparedStatement pstm = conn.prepareStatement(sql); pstm.setInt(1, id); ResultSet rs = pstm.executeQuery(); if (!rs.next()) { return null; } resposta.setId(id); resposta.setNome(rs.getString("nome")); resposta.setContinente(rs.getString("continente")); resposta.setPopulação(rs.getInt("população")); conn.close(); return resposta; } catch (Exception e) { e.printStackTrace(); return null; } } @Override public List<País> getAll() { try { ArrayList<País> paises = new ArrayList(); País resposta = new País(); Connection conn = getConnection(); String sql = ("SELECT * FROM país"); PreparedStatement pstm = conn.prepareStatement(sql); ResultSet rs = pstm.executeQuery(); while (rs.next()) { resposta.setId(rs.getInt("id")); resposta.setNome(rs.getString("nome")); resposta.setContinente(rs.getString("continente")); resposta.setPopulação(rs.getInt("população")); paises.add(resposta); } conn.close(); return paises; } catch (Exception e) { e.printStackTrace(); return null; } } }
package com.appdirect.model.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.appdirect.model.entity.AccountEntity; @Repository public interface AccountRepository extends JpaRepository<AccountEntity, String> { AccountEntity findById(String id); }
package com.design.pattern.factoryMethed; /** * @author zhangbingquan * @desc 小米电视机实现类 * @time 2019/7/27 23:33 */ public class XiaomiTv implements Tv { @Override public void play() { System.out.println("小米电视机正在播放"); } }
package com.tencent.mm.ak; import com.tencent.mm.ab.e; import com.tencent.mm.ab.f; import com.tencent.mm.ab.l; import com.tencent.mm.kernel.g; import com.tencent.mm.sdk.platformtools.x; import java.util.HashSet; import java.util.LinkedList; import java.util.List; public final class d implements e, f { b dTA = null; private k dTB = null; public boolean dTC = false; List<b> dTy = new LinkedList(); private HashSet<b> dTz = new HashSet(); public d() { g.Eh().dpP.a(109, (e) this); } public final boolean a(long j, long j2, int i, Object obj, int i2, a aVar) { return a(j, j2, i, obj, i2, aVar, -1) >= 0; } public final int a(long j, long j2, int i, Object obj, int i2, a aVar, int i3) { if (aVar == null) { x.e("ModelImage.DownloadImgService", "listener is null"); return -1; } b bVar = new b(j, j2, i); bVar.dTG = i2; if (this.dTz.contains(bVar)) { x.e("ModelImage.DownloadImgService", "[" + aVar.hashCode() + "] add failed, task already done"); return -2; } else if (this.dTA != null && bVar.equals(this.dTA)) { return this.dTA.a(aVar, obj) ? 0 : -3; } else { int indexOf = this.dTy.indexOf(bVar); if (indexOf >= 0 && indexOf < this.dTy.size()) { return ((b) this.dTy.get(indexOf)).a(aVar, obj) ? 0 : -4; } else { x.i("ModelImage.DownloadImgService", "[" + aVar.hashCode() + "] no found task, create a new task(" + j + " " + j2 + " " + i + ") mLockStart: %s callbackDuration %s", Boolean.valueOf(this.dTC), Integer.valueOf(i3)); bVar.a(aVar, obj); this.dTy.add(bVar); hI(i3); return 0; } } } public final boolean a(long j, long j2, int i) { b bVar = new b(j, j2, i); if ((this.dTA == null || !this.dTA.equals(bVar)) && this.dTy.indexOf(bVar) < 0) { return false; } return true; } public final boolean a(long j, long j2, a aVar) { if (aVar == null) { x.e("ModelImage.DownloadImgService", "listener is null"); return false; } b bVar = new b(j, j2, 1); b bVar2 = null; if (this.dTA == null || !this.dTA.equals(bVar)) { int indexOf = this.dTy.indexOf(bVar); if (-1 != indexOf) { bVar2 = (b) this.dTy.get(indexOf); } } else { bVar2 = this.dTA; } if (bVar2 != null) { bVar2.b(aVar); a(bVar2); x.i("ModelImage.DownloadImgService", "[" + aVar.hashCode() + "] task has been canceled, (" + j + ", " + j2 + ", 1)"); return true; } x.e("ModelImage.DownloadImgService", "[" + aVar.hashCode() + "] task no found, (" + j + ", " + j2 + ", 1)"); return false; } public final void a(a aVar) { if (aVar == null) { x.e("ModelImage.DownloadImgService", "listener is null"); return; } String str; String str2; Object[] objArr; b bVar; x.i("ModelImage.DownloadImgService", "[" + aVar.hashCode() + "] cancel all tasks of listener"); this.dTC = true; if (this.dTA != null) { String str3; str = "ModelImage.DownloadImgService"; str2 = "cancelAllTaskByListener CurTaskInfo %s mTodoList %s mLockStart %s"; objArr = new Object[3]; if (this.dTA == null) { str3 = "mCurTaskInfo is null"; } else { str3 = this.dTA.dTD + ", " + this.dTA.dTE + ", " + this.dTA.dTF; } objArr[0] = str3; objArr[1] = Integer.valueOf(this.dTy.size()); objArr[2] = Boolean.valueOf(this.dTC); x.i(str, str2, objArr); this.dTA.b(aVar); bVar = this.dTA; if (bVar.dTH != null) { bVar.dTH.clear(); } a(this.dTA); } List<b> linkedList = new LinkedList(); for (b bVar2 : this.dTy) { linkedList.add(bVar2); } for (b bVar22 : linkedList) { bVar22.b(aVar); a(bVar22); } OL(); str = "ModelImage.DownloadImgService"; str2 = "[ %s ] cancelAllTaskByListener done mCurTaskInfo %s"; objArr = new Object[2]; objArr[0] = Integer.valueOf(aVar.hashCode()); objArr[1] = this.dTA == null ? "mCurTaskInfo is null" : this.dTA.dTD + ", " + this.dTA.dTE + ", " + this.dTA.dTF; x.i(str, str2, objArr); } private boolean a(b bVar) { if (bVar == null || bVar.dTH.size() > 0) { return false; } return b(bVar); } public final boolean l(long j, long j2) { return b(new b(j, j2, 1)); } final boolean b(b bVar) { if (bVar == null) { x.e("ModelImage.DownloadImgService", "task is null"); return false; } x.i("ModelImage.DownloadImgService", "cancel scene, (" + bVar.dTD + ", " + bVar.dTE + ", " + bVar.dTF + ")"); if (this.dTA != null && this.dTA.equals(bVar)) { g.Eh().dpP.c(this.dTB); this.dTB = null; x.i("ModelImage.DownloadImgService", "cancelNetScene reset curTaskInfo (%s %s %s)", Long.valueOf(bVar.dTD), Long.valueOf(bVar.dTE), Integer.valueOf(bVar.dTF)); c(this.dTA); this.dTA = null; hI(-1); return true; } else if (!this.dTy.contains(bVar)) { return false; } else { b bVar2 = (b) this.dTy.get(this.dTy.indexOf(bVar)); if (bVar2 != null) { this.dTy.remove(bVar2); c(bVar2); } return true; } } private static void c(b bVar) { if (bVar == null) { x.e("ModelImage.DownloadImgService", "task is null"); } else if (bVar.dTH == null) { x.e("ModelImage.DownloadImgService", "task callback list is null"); } else { for (c cVar : bVar.dTH) { if (cVar.dTI != null) { cVar.dTI.a(bVar.dTD, bVar.dTE, bVar.dTF, bVar.dTG, cVar.dTJ); } } } } public final void OL() { this.dTC = false; hI(-1); } public final void a(int i, int i2, String str, l lVar) { if (this.dTB != lVar) { x.d("ModelImage.DownloadImgService", "scene changed"); return; } this.dTz.add(new b(this.dTA.dTD, this.dTA.dTE, this.dTA.dTF)); x.i("ModelImage.DownloadImgService", "scene end, (" + this.dTA.dTD + ", " + this.dTA.dTE + ", " + this.dTA.dTF + ")"); for (c cVar : this.dTA.dTH) { if (cVar.dTI != null) { cVar.dTI.a(this.dTA.dTD, this.dTA.dTE, this.dTA.dTF, this.dTA.dTG, cVar.dTJ, i, i2, str, lVar); } } this.dTA = null; this.dTB = null; hI(-1); } public final void a(int i, int i2, l lVar) { if (this.dTB != lVar) { x.d("ModelImage.DownloadImgService", "scene changed"); return; } for (c cVar : this.dTA.dTH) { if (cVar.dTI != null) { cVar.dTI.a(this.dTA.dTD, this.dTA.dTE, this.dTA.dTF, this.dTA.dTG, cVar.dTJ, i, i2, lVar); } } } private void hI(int i) { if (this.dTA != null || this.dTy.size() <= 0 || true == this.dTC) { String str = "ModelImage.DownloadImgService"; String str2 = "mCurTaskInfo %s mTodoList %s mLockStart %s"; Object[] objArr = new Object[3]; objArr[0] = this.dTA == null ? "mCurTaskInfo is null" : this.dTA.dTD + ", " + this.dTA.dTE + ", " + this.dTA.dTF; objArr[1] = Integer.valueOf(this.dTy.size()); objArr[2] = Boolean.valueOf(this.dTC); x.i(str, str2, objArr); return; } this.dTA = (b) this.dTy.get(0); this.dTy.remove(0); this.dTB = new k(this.dTA.dTD, this.dTA.dTE, this.dTA.dTF, this, i); this.dTB.dVo = this.dTA.dTG; x.i("ModelImage.DownloadImgService", "do scene, (" + this.dTA.dTD + ", " + this.dTA.dTE + ", " + this.dTA.dTF + ")"); g.Eh().dpP.a(this.dTB, 0); } }
package com.tencent.mm.plugin.fts.b; import com.tencent.mm.kernel.g; import com.tencent.mm.plugin.fts.PluginFTS; import com.tencent.mm.plugin.fts.a.a.a; import com.tencent.mm.plugin.fts.a.c; import java.util.List; class b$d extends a { final /* synthetic */ b jum; private String path; public b$d(b bVar, String str) { this.jum = bVar; this.path = str; } public final String getName() { return "UpdateFeatureIndexTask"; } public final boolean execute() { List CF = b.CF(this.path); this.jum.juk.beginTransaction(); this.jum.juk.bl(CF); this.jum.juk.commit(); this.jum.juk.k(c.jqe); this.jum.dhW.a(131132, new b.a(this.jum, (byte) 0)); e topHitsLogic = ((PluginFTS) g.n(PluginFTS.class)).getTopHitsLogic(); topHitsLogic.juO.e(c.jqe, 1); return true; } }
package com.fc.common; import android.os.Environment; public class Constant { // public static String ImgPath = "http://192.168.10.86/"; // public static String STM_WEBSERVICE_URL_dx = "http://192.168.10.86:8000//ws/services/zdgl_kdg_fc_u_getdata_web?wsdl"; // 测试换 public static String STM_WEBSERVICE_URL_dx = "http://115.28.55.47:7001/ws/services/zdgl_kdg_fc_u_getdata_web?wsdl"; // 正式环境 public static String ImgPath = "http://115.28.55.47/"; public static String AppName = "kdgfc.apk"; public static String PackageName = "com.fc"; public static String STM_NAMESPACE = "http://zdgl_kdg_fc"; public static final int NETWORK_ERROR = 1; public static final int SUCCESS = 2; public static final int FAIL = 3; public static final int DOWNLOAD_FAIL = 4; public static final int SUBMIT_SUCCESS = 5; public static final int NUM_6 = 6; public static final int NUM_7 = 7; public static final int NUM_8 = 8; public static final int NUM_9 = 9; public static final int NUM_10 = 10; public static final int NUM_11 = 11; public static final int NUM_12 = 12; public static final int NUM_13 = 13; public static final String NETWORK_ERROR_STR = "网络连接失败!"; public static final String SUCCESS_STR = "操作成功!"; public static final String SUBMIT_SUCCESS_STR = "提交成功!"; public static final String FAIL_STR = "操作失败!"; public static final String TIME_OUT = "操作超时!"; public static final String DOWNLOAD_FAIL_STR = "下载失败!"; public static String SAVE_PIC_PATH = Environment.getExternalStorageState() .equalsIgnoreCase(Environment.MEDIA_MOUNTED) ? Environment .getExternalStorageDirectory().getAbsolutePath() : "/mnt/sdcard";// 保存到SD卡; }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import Conexion.ConexionBD; import logica.CamaraComercio; import logica.CrediGas; import logica.CrediGasId; /** * Clase que permite realizar acciones sobre los creditos * sacados con el recio de gas * @author LEIDY * */ public class CrediGasDao{ /** * Método que permite almacenar un nuevo recibo de credigas * @param crediGas * @return */ public boolean guardaCrediGas(CrediGas crediGas){ try { Connection conn = ConexionBD.obtenerConexion(); String queryInsertar = "INSERT INTO credi_gas VALUES(?,?,?,?)"; PreparedStatement ppStm = conn.prepareStatement(queryInsertar); ppStm.setInt(1, crediGas.getId().getContratoGas()); ppStm.setInt(2, crediGas.getValorArticulo()); ppStm.setString(3, crediGas.getDetalleContratogas()); ppStm.setInt(4, crediGas.getId().getEGasNReciboGas()); ppStm.executeUpdate(); conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } return true; } /** * Método que permite actualizar la informacion * del credito de gas * @param crediGas * @return */ public boolean actualizaCrediGas(CrediGas crediGas){ try { Connection conn = ConexionBD.obtenerConexion(); String queryUpdate = "UPDATE credi_gas SET" + " Detalle_contratogas = ?, E_Gas_N_Recibo_Gas = ? " + "WHERE Contrato_Gas= ?"; PreparedStatement ppStm = conn.prepareStatement(queryUpdate); ppStm.setString(1, crediGas.getDetalleContratogas()); ppStm.setInt(2, crediGas.getId().getEGasNReciboGas()); ppStm.setInt(3, crediGas.getId().getContratoGas()); ppStm.executeUpdate(); conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } return true; } /** * Método que permite eliminar la informacion de crediGas * @param crediGas * @return */ public boolean eliminaCrediGas(CrediGas crediGas){ try { Connection conn = ConexionBD.obtenerConexion(); String queryDelete = "DELETE FROM credi_gas " + "WHERE Contrato_Gas = ?"; PreparedStatement ppStm = conn.prepareStatement(queryDelete); ppStm.setInt(1, crediGas.getId().getContratoGas()); ppStm.executeUpdate(); conn.close(); return true; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } } /** * Método que permite obtener la informacion de credigas * @param id * @return */ public CrediGas obtenCrediGas(CrediGasId id){ CrediGas crediGas = null; try { Connection conn = ConexionBD.obtenerConexion(); String querySearch = "SELECT FROM credi_gas " + "WHERE Contrato_Gas = ?"; PreparedStatement ppStm = conn.prepareStatement(querySearch); ppStm.setInt(1, id.getContratoGas()); ResultSet resultSet = ppStm.executeQuery(); if(resultSet.next()){ crediGas = new CrediGas(); crediGas.setId(new CrediGasId(resultSet.getInt(1), resultSet.getInt(4))); crediGas.setValorArticulo(resultSet.getInt(2)); crediGas.setDetalleContratogas(resultSet.getString(3)); }else{ return crediGas; } conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return crediGas; } public List<CrediGas> obtenListaCrediGas(){ List<CrediGas> listaCrediGas = null; return listaCrediGas; } // public static void main(String[] args) { // // GasDao daog = new GasDao(); // CrediGasDao daocg = new CrediGasDao(); // // Agregar // // daocg.guardaCrediGas(new CrediGas(new CrediGasId(8612035, 98745852), 450000, "Chimenea")); // // Actualizar // // daocg.actualizaCrediGas(new CrediGas(new CrediGasId(8612035, 98745852), 1200000,"chimenea a gas natural")); // // Eliminar // // daocg.eliminaCrediGas(new CrediGas(new CrediGasId(8612035, 98745852), 0, null)); // } }
package com.gtfs.service.impl; import java.io.Serializable; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import com.gtfs.bean.LicBranchHubPicMapping; import com.gtfs.bean.ProcessMst; import com.gtfs.dao.interfaces.LicBranchHubPicMappingDao; import com.gtfs.service.interfaces.LicBranchHubPicMappingService; @Service public class LicBranchHubPicMappingServiceImpl implements LicBranchHubPicMappingService,Serializable{ @Autowired private LicBranchHubPicMappingDao licBranchHubPicMappingDao; public List<Long> findHubIdForBranchIdByProcessName(Long branchId,String processName){ return licBranchHubPicMappingDao.findHubIdForBranchIdByProcessName(branchId, processName); } public List<LicBranchHubPicMapping> findSourceByIdTypeAndProcss(Long sourceId,String sourceType,ProcessMst processMst){ return licBranchHubPicMappingDao.findSourceByIdTypeAndProcss(sourceId, sourceType, processMst); } public List<LicBranchHubPicMapping> findDestinationByIdTypeAndProcss(Long sourceId,String sourceType,ProcessMst processMst){ return licBranchHubPicMappingDao.findDestinationByIdTypeAndProcss(sourceId, sourceType, processMst); } public Boolean saveForMapping(List<LicBranchHubPicMapping> list){ return licBranchHubPicMappingDao.saveForMapping(list); } @Override public List<Long> findHubIdForRnlDespatch(Long branchId) { return licBranchHubPicMappingDao.findHubIdForRnlDespatch(branchId); } }
package com.jiw.dudu.enums; import lombok.AllArgsConstructor; import lombok.Getter; import java.util.Arrays; /** * 厂商枚举类 */ @Getter @AllArgsConstructor public enum FirmEnum { ZONGHE_KEFU("zhkf","综合客服"), // XYK_GZH("xyk_gzh","信用卡公众号"), CRM("crm","CRM系统"); private String code; private String desc; /** * 枚举遍历和查找 * * @param code * @return */ public static FirmEnum getFirmEnum(String code){ return Arrays.stream(FirmEnum.values()).filter(x -> x.code.equalsIgnoreCase(code)).findFirst().orElse(null); } }
package TreadDemo01; /** * 静态方法的同步 * 当一个静态方法被synchronized修饰后,那么该方法即为同步方法,由于静态方法从属类, * 全局就一份,所以同步的静态方法一定具有同步效果(和对象没有关系), * synchronized也叫互斥锁 * @author Administrator * */ public class Thread_staticsyn { public static void main(String[] args) { final Foo f1 = new Foo(); final Foo f2 = new Foo(); Thread t1 = new Thread() { public void run() { f1.dosome();//和对象没有关系 } }; Thread t2 = new Thread() { public void run() { f2.dosome(); } }; t1.start(); t2.start(); } } class Foo{ public synchronized static void dosome() { try { Thread t = Thread.currentThread(); System.out.println(t.getName()+":"+"正在运行dosome()方法"); Thread.sleep(5000); System.out.println(t.getName()+":"+"dosome()方法运行完毕"); } catch (InterruptedException e) { e.printStackTrace(); } } }
package gr.athena.innovation.fagi.preview; import gr.athena.innovation.fagi.core.normalizer.SimpleLiteralNormalizer; import gr.athena.innovation.fagi.exception.ApplicationException; import gr.athena.innovation.fagi.specification.EnumDataset; import gr.athena.innovation.fagi.specification.Configuration; import gr.athena.innovation.fagi.specification.Namespace; import gr.athena.innovation.fagi.specification.SpecificationConstants; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /** * Calculates frequencies of words extracted from the literal of a given property. Expects RDF N-triples but treats the * input as plain text. * * @author nkarag */ public class FileFrequencyCounter implements FrequencyCounter { private static final Logger LOG = LogManager.getLogger(FileFrequencyCounter.class); private Locale locale; private List<String> properties; private final Configuration configuration; private final int frequentTopK; /** * Constructor of a file frequency counter object. * * @param frequentTopK the desired k top value. */ public FileFrequencyCounter(int frequentTopK) { this.configuration = Configuration.getInstance(); this.frequentTopK = frequentTopK; } /** * Exports the results under the "frequencies/" directory inside the output directory of the configuration. * Creates filenames based on the properties of the input file. * * @param inputFilename the input filename. Contains user defined RDF properties (with line breaks). The frequency results will be calculated only for these properties. * @param dataset the dataset id. */ @Override public void export(String inputFilename, EnumDataset dataset) { int index = 0; for (String property : properties) { StringBuilder prop = new StringBuilder(property); if (!property.startsWith("<")) { prop.insert(0, "<"); prop.insert(prop.length(), ">"); } String outputFilename = getFilename(property, index, inputFilename, dataset); if(property.equals(Namespace.NAME_VALUE_NO_BRACKETS)){ //nameValue property: Set the output result path of this property to be used in learning process. switch(dataset){ case LEFT: Configuration.getInstance().setPropertyFrequencyA(outputFilename); break; case RIGHT: Configuration.getInstance().setPropertyFrequencyB(outputFilename); break; } } File outputFile = new File(outputFilename); LOG.info("frequency file:" + outputFilename); PrintWriter pw = null; try { if (outputFile.exists()) { //clear contents pw = new PrintWriter(outputFile); pw.close(); } else { outputFile.getParentFile().mkdirs(); outputFile.createNewFile(); } writePropertyFrequency(prop, inputFilename, outputFilename); } catch (FileNotFoundException ex) { throw new ApplicationException(ex.getMessage()); } catch (IOException ex) { throw new ApplicationException(ex.getMessage()); } finally { if(pw != null){ pw.close(); } } } } private String getFilename(String property, int index, String inputFilename, EnumDataset dataset) throws ApplicationException { //Create a user friendly filename based on each property and input dataset. String filenamePrefix; if (property.lastIndexOf("#") != -1) { filenamePrefix = property.substring(property.lastIndexOf("#") + 1); } else if (property.lastIndexOf("/") != -1) { filenamePrefix = property.substring(property.lastIndexOf("/") + 1); } else { filenamePrefix = "_" + index; } String filenameTemp = inputFilename.substring(inputFilename.lastIndexOf("/") + 1); String filename; if(filenameTemp.indexOf('.') > -1){ filename = "_" + filenameTemp.substring(0, filenameTemp.lastIndexOf(".")); } else { filename = "_" + filenameTemp; } String filenameSuffix; switch(dataset){ case LEFT: filenameSuffix = SpecificationConstants.Config.FREQ_SUFFIX_A; break; case RIGHT: filenameSuffix = SpecificationConstants.Config.FREQ_SUFFIX_B; break; default: throw new ApplicationException("Wrong parameter for EnumDataset in Frequency export. " + "Only LEFT or RIGHT allowed."); } String outputFilename = configuration.getOutputDir() + "frequencies/" + filenamePrefix + filename + filenameSuffix; return outputFilename; } private void writePropertyFrequency(StringBuilder property, String inputFilename, String outputFilename) throws IOException { BufferedWriter writer = null; try { BufferedReader bufferedReader = new BufferedReader(new FileReader(inputFilename)); writer = new BufferedWriter(new FileWriter(outputFilename, true)); String line; String splitBy = "\\s+"; Frequency frequency = new Frequency(); while ((line = bufferedReader.readLine()) != null) { if(StringUtils.isBlank(line)){ continue; } String[] spl = line.split(splitBy); if (spl[1].contentEquals(property)) { String[] tokens = Arrays.copyOfRange(spl, 2, spl.length); String literal = String.join(" ", tokens); SimpleLiteralNormalizer normalizer = new SimpleLiteralNormalizer(); String bNorm = normalizer.normalize(literal, locale); String[] toks = tokenize(bNorm); frequency.insert(toks); } } Map<String, Integer> frequencyMap = frequency.getTopKFrequency(frequentTopK); //title with the name of the property writer.append("# " + property); writer.newLine(); for (String key : frequencyMap.keySet()) { String value = frequencyMap.get(key).toString(); String pair = key + "=" + value; writer.append(pair); writer.newLine(); } writer.close(); } catch (IOException | RuntimeException ex) { if (writer != null) { writer.close(); } throw new ApplicationException(ex.getMessage()); } } //tokenize on whitespaces private static String[] tokenize(final CharSequence text) { Validate.isTrue(StringUtils.isNotBlank(text), "Invalid text"); String[] split = text.toString().split("\\s+"); return split; } /** * Return the locale. * * @return the locale. */ public Locale getLocale() { return locale; } /** * Set the locale. * * @param locale the locale. */ public void setLocale(Locale locale) { this.locale = locale; } /** * Return the list with the defined properties as string values. * * @return the list of the RDF properties. */ public List<String> getProperties() { return properties; } /** * Set the list of RDF properties that will participate in the calculation. * * @param properties the RDF properties. */ public void setProperties(List<String> properties) { this.properties = properties; } }
package com.jack.jkbase.service.impl; import com.jack.jkbase.entity.SysRole; import com.jack.jkbase.mapper.SysRoleMapper; import com.jack.jkbase.service.ISysRoleService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** * <p> * 服务实现类 * </p> * * @author LIBO * @since 2020-09-23 */ @Service public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService { }
package ArrayList; public class FruitList { static int logicalSize = 5; public static void main(String[] args) { String fruit[] = new String[10]; fruit[0] = "Apple"; fruit[1] = "Banana"; fruit[2] = "Cherry"; fruit[3] = "Kiwi"; fruit[4] = "Pineapple"; showFruit(fruit); System.out.println("================"); //insert orange System.out.println("Inserting Orange"); int loc = findInsertPoint(fruit, "Orange"); insert(fruit, "Orange", loc); showFruit(fruit); System.out.println("================"); //insert strawberry and papaya System.out.println("Adding Strawberry and Papaya"); loc = findInsertPoint(fruit, "Strawberry"); if (insert(fruit, "Strawberry", loc)) System.out.println("Added Strawberry ok"); else System.out.println("Could not add Strawberry"); insert(fruit, "Papaya", findInsertPoint(fruit, "Papya")); showFruit(fruit); System.out.println("================"); //delete cherrt System.out.println("Deleting Cherry"); loc = search(fruit, "Cherry"); delete(fruit, loc); showFruit(fruit); System.out.println("================"); //delete tomato System.out.println("Deleting Tomato"); loc = search(fruit, "Tomato"); if (delete(fruit, loc)) System.out.println("Tomato was removed"); else System.out.println("Tomato not found"); } public static void showFruit(String arr[]) { for (int i = 0; i < logicalSize; i++) { System.out.println(arr[i]); } } public static int search(Object[] a, Object searchValue) { int left = 0; int right = logicalSize - 1; while (left <= right) { int midpoint = (left + right) / 2; int result = ((Comparable) a[midpoint]).compareTo(searchValue); if (result == 0) { return midpoint; } else if (result < 0) { left = midpoint + 1; } else { right = midpoint - 1; } } return -1; } public static boolean insert(Object array[], Object newItem, int targetIndex) { // Check for a full array and return false if full if (logicalSize == array.length) { return false; } // Check for valid target index or return false if (targetIndex < 0 || targetIndex > logicalSize) { return false; } // Shift items down by one position for (int i = logicalSize; i > targetIndex; i--) { array[i] = array[i - 1]; } // Add new item, increment logical size,return true array[targetIndex] = newItem; logicalSize++; return true; } public static boolean delete(Object array[], int targetIndex) { if (targetIndex < 0 || targetIndex >= logicalSize) { return false; } // Shift items up by one position for (int i = targetIndex; i < logicalSize - 1; i++) { array[i] = array[i + 1]; } // Decrement logical size and return true logicalSize--; return true; } public static int findInsertPoint(Object a[], Object searchValue) { int left = 0; int right = logicalSize - 1; int midpoint = 0; while (left <= right) { midpoint = (left + right) / 2; int result = ((Comparable) a[midpoint]).compareTo(searchValue); if (result < 0) { left = midpoint + 1; } else { right = midpoint - 1; } } if (((Comparable) a[midpoint]).compareTo(searchValue) < 0) { midpoint++; } return midpoint; } }
package com.isystk.sample.common.dto; public interface Dto { }
package negocio.excecao; public class OperacaoIncompativelException extends Exception{ public OperacaoIncompativelException(){ super("Operacao incompativel"); } }
package com.trey.fitnesstools; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v7.app.AlertDialog; import android.view.LayoutInflater; import android.view.View; import android.widget.SeekBar; import android.widget.TextView; public class DialogFragmentDeloadPercent extends DialogFragment { private SeekBar seekBarSelectPercent; private TextView displayPercent; private int percentOfRM; private double passedWeight; public static String KEY_PASSED_WEIGHT = "key_passed_weight"; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { View v = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_fragment_deload_percent,null); displayPercent = v.findViewById(R.id.textViewRMPercent); seekBarSelectPercent = v.findViewById(R.id.seekBarDialogPercent); seekBarSelectPercent.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progressValue, boolean b) { percentOfRM = progressValue; displayPercent.setText(Integer.toString(percentOfRM) + "%"); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); //intitial values for fields. passedWeight = getArguments().getDouble(KEY_PASSED_WEIGHT,0); percentOfRM = seekBarSelectPercent.getProgress(); displayPercent.setText(Integer.toString(percentOfRM) + "%"); //listener for the OK button on the dialog box. DialogInterface.OnClickListener okListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { ActivityDeloadCalculator.startActivityDeloadCalculator(getActivity(),passedWeight,percentOfRM); } }; return new AlertDialog.Builder(getActivity()) .setView(v) .setTitle(R.string.dialog_title_deload_percent) .setPositiveButton(android.R.string.ok,okListener) .create(); } //used to instantiate the dialog fragment and pass it a weight value public static DialogFragmentDeloadPercent newInstance(double repMaxWeight) { Bundle args = new Bundle(); args.putDouble(KEY_PASSED_WEIGHT,repMaxWeight); DialogFragmentDeloadPercent dialog = new DialogFragmentDeloadPercent(); dialog.setArguments(args); return dialog; } }
package com.sunteam.library.asynctask; import java.util.ArrayList; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import com.sunteam.common.menu.MenuConstant; import com.sunteam.common.tts.TtsUtils; import com.sunteam.library.R; import com.sunteam.library.activity.DownloadList; import com.sunteam.library.db.DownloadChapterDBDao; import com.sunteam.library.db.DownloadResourceDBDao; import com.sunteam.library.entity.DownloadChapterEntity; import com.sunteam.library.entity.DownloadResourceEntity; import com.sunteam.library.utils.LibraryConstant; import com.sunteam.library.utils.PublicUtils; /** * 得到下载资源列表异步加载类 * * @author wzp * @Created 2017/02/15 */ public class GetDownloadResourceAsyncTask extends AsyncTask<Integer, Void, Void> { private Context mContext; private String mTitle; private int type; private ArrayList<DownloadResourceEntity> mDownloadResourceEntityList; public GetDownloadResourceAsyncTask(Context context, String title) { mContext = context; mTitle = title; } @Override protected Void doInBackground(Integer... params) { type = params[0]; String username = PublicUtils.getUserName(mContext); DownloadResourceDBDao dao = new DownloadResourceDBDao( mContext ); if( 0 == type ) //未完成 { mDownloadResourceEntityList = dao.findAllUnCompleted(username); } else //已完成 { mDownloadResourceEntityList = dao.findAllCompleted(username); } dao.closeDb(); if( null == mDownloadResourceEntityList ) { mDownloadResourceEntityList = new ArrayList<DownloadResourceEntity>(); } else { if( 0 == type ) //未完成 { DownloadChapterDBDao dcDao = new DownloadChapterDBDao( mContext ); int size = mDownloadResourceEntityList.size(); for( int i = 0; i < size; i++ ) { if( LibraryConstant.DOWNLOAD_STATUS_GOING == mDownloadResourceEntityList.get(i).status ) //如果当前这本书正在下载 { ArrayList<DownloadChapterEntity> list = dcDao.findAll(mDownloadResourceEntityList.get(i)._id); //得到所有的章节信息 if( list != null ) { int count = list.size(); for( int j = 0; j < count; j++ ) { if( list.get(j).chapterStatus == LibraryConstant.DOWNLOAD_STATUS_GOING ) //正在下载 { mDownloadResourceEntityList.get(i).curDownloadChapterIndex = j; //保存当前正在下载的章节序号 break; } } } } } dcDao.closeDb(); } } return null; } @Override protected void onPreExecute() { super.onPreExecute(); PublicUtils.showProgress(mContext, this); String s = mContext.getResources().getString(R.string.library_wait_reading_data); TtsUtils.getInstance().speak(s); } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); PublicUtils.cancelProgress(); if(null != mDownloadResourceEntityList && mDownloadResourceEntityList.size() > 0) { startNextActivity(); } else { String s = mContext.getResources().getString(R.string.library_downloading_empty); if (0 != type) { s = mContext.getResources().getString(R.string.library_downloaded_empty); } PublicUtils.showToast(mContext, s, TtsUtils.TTS_QUEUE_ADD); } } private void startNextActivity() { Intent intent = new Intent(); intent.putExtra(MenuConstant.INTENT_KEY_TITLE, mTitle); // 菜单名称 intent.putExtra(MenuConstant.INTENT_KEY_LIST, mDownloadResourceEntityList); // 数据列表 intent.putExtra(LibraryConstant.INTENT_KEY_TYPE, type); // 0 下载中,1已下载 intent.setClass(mContext, DownloadList.class); mContext.startActivity(intent); } }
package com.checkers.controllers; import CheckersClient.core.CheckersClient; import com.badlogic.gdx.math.Vector2; import com.checkers.model.Board; import com.checkers.model.Cell; import com.checkers.model.Checker; import com.checkers.network.client.GameListener; import com.checkers.network.client.NetworkClient; import com.checkers.network.client.SocketListener; import com.checkers.server.beans.Step; import java.io.IOException; import java.util.StringTokenizer; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class BoardController { private MoveValidator validator; public NetworkClient network; public CheckersClient thisClient; private Cell startCell; private Cell targetCell; private static Checker selectedChecker; private static String currResult; private SocketListener sListener; private GameListener gameListener; private boolean isMove = false; private boolean init = true; private int time = 0; private long Suid = 0; private boolean isExec = true; private Board board; public BoardController(Board inpBoard, MoveValidator inpValidator, CheckersClient inputClient){ this.validator = inpValidator; thisClient = inputClient; this.board = inpBoard; network = new NetworkClient(); validator.setNetwork(network); try{ for(Step tmpStep : network.getAllSteps()){ parseStep(tmpStep); } } catch(Exception e){ System.out.println("Ходов нет"); } } public void setIsMove(boolean b) { isMove = b; } public void setCoord1(float iX, float iY){ //This making for enforce from crash in case no checker choose. try{ selectedChecker = board.getCheckerByDeskCoord(iX, iY); //Here we compare color selected checker with player color //And if fighting in progress check fighting checker with selected System.out.println(selectedChecker.getColor() + " : " + MoveValidator.isPlayerWhite); System.out.println("GL pos:"+selectedChecker.getPosition()); System.out.println(MoveValidator.getFightinChecker() == null); if(selectedChecker.getColor() != MoveValidator.isPlayerWhite && (MoveValidator.getFightinChecker() == null || MoveValidator.getFightinChecker().getIndex() == selectedChecker.getIndex()) ){ validator.setSelectedChecker(iX, iY); startCell = board.getCellByDeskCoord(iX, iY); } } catch(Exception e){} } public void setCoord2(float iX, float iY){ //Here we compare color selected checker with player color //And if fighting in progress check fighting checker with selected try{ if(selectedChecker.getColor() != MoveValidator.isPlayerWhite && (MoveValidator.getFightinChecker() == null || (MoveValidator.getFightinChecker().getIndex() == selectedChecker.getIndex())) ){ validator.setTargetCell(iX, iY); targetCell = board.getCellByDeskCoord(iX, iY); } }catch(Exception e){ } } public void setNetCoord1(float iX, float iY){ validator.setNetSelectedChecker(iX, iY); startCell = board.getCellByGLCoord(iX, iY); selectedChecker = board.getCheckerByGLCoord(iX, iY); } public void setNetCoord2(float iX, float iY){ validator.setNetTargetCell(iX, iY); targetCell = board.getCellByGLCoord(iX, iY); String result; result = validator.doCheckMove(); System.out.println("result:"+result); switch (Integer.parseInt(result)){ case 2: virtualStep(result);break; case 3: virtualStep(result);break; case 4: virtualStep(result);break; case 5: virtualStepExt(result);break; case 6: virtualStepExt(result);break; case 7: virtualStep(result);break; default: validator.returnChecker();break; } validator.selectedChecker = null; validator.clearCells(); clearKilled(); //selectedChecker.setPosition(targetCell.getPosition()); ///selectedChecker = null; //validator.isBlackTurn = !validator.isBlackTurn; //if(validator.isBlackTurn)System.out.println("Black turn"); //else System.out.println("White turn"); } private boolean parseStep(Step iStep){ System.out.println("Virtual step:"+iStep.getStep()); try{ StringTokenizer stok = new StringTokenizer(iStep.getStep(), "-:"); if(stok.hasMoreTokens()){ String lastMove = new String(); String nextTok = new String(); Vector2 vec = new Vector2(); nextTok = stok.nextToken(); vec = validator.strToMove(nextTok); setNetCoord1(vec.x, vec.y); nextTok = stok.nextToken(); vec = validator.strToMove(nextTok); setNetCoord2(vec.x,vec.y); lastMove = nextTok; while(stok.hasMoreTokens()){ vec = validator.strToMove(lastMove); setNetCoord1(vec.x, vec.y); nextTok = stok.nextToken(); vec = validator.strToMove(nextTok); setNetCoord2(vec.x,vec.y); lastMove = nextTok; } } } catch(Exception e){ System.out.println("Smth wrang in parsing step!:"+e.getMessage()); e.printStackTrace(); return false; } return true; } private String moveToStr(float x, float y){ if(!MoveValidator.isPlayerWhite){ x = 8.0f - x; y = 8.0f - y; } String currStep = new String(); if(currStep.length() != 0)currStep += '-'; currStep += (char)((int)(x - board.getBoardBottom()) + (int)'a'); currStep += Integer.toString((int)(y+ board.getBoardBottom())); return currStep; } private boolean realStep(String result){ System.out.println("one cell step:"+result); currResult = ""; currResult += moveToStr(startCell.getPosition().x, startCell.getPosition().y); currResult += "-"; currResult += moveToStr(targetCell.getPosition().x, targetCell.getPosition().y); boolean serverIsAllowed = network.sendStepInStr(currResult, validator.isBlackTurn); System.out.println(serverIsAllowed); if(serverIsAllowed){ selectedChecker.setPosition(targetCell.getPosition()); validator.checkQueen(); } else{ selectedChecker.setPosition(startCell.getPosition()); return false; } validator.isBlackTurn = !validator.isBlackTurn; if(validator.isBlackTurn)System.out.println("Black turn"); else System.out.println("White turn"); return true; } private boolean realSingleKill(String result){ System.out.println("Single kill:"+result); currResult = ""; currResult += moveToStr(startCell.getPosition().x, startCell.getPosition().y); currResult += ":"; currResult += moveToStr(targetCell.getPosition().x, targetCell.getPosition().y); boolean serverIsAllowed = network.sendStepInStr(currResult, validator.isBlackTurn); System.out.println(serverIsAllowed); if(serverIsAllowed)selectedChecker.setPosition(targetCell.getPosition()); else{ selectedChecker.setPosition(startCell.getPosition()); unmarkKilled(); return false; } validator.isBlackTurn = !validator.isBlackTurn; //validator.isCanFight = true; if(validator.isBlackTurn)System.out.println("Black turn"); else System.out.println("White turn"); return true; } private boolean firstStepFromMultiKill(String result){ System.out.println("First step from multi kill:" + currResult); currResult = ""; currResult += moveToStr(startCell.getPosition().x, startCell.getPosition().y); currResult += ":"; currResult += moveToStr(targetCell.getPosition().x, targetCell.getPosition().y); currResult += ":"; return true; } private boolean nextStepFromMultiKill(String result){ System.out.println("Next step from multi kill:" + currResult); currResult += moveToStr(targetCell.getPosition().x, targetCell.getPosition().y); currResult += ":"; return true; } private boolean lastStepFromMultiKill(String result){ System.out.println("Last step from multi kill:" + currResult); currResult += moveToStr(targetCell.getPosition().x, targetCell.getPosition().y); System.out.println("Send to server:" + currResult); boolean serverIsAllowed = network.sendStepInStr(currResult, validator.isBlackTurn); System.out.println(serverIsAllowed); if(serverIsAllowed)selectedChecker.setPosition(targetCell.getPosition()); else{ selectedChecker.setPosition(startCell.getPosition()); unmarkKilled(); return false; } validator.isBlackTurn = !validator.isBlackTurn; if(validator.isBlackTurn)System.out.println("Black turn"); else System.out.println("White turn"); return true; } private boolean virtualStep(String result){ System.out.println("Controller virtual step"); selectedChecker.setPosition(targetCell.getPosition()); validator.isBlackTurn = !validator.isBlackTurn; if(validator.isBlackTurn)System.out.println("Black turn"); else System.out.println("White turn"); clearKilled(); return true; } private boolean virtualStepExt(String result){ System.out.println("Controller virtual step"); selectedChecker.setPosition(targetCell.getPosition()); clearKilled(); return true; } private boolean clearKilled(){ int i = 0; for(Checker tmpChecker : board.getCheckers()) if(tmpChecker.getIsKilled()){ board.delChecker(tmpChecker); i++; System.out.println("marked to delete:"+i); } return true; } private boolean unmarkKilled(){ int i = 0; for(Checker tmpChecker : board.getCheckers()) if(tmpChecker.getIsKilled()){ tmpChecker.clearIsKilled(); i++; System.out.println("marked to live:"+i); } return true; } /** The main update method **/ public void update(float delta) { //if(false){ if(validator.isPlayerWhite == validator.isBlackTurn){ if(isExec){ gameListener = new GameListener(network); ExecutorService exec = Executors.newSingleThreadExecutor(); exec.execute(gameListener); isExec = !isExec; } if(gameListener.isCanceled()){ try { System.out.println("Game state:"+NetworkClient.gameH.game.getState()); if(NetworkClient.gameH.game.getState().toUpperCase().contains("CLOSE")){ System.out.println("Game is closed:"+NetworkClient.gameH.game.getResolution()); thisClient.setScreen(thisClient.endGame); } else if(network.listenGame().getListenObjects().getStep() != null) parseStep(network.listenGame().getListenObjects().getStep()); } catch (IOException e) { System.out.println("BCSPERR:"+e.getMessage()); } isExec = !isExec; } } if(isMove){ String result; result = validator.doCheckMove(); System.out.println("result:"+result); switch (Integer.parseInt(result)){ case 2: virtualStep(result);break; case 3: realStep(result);break; case 4: realSingleKill(result);break; case 5: firstStepFromMultiKill(result);break; case 6: nextStepFromMultiKill(result);break; case 7: lastStepFromMultiKill(result);break; default: validator.returnChecker();break; } validator.selectedChecker = null; setIsMove(false); validator.clearCells(); clearKilled(); } } }
package page; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class SearchAndSearchResults { private WebDriver driver = null; private WebDriverWait wait; private WebElement element; By searchBar_homePage = By.className("shopee-searchbar-input__input"); By searchButton_homePage = By.cssSelector("div._1Bj1VS.qEcSbS:nth-child(2) div.shopee-top.shopee-top--sticky div.container-wrapper.header-with-search-wrapper div.container.header-with-search div.header-with-search__search-section div.shopee-searchbar > button.btn.btn-solid-primary.btn--s.btn--inline"); public SearchAndSearchResults(WebDriver driver) { this.driver = driver; } // end constructor SearchAndSearchResults() public void inputSearchBar(String text) { wait = new WebDriverWait(driver, 20); element = wait.until(ExpectedConditions.visibilityOfElementLocated(searchBar_homePage)); element.sendKeys(text); } // end method inputSearchBar public void clickSearchButton() { wait = new WebDriverWait(driver, 20); wait.until(ExpectedConditions.elementToBeClickable(searchButton_homePage)).sendKeys(Keys.RETURN); } // end method clickSearchButton() } // end class SearchAndSearchResults
package day18; import heima.bean.employee; import java.util.Comparator; import java.util.Scanner; import java.util.TreeSet; /* * 创建5个对象装入TreeSet,按照工资从高到底排序输出结果(工资相同,按照年龄从低到高,工资和年龄都相同, 按照姓名字典顺序排列,但是不能去重(姓名、年龄、工资都相同)) */ public class home3 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("请输入姓名,年龄,工资"); TreeSet<employee> ts = new TreeSet<employee>(new Comparator<employee>() { @Override public int compare(employee o1, employee o2) { int num = o1.getSalary()-o2.getSalary(); int age = num==0 ? o1.getAge() - o2.getAge():num; return num == 0 ? age : o1.getName().compareTo(o2.getName()); } }); //String line = new sc.nextline(); //String [] arr = line.split(","); //int age = Integer.parseInt(arr[1]); //int salary = Integer.parseInt(arr[2]); } }
package net.acomputerdog.lccontroller.gui.window; import net.acomputerdog.lccontroller.LaserProperties; import net.acomputerdog.lccontroller.gui.GUIMain; import javax.swing.*; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class LaserPropWindow extends JDialog { private JPanel contentPane; private JButton buttonOK; private JButton buttonCancel; private JTextField heightField; private JTextField widthField; private final GUIMain main; private final JFrame owner; public LaserPropWindow(JFrame owner, GUIMain main) { super(owner); this.main = main; this.owner = owner; setContentPane(contentPane); setModal(true); getRootPane().setDefaultButton(buttonOK); buttonOK.addActionListener(e -> onOK()); buttonCancel.addActionListener(e -> onCancel()); // call onCancel() when X is clicked setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { onCancel(); } }); // call onCancel() on ESCAPE contentPane.registerKeyboardAction(e -> onCancel(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); super.setTitle("Laser cutter properties"); super.setVisible(true); } private void onOK() { try { int width = Integer.parseInt(widthField.getText()); int height = Integer.parseInt(heightField.getText()); main.setLaserProperties(new LaserProperties(width, height)); dispose(); } catch (NumberFormatException e) { new PopupMessage(owner, "Invalid input", "Please enter only integers."); } } private void onCancel() { dispose(); } }
package com.recipeBook.recipebook.domain; import lombok.*; import javax.persistence.*; @Getter @Setter @EqualsAndHashCode(exclude = "recipe") @Entity public class Notes { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @OneToOne private Recipe recipe; @Lob @Column(name = "recipe_notes") private String recipeNote; /** getters and setters **/ }
public class Library{ //Variables String name; String[] titles = new String[50]; boolean[] available = new boolean[50]; static int counter = 0; boolean borrowed; //Constructor for Library public Library(String libName){ name = libName; } //Add Book Method public void addBook(Book bookName ){ titles[counter]=bookName.title; available[counter]=true; counter++; } //Print Opening Hours - Static public static void printOpeningHours(){ System.out.println("Libraries are open daily from 9am to 5pm."); } //Print address of Library public void printAddress(){ System.out.println(name); } //Find book and mark it as borrowed public void borrowBook(String book){ for(int i=0;i<50;i++){ if(book == titles[i]){ available[i]=false; System.out.println("Book has been borrowed"); return; } } System.out.println("Book is unavailable from this library"); } //Return Book public void returnBook(String book){ for(int i=0;i<50;i++){ if(book == titles[i]){ available[i]=true; System.out.println("Book has been returned"); return; } } System.out.println("Book is not from this library"); } //Display of books available in both libraries public void printAvailableBooks(){ for(int i=0;i<50;i++){ if(titles[i]!=null & available[i]!=false) System.out.println(titles[i]); } } public static void main(String[] args) { // Create two libraries Library firstLibrary = new Library("10 Main St."); Library secondLibrary = new Library("228 Liberty St."); // Add four books to the first library firstLibrary.addBook(new Book("The Da Vinci Code")); firstLibrary.addBook(new Book("Le Petit Prince")); firstLibrary.addBook(new Book("A Tale of Two Cities")); firstLibrary.addBook(new Book("The Lord of the Rings")); secondLibrary.addBook(new Book("A Game of Thrones")); // Print opening hours and the addresses System.out.println("Library hours:"); printOpeningHours(); System.out.println(); System.out.println("Library addresses:"); firstLibrary.printAddress(); secondLibrary.printAddress(); System.out.println(); // Try to borrow The Lords of the Rings from both libraries System.out.println("Borrowing The Lord of the Rings:"); System.out.println(); System.out.println("Library 1:"); firstLibrary.borrowBook("The Lord of the Rings"); System.out.println("Library 2:"); secondLibrary.borrowBook("The Lord of the Rings"); System.out.println(); // Print the titles of all available books from both libraries System.out.println("Books available in the first library:"); firstLibrary.printAvailableBooks(); System.out.println(); System.out.println("Books available in the second library:"); secondLibrary.printAvailableBooks(); System.out.println(); // Return The Lords of the Rings to the first library System.out.println("Returning The Lord of the Rings:"); firstLibrary.returnBook("The Lord of the Rings"); System.out.println(); // Print the titles of available from the first and second library System.out.println("Books available in the first library:"); firstLibrary.printAvailableBooks(); System.out.println("\nBooks available in the second library:"); secondLibrary.printAvailableBooks(); } }
package com.av.acciones.adeudo; import org.apache.log4j.Logger; import com.av.acciones.BaseAccion; import com.av.db.dataobjects.Adeudo; import com.av.db.layer.interfaces.AdeudoLayer; import com.av.exceptions.AvException; import com.av.rmi.Parametro; import com.av.rmi.Parametro.Tipo; /** * Accion que elimina un adeudo en la base de datos configurada * * @author J Francisco Ruvalcaba C * */ public class EliminarAccion extends BaseAccion { private static Logger log = Logger.getLogger(EliminarAccion.class); @Override public Parametro ejecutar(Parametro parametro) throws AvException { log.info("Inicio - ejecutar(Parametro parametro)"); AdeudoLayer al = (AdeudoLayer) getBean(AdeudoLayer.BEAN_NAME); Adeudo a = null; if (parametro.getValor(Tipo.INPUT) instanceof Adeudo) { a = (Adeudo) parametro.getValor(Tipo.INPUT); al.eliminar(a); } log.info("Fin - ejecutar(Parametro parametro)"); return parametro; }// ejecutar }// EliiminarAccion
package club.banyuan; public class A { }
package test; public class Greetings { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("L00143552"); System.out.println("Greetings Everyone"); } }
package registration.booking.service.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import lombok.Data; import lombok.NoArgsConstructor; @Data @Entity @Table(name = "clients") @NoArgsConstructor public class Client { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @Column(unique = true) private String email; private byte discount; public Client(String name, String email) { this.name = name; this.email = email; } }
package twosumI; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public class Solution { public List<List<Integer>> allPairs(int[] array, int target) { // Write your solution here. List<List<Integer>> result = new ArrayList<List<Integer>>(); //key : number, value:list of all possible index; Map<Integer, List<Integer>> map = new HashMap<>(); for (int i = 0; i < array.length; i++){ List<Integer> list = map.get(target - array[i]); if(list != null){ for(Integer m : list){ result.add(Arrays.asList(m,i)); } } if(!map.containsKey(array[i])){ map.put(array[i], new ArrayList()); } map.get(array[i]).add(i); } return result; } }
package base_classes; import java.util.List; import java.util.ListIterator; public class GradeBook { GradeBook.GradingSchema GradingSchema; Grades Grades; public String toString() { return GradingSchema.toString() + Grades.toString(); } public static class GradingSchema { public List<GradeItem> GradeItem; public String toString() { String ts = ""; ListIterator<GradeItem> list = GradeItem.listIterator(); while(list.hasNext()) { ts += list.next().toString(); } return ts; } } public static class GradeItem { public String Category; public String Percentage; public String toString() { return "Grade Item:\n" + "Category: " + Category +"\n" + "Percentage: " + Percentage + "\n"; } } public static class Grades { public List<Student> Student; public String toString() { String awToString = ""; ListIterator<Student> list = Student.listIterator(); while(list.hasNext()) { awToString += list.next().toString(); } return awToString; } } public static class Student { public String Name; public String ID; public List<AssignedWork> AssignedWork; public String toString() { String awToString = "Student:\n" + "Name: " + Name + "\n" + "ID: " + ID + "\n" ; ListIterator<AssignedWork> list = AssignedWork.listIterator(); while(list.hasNext()) { awToString += list.next().toString(); } return awToString; } } public static class AssignedWork { public String _category; public List<GradedWork> GradedWork; public String toString() { String awToString = "Assigned Work:\n" + "Category: " + _category + "\n" ; ListIterator<GradedWork> list = GradedWork.listIterator(); while(list.hasNext()) { awToString += list.next().toString(); } return awToString; } } public static class GradedWork { public String Name; public String Grade; public String toString() { return "Grade Work:\n" + "Name: " + Name +"\n" + "Grade: " + Grade + "\n"; } public void initTestGradebook() { Name = "Test Name"; Grade = "Test Grade"; } public void testGradebook() { initTestGradebook(); System.out.println(toString()); } } }
package com.tencent.mm.plugin.appbrand.appcache.a; import android.database.Cursor; import com.tencent.mm.kernel.g; import com.tencent.mm.platformtools.u; import com.tencent.mm.plugin.appbrand.app.e; import com.tencent.mm.plugin.appbrand.appcache.WxaPkgWrappingInfo; import com.tencent.mm.plugin.appbrand.appusage.d; import com.tencent.mm.plugin.appbrand.config.AppBrandGlobalSystemConfig; import com.tencent.mm.plugin.appbrand.config.WxaAttributes; import com.tencent.mm.protocal.c.bsc; import com.tencent.mm.protocal.c.go; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.aa.a; import java.util.Collections; import java.util.LinkedList; import java.util.List; class a$1 implements Runnable { public final void run() { int i = 0; if (g.Eg().dpD && e.aaV() != null) { long longValue = ((Long) g.Ei().DT().get(a.sTV, Long.valueOf(0))).longValue(); long j = AppBrandGlobalSystemConfig.adZ().fpY.fqn; long VE = bi.VE(); if (VE >= longValue + j) { boolean z; List emptyList; g.Ei().DT().a(a.sTV, Long.valueOf(VE)); if (((Boolean) g.Ei().DT().get(a.sTW, Boolean.valueOf(true))).booleanValue()) { z = false; } else { z = true; } if (z) { d dVar = (d) e.x(d.class); Cursor rawQuery = dVar.fgu.rawQuery("select distinct username,updateTime from AppBrandLocalUsageRecord where updateTime >= " + (bi.VE() - AppBrandGlobalSystemConfig.adZ().fpY.fqo) + " order by updateTime desc limit " + AppBrandGlobalSystemConfig.adZ().fpY.fqp + " offset 0 ", null); if (!(rawQuery == null || rawQuery.isClosed())) { if (rawQuery.moveToLast()) { do { dVar.u(rawQuery.getString(0), rawQuery.getLong(1)); } while (rawQuery.moveToPrevious()); } rawQuery.close(); } g.Ei().DT().a(a.sTW, Boolean.valueOf(true)); } u.a aaV = e.aaV(); int i2 = AppBrandGlobalSystemConfig.adZ().fpY.fqp; x.i("MicroMsg.AppBrand.CgiBatchSyncPkgVersion", "collectReqInfoList with minUpdateTime( %s )", new Object[]{bi.gb(bi.VE() - AppBrandGlobalSystemConfig.adZ().fpY.fqo)}); Cursor b = aaV.b("select distinct WxaAttributesTable.username,WxaAttributesTable.appId,WxaAttributesTable.versionInfo from AppBrandAppLaunchUsernameDuplicateRecord left outer join WxaAttributesTable on AppBrandAppLaunchUsernameDuplicateRecord.username=WxaAttributesTable.username where AppBrandAppLaunchUsernameDuplicateRecord.updateTime >= " + j + " order by AppBrandAppLaunchUsernameDuplicateRecord.updateTime desc limit " + i2 + " offset 0", null, 2); if (b == null || b.isClosed()) { emptyList = Collections.emptyList(); } else { List linkedList = new LinkedList(); if (b.moveToFirst()) { WxaAttributes wxaAttributes = new WxaAttributes(); do { String string = b.getString(0); if (!bi.oW(string)) { wxaAttributes.d(b); bsc bsc = new bsc(); bsc.spJ = string; if (wxaAttributes.ael() != null) { bsc.spK = wxaAttributes.ael().cbu; } if (!bi.oW(wxaAttributes.field_appId)) { WxaPkgWrappingInfo aG = com.tencent.mm.plugin.appbrand.launching.e.aG(wxaAttributes.field_appId, 0); bsc.spL = aG != null ? aG.fii : 0; } linkedList.add(bsc); } } while (b.moveToNext()); } b.close(); i2 = aaV.delete("AppBrandAppLaunchUsernameDuplicateRecord", "updateTime < ?", new String[]{String.valueOf(j)}); x.i("MicroMsg.AppBrand.CgiBatchSyncPkgVersion", "collectReqInfoList, delete records updateTime < %s, count %d", new Object[]{bi.gb(j), Integer.valueOf(i2)}); emptyList = linkedList; } if (bi.cX(emptyList)) { x.e("MicroMsg.AppBrand.CgiBatchSyncPkgVersion", "pullIfExceedLimit, empty list"); return; } int i3; int i4 = AppBrandGlobalSystemConfig.adZ().fpY.fqq; int i5 = 0; while (true) { i3 = i; if (i5 >= emptyList.size() / i4) { break; } i = i5 * i4; ai(emptyList.subList(i, i + i4)); i = i5 + 1; } if (i3 < emptyList.size()) { ai(emptyList.subList(i3, emptyList.size())); } } } } private void ai(List<bsc> list) { int i = com.tencent.mm.plugin.appbrand.appcache.a.c.a.fiY; com.tencent.mm.plugin.appbrand.appcache.a.c.a.n(0, 0); new a(list, (byte) 0).KM().d(new com.tencent.mm.vending.c.a<Void, com.tencent.mm.ab.a.a<go>>() { public final /* synthetic */ Object call(Object obj) { com.tencent.mm.ab.a.a aVar = (com.tencent.mm.ab.a.a) obj; int i = aVar.errType; int i2 = aVar.errCode; String str = aVar.Yy; go goVar = (go) aVar.dIv; x.i("MicroMsg.AppBrand.CgiBatchSyncPkgVersion", "onCgiBack, errType %d, errCode %d, errMsg %s", new Object[]{Integer.valueOf(i), Integer.valueOf(i2), str}); int i3; if (i != 0 || i2 != 0 || goVar == null || goVar.rgX == null) { i3 = com.tencent.mm.plugin.appbrand.appcache.a.c.a.fiY; com.tencent.mm.plugin.appbrand.appcache.a.c.a.n(0, 2); } else { b.aj(goVar.rgX); i3 = com.tencent.mm.plugin.appbrand.appcache.a.c.a.fiY; com.tencent.mm.plugin.appbrand.appcache.a.c.a.n(0, 1); } return uQG; } }); } }