text
stringlengths
10
2.72M
package com.ims.dto; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; @Entity @Table(name = "purchase_payment_info") public class PurchasePaymentInfoDTO implements Serializable { private int id; private String company_name; private Double payment=0.0; private Double balance=0.0; private Double advance=0.0; private String billNo; @Id @Column(name = "id") @GeneratedValue(strategy=GenerationType.SEQUENCE, generator=" purchase_payment_info_seqs_gen") @SequenceGenerator( name=" purchase_payment_info_seqs_gen", sequenceName=" purchase_payment_info_seqs", allocationSize=1 ) public int getId() { return id; } public void setId(int id) { this.id = id; } @Column(name="company_name") public String getCompany_name() { return company_name; } public void setCompany_name(String company_name) { this.company_name = company_name; } public Double getPayment() { return payment; } public void setPayment(Double payment) { this.payment = payment; } public Double getBalance() { return balance; } public void setBalance(Double balance) { this.balance = balance; } public Double getAdvance() { return advance; } public void setAdvance(Double advance) { this.advance = advance; } @Column(name="bill_no") public String getBillNo() { return billNo; } public void setBillNo(String billNo) { this.billNo = billNo; } @Override public String toString() { return "PurchasePaymentInfoDTO [id=" + id + ", company_name=" + company_name + ", payment=" + payment + ", balance=" + balance + ", advance=" + advance + ", billNo=" + billNo + "]"; } }
package com.javaneversleep.tankwar; import java.awt.Image; public enum Direction { UP("U", 0, -1, 4), DOWN("D", 0, 1, 8), LEFT("L", -1, 0, 1), RIGHT("R", 1, 0, 2), LEFT_UP("LU", -1, -1, 5), RIGHT_UP("RU", 1, -1, 6), LEFT_DOWN("LD", -1, 1, 9), RIGHT_DOWN("RD", 1, 1, 10); private final String abbrev; final int xFactor, yFactor; final int code; Direction(String abbrev, int xFactor, int yFactor, int code) { this.abbrev = abbrev; this.xFactor = xFactor; this.yFactor = yFactor; this.code = code; } static Direction get(int code) { for (Direction dir : Direction.values()) { if (dir.code == code) { return dir; } } return null; } Image getImage(String prefix) { return Tools.getImage(prefix + abbrev + ".gif"); } }
/* * Copyright (c) 2012-2013 by Lukas Kairies, Zuse Institute Berlin * * Licensed under the BSD License, see LICENSE file for details. * */ package org.xtreemfs.utils; import static org.junit.Assert.assertEquals; import java.io.File; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.net.InetSocketAddress; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestRule; import org.xtreemfs.babudb.config.BabuDBConfig; import org.xtreemfs.common.ReplicaUpdatePolicies; import org.xtreemfs.common.libxtreemfs.AdminClient; import org.xtreemfs.common.libxtreemfs.AdminFileHandle; import org.xtreemfs.common.libxtreemfs.AdminVolume; import org.xtreemfs.common.libxtreemfs.ClientFactory; import org.xtreemfs.common.libxtreemfs.Helper; import org.xtreemfs.common.libxtreemfs.Options; import org.xtreemfs.common.xloc.ReplicationFlags; import org.xtreemfs.foundation.logging.Logging; import org.xtreemfs.foundation.pbrpc.client.RPCAuthentication; import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.UserCredentials; import org.xtreemfs.foundation.util.FSUtils; import org.xtreemfs.mrc.MRCConfig; import org.xtreemfs.osd.storage.HashStorageLayout; import org.xtreemfs.osd.storage.MetadataCache; import org.xtreemfs.pbrpc.generatedinterfaces.DIR.ServiceStatus; import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.SYSTEM_V_FCNTL; import org.xtreemfs.pbrpc.generatedinterfaces.MRC.DirectoryEntries; import org.xtreemfs.pbrpc.generatedinterfaces.MRC.Stat; import org.xtreemfs.test.SetupUtils; import org.xtreemfs.test.TestEnvironment; import org.xtreemfs.test.TestHelper; import org.xtreemfs.utils.xtfs_scrub.xtfs_scrub; public class ScrubberTest { @Rule public final TestRule testLog = TestHelper.testLog; private static MRCConfig mrcCfg1; private static BabuDBConfig mrcDBCfg1; private static InetSocketAddress mrc1Address; private static InetSocketAddress dirAddress; private static int accessMode; private static TestEnvironment testEnv; private static AdminClient client; private static byte[] content; private static final UserCredentials userCredentials = xtfs_scrub.credentials; @BeforeClass public static void initializeTest() throws Exception { Logging.start(Logging.LEVEL_WARN); accessMode = 0777; // rwxrwxrwx dirAddress = SetupUtils.getDIRAddr(); mrcCfg1 = SetupUtils.createMRC1Config(); mrcDBCfg1 = SetupUtils.createMRC1dbsConfig(); mrc1Address = SetupUtils.getMRC1Addr(); // cleanup File testDir = new File(SetupUtils.TEST_DIR); FSUtils.delTree(testDir); testDir.mkdirs(); SetupUtils.CHECKSUMS_ON = true; // startup test environment testEnv = new TestEnvironment(new TestEnvironment.Services[] { TestEnvironment.Services.DIR_SERVICE, TestEnvironment.Services.TIME_SYNC, TestEnvironment.Services.UUID_RESOLVER, TestEnvironment.Services.MRC_CLIENT, TestEnvironment.Services.OSD_CLIENT, TestEnvironment.Services.MRC, TestEnvironment.Services.OSD, TestEnvironment.Services.OSD, TestEnvironment.Services.OSD, TestEnvironment.Services.OSD }); testEnv.start(); SetupUtils.CHECKSUMS_ON = false; // create client client = ClientFactory.createAdminClient(dirAddress.getHostName() + ":" + dirAddress.getPort(), userCredentials, null, new Options()); client.start(); // create content String tmp = ""; for (int i = 0; i < 12000; i++) { tmp = tmp.concat("Hello World "); } content = tmp.getBytes(); } @AfterClass public static void shutdownTest() throws Exception { client.shutdown(); testEnv.shutdown(); } @Test public void testNonReplicatedFileOnDeadOSD() throws Exception { final String VOLUME_NAME = "testNonReplicatedFileOnDeadOSD"; final String FILE_NAME = "myDir/test0.txt"; // create Volume client.createVolume(mrc1Address.getHostName() + ":" + mrc1Address.getPort(), RPCAuthentication.authNone, userCredentials, VOLUME_NAME); AdminVolume volume = client.openVolume(VOLUME_NAME, null, new Options()); volume.start(); // create dir and file volume.createDirectory(userCredentials, "myDir", accessMode); AdminFileHandle file = volume.openFile( userCredentials, FILE_NAME, SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_CREAT.getNumber() | SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR.getNumber(), accessMode); // write file file.write(userCredentials, content, content.length, 0); file.close(); DirectoryEntries de = volume.readDir(userCredentials, "/myDir/", 0, 2, true); assertEquals(3, de.getEntriesCount()); // mark OSD as removed client.setOSDServiceStatus(file.getReplica(0).getOsdUuids(0), ServiceStatus.SERVICE_STATUS_REMOVED); // scrub volume xtfs_scrub scrubber = new xtfs_scrub(client, volume, 3, true, true, true); scrubber.scrub(); // file should be removed de = volume.readDir(userCredentials, "/myDir/", 0, 2, true); assertEquals(2, de.getEntriesCount()); // delete volume client.deleteVolume(mrc1Address.getHostName() + ":" + mrc1Address.getPort(), RPCAuthentication.authNone, userCredentials, VOLUME_NAME); // mark OSD as available client.setOSDServiceStatus(file.getReplica(0).getOsdUuids(0), ServiceStatus.SERVICE_STATUS_AVAIL); } @Test public void testNonReplicatedFileWithWrongChecksum() throws Exception { final String VOLUME_NAME = "testNonReplicatedFileWithWrongChecksum"; final String FILE_NAME = "test0.txt"; // create Volume client.createVolume(mrc1Address.getHostName() + ":" + mrc1Address.getPort(), RPCAuthentication.authNone, userCredentials, VOLUME_NAME); AdminVolume volume = client.openVolume(VOLUME_NAME, null, new Options()); volume.start(); // create file AdminFileHandle file = volume.openFile( userCredentials, FILE_NAME, SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_CREAT.getNumber() | SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR.getNumber(), accessMode); // write file file.write(userCredentials, content, file.getStripingPolicy().getStripeSize() * 1024 - 20, 0); // modify first Object on OSD File objFile = openObjectFile(file, 0, 0); FileWriter fw = new FileWriter(objFile, false); fw.write("foofoofoofoofoo"); fw.close(); // scrub volume xtfs_scrub scrubber = new xtfs_scrub(client, volume, 3, true, true, true); scrubber.scrub(); file.close(); // delete volume client.deleteVolume(mrc1Address.getHostName() + ":" + mrc1Address.getPort(), RPCAuthentication.authNone, userCredentials, VOLUME_NAME); } @Test public void testNonReplicatedFileWithWrongFileSizeOnMrc() throws Exception { final String VOLUME_NAME = "testNonReplicatedFileWithWrongFileSizeOnMrc"; final String FILE_NAME = "test0.txt"; // create Volume client.createVolume(mrc1Address.getHostName() + ":" + mrc1Address.getPort(), RPCAuthentication.authNone, userCredentials, VOLUME_NAME); AdminVolume volume = client.openVolume(VOLUME_NAME, null, new Options()); volume.start(); // create file AdminFileHandle file = volume.openFile( userCredentials, FILE_NAME, SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_CREAT.getNumber() | SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR.getNumber(), accessMode); // write file file.write(userCredentials, content, content.length, 0); Stat stat = file.getAttr(userCredentials); assertEquals(content.length, stat.getSize()); // truncate file on MRC file.truncate(userCredentials, 10, true); stat = file.getAttr(userCredentials); assertEquals(10, stat.getSize()); // scrub volume xtfs_scrub scrubber = new xtfs_scrub(client, volume, 3, true, true, true); scrubber.scrub(); // file size should be correct from 10 to content.length stat = file.getAttr(userCredentials); assertEquals(content.length, stat.getSize()); file.close(); // delete volume client.deleteVolume(mrc1Address.getHostName() + ":" + mrc1Address.getPort(), RPCAuthentication.authNone, userCredentials, VOLUME_NAME); } @Test public void testROnlyReplicatedFileWithLostReplica() throws Exception { final String VOLUME_NAME = "testROnlyReplicatedFileWithLostReplica"; final String FILE_NAME = "test0.txt"; // create Volume client.createVolume(mrc1Address.getHostName() + ":" + mrc1Address.getPort(), RPCAuthentication.authNone, userCredentials, VOLUME_NAME); AdminVolume volume = client.openVolume(VOLUME_NAME, null, new Options()); volume.start(); // set replica update Policy int replicationFlags = ReplicationFlags.setRarestFirstStrategy(0); replicationFlags = ReplicationFlags.setFullReplica(replicationFlags); volume.setDefaultReplicationPolicy(userCredentials, "/", ReplicaUpdatePolicies.REPL_UPDATE_PC_RONLY, 3, replicationFlags); // create file AdminFileHandle file = volume.openFile( userCredentials, FILE_NAME, SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_CREAT.getNumber() | SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR.getNumber(), accessMode); // write file file.write(userCredentials, content, content.length, 0); // re-open file to trigger replication file.close(); file = volume.openFile(userCredentials, FILE_NAME, SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDONLY.getNumber()); // wait for replication Thread.sleep(5000); // mark OSD of the second replica as removed client.setOSDServiceStatus(file.getReplica(1).getOsdUuids(0), ServiceStatus.SERVICE_STATUS_REMOVED); // scrub volume xtfs_scrub scrubber = new xtfs_scrub(client, volume, 3, true, true, true); scrubber.scrub(); // re-open file file.close(); file = volume.openFile(userCredentials, FILE_NAME, SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDONLY.getNumber()); // file has still three replicas assertEquals(3, file.getReplicasList().size()); file.close(); // delete volume client.deleteVolume(mrc1Address.getHostName() + ":" + mrc1Address.getPort(), RPCAuthentication.authNone, userCredentials, VOLUME_NAME); client.setOSDServiceStatus(file.getReplica(1).getOsdUuids(0), ServiceStatus.SERVICE_STATUS_AVAIL); } @Test public void testROnlyReplicatedFileWithWrongChecksum() throws Exception { final String VOLUME_NAME = "testROnlyReplicatedFileWithWrongChecksum"; final String FILE_NAME = "test0.txt"; // create Volume client.createVolume(mrc1Address.getHostName() + ":" + mrc1Address.getPort(), RPCAuthentication.authNone, userCredentials, VOLUME_NAME); AdminVolume volume = client.openVolume(VOLUME_NAME, null, new Options()); volume.start(); // set replica update Policy int replicationFlags = ReplicationFlags.setRarestFirstStrategy(0); replicationFlags = ReplicationFlags.setFullReplica(replicationFlags); volume.setDefaultReplicationPolicy(userCredentials, "/", ReplicaUpdatePolicies.REPL_UPDATE_PC_RONLY, 3, replicationFlags); // create file AdminFileHandle file = volume.openFile( userCredentials, FILE_NAME, SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_CREAT.getNumber() | SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR.getNumber(), accessMode); // write file int contentSize = file.getStripingPolicy().getStripeSize() * 1024; file.write(userCredentials, content, contentSize, 0); // re-open file to trigger replication file.close(); file = volume.openFile(userCredentials, FILE_NAME, SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDONLY.getNumber()); // wait for replication Thread.sleep(5000); // modify first Object of the second replica on OSD File objFile = openObjectFile(file, 1, 0); FileWriter fw = new FileWriter(objFile, false); fw.write("foofoofoofoofoo"); fw.close(); // scrub volume xtfs_scrub scrubber = new xtfs_scrub(client, volume, 3, true, true, true); scrubber.scrub(); //object file should be as long as the originally written content Thread.sleep(5000); objFile = openObjectFile(file, 1, 0); assertEquals(contentSize, objFile.length()); // delete volume file.close(); client.deleteVolume(mrc1Address.getHostName() + ":" + mrc1Address.getPort(), RPCAuthentication.authNone, userCredentials, VOLUME_NAME); } //@Test public void testRWReplicatedFileWithLostReplica() throws Exception { final String VOLUME_NAME = "testRWReplicatedFileWithLostReplica"; final String FILE_NAME = "test0.txt"; // create Volume client.createVolume(mrc1Address.getHostName() + ":" + mrc1Address.getPort(), RPCAuthentication.authNone, userCredentials, VOLUME_NAME); AdminVolume volume = client.openVolume(VOLUME_NAME, null, new Options()); volume.start(); // set replica update Policy volume.setDefaultReplicationPolicy(userCredentials, "/", ReplicaUpdatePolicies.REPL_UPDATE_PC_WQRQ, 3, 0); // create file AdminFileHandle file = volume.openFile( userCredentials, FILE_NAME, SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_CREAT.getNumber() | SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR.getNumber(), accessMode); // write file file.write(userCredentials, content, content.length, 0); // mark OSD of the second replica as removed client.setOSDServiceStatus(file.getReplica(1).getOsdUuids(0), ServiceStatus.SERVICE_STATUS_REMOVED); // scrub volume xtfs_scrub scrubber = new xtfs_scrub(client, volume, 3, true, true, true); scrubber.scrub(); // re-open file file.close(); file = volume.openFile(userCredentials, FILE_NAME, SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR.getNumber()); // file has still three replicas assertEquals(3, file.getReplicasList().size()); file.close(); // delete volume client.deleteVolume(mrc1Address.getHostName() + ":" + mrc1Address.getPort(), RPCAuthentication.authNone, userCredentials, VOLUME_NAME); client.setOSDServiceStatus(file.getReplica(1).getOsdUuids(0), ServiceStatus.SERVICE_STATUS_AVAIL); } @Test public void testRWReplicatedFileWithWrongChecksum() throws Exception { final String VOLUME_NAME = "testRWReplicatedFileWithWrongChecksum"; final String FILE_NAME = "test0.txt"; // create Volume client.createVolume(mrc1Address.getHostName() + ":" + mrc1Address.getPort(), RPCAuthentication.authNone, userCredentials, VOLUME_NAME); AdminVolume volume = client.openVolume(VOLUME_NAME, null, new Options()); volume.start(); // set replica update Policy volume.setDefaultReplicationPolicy(userCredentials, "/", ReplicaUpdatePolicies.REPL_UPDATE_PC_WQRQ, 3, 0); // create file AdminFileHandle file = volume.openFile( userCredentials, FILE_NAME, SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_CREAT.getNumber() | SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR.getNumber(), accessMode); // write file file.write(userCredentials, content, content.length, 0); // modify second Object File objFile = openObjectFile(file, 0, 1); FileWriter fw = new FileWriter(objFile, false); fw.write("foofoofoofoofoo"); fw.close(); // scrub volume xtfs_scrub scrubber = new xtfs_scrub(client, volume, 3, true, true, true); scrubber.scrub(); file.close(); // delete volume client.deleteVolume(mrc1Address.getHostName() + ":" + mrc1Address.getPort(), RPCAuthentication.authNone, userCredentials, VOLUME_NAME); } @Test public void testRWReplicatedFileWithWrongFileSizeOnMrc() throws Exception { final String VOLUME_NAME = "testRWReplicatedFileWithWrongFileSizeOnMrc"; final String FILE_NAME = "test0.txt"; // create Volume client.createVolume(mrc1Address.getHostName() + ":" + mrc1Address.getPort(), RPCAuthentication.authNone, userCredentials, VOLUME_NAME); AdminVolume volume = client.openVolume(VOLUME_NAME, null, new Options()); volume.start(); // set replica update Policy volume.setDefaultReplicationPolicy(userCredentials, "/", ReplicaUpdatePolicies.REPL_UPDATE_PC_WQRQ, 3, 0); // create file AdminFileHandle file = volume.openFile( userCredentials, FILE_NAME, SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_CREAT.getNumber() | SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR.getNumber(), accessMode); // write file file.write(userCredentials, content, content.length, 0); Stat s = file.getAttr(userCredentials); assertEquals(content.length, s.getSize()); // truncate file on MRC file.truncate(userCredentials, 10, true); s = file.getAttr(userCredentials); assertEquals(10, s.getSize()); // scrub volume xtfs_scrub scrubber = new xtfs_scrub(client, volume, 3, true, true, true); scrubber.scrub(); // file size should be correct from 10 to content.length s = file.getAttr(userCredentials); assertEquals(content.length, s.getSize()); file.close(); // delete volume client.deleteVolume(mrc1Address.getHostName() + ":" + mrc1Address.getPort(), RPCAuthentication.authNone, userCredentials, VOLUME_NAME); } private File openObjectFile(AdminFileHandle file, int replicaIndex, int objectIndex) throws IOException { String osdUUID = Helper.getOSDUUIDFromObjectNo(file.getReplica(replicaIndex), objectIndex); HashStorageLayout hsl = new HashStorageLayout(testEnv.getOSDConfig(osdUUID), new MetadataCache()); String filePath = hsl.generateAbsoluteFilePath(file.getGlobalFileId()); File fileDir = new File(filePath); File[] objFiles = fileDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return !name.matches("\\..*"); } }); return objFiles[objectIndex / file.getStripingPolicy(replicaIndex).getWidth()]; } }
package algorithm; import com.google.gson.Gson; import org.junit.Test; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.*; /** * Author: fangxueshun * Description: * Date: 2017/10/24 * Time: 23:20 */ public class ClassroomPlanningSolutionsTest { @Test public void solution() throws Exception { Gson gson = new Gson(); ClassroomPlanningSolutions planningSolutions = new ClassroomPlanningSolutions(); Map<String,ClassroomPlanningSolutions.ClassTime> subjectsMap = new HashMap<>(); ClassroomPlanningSolutions.ClassTime classTime1 = new ClassroomPlanningSolutions.ClassTime(0,3); ClassroomPlanningSolutions.ClassTime classTime2 = new ClassroomPlanningSolutions.ClassTime(2,3); ClassroomPlanningSolutions.ClassTime classTime3 = new ClassroomPlanningSolutions.ClassTime(4,7); ClassroomPlanningSolutions.ClassTime classTime4 = new ClassroomPlanningSolutions.ClassTime(3,8); ClassroomPlanningSolutions.ClassTime classTime5 = new ClassroomPlanningSolutions.ClassTime(6,10); ClassroomPlanningSolutions.ClassTime classTime6 = new ClassroomPlanningSolutions.ClassTime(8,10); ClassroomPlanningSolutions.ClassTime classTime7 = new ClassroomPlanningSolutions.ClassTime(9,11); ClassroomPlanningSolutions.ClassTime classTime8 = new ClassroomPlanningSolutions.ClassTime(11,15); ClassroomPlanningSolutions.ClassTime classTime9 = new ClassroomPlanningSolutions.ClassTime(12,15); ClassroomPlanningSolutions.ClassTime classTime10 = new ClassroomPlanningSolutions.ClassTime(10,13); ClassroomPlanningSolutions.ClassTime classTime11 = new ClassroomPlanningSolutions.ClassTime(13,17); ClassroomPlanningSolutions.ClassTime classTime12 = new ClassroomPlanningSolutions.ClassTime(15,18); subjectsMap.put("subject1",classTime1); subjectsMap.put("subject2",classTime2); subjectsMap.put("subject3",classTime3); subjectsMap.put("subject4",classTime4); subjectsMap.put("subject5",classTime5); subjectsMap.put("subject6",classTime6); subjectsMap.put("subject7",classTime7); subjectsMap.put("subject8",classTime8); subjectsMap.put("subject9",classTime9); subjectsMap.put("subject10",classTime10); subjectsMap.put("subject11",classTime11); subjectsMap.put("subject12",classTime12); System.out.println(gson.toJson(planningSolutions.solution(subjectsMap))); } }
import java.util.Scanner; public class Main{ public static void main(String [] args){ Scanner scan = new Scanner(System.in); } }
package org.apache.pig.backend.stratosphere.executionengine.contractsLayer; import org.apache.pig.impl.io.SPigFileInputFormat; import org.apache.pig.impl.io.SPigTextInputFormat; import eu.stratosphere.pact.common.contract.GenericDataSource; public class PigDataSource extends GenericDataSource<SPigTextInputFormat> { private final String inputFile; public PigDataSource(Class<? extends SPigTextInputFormat> clazz) { super(clazz); inputFile = ""; } public PigDataSource(Class<? extends SPigTextInputFormat> clazz, String inputFile) { super(clazz); this.inputFile = inputFile; this.parameters.setString(SPigFileInputFormat.FILE_PARAMETER_KEY, inputFile); } /** * Returns the file path from which the input is read. * * @return The path from which the input shall be read. */ public String getFilePath() { return this.inputFile; } // -------------------------------------------------------------------------------------------- /* (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { return this.inputFile; } }
package fr.atlasmuseum.search.module; import java.util.List; import android.content.Context; import android.graphics.Typeface; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import fr.atlasmuseum.R; public class SimpleAdapterSearch extends BaseAdapter { private class ViewHolder { TextView text; } @SuppressWarnings("unused") private static final String DEBUG_TAG = "AltasMuseum/SimpleAdapterSearch"; private Context mContext; private LayoutInflater mInflater; private List<String> mList; public Typeface mFontRegular; public SimpleAdapterSearch(Context context, List<String> alistN) { mContext = context; mList = alistN; mInflater = LayoutInflater.from(mContext); mFontRegular = Typeface.createFromAsset(mContext.getAssets(), "RobotoCondensed-Regular.ttf"); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = mInflater.inflate(R.xml.my_item_list, parent, false); holder = new ViewHolder(); holder.text = (TextView)convertView.findViewById(R.id.text); convertView.setTag(holder); } else { holder = (ViewHolder)convertView.getTag(); } holder.text.setTypeface(mFontRegular); holder.text.setText(mList.get(position)); return convertView; } @Override public int getCount() { return mList.size(); } @Override public Object getItem(int arg0) { return mList.get(arg0); } @Override public long getItemId(int arg0) { return arg0; } }
package com.liuhy.springproxy; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Created by liuhy on 2017/2/19. */ public class TestSpringManualProxy { @Test public void testProxy() { String path = "beans.xml"; ApplicationContext applicationContext = new ClassPathXmlApplicationContext(path); UserService proxyService = (UserService) applicationContext.getBean("proxyService"); proxyService.addUser(); proxyService.updateUser(); proxyService.deleteUser(); } }
package javalab3; import java.util.*; public class IdentityMatrix_19BS0127 { public static void main(String[] args) { System.out.println(" Solved by Reg No. : 19BDS0127"); System.out.println(" ---------"); int i,j; Scanner test=new Scanner(System.in); System.out.println("Enter the number of rows in the matrix:"); int m=test.nextInt(); System.out.println("Enter the number of columns in the matrix:"); int n=test.nextInt(); int [][] A= new int[n][m]; System.out.println("Enter the Matrix A:"); for(i=0;i<m;i++) { for(j=0;j<n;j++) { A[i][j]=test.nextInt( ); } } for(i=0;i<m;i++) { for(j=0;j<n;j++) { if(A[0][0]==1 && A[1][1]==1 && A[2][2]==1 ) { if(i!=j && A[i][j]==0) { System.out.println("It is an identity matirx"); break; } } else{ System.out.println("It is not an identity matrix"); break; } } break; } } }
public class MergeSort { public void mergeSort(int[] arr) { mergeSort(arr, 0, arr.length - 1); } // 합병 정렬 private void mergeSort(int[] arr, int start, int end) { if(start < end) { int middle = (start + end) / 2; // 분할 mergeSort(arr, start, middle); mergeSort(arr,middle+1, end); // 합병 merge(arr, start, middle, end); } } // 합병 public void merge(int[] arr, int start, int middle, int end) { int i = start, j = middle + 1, k = i; int[] temp = new int[arr.length]; while(i <= middle && j <= end) { if(arr[i] < arr[j]) { temp[k++] = arr[i++]; } else { temp[k++] = arr[j++]; } } while(i <= middle) { temp[k++] = arr[i++]; } while(j <= end) { temp[k++] = arr[j++]; } // 원래 배열에 복사 for(int r=start; r<=end; r++) { arr[r] = temp[r]; } } public void print(int[] arr) { for(int i=0; i<arr.length; i++){ System.out.print(arr[i]+" "); } System.out.println(); } public static void main(String[] args) { int[] arr = new int[] {2, 5, 4, 1, 9, 8, 7, 6, 3, 0}; MergeSort sort = new MergeSort(); sort.print(arr); sort.mergeSort(arr); sort.print(arr); } }
package game.model; import java.io.Serializable; import java.util.ArrayList; /** * Diese Klasse speichert bis zu 10 Highscores zu einem Starfield. * * @author Nikolaj */ public class HighscoreList implements Serializable { private static final long serialVersionUID = -540584146513677462L; /** Liste der 10 höchsten Punktzahlen. Länge wird nach dem Hinzufügen eines neuen Highscores gekürzt. */ private ArrayList<Highscore> highscores = new ArrayList<Highscore>(); /** * Prüft, ob eine Punktzahl für die Highscoreliste ausreicht. * * @param time * - Gespielte Zeit * @param attempts * - Getätigte Versuche * @return * - <b>true</b>, falls in Highscoreliste, <b>false</b> falls nicht */ public boolean checkHighscore(long time, int attempts) { Highscore score = new Highscore(null, time, attempts); if (highscores.get(9).getPoints() < score.calculatePoints()) { return true; } else { return false; } } /** * Fügt einen Highscore in die Liste der Highscores an entsprechender Stelle hinzu. * Kürzt anschließen die Liste auf 10 Highscores. * * @param highscore * - Hinzuzufügender Highscore */ public void addHighscore(Highscore highscore) { int i = 0; while (highscore.getPoints() < highscores.get(i).getPoints()) { i++; } highscores.add(i, highscore); for (int j = 10; j < highscores.size(); j++) { highscores.remove(i); } } /** * Gibt die Highscore Liste zurück. * * @return highscores * - Liste der 10 Highscores */ public ArrayList<Highscore> getHighscores() { return highscores; } }
package H04; import java.awt.*; import java.applet.*; public class H045_Dobbelsteen extends Applet { public void init () { } public void paint (Graphics g) { setBackground(Color.white); g.setColor(Color.black); g.drawRoundRect(110, 70, 170, 170, 10, 10);; g.fillOval(130, 90, 50, 50); g.fillOval(210, 90, 50, 50); g.fillOval(130, 170, 50, 50); g.fillOval(210, 170, 50, 50); } }
package com.sudipatcp.backtracking; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class LetterPhone { Map<String, String> phone = new HashMap<String, String>() {{ put("2", "abc"); put("3", "def"); put("4", "ghi"); put("5", "jkl"); put("6", "mno"); put("7", "pqrs"); put("8", "tuv"); put("9", "wxyz"); put("1", "1"); put("0", "0"); }}; public ArrayList<String> letterCombinations(String A) { ArrayList<String> output = new ArrayList<String>(); if (A.length() != 0) backtrack(output,"", A); return output; } private void backtrack(ArrayList<String> res, String combination, String nextDigits) { if(nextDigits.length() == 0){ res.add(combination); }else { String digit = nextDigits.substring(0, 1); String letters = phone.get(digit); for (int i = 0; i < letters.length(); i++) { String letter = phone.get(digit).substring(i, i + 1); backtrack(res, combination + letter, nextDigits.substring(1)); } } } public static void main(String[] args) { String s = "23"; LetterPhone lt = new LetterPhone(); ArrayList<String> ans = lt.letterCombinations(s); System.out.println(ans); } }
package micronaut.starter.kit; import org.dom4j.Element; import org.dom4j.Node; import javax.inject.Singleton; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Set; @Singleton public class FormulasNode { HashMap<String, FormulasBean> map; public FormulasNode() { this.map = new HashMap<String, FormulasBean>(); } public void parse(Element el) { FormulasBean bn = new FormulasBean(el); this.map.put(bn.name, bn); } public Set<String> keySet() { return (Set<String>) this.map.keySet(); } public List<FormulasBean> values() { return new ArrayList<FormulasBean>(this.map.values()); } public FormulasBean findFormulas(String name) throws ClassNotFoundException { if (this.map.containsKey(name)){ return this.map.get(name); } throw new ClassNotFoundException("The formulas:" + name + " not found"); } }
package com.tencent.tencentmap.mapsdk.a; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; public class w { private static String a = "fdea30d4-c4f3-11e7-ae5f-6c0b84ab3a9e"; public static final byte[] a(String str) { byte[] bArr = null; try { Mac instance = Mac.getInstance("HmacSHA256"); instance.init(new SecretKeySpec(a.getBytes("UTF-8"), "HmacSHA256")); return instance.doFinal(str.getBytes()); } catch (UnsupportedEncodingException e) { i.a("sha256Encode failed with error:" + e.getMessage()); return bArr; } catch (NoSuchAlgorithmException e2) { i.a("sha256Encode failed with error:" + e2.getMessage()); return bArr; } catch (InvalidKeyException e3) { i.a("sha256Encode failed with error:" + e3.getMessage()); return bArr; } } }
package GameFrame; import javax.swing.*; import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.function.Function; /* * @author Guihution * 2020/5/26 12:10 */ @SuppressWarnings("warning") public class GamePanel extends JPanel implements MouseMotionListener { // 飞机 private Plan plan = new Plan(200,520); // 子弹 private ArrayList<Bullet> bullets = new ArrayList<Bullet>(); private ArrayList<Bullet> bulletYs = new ArrayList<Bullet>(); // 敌机 private ArrayList<Enemy> enemies = new ArrayList<Enemy>(); // 背景 private ArrayList<Background> backgrounds = new ArrayList<Background>(); // 提示 private ArrayList<TipItem> tips = new ArrayList<TipItem>(); // 分数 private long achievement = 0; // 子弹添加时间系数 private long count = 1; // 游戏结束 boolean gameOver = false; // 提示 private String tip = ""; // 敌机速度 private int speed = 2; private int enemy_leval = 1; private int max_enemy_leval = 7;// 最高等级 // 武器等级 private int aream_leval = 1; // 升级标准 // private int[] up_pip = {10,20,30,40,50,60,70,80,90,100}; private int[] up_pip = {100,200,500,1000,1500,2000,3000,4000,5000,10000}; private int max_aream_leval = 10; // 最高等级 // 提示读秒 private int tiptemp = 1; private void aream_leval_up(){ // 武器升级 tip = Tip.ARMS_LEVEL_UP.getTip(); aream_leval++ ; tips.add(new TipItem("--武器升级--")); } private void enemy_speed_up(){ // 敌机速度升级 tip = Tip.ENEMY_SPEED_UP.getTip(); speed ++ ; tips.add(new TipItem("--敌机速度加快--")); } private class mThread extends Thread { private long sleep = 0; private Object args = null; private Function<Object,Object> func; public mThread(Function<Object,Object> f,Object args,long s){ this.func = f; this.sleep = s; this.args = args; } @Override public void run() { try { Thread.sleep(sleep); if(func!=null)func.apply(args); } catch (Exception ex){ ex.printStackTrace(); } } } // 初始化 public void init() { // 添加背景 backgrounds.add(new Background(0,0)); System.out.println("--游戏初始化--"); while (!gameOver){ count ++ ;//2147483647 // 添加另外一张背景图 if(backgrounds.size()==1) backgrounds.add(new Background(0,-700)); // 控制背景图片 for (int i = 0;i < backgrounds.size();i++) { Background bg = backgrounds.get(i); if(bg != null){ if(bg.getY()>690) backgrounds.remove(bg); bg.move(); } } // 子弹间隔 if(count % Math.max (15 - aream_leval,5) == 0) { Bullet b = new Bullet(plan.getX() + 45,plan.getY() - 15); bullets.add(b); bulletYs.add(b); } // 控制子弹个数 for (int i = 0;i < bullets.size();i++) { Bullet b = bullets.get(i); if(b != null) { if (b.getY() < - 15) bullets.remove(b); b.move(); } } // 敌机间隔 for (int i = 0; i < Math.max(enemy_leval/2,1); i++) { if(count % Math.max (50 - enemy_leval,15) == 0) enemies.add(new Enemy((int)(Math.random()*430),0 , speed)); } // 敌机间隔 for (int i = 0;i < enemies.size();i++) { Enemy e = enemies.get(i); if(e != null){ if(e.getY()>700) enemies.remove(e); haveBullet(e); if(plan.getIsLive() == 1 && e.getIslive() == 1 && isHit(plan,e)){ // 飞机是否坠毁 gameOver(); gameOver = false;// 游戏结束 }; e.move(); } } // 武器升级 if(aream_leval < max_aream_leval && achievement > up_pip[aream_leval]) { ++tiptemp; System.out.println("当前武器等级:"+aream_leval); aream_leval_up(); System.out.println("武器升级,当前武器等级:"+aream_leval); } // 敌机升级 if(enemy_leval < max_enemy_leval && count % (1000 + enemy_leval * 1000) == 0) { System.out.println("当前敌机速度等级:"+enemy_leval+";数量"+enemy_leval/2); ++enemy_leval; if(enemy_leval%2!=0) { System.out.println("敌机速度升级:"+speed); enemy_speed_up(); System.out.println("当前敌机速度:"+speed); } else { tips.add(new TipItem("--敌机数量变多--")); } } if(tiptemp > 0 ) { // 提示读秒 && ++tiptemp >100 for (int i = 0; i < tips.size(); i++) { TipItem t = tips.get(i); if(null!=t){ if(t.getTime() > 200) { tips.remove(t); }else { t.setTime(t.getTime()+1); } } } } repaint(); try { Thread.sleep(10);//10ms 基数 } catch (InterruptedException e) { e.printStackTrace(); } } } private void reCome(){ plan.reCome();// 重置飞机状态 bullets.removeAll(bullets); bulletYs.removeAll(bulletYs); enemies.removeAll(enemies); tips.removeAll(tips); achievement = 0; aream_leval = enemy_leval = 1; count = 1; speed = 2; repaint(); gameOver = false; } private void exit(){ new mThread(v -> { gameOver = true; System.exit(0); return v; }, null,500).start(); } private void gameOver(){ System.out.println("---GameOver--游戏结束!---"); int time = plan.getOverTime(); plan.setIsLive(0); if(plan.getIsLive()==0) plan.setPlanImage(IconDictionaries.getInstance().getPD()); Object [] obj = {"重来","退出"}; int n = JOptionPane.showOptionDialog(null, "飞机坠毁!您的得分是:"+achievement, "提示",JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE,new ImageIcon("warning"),obj,obj[0]); if(n==0){ reCome(); } else { exit(); } } private boolean isHit(Plan p,Enemy e){ // 飞机坠毁 Rectangle pwRect = new Rectangle(p.getX(),p.getY()+65,p.getWidth(),p.getHeight()-114);// 飞机底部 124-114 底部高度 10 Rectangle phRect = new Rectangle(p.getX()+42,p.getY(),p.getWidth()-85,p.getHeight()-32); // 飞机中心 Rectangle ewRect = new Rectangle(e.getX(),e.getY()-10,e.getWidth(),e.getHeight()-20); // 敌机尾翼 宽度 49 高度 36-20 16 Rectangle ehRect = new Rectangle(e.getX()+10,e.getY(),e.getWidth()-20,e.getHeight()); // 敌机中心 return phRect.intersects(ewRect) || phRect.intersects(ehRect) || pwRect.intersects(ewRect) || pwRect.intersects(ehRect);// 是否碰撞 } private boolean isHit(Enemy e,Bullet b){ Rectangle eRect = new Rectangle(e.getX(),e.getY(),e.getWidth(),e.getHeight()); Rectangle bRect = new Rectangle(b.getX(),b.getY(),b.getWidth(),b.getHeight()); return eRect.intersects(bRect); } // 是否有子弹 private boolean haveBullet(Enemy e){ int elength = enemies.size(); for (int j = 0;j < bullets.size();j++) { Bullet b = bullets.get(j); if(b!=null && isHit(e,b)){ hit(e); bullets.remove(b); } } return false; } // 是否打中敌机 private boolean isHit(Bullet b,Enemy e,Integer y){ new Thread(new Runnable() { @Override public void run() { if(e.getY()+b.getY()>y) { hit(e); bullets.remove(b); } } }).start(); return false; } private void hit(Enemy e){ e.setEnemyImage(IconDictionaries.getInstance().getBom()); new mThread(o -> { if(e != null) { enemies.remove(e) ; achievement += 10; } return o; },null,500).start(); } // 展示飞机 @Override public void paint(Graphics g) { // 让父类画完 super.paint(g); // 背景 for (int i = 0;i < backgrounds.size();i++) { Background bg = backgrounds.get(i); g.drawImage(bg.getBackgroundImage().getImage(),bg.getX(),bg.getY(),null); } // 飞机 if (plan!=null){ Image image = plan.getPlanImage().getImage(); g.drawImage(image,plan.getX(),plan.getY(),null); } // 子弹 for (int i = 0;i < bullets.size();i++) { Bullet b = bullets.get(i); if(b!=null) g.drawImage(b.getBulletImage().getImage(),b.getX(),b.getY(),null); } // 敌机 for (int i = 0;i < enemies.size();i++) { Enemy e = enemies.get(i); if(e!=null) g.drawImage(e.getEnemyImage().getImage(),e.getX(),e.getY(),null); } // 暂时通知 for (int i = 0; i < tips.size(); i++) { TipItem t = tips.get(i); if(null!=t) g.drawString(t.getContent(),380,Math.max((tips.size()-i)*20+60,60)); } // 武器下次升级提示消息 if(aream_leval<max_aream_leval) g.drawString("下次升级需要达到 "+up_pip[aream_leval]+" 积分",10,40); // 武器等级 g.drawString("武器等级:"+aream_leval+(aream_leval<max_aream_leval?"":"(Max)"),380,20); // 敌机等级 g.drawString("敌机等级:"+enemy_leval+(enemy_leval<max_enemy_leval?"":"(Max)"),380,40); g.drawString("战斗积分:"+achievement,10,20); } // 计算飞机位置 private void calcPlanPostion(MouseEvent e){ int tempX = e.getX(); int tempY = e.getY(); if(plan != null && plan.getIsLive() == 1) { // 确认飞机对象存在并存活 if(Math.abs(tempX-plan.getX()) < 150 && Math.abs(tempY-plan.getY()) < 150 ){ // 防止闪现 if(tempX > 2 && tempX < 476){ plan.setX(tempX-50); } if(tempY > 100 && tempY < 680){ plan.setY(tempY-100); } } } // 重新画 repaint(); } @Override public void mouseDragged(MouseEvent e) { if(plan.getIsLive()==1)calcPlanPostion(e); } @Override public void mouseMoved(MouseEvent e) { } }
package at.fhj.swd.presentation.exceptions; import at.fhj.swd.exceptions.FhjWs2014Sd12PseException; /** * Denotes the top-level-exception-base-class for all presentation-layer-exceptions. * */ public class PresentationLayerException extends FhjWs2014Sd12PseException { private static final long serialVersionUID = -7147962666368460968L; PresentationLayerException() { super(); } PresentationLayerException(String msg) { super(msg); } PresentationLayerException(String msg, Throwable t) { super(msg, t); } // TODO: Implement presentation-layer specific exception-functionalities here! }
package slepec.hra.prikazy; import slepec.hra.Hra; import slepec.hra.planek.HerniPlan; import slepec.hra.planek.prostor.Prostor; import slepec.hra.planek.prostor.vec.Vec; import slepec.hra.planek.prostor.vec.VecKlic; /** * Pomoci PrikazOdemkni lze odemknout danou mistnost, paklize ma od ni hrac klic * * @author Pavel Jurca, xjurp20@vse.cz * @version 2 */ public class PrikazOdemkni extends Prikaz { public PrikazOdemkni(Hra hra, String popis) { super(hra, popis); } @Override public boolean proved(String[] parametry) { if (null == parametry || parametry.length < 1 || parametry[0].equals("")) { result = " err: dobre, odemkni, ale co?"; return false; } HerniPlan planek = hra.getHerniPlan(); switch (parametry.length) { case 1: String co = parametry[0]; Prostor prostor = planek.selectProstor(co); if (prostor != null) { //lze odemknout i mistnost, ve ktere prave jste if (planek.kdeJsem().isPruchoziS(prostor) || planek.kdeJsem().equals(prostor)) { if (prostor.lzeZamknout()) { if (prostor.isZamknuto()) { //takoveto pojmenovani klice je uz implicitne _ //definovano v konstruktoru String klicNazev = "klic" + co.toUpperCase(); Vec klic = planek.hlavniPostava().selectVec(klicNazev); if (klic != null) { if (klic instanceof VecKlic) { prostor.odemknout(); result = " USPECH: odemkli jste " + prostor; return true; } else { result = " neuspech: klic je padelek!"; } } else { result = " neuspech: od prostoru " + prostor + " musite mit klic"; } } else { result = " neuspech: prostor " + prostor + " je uz odemceny"; } } else { result = " neuspech: prostor " + prostor + " nema zadne dvere!"; } } else { result = " neuspech: " + prostor + " neni jednim z vychodu"; } } else { result = " err: prostor \"" + co + "\" neexistuje"; } break; default: result = " err: spatny pocet parametru" + String.format("\n%6s%s", "", "tip: 'napovez'"); break; } return false; } @Override public String toString() { return PrikazyVycet.ODEMKNI.toString(); } }
package com.takshine.wxcrm.domain; import java.util.List; import com.takshine.wxcrm.model.ScheduleModel; /** * 日程 * @author 刘淋 * */ public class Schedule extends ScheduleModel{ /** * 调用sugar接口传递的参数 */ private String viewtype = null;//视图类型 myview , teamview, focusview, allview private String title = null;//标题 private String startdate = null ;//开始日期 private String enddate = null ;//结束日期 private String status = null ;//状态 private String desc = null;//说明 private String driority = null;//优先级 private String contact = null;//联系人 private String participant = null ; //参与人 private List<TaskParent> parent = null ;//相关Id private String parentId = null ;//相关Id private String parentType = null ;//相关类型 private String assignerId = null ;//责任人Id private String assignerName = null ;//责任人名字 private String creater = null;//创建人 private String createdate = null ;//创建时间 private String modifier = null;//修改人 private String modifyDate = null;//修改时间 private String rowid = null; private String cycliKey = null;//周期键 private String cycliValue = null;//周期名字 private String schetype = null; private String addr = null; private String ispublic=null;//0 不公开,1公开 private String deleted=null;//是否被删除 private String optype=null;//0 不公开,1公开 private String subtaskid = null; public String getDeleted() { return deleted; } public void setDeleted(String deleted) { this.deleted = deleted; } public String getSubtaskid() { return subtaskid; } public void setSubtaskid(String subtaskid) { this.subtaskid = subtaskid; } public String getIspublic() { return ispublic; } public void setIspublic(String ispublic) { this.ispublic = ispublic; } public String getSchetype() { return schetype; } public void setSchetype(String schetype) { this.schetype = schetype; } public String getAddr() { return addr; } public void setAddr(String addr) { this.addr = addr; } public String getParticipant() { return participant; } public void setParticipant(String participant) { this.participant = participant; } public String getRowid() { return rowid; } public void setRowid(String rowid) { this.rowid = rowid; } public String getViewtype() { return viewtype; } public void setViewtype(String viewtype) { this.viewtype = viewtype; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getStartdate() { return startdate; } public void setStartdate(String startdate) { this.startdate = startdate; } public String getEnddate() { return enddate; } public void setEnddate(String enddate) { this.enddate = enddate; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public String getDriority() { return driority; } public void setDriority(String driority) { this.driority = driority; } public String getAssignerId() { return assignerId; } public void setAssignerId(String assignerId) { this.assignerId = assignerId; } public String getAssignerName() { return assignerName; } public void setAssignerName(String assignerName) { this.assignerName = assignerName; } public String getCreater() { return creater; } public void setCreater(String creater) { this.creater = creater; } public String getCreatedate() { return createdate; } public void setCreatedate(String createdate) { this.createdate = createdate; } public String getModifier() { return modifier; } public void setModifier(String modifier) { this.modifier = modifier; } public String getModifyDate() { return modifyDate; } public void setModifyDate(String modifyDate) { this.modifyDate = modifyDate; } public String getContact() { return contact; } public void setContact(String contact) { this.contact = contact; } public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } public String getParentType() { return parentType; } public void setParentType(String parentType) { this.parentType = parentType; } public String getCycliKey() { return cycliKey; } public void setCycliKey(String cycliKey) { this.cycliKey = cycliKey; } public String getCycliValue() { return cycliValue; } public void setCycliValue(String cycliValue) { this.cycliValue = cycliValue; } public String getOptype() { return optype; } public void setOptype(String optype) { this.optype = optype; } public List<TaskParent> getParent() { return parent; } public void setParent(List<TaskParent> parent) { this.parent = parent; } }
package controllers; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.ServletException; import java.io.IOException; import models.User; import models.Product; public class SaveProductReturningPolicyServlet extends HttpServlet{ public void doGet(HttpServletRequest request,HttpServletResponse response)throws IOException,ServletException{ HttpSession session = request.getSession(); User user = (User)session.getAttribute("user"); String resp =""; if(user!=null){ String returningPolicy = request.getParameter("product_returning_policy"); Product product = (Product)session.getAttribute("product"); product.setReturningPolicy(returningPolicy); if(product.saveReturningPolicy()){ resp += "{\"resp\":1}"; }else{ resp += "{\"resp\":0}"; } }else{ resp += "{\"resp\":-1}"; } response.getWriter().write(resp); } }
package testRouleTaBoule.window; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.Scanner; import testRouleTaBoule.elements.*; public class GenerateurCoordCarte { public static Element[][] element = new Element[30][30]; public static ElementBoule laBoule = null; public static int startX, startY; // ========== CONSTRUCTEUR ============ public GenerateurCoordCarte() { try { genereMap(); } catch (FileNotFoundException e) { e.printStackTrace(); } } // ========== Fonction qui créé un tableau d'"Element" à partir d'un fichier texte ============ public void genereMap() throws FileNotFoundException { int x = 0; int y = 0; Scanner sc = new Scanner(new FileReader("map.txt")); while (sc.hasNextLine()) { String ligne = sc.nextLine(); for (int i = 0; i < ligne.length(); i++) { char charLigne = ligne.charAt(i); if (charLigne == 'X') { element[x / 30][y / 30] = new ElementLimite(new Coordonnees(x, y)); // System.out.println(""); } else if (charLigne == 'M') { element[x / 30][y / 30] = new ElementMur(new Coordonnees(x, y)); // System.out.print("M"); } else if (charLigne == 'P') { element[x / 30][y / 30] = new ElementPiege(new Coordonnees(x, y)); // System.out.print("P"); } else if (charLigne == 'S') { element[x / 30][y / 30] = new ElementStart(new Coordonnees(x, y)); startX = x; startY = y; // System.out.println(bouleX); // System.out.print("S"); } else if (charLigne == 'O'){ element[x / 30][y / 30] = new ElementObjectif(new Coordonnees(x, y)); }else if (charLigne == ' ') { element[x / 30][y / 30] = new ElementVide(new Coordonnees(x, y)); // System.out.print(" "); } x += 30; } y += 30; x = 0; // System.out.print("\r"); } sc.close(); System.out.println("fin generation coordonnees"); } }
package ro.redeul.google.go.lang.psi.processors; import com.intellij.psi.PsiElement; import com.intellij.psi.ResolveState; import com.intellij.psi.scope.BaseScopeProcessor; import ro.redeul.google.go.lang.psi.toplevel.GoTypeNameDeclaration; import ro.redeul.google.go.lang.psi.toplevel.GoTypeSpec; import ro.redeul.google.go.lang.psi.types.GoTypeName; /** * Author: Toader Mihai Claudiu <mtoader@gmail.com> * <p/> * Date: Sep 21, 2010 * Time: 4:47:46 AM */ public class NamedTypeResolver extends BaseScopeProcessor { private PsiElement resolvedTypeName; private GoTypeName targetName; public NamedTypeResolver(GoTypeName targetName) { this.targetName = targetName; } public boolean execute(PsiElement element, ResolveState state) { if ( element instanceof GoTypeSpec ) { if ( tryFindTypeName((GoTypeSpec)element, state) ) { return false; } } return true; } private boolean tryFindTypeName(GoTypeSpec typeSpec, ResolveState state) { GoTypeNameDeclaration typeNameDeclaration = typeSpec.getTypeNameDeclaration(); if ( typeNameDeclaration == null ) { return false; } String declaredTypeName = typeNameDeclaration.getName(); String visiblePackageName = state.get(GoResolveStates.VisiblePackageName); String fqm = String.format("%s%s", visiblePackageName != null ? visiblePackageName + "." : "", declaredTypeName); if ( fqm.equals(this.targetName.getText())) { resolvedTypeName = typeNameDeclaration; return true; } return false; } public PsiElement getResolvedTypeName() { return resolvedTypeName; } }
/* *Purpose:-create a Player Object having Deck of Cards, and having ability to Sort by Rank and maintain the * cards in a Queue implemented using Linked List. * *@Author:-Arpana Kumari * Version:1.0 * @Since:-12 May 2018 */ package com.bridgeit.DeckOfCardUsingQueue; import java.util.LinkedList; import com.bridgeit.dataStructurePrograms.Queue; import com.bridgeit.utility.Utility; public class DeckOfCard { public static void main(String[] args) { String[] suits = { "Clubs", "Diamonds", "Hearts", "Spades" }; String[] ranks = { "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace" }; Queue1 queue = new Queue1(0); int indexOfDeck = 0; String[] array = Utility.deck(suits, ranks); System.out.println("Deck of Cards: "); System.out.println("--------------"); for (int i = 0; i < 4; i++) { LinkedList<String> list = new LinkedList<String>(); for (int j = 0; j < 9; j++) { list.add(array[indexOfDeck]); indexOfDeck++; } queue.enqueue(list); } queue.getData(); } }
package net.minecraft.util.datafix.fixes; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ResourceLocation; import net.minecraft.util.datafix.IFixableData; public class CookedFishIDTypo implements IFixableData { private static final ResourceLocation WRONG = new ResourceLocation("cooked_fished"); public int getFixVersion() { return 502; } public NBTTagCompound fixTagCompound(NBTTagCompound compound) { if (compound.hasKey("id", 8) && WRONG.equals(new ResourceLocation(compound.getString("id")))) compound.setString("id", "minecraft:cooked_fish"); return compound; } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraf\\util\datafix\fixes\CookedFishIDTypo.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package iut.cours1.projet.dummy; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.nfc.Tag; import iut.cours1.projet.MainActivity; import static androidx.constraintlayout.widget.Constraints.TAG; /** * Helper class for providing sample content for user interfaces created by * Android template wizards. * <p> * TODO: Replace all uses of this class before publishing your app. */ public class DummyContent { /** * An array of sample (dummy) items. */ public static final List<DummyItem> ITEMS = new ArrayList<DummyItem>(); /** * A map of sample (dummy) items, by ID. */ public static final Map<String, DummyItem> ITEM_MAP = new HashMap<String, DummyItem>(); // private static final int COUNT = 25; // // static { // // Add some sample items. // for (int i = 1; i <= COUNT; i++) { // addItem(createDummyItem(i)); // } // } private static void addItem(DummyItem item) { ITEMS.add(item); ITEM_MAP.put(item.id, item); } // private static DummyItem createDummyItem(int position) { // return new DummyItem(String.valueOf(position), "Item " + position, makeDetails(position)); // } private static String makeDetails(int position) { StringBuilder builder = new StringBuilder(); builder.append("Details about Item: ").append(position); for (int i = 0; i < position; i++) { builder.append("\nMore details information here."); } return builder.toString(); } /** * A dummy item representing a piece of content. */ public static class DummyItem { public final String id; public final String content; public final String region; public final String annee; public final String filename; public DummyItem(String id, String content, String filename, String region, String annee) { this.id = id; this.content = content; this.filename = filename; this.region = region; this.annee = annee; } @Override public String toString() { return content; } } public static String jtoString() throws JSONException, IOException { String str = new String(); try { BufferedReader br = new BufferedReader(new InputStreamReader(MainActivity.getContext().getAssets().open("fp"))); StringBuilder sb = new StringBuilder(); String line = null; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } str = new String(sb.toString()); }catch(IOException e){ e.printStackTrace(); } return str; } public static void loadPhareJson(){ try { String str = jtoString(); JSONObject jObjConnection = null; jObjConnection = new JSONObject(str); JSONObject jsonBix = jObjConnection.getJSONObject("phares"); JSONArray jsonA = jsonBix.getJSONArray("liste"); for (int i = 0; i< jsonA.length(); i++){ JSONObject msg = (JSONObject) jsonA.get(i); Log.d(TAG,"coucou"+ msg.getString("construction")); addItem(new DummyItem( msg.getString("id"), msg.getString("name"), msg.getString("filename"), msg.getString("region"), msg.getString("construction") )); } } catch (JSONException | IOException e) { e.printStackTrace(); } } }
package zystudio.cases.javabase; import java.util.Enumeration; public class CaseEnumeration { public static void work() { } public static class MyBean { } public static class MyEnumerator implements Enumeration<MyBean> { @Override public boolean hasMoreElements() { return false; } @Override public MyBean nextElement() { return null; } } }
package java_Programs; public class Amstrong { public static void main(String[] args) { int num=371, temp=0, amstrongnumber=0; int check=0; check=num; while(num>0) { amstrongnumber=num%10; num=num/10; temp=temp+(amstrongnumber*amstrongnumber*amstrongnumber); } if(temp==check) { System.out.println("Amstrong Number"); } else { System.out.println("Not a Amstrong Number"); } } }
package kademlia.monitor; public enum MonitorType { PING, FIND_NODE, REPLY_NODE, SEND; }
package entities.pages; import entities.components.BaseComponent; import entities.components.TitleComponent; import org.openqa.selenium.By; import utils.TestGlobalsManager; import static org.testng.Assert.assertTrue; public class PaymentAndReviewCheckoutPage extends BasePage { private TitleComponent titleComponent = new TitleComponent(); public void clickTerms() { click(By.xpath("//a[text()='Terms']")); } public void clickArrowFor(String componentName) { javascriptScroll(500); assertTrue(titleComponent.isExist(componentName), String.format("Looks like \"%s\" arrow doesn't present on page.", componentName)); BaseComponent.getComponentByTitle(componentName).findElement(By.cssSelector("div.display-well-arrow")).click(); } public String getInstallationTime() { By installationTime = By.cssSelector("span.est-pickup-time-value"); waitForElementVisible(installationTime); return findElement(installationTime).getText(); } public void checkPickUpInStoreInfo() { String address = findElement(By.cssSelector("div.review-ship-to-store div.address-recipient")).getText(); String storeId = (String) TestGlobalsManager.getTestGlobal("storeId"); assertTrue(address.contains(storeId), "Store info does not contains expected store id. \nExpected: " + storeId + "\nGot: " + address); } @Override public boolean isPage() { return false; } }
package com.steatoda.commons.fields; import java.text.ParseException; import java.util.AbstractSet; import java.util.Collection; import java.util.EnumMap; import java.util.EnumSet; import java.util.Iterator; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import com.google.common.collect.Iterators; /** * <p>Defines complete object's field graph with exact subfields for each fields-enabled subobject.</p> * <p>Implements {@link Set} interface for first-level fields.</p> * * @param <F> Field enum (first-level fields) */ public class FieldGraph<F extends Enum<F> & FieldEnum> extends AbstractSet<F> { // builder-style factories /** Builder for constructing {@link FieldGraph}(s) */ public static class Builder<F extends Enum<F> & FieldEnum> { /** * Constructs empty {@link FieldGraph} builder using {@code clazz} as first-level field type. * @param clazz first-level field class type * @param <F> first-level field type * @return Empty builder */ public static <F extends Enum<F> & FieldEnum> Builder<F> of(Class<F> clazz) { return new Builder<>(clazz); } /** * Constructs {@link FieldGraph} builder using {@code graph} as initial value. * @param graph Initial graph to initialize * @param <F> first-level field type * @return Builder pre-initialized to {@code graph} */ public static <F extends Enum<F> & FieldEnum> Builder<F> of(FieldGraph<F> graph) { return new Builder<>(graph.getDeclaringClass()).add(graph); } private Builder(Class<F> clazz) { this.clazz = clazz; data = new EnumMap<>(clazz); } /** * Removes given field from graph together with its complete subgraph. * @param field field to remove * @return Builder with field removed */ public Builder<F> remove(F field) { data.remove(field); return this; } /** * Adds field to graph. If field describes field-enabled object, it's subgraph will be empty. * @param field field to add * @return Builder with field added */ public Builder<F> add(F field) { return add(field, null); } /** * Adds field describing fields-enabled subobject to graph and initializes its subgraph. * @param field field to add * @param subgraph field's subgraph * @param <F2> subgraph's field type * @return Builder with field added * @throws IllegalArgumentException if {@code field} defines object with fields of type other than {@code F2} */ public <F2 extends Enum<F2> & FieldEnum> Builder<F> add(F field, FieldGraph<F2> subgraph) { if (subgraph != null && !subgraph.getDeclaringClass().equals(field.getFieldsClass())) throw new IllegalArgumentException("Trying to add sub-graph for field " + field + " of type " + subgraph.getDeclaringClass() + " but field declares sub-graph of type " + field.getFieldsClass()); extend(data, field, subgraph); return this; } /** NOTE: setting field <b>overwrites</b> existing subfields if field was already initialized */ <F2 extends Enum<F2> & FieldEnum> Builder<F> set(F field, FieldGraph<F2> subgraph) { if (subgraph != null && !subgraph.getDeclaringClass().equals(field.getFieldsClass())) throw new IllegalArgumentException("Trying to set sub-graph for field " + field + " of type " + subgraph.getDeclaringClass() + " but field declares sub-graph of type " + field.getFieldsClass()); data.put(field, subgraph); return this; } /** * Extends builder (using {@link #extend(Map, FieldGraph)}) with given fields. * @param extension fields to extend builder with * @return Builder with all requested fields added */ public Builder<F> add(Set<F> extension) { if (!extension.isEmpty()) { if (extension instanceof FieldGraph) extend(data, (FieldGraph<F>) extension); else extend(data, FieldGraph.of(extension)); } return this; } private static <F extends Enum<F> & FieldEnum> void extend(Map<F, FieldGraph<?>> data, FieldGraph<F> extension) { for (F field : extension) { FieldGraph<?> extensionSubset = extension.data.get(field); extend(data, field, extensionSubset); } } @SuppressWarnings("unchecked") private static <F extends Enum<F> & FieldEnum, F2 extends Enum<F2> & FieldEnum> void extend(Map<F, FieldGraph<?>> data, F field, FieldGraph<F2> subgraph) { if (subgraph != null && !subgraph.getDeclaringClass().equals(field.getFieldsClass())) throw new IllegalArgumentException("Trying to extend sub-graph for field " + field + " with type " + subgraph.getDeclaringClass() + " but field declares sub-graph of type " + field.getFieldsClass()); FieldGraph<F2> thisSubGraph = (FieldGraph<F2>) data.get(field); FieldGraph<F2> mergedSubGraph; if (thisSubGraph == null) mergedSubGraph = subgraph != null ? subgraph.clone() : null; else if (subgraph == null) mergedSubGraph = thisSubGraph; else { extend(thisSubGraph.data, subgraph); mergedSubGraph = thisSubGraph; } data.put(field, mergedSubGraph); } /** * Constructes {@link FieldGraph}. * @return {@link FieldGraph} */ public FieldGraph<F> build() { return new FieldGraph<>(clazz, data); } private final Class<F> clazz; private final Map<F, FieldGraph<?>> data; } // enum-style factories /** * Constructs empty {@link FieldGraph} of {@code F} first-level fields. * @param clazz class describing first-level field type * @param <F> first-level field type * @return empty {@link FieldGraph} */ public static <F extends Enum<F> & FieldEnum> FieldGraph<F> noneOf(Class<F> clazz) { return new FieldGraph<>(clazz); } /** * Constructs {@link FieldGraph} of {@code F} first-level fields with all fields initialized. If any field described * field-enabled object, its subgraph will be empty. * @param clazz class describing first-level field type * @param <F> first-level field type * @return {@link FieldGraph} of type {@code F} with all first-level fields set */ public static <F extends Enum<F> & FieldEnum> FieldGraph<F> allOf(Class<F> clazz) { return of(EnumSet.allOf(clazz)); } /** * Constructs {@link FieldGraph} of {@code F} first-level fields with fields initialized to complement of {@code fields}. * If any field described field-enabled object, its subgraph will be empty. * @param fields fields which <u>complement</u> to initialize * @param <F> first-level field type * @return {@link FieldGraph} of type {@code F} with first-level fields initialized to complement of {@code fields} */ public static <F extends Enum<F> & FieldEnum> FieldGraph<F> complementOf(Collection<F> fields) { return of(EnumSet.complementOf(EnumSet.copyOf(fields))); } /** * Constructs {@link FieldGraph} of {@code F} first-level fields with given fields initialized. * @param fields fields to initialize * @param <F> first-level field type * @return {@link FieldGraph} of type {@code F} with first-level fields initialized to {@code fields} */ public static <F extends Enum<F> & FieldEnum> FieldGraph<F> of(Collection<F> fields) { if (fields.isEmpty()) throw new IllegalArgumentException("fields param can not be empty"); FieldGraph<F> graph = null; for (F field : fields) { if (graph == null) graph = new FieldGraph<>(field.getDeclaringClass()); graph.data.put(field, null); } return graph; } /** * Constructs {@link FieldGraph} of {@code F} first-level fields with given fields initialized. * @param first first field to initialize * @param rest other fields to initialize * @param <F> first-level field type * @return {@link FieldGraph} of type {@code F} with first-level fields initialized to {@code fields} */ public static <F extends Enum<F> & FieldEnum> FieldGraph<F> of(F first, Object... rest) { Class<F> clazz = first.getDeclaringClass(); FieldGraph<F> graph = new FieldGraph<>(clazz); graph.data.put(first, null); add(clazz, graph, rest); return graph; } // string-style factories /** * Constructs {@link FieldGraph} of {@code F} first-level fields by parsing its string representation. String representation * follows thwse rules: * <ul> * <li>fields are represented bay their enum names separated by commas: {@code foo,bar,baz}</li> * <li>each field's subfields are sourounded by curley braces (hierarchy may go as deep as needed): {@code foo,bar{b1,b2},baz{c1{c11,c12},c2}}</li> * </ul> * @param value string to parse * @param clazz class representing first-level field type * @param <F> first-level field type * @return {@link FieldGraph} of type {@code F} initialized with field graph parsed from {@code value} * @throws ParseException is value cannot be parsed */ public static <F extends Enum<F> & FieldEnum> FieldGraph<F> of(String value, Class<F> clazz) throws ParseException { return parse(RecursiveStringMap.of(value), clazz); } @SuppressWarnings("unchecked") private static <F extends Enum<F> & FieldEnum> void add(Class<F> clazz, FieldGraph<F> graph, Object... objects) { for (Object object : objects) { if (!clazz.equals(object.getClass())) throw new IllegalArgumentException("Expected " + clazz + ", but got " + object.getClass()); graph.data.put((F) object, null); } } // recursive @SuppressWarnings("unchecked") private static <F extends Enum<F> & FieldEnum> FieldGraph<F> parse(RecursiveStringMap raw, Class<F> clazz) throws UnknownFieldException { if (raw == null) return null; FieldGraph<F> graph = new FieldGraph<>(clazz); for (Map.Entry<RecursiveStringMap.Key, RecursiveStringMap> entry : raw.entrySet()) { F field; try { field = Enum.valueOf(clazz, entry.getKey().name); } catch (IllegalArgumentException e) { throw new UnknownFieldException(entry.getKey().name, clazz, entry.getKey().offset); } // NOTE this cast if WRONG, but Java complains otherwise (we need to recurse with parse using different type in each step) // Works OK due to type erasure, but beware... graph.data.put(field, parse(entry.getValue(), (Class<F>) field.getFieldsClass())); } return graph; } private FieldGraph(Class<F> clazz) { this(clazz, new EnumMap<>(clazz)); } private FieldGraph(Class<F> clazz, Map<F, FieldGraph<?>> data) { this.clazz = clazz; this.data = data; } // (Immutable)Set interface @Override public int size() { return data.size(); } @Override public boolean isEmpty() { return data.isEmpty(); } @Override public boolean contains(Object o) { return data.containsKey(o); } @Override public Iterator<F> iterator() { return Iterators.unmodifiableIterator(data.keySet().iterator()); } @Override public Object[] toArray() { return data.keySet().toArray(); } @Override public <X> X[] toArray(X[] a) { return data.keySet().toArray(a); } @Override public boolean add(F field) { throw new UnsupportedOperationException(); } @Override public boolean remove(Object o) { throw new UnsupportedOperationException(); } @Override public boolean containsAll(Collection<?> c) { return data.keySet().containsAll(c); } @Override public boolean addAll(Collection<? extends F> c) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(Collection<?> c) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(Collection<?> c) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } /** * Clones this field graph with all subgraphs. * @return new {@link FieldGraph} clone */ //@Override // GWT complains public FieldGraph<F> clone() { return new FieldGraph<>(clazz, data.isEmpty() ? new EnumMap<>(clazz) : new EnumMap<>(data)); } /** * (deep) Compares this {@link FieldGraph} to another one. * @param obj another {@link FieldGraph} to which to compare this one * @return {@code true} if given field graph contains exactly the same fields initialized as this one, {@code false} otherwise */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; FieldGraph<?> other = (FieldGraph<?>) obj; if (clazz != other.clazz) return false; if (data.size() != other.data.size()) return false; for (Map.Entry<F, FieldGraph<?>> entry : data.entrySet()) { if (!other.data.containsKey(entry.getKey())) return false; if (!Objects.equals( Optional.ofNullable(entry.getValue()).filter(subfields -> !subfields.isEmpty()).orElse(null), Optional.ofNullable(other.data.get(entry.getKey())).filter(subfields -> !subfields.isEmpty()).orElse(null) )) return false; } return true; } /** * Converts this field graph to its string representation. * @return String representation of this field graph */ @Override public String toString() { StringBuilder builder = new StringBuilder(); toString(this, builder); return builder.toString(); } // recursive private void toString(FieldGraph<?> graph, StringBuilder builder) { boolean first = true; for (Map.Entry<?, FieldGraph<?>> entry : graph.data.entrySet()) { if (first) first = false; else builder.append(','); builder.append(entry.getKey()); if (entry.getValue() != null && !entry.getValue().isEmpty()) { builder.append('{'); toString(entry.getValue(), builder); builder.append('}'); } } } /** * @return {@link FieldEnum} field class which describes first-level fields */ public Class<F> getDeclaringClass() { return clazz; } /** * <p>Retrieves (unchecked) subgraph associated with given field. If field doesn't have a subset, empty set is returned.</p> * <p>For checked subgraph retrieval, see {@link #getGraph(Enum, Class)}.</p> * * @param field field for which to retrieve subgraph * * @return subgraph associated with given field * * @see #getGraph(Enum, Class) */ public FieldGraph<?> getGraph(F field) { return data.get(field); } /** * Retrieves subgraph associated with given field. If field doesn't have a subset, empty set is returned. * * @param field field for which subset is requested * @param clazz enum to which to cast returned subset * @param <X> {@link FieldEnum} describing expected first-level field type in retrieved graph * * @return field's subset (possibly empty) * * @throws IllegalArgumentException if subgraph defines fields of type other than {@code clazz} param */ @SuppressWarnings("unchecked") public <X extends Enum<X> & FieldEnum> FieldGraph<X> getGraph(F field, Class<X> clazz) { if (!clazz.equals(field.getFieldsClass())) throw new IllegalArgumentException("Requested sub-graph for field " + field + " of type " + clazz + " but field declares sub-graph of type " + field.getFieldsClass()); FieldGraph<?> subGraphRaw = getGraph(field); if (subGraphRaw == null) return new FieldGraph<>(clazz); Class<?> subGraphDeclaringClass = subGraphRaw.getDeclaringClass(); if (!subGraphDeclaringClass.equals(clazz)) throw new IllegalArgumentException("Requested sub-graph for field " + field + " of type " + clazz + " but stored sub-graph was of type " + subGraphDeclaringClass); return (FieldGraph<X>) subGraphRaw; } private final Class<F> clazz; private final Map<F, FieldGraph<?>> data; }
package com.pineapple.mobilecraft.tumcca.activity; import android.app.ActionBar; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.Window; import android.widget.TextView; import com.pineapple.mobilecraft.R; import com.pineapple.mobilecraft.tumcca.data.WorksInfo; import com.pineapple.mobilecraft.tumcca.fragment.AlbumListFragment; import com.pineapple.mobilecraft.tumcca.fragment.WorkListFragment; import com.pineapple.mobilecraft.tumcca.manager.UserManager; import com.pineapple.mobilecraft.tumcca.server.WorksServer; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executors; /** * Created by yihao on 15/7/4. * * 用于 See All功能 */ public class WorksListActivity extends TumccaBaseActivity { private TextView mTvTitle; private long mId; public static final int MODE_LIKE = 0; public static final int MODE_COLLECT = 1; private int mDataMode = MODE_LIKE; private WorkListFragment mWorksFragment; private int mAuthorId = 0; // public static void startActivity(Activity activity, long id, long authorId, String albumName){ // Intent intent = new Intent(activity, WorksListActivity.class); // intent.putExtra("id", id); // intent.putExtra("author", authorId); // intent.putExtra("albumName", albumName); // activity.startActivity(intent); // // } public static void startActivity(Activity activity, int mode, int authorId){ Intent intent = new Intent(activity, WorksListActivity.class); intent.putExtra("data_mode", mode); intent.putExtra("authorId", authorId); activity.startActivity(intent); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getActionBar().setDisplayHomeAsUpEnabled(true); // final ActionBar actionBar = getActionBar(); // if(null!=actionBar){ // actionBar.setDisplayHomeAsUpEnabled(true); // actionBar.setTitle(getIntent().getStringExtra("albumName")); // } //final List<WorksInfo> worksInfoList = WorksManager.getInstance().getAlbumWorks(getIntent().getLongExtra("id", -1)); setContentView(R.layout.activity_album_calligraphy_list); mDataMode = getIntent().getIntExtra("data_mode", MODE_COLLECT); mAuthorId = getIntent().getIntExtra("authorId", 0); mWorksFragment = new WorkListFragment(); mWorksFragment.setWorksLoader(new WorkListFragment.WorkListLoader() { @Override public List<WorksInfo> getInitialWorks() { List<WorksInfo> worksInfoList = new ArrayList<WorksInfo>(); if(mDataMode == MODE_LIKE){ worksInfoList = WorksServer.getLikeWorks(mAuthorId, 1, 5, 400); } else if(mDataMode == MODE_COLLECT){ worksInfoList = WorksServer.getCollectWorks(mAuthorId, 1, 5, 400); } return worksInfoList; } @Override public void loadHeadWorks() { List<WorksInfo> worksInfoList = new ArrayList<WorksInfo>();; if(mDataMode == MODE_LIKE){ worksInfoList = WorksServer.getLikeWorks(mAuthorId, 1, 5, 400); } else if(mDataMode == MODE_COLLECT){ worksInfoList = WorksServer.getCollectWorks(mAuthorId, 1, 5, 400); } mWorksFragment.addWorksHead(worksInfoList); } @Override public void loadTailWorks(int page) { List<WorksInfo> worksInfoList = new ArrayList<WorksInfo>();; if(mDataMode == MODE_LIKE){ worksInfoList = WorksServer.getLikeWorks(mAuthorId, page, 5, 400); } else if(mDataMode == MODE_COLLECT){ worksInfoList = WorksServer.getCollectWorks(mAuthorId, page, 5, 400); } mWorksFragment.addWorksTail(worksInfoList); } }); getSupportFragmentManager().beginTransaction().add(R.id.layout_container, mWorksFragment).commit(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: //NavUtils.navigateUpFromSameTask(this); finish(); return true; default: break; } return super.onOptionsItemSelected(item); } }
package mk.petrovski.weathergurumvp.ui.base; import android.support.annotation.NonNull; import javax.inject.Inject; import mk.petrovski.weathergurumvp.data.DataManager; import mk.petrovski.weathergurumvp.data.remote.helper.CompositeDisposableHelper; /** * Base class that implements the Presenter interface and provides a base implementation for * attachView() and detachView(). It also handles keeping a reference to the mvpView that * can be accessed from the children classes by calling getMvpView(). */ public class BasePresenter<V extends BaseMvpView> implements Presenter<V> { CompositeDisposableHelper compositeDisposableHelper; DataManager dataManager; @Inject public BasePresenter(CompositeDisposableHelper compositeDisposableHelper, DataManager dataManager) { this.compositeDisposableHelper = compositeDisposableHelper; this.dataManager = dataManager; } private V mvpView; @Override public void attachView(@NonNull V mvpView) { this.mvpView = mvpView; } @Override public void detachView() { mvpView = null; compositeDisposableHelper.dispose(); } public boolean isViewAttached() { return mvpView != null; } public V getMvpView() { return mvpView; } public void checkViewAttached() { if (!isViewAttached()) throw new MvpViewNotAttachedException(); } public static class MvpViewNotAttachedException extends RuntimeException { public MvpViewNotAttachedException() { super("Please call Presenter.attachView(BaseMvpView) before" + " requesting data to the Presenter"); } } public DataManager getDataManager() { return dataManager; } public CompositeDisposableHelper getCompositeDisposableHelper() { return compositeDisposableHelper; } public void setCompositeDisposableHelper(CompositeDisposableHelper compositeDisposableHelper) { this.compositeDisposableHelper = compositeDisposableHelper; } }
import java.util.regex.Pattern; public class RegexDemo { public static void main(String[] args) { System.out.println(Pattern.matches("\\d*", "245")); // true } }
package org.sacc.SaccHome.util; import io.minio.BucketExistsArgs; import io.minio.ListObjectsArgs; import io.minio.MinioClient; import io.minio.Result; import io.minio.errors.*; import io.minio.messages.Item; import java.io.IOException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; public class FileUtil { /** * 判断bucket是否存在 * @param bucketname * @return */ public boolean isbucketexist(String bucketname, MinioClient minioClient) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException { if(minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketname).build())) return true; else return false; } /** * 判断file是否存在 * @param bucketname * @return */ public boolean isfileexist(String bucketname,String filename,MinioClient minioClient) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException { boolean exist = false; Iterable<Result<Item>> results = minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketname).build()); for (Result<Item> result : results) { Item item = result.get(); if(item.objectName().equals(filename)) { exist = true; } } return exist; } }
package com.smxknife.cache.redis; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import java.util.Objects; /** * @author smxknife * 2020/7/22 */ public class _02_JedisPool { public static void main(String[] args) { GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig(); JedisPool jedisPool = new JedisPool(poolConfig, "localhost", 6379); Jedis jedis = null; try { // 1. 从连接池中获取jedis对象 jedis = jedisPool.getResource(); // 2. 执行操作 Long del = jedis.del("a"); System.out.println(del); } catch (Exception e) { e.printStackTrace(); } finally { if (Objects.nonNull(jedis)) { jedis.close(); } } } }
package tom.graphic.DataView; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyVetoException; import java.beans.VetoableChangeListener; import java.io.PrintStream; import java.util.EventObject; import javax.infobus.InfoBus; import javax.infobus.InfoBusDataConsumer; import javax.infobus.InfoBusEvent; import javax.infobus.InfoBusItemAvailableEvent; import javax.infobus.InfoBusItemRevokedEvent; import javax.infobus.InfoBusMember; import javax.infobus.InfoBusMemberSupport; import tom.graphic.ThreeD.View3D; import tom.graphic.ThreeD.View3DCommon; import tom.graphic.ThreeD.World3D; // Referenced classes of package tom.graphic.DataView: // DataView, IBArray public class IBDataView extends DataView implements InfoBusMember, InfoBusDataConsumer { private InfoBusMemberSupport m_ibmImpl; private void initCommon() { m_ibmImpl = new InfoBusMemberSupport(this); } public IBDataView() { initCommon(); } public InfoBus getInfoBus() { return m_ibmImpl.getInfoBus(); } public void setInfoBus(InfoBus b) throws PropertyVetoException { m_ibmImpl.setInfoBus(b); } public void addInfoBusVetoableListener(VetoableChangeListener l) { m_ibmImpl.addInfoBusVetoableListener(l); } public void removeInfoBusVetoableListener(VetoableChangeListener l) { m_ibmImpl.removeInfoBusVetoableListener(l); } public void addInfoBusPropertyListener(PropertyChangeListener l) { m_ibmImpl.addInfoBusPropertyListener(l); } public void removeInfoBusPropertyListener(PropertyChangeListener l) { m_ibmImpl.removeInfoBusPropertyListener(l); } public void dataItemRevoked(InfoBusItemRevokedEvent e) { String itemName = e.getDataItemName(); System.out.println("InfoBusItemRevoked: { " + itemName + " } from " + e.getSource().toString() + "\n"); } public void propertyChange(PropertyChangeEvent propertychangeevent) { } public void dataItemAvailable(InfoBusItemAvailableEvent e) { System.out.println("Data item available" + e); if (e.getDataItemName().equals("DataView")) { System.out.println("DataView..."); IBArray array = new IBArray(); array.dataItemAvailable(e.requestDataItem(this, null), null); super.view.world().remObj(super.obj); super.obj = getCurrentRepr(array); super.view.world().addObj(super.obj); } } }
package com.tencent.mm.ui.conversation.a; import android.content.Context; import android.content.Intent; import android.view.View; import android.view.View.OnClickListener; import com.tencent.mm.bg.d; import com.tencent.mm.model.au; import com.tencent.mm.model.bc; import com.tencent.mm.model.c; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.plugin.sns.b.n; import com.tencent.mm.sdk.platformtools.bi; class k$8 implements OnClickListener { final /* synthetic */ int bpX; final /* synthetic */ int tiP; final /* synthetic */ k usq; k$8(k kVar, int i, int i2) { this.usq = kVar; this.bpX = i; this.tiP = i2; } public final void onClick(View view) { boolean z; bc.Ig().ba(this.bpX, this.tiP); Context context = (Context) this.usq.qJS.get(); au.HU(); String str = (String) c.DT().get(68377, null); au.HU(); c.DT().set(68377, ""); Intent intent = new Intent(); intent.putExtra("sns_timeline_NeedFirstLoadint", true); if (bi.oW(str)) { z = true; } else { z = false; } if (n.nkz != null && n.nkz.axd() > 0) { z = false; } intent.putExtra("sns_resume_state", z); d.b(context, "sns", ".ui.SnsTimeLineUI", intent); h.mEJ.h(11002, new Object[]{Integer.valueOf(8), Integer.valueOf(1)}); } }
package com.tencent.mm.ui.chatting; import com.tencent.mm.R; import com.tencent.mm.ui.base.h; class ChattingUI$1 implements Runnable { final /* synthetic */ ChattingUI tLZ; ChattingUI$1(ChattingUI chattingUI) { this.tLZ = chattingUI; } public final void run() { h.a(this.tLZ, this.tLZ.getString(R.l.notification_need_resend_dialog_prompt), "", this.tLZ.getString(R.l.notification_need_resend_dialog_prompt_resend_now), this.tLZ.getString(R.l.app_cancel), new 1(this), new 2(this)); } }
import javax.swing.ButtonModel; import javax.swing.JOptionPane; /* * 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. */ /** * * @author aluno */ public class JFrameQuestao extends javax.swing.JFrame { /** * Creates new form JFrameQuestao */ public Prova prova; public Questao questao; public boolean editando; public JFrameQuestao() { initComponents(); } // Cria questão public JFrameQuestao(Prova prova) { this.prova = prova; questao = new Questao(); editando = false; initComponents(); } // Edita questão public JFrameQuestao(Prova prova, Questao questao) { initComponents(); this.prova = prova; this.questao = questao; editando = true; jTextArea1.setLineWrap(true); jTextArea1.setWrapStyleWord(true); jTextArea1.setText(questao.getPergunta()); jTextAreaAltenativa1.setLineWrap(true); jTextAreaAltenativa1.setWrapStyleWord(true); jTextAreaAltenativa1.setText(questao.listaDeAlternativas().get(0).getAlt()); buttonAlternativa1.setSelected(questao.listaDeAlternativas().get(0).getEhCerta()); jTextAreaAltenativa2.setLineWrap(true); jTextAreaAltenativa2.setWrapStyleWord(true); jTextAreaAltenativa2.setText(questao.listaDeAlternativas().get(1).getAlt()); buttonAlternativa2.setSelected(questao.listaDeAlternativas().get(1).getEhCerta()); jTextAreaAltenativa3.setLineWrap(true); jTextAreaAltenativa3.setWrapStyleWord(true); jTextAreaAltenativa3.setText(questao.listaDeAlternativas().get(2).getAlt()); buttonAlternativa3.setSelected(questao.listaDeAlternativas().get(2).getEhCerta()); jTextAreaAltenativa4.setLineWrap(true); jTextAreaAltenativa4.setWrapStyleWord(true); jTextAreaAltenativa4.setText(questao.listaDeAlternativas().get(3).getAlt()); buttonAlternativa4.setSelected(questao.listaDeAlternativas().get(3).getEhCerta()); jTextAreaAltenativa5.setLineWrap(true); jTextAreaAltenativa5.setWrapStyleWord(true); jTextAreaAltenativa5.setText(questao.listaDeAlternativas().get(4).getAlt()); buttonAlternativa5.setSelected(questao.listaDeAlternativas().get(4).getEhCerta()); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroup1 = new javax.swing.ButtonGroup(); jScrollPane2 = new javax.swing.JScrollPane(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); buttonAlternativa1 = new javax.swing.JRadioButton(); buttonAlternativa2 = new javax.swing.JRadioButton(); buttonAlternativa3 = new javax.swing.JRadioButton(); buttonAlternativa4 = new javax.swing.JRadioButton(); buttonAlternativa5 = new javax.swing.JRadioButton(); jButtonSalvar = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jScrollPane3 = new javax.swing.JScrollPane(); jTextAreaAltenativa1 = new javax.swing.JTextArea(); jScrollPane4 = new javax.swing.JScrollPane(); jTextAreaAltenativa2 = new javax.swing.JTextArea(); jScrollPane5 = new javax.swing.JScrollPane(); jTextAreaAltenativa3 = new javax.swing.JTextArea(); jScrollPane6 = new javax.swing.JScrollPane(); jTextAreaAltenativa4 = new javax.swing.JTextArea(); jScrollPane7 = new javax.swing.JScrollPane(); jTextAreaAltenativa5 = new javax.swing.JTextArea(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setAutoRequestFocus(false); setBackground(new java.awt.Color(255, 255, 255)); jPanel1.setBackground(new java.awt.Color(255, 255, 255)); jPanel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setText("Enunciado:"); jLabel2.setText("Alternativas: (Preencha as alternativas e selecione a resposta correta)"); buttonAlternativa1.setBackground(new java.awt.Color(255, 255, 255)); buttonGroup1.add(buttonAlternativa1); buttonAlternativa2.setBackground(new java.awt.Color(255, 255, 255)); buttonGroup1.add(buttonAlternativa2); buttonAlternativa3.setBackground(new java.awt.Color(255, 255, 255)); buttonGroup1.add(buttonAlternativa3); buttonAlternativa4.setBackground(new java.awt.Color(255, 255, 255)); buttonGroup1.add(buttonAlternativa4); buttonAlternativa5.setBackground(new java.awt.Color(255, 255, 255)); buttonGroup1.add(buttonAlternativa5); jButtonSalvar.setText("Salvar"); jButtonSalvar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonSalvarActionPerformed(evt); } }); jTextArea1.setColumns(20); jTextArea1.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N jTextArea1.setRows(5); jScrollPane1.setViewportView(jTextArea1); jTextAreaAltenativa1.setColumns(20); jTextAreaAltenativa1.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N jTextAreaAltenativa1.setRows(5); jTextAreaAltenativa1.setBorder(null); jScrollPane3.setViewportView(jTextAreaAltenativa1); jTextAreaAltenativa2.setColumns(20); jTextAreaAltenativa2.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N jTextAreaAltenativa2.setRows(5); jTextAreaAltenativa2.setBorder(null); jScrollPane4.setViewportView(jTextAreaAltenativa2); jTextAreaAltenativa3.setColumns(20); jTextAreaAltenativa3.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N jTextAreaAltenativa3.setRows(5); jTextAreaAltenativa3.setBorder(null); jScrollPane5.setViewportView(jTextAreaAltenativa3); jTextAreaAltenativa4.setColumns(20); jTextAreaAltenativa4.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N jTextAreaAltenativa4.setRows(5); jTextAreaAltenativa4.setBorder(null); jScrollPane6.setViewportView(jTextAreaAltenativa4); jTextAreaAltenativa5.setColumns(20); jTextAreaAltenativa5.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N jTextAreaAltenativa5.setRows(5); jTextAreaAltenativa5.setBorder(null); jScrollPane7.setViewportView(jTextAreaAltenativa5); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(11, 11, 11) .addComponent(buttonAlternativa1)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(buttonAlternativa2))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane3) .addComponent(jScrollPane4))) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel1) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(1, 1, 1) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(buttonAlternativa5) .addComponent(buttonAlternativa3) .addComponent(buttonAlternativa4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane6) .addComponent(jScrollPane5) .addComponent(jScrollPane7)))))) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jButtonSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 385, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(291, 291, 291)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel2) .addContainerGap(631, Short.MAX_VALUE))) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(48, 48, 48) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(buttonAlternativa1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(buttonAlternativa2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(buttonAlternativa3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(buttonAlternativa4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane7, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(buttonAlternativa5)) .addGap(44, 44, 44) .addComponent(jButtonSalvar) .addContainerGap(267, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(235, 235, 235) .addComponent(jLabel2) .addContainerGap(805, Short.MAX_VALUE))) ); jScrollPane2.setViewportView(jPanel1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 1000, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 833, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(22, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButtonSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSalvarActionPerformed ButtonModel m = buttonGroup1.getSelection(); if(jTextArea1.getText().equals("") || jTextAreaAltenativa1.getText().equals("") || jTextAreaAltenativa2.getText().equals("") || jTextAreaAltenativa3.getText().equals("") || jTextAreaAltenativa4.getText().equals("") || jTextAreaAltenativa5.getText().equals("") || !apenasUmSelecionado()){ JOptionPane.showMessageDialog(this, "Preencha todos os campos.", "Erro", JOptionPane.ERROR_MESSAGE); }else{ questao.setPergunta(jTextArea1.getText()); if(editando){ questao.listaDeAlternativas().get(0).setAlt(jTextAreaAltenativa1.getText()); questao.listaDeAlternativas().get(0).setEhCerta(buttonAlternativa1.isSelected()); questao.listaDeAlternativas().get(1).setAlt(jTextAreaAltenativa2.getText()); questao.listaDeAlternativas().get(1).setEhCerta(buttonAlternativa2.isSelected()); questao.listaDeAlternativas().get(2).setAlt(jTextAreaAltenativa3.getText()); questao.listaDeAlternativas().get(2).setEhCerta(buttonAlternativa3.isSelected()); questao.listaDeAlternativas().get(3).setAlt(jTextAreaAltenativa4.getText()); questao.listaDeAlternativas().get(3).setEhCerta(buttonAlternativa4.isSelected()); questao.listaDeAlternativas().get(4).setAlt(jTextAreaAltenativa5.getText()); questao.listaDeAlternativas().get(4).setEhCerta(buttonAlternativa5.isSelected()); } else { Alternativas alternativa1 = new Alternativas(jTextAreaAltenativa1.getText(), buttonAlternativa1.isSelected()); questao.adicionaAlternativa(alternativa1); Alternativas alternativa2 = new Alternativas(jTextAreaAltenativa2.getText(), buttonAlternativa2.isSelected()); questao.adicionaAlternativa(alternativa2); Alternativas alternativa3 = new Alternativas(jTextAreaAltenativa3.getText(), buttonAlternativa3.isSelected()); questao.adicionaAlternativa(alternativa3); Alternativas alternativa4 = new Alternativas(jTextAreaAltenativa4.getText(), buttonAlternativa4.isSelected()); questao.adicionaAlternativa(alternativa4); Alternativas alternativa5 = new Alternativas(jTextAreaAltenativa5.getText(), buttonAlternativa5.isSelected()); questao.adicionaAlternativa(alternativa5); prova.adicionaQuestao(questao); } dispose(); } }//GEN-LAST:event_jButtonSalvarActionPerformed public boolean apenasUmSelecionado(){ int quantidade = 0; if(buttonAlternativa1.isSelected()) quantidade++; if(buttonAlternativa2.isSelected()) quantidade++; if(buttonAlternativa3.isSelected()) quantidade++; if(buttonAlternativa4.isSelected()) quantidade++; if(buttonAlternativa5.isSelected()) quantidade++; if(quantidade != 1 ){ return false; } else { return true; } } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(JFrameQuestao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(JFrameQuestao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(JFrameQuestao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(JFrameQuestao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new JFrameQuestao().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JRadioButton buttonAlternativa1; private javax.swing.JRadioButton buttonAlternativa2; private javax.swing.JRadioButton buttonAlternativa3; private javax.swing.JRadioButton buttonAlternativa4; private javax.swing.JRadioButton buttonAlternativa5; private javax.swing.ButtonGroup buttonGroup1; private javax.swing.JButton jButtonSalvar; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JScrollPane jScrollPane5; private javax.swing.JScrollPane jScrollPane6; private javax.swing.JScrollPane jScrollPane7; private javax.swing.JTextArea jTextArea1; private javax.swing.JTextArea jTextAreaAltenativa1; private javax.swing.JTextArea jTextAreaAltenativa2; private javax.swing.JTextArea jTextAreaAltenativa3; private javax.swing.JTextArea jTextAreaAltenativa4; private javax.swing.JTextArea jTextAreaAltenativa5; // End of variables declaration//GEN-END:variables }
package aps_pota; public class RadixSort extends AlgOrd{ public RadixSort(String nome) { super(nome); } public int NumDigitos(int[] vet){//retorna a quantidade máxima de digitos em um array. int dig=0; this.comparacoes++; for (int i = 0; i < vet.length; i++) { int temp = String.valueOf(vet[i]).length(); dig=dig>temp?dig:temp; this.comparacoes++; } return dig; } public int[] CountingSort(int[] vet,int dec) { //count parcial olha apenas a dezena atual. logo so olha numeros de 0 ate 9. int[] contador= new int[10];//o contador vai guardar quantas vezes um numero apareceu em uma dezena numa varredura de vet. int[] saida=new int[vet.length]; this.comparacoes++; for (int i = 0; i < vet.length; i++) { contador[ (vet[i]/dec)%10 ]++; // guarda a contagem da ocorrencia da dezena atual this.comparacoes++; } this.comparacoes++; for (int i = 1; i < 10; i++) { contador[i] += contador[i - 1]; //transforma um contador num array de apontamentos para indices do vetor saída descobrindo quantos numeros menores existem para o indice atual. this.comparacoes++; } this.comparacoes++; for (int i = vet.length - 1; i >= 0; i--) { saida[contador[ (vet[i]/dec)%10 ] - 1] = vet[i]; //conclui ordenando o vetor saida usando apenas a dezena atual. contador[ (vet[i]/dec)%10 ]--; this.comparacoes++; } this.comparacoes++; for (int i = 0; i < vet.length; i++) { vet[i] = saida[i]; // copia os valores para vet this.comparacoes++; } return vet; // retorna vet } public void radixSort(int[] vet) { int dig = NumDigitos(vet); int decimal=1; this.comparacoes++; for (int i = 0; i < dig; i++) { //para cada dígito do maior numero de vet, este for itera uma vez. ex: 300 iteraria 3 vezes. CountingSort(vet, decimal); decimal*=10; this.comparacoes++; } } @Override public void Orderna() { radixSort(vetor); this.tamanho = vetor.length; } }
/* * Copyright (C) 2019 TopCoder Inc., All Rights Reserved. */ package com.tmobile.percy.editor; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.FileEditorPolicy; import com.intellij.openapi.fileEditor.WeighedFileEditorProvider; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.SingleRootFileViewProvider; /** * The percy editor provider. * * @author TCSCODER * @version 1.0 */ public class PercyEditorProvider extends WeighedFileEditorProvider { /** * The editor type id. */ private static final String EDITOR_TYPE_ID = "percy-editor"; /** * Get editor type id. * * @return editor type id */ @Override public String getEditorTypeId() { return EDITOR_TYPE_ID; } /** * Get editor policy. * * @return editor policy */ @Override public FileEditorPolicy getPolicy() { return FileEditorPolicy.PLACE_AFTER_DEFAULT_EDITOR; } /** * Check whether file is accepted. * * @param project The project * @param file The file * @return true if file is accepted; false otherwise */ @Override public boolean accept(Project project, VirtualFile file) { if (file.isDirectory() || !file.exists() || SingleRootFileViewProvider.isTooLargeForContentLoading(file)) { return false; } // when a project is already disposed due to a slow initialization, // reject this file if (project.isDisposed()) { return false; } return "yaml".equalsIgnoreCase(file.getExtension()) || "yml".equalsIgnoreCase(file.getExtension()); } /** * Create editor. * * @param project The project * @param file The file * @return editor */ @Override public FileEditor createEditor(Project project, VirtualFile file) { return new PercyEditor(project, file); } }
package application; import java.util.Calendar; import java.util.TimeZone; public class Exercise05 { public static void main(String[] args) { //Write a Java program to get the current time in New York Calendar calNY = Calendar.getInstance(); calNY.setTimeZone(TimeZone.getTimeZone("America/New_York")); System.out.println("Time in NY: " + calNY.get(Calendar.HOUR_OF_DAY) + ":" + calNY.get(Calendar.MINUTE) + ":" + calNY.get(Calendar.SECOND)); } }
package server.by.epam.fullparser.service; /** * Exception handler of service layer. */ public class ServiceException extends Exception{ public ServiceException(String message){ super(message); } public ServiceException(String message,Throwable cause){ super(message,cause); } }
package com.qy.zgz.kamiduo.vbar; import android.os.Environment; import android.util.Log; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; public class WriteLog { //日志记录方法 public static void log(final String filename) { Log.e("ads","ww"); try { final String publicDir = Environment.getExternalStorageDirectory().toString(); limitFile(publicDir,filename); // final String publicDir = FileManager.getInstance().getDownFileDir(); Process p = Runtime.getRuntime().exec(new String[]{"logcat","-v","time","*:W","*:E","*:D","*:V"}); final InputStream is = p.getInputStream(); new Thread() { @Override public void run() { FileOutputStream os = null; try { os = new FileOutputStream(publicDir+"/"+filename,true); File file=new File(publicDir+"/"+filename); int len = 0; byte[] buf = new byte[1024]; while (-1 != (len = is.read(buf))) { if (file.length()>20*1024*1024) { FileWriter fileWriter =new FileWriter(file); fileWriter.write(""); fileWriter.flush(); fileWriter.close(); } os.write(buf, 0, len); os.flush(); } } catch (Exception e) { Log.d("writelog", "read logcat process failed. message: " + e.getMessage()); } finally { if (null != os) { try { os.close(); os = null; } catch (IOException e) { // Do nothing } } } } }.start(); Log.d("writelog", "open logcat process sussess. message: " ); } catch (Exception e) { Log.d("writelog", "open logcat process failed. message: " + e.getMessage()); } } //限制文件个数 2个 //删除时间最早的那个文件 public static void limitFile(String publicDir,final String filename){ File file=new File(publicDir); //过滤子文件中 符合名称的文件 File[] childfiles=file.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return (name.indexOf(filename.split("_")[0])!=-1); } }); try{ if (childfiles.length>3){ for (int i=0;i<childfiles.length;i++){ if (i>=childfiles.length-2){ break; }else { childfiles[i].delete(); } } } }catch (Exception e){ } //判断文件最后修改时间 if (childfiles.length>1) { long time1=childfiles[0].lastModified(); long time2=childfiles[1].lastModified(); if (time1>time2) { childfiles[1].delete(); } else childfiles[0].delete(); } } }
package com.hesoyam.pharmacy.user.repository; import com.hesoyam.pharmacy.user.model.Role; import org.springframework.data.jpa.repository.JpaRepository; public interface RoleRepository extends JpaRepository<Role, Long> { Role findByRoleName(String name); }
package Main; import java.io.File; import java.io.IOException; import java.util.Scanner; /** * UserInputUtil class is used to userInput so it can be manipulated * @author Philip Evans * */ public class UserInputUtil { /** * These class variables are Strings that was be passed onto other methods * in main. * m_Name = customer first name * m_Surname = customer surname * m_InputCSVFile the filename of the input file * m_OutputFile the filename of the output file */ private String m_Name; private String m_Surname; private String m_InputCSVFile; private String m_OutputCSVFile; public UserInputUtil(Scanner input){ System.out.println("Welcome to Philip Moses Evans' Backbase application" + " task"); this.m_Name = UserInputUtil.InputString(input, "firstname"); this.m_Surname = UserInputUtil.InputString(input, "surname"); this.m_InputCSVFile = UserInputUtil.InputFile(input); this.m_OutputCSVFile = "OutPutFileOf"+ m_InputCSVFile; } /** * Accessor to get the m_Name class variable * @return the first name of the customer */ public String getName() { return m_Name; } /** * Accessor to get the m_Surname class variable * @return the surname of the customer */ public String getSurname() { return m_Surname; } /** * Accessor to get the m_InputCSVFile class variable * @return the name of the inputFile */ public String getInputCSVFile() { return m_InputCSVFile; } /** * Accessor to get the m_OutputCSVFile class variable * @return the name of the outputFile */ public String getOutputCSVFile() { return m_OutputCSVFile; } /** * Method which generates the userinput to get the firstname or surname of * a customer * @param in the scanner used in the constructor * @param type helps differentiate which type of user input to show * appropriate prompt message * @return */ private static String InputString(Scanner in, String type){ String outputString = ""; boolean hasNext = true; do{ if (type.equals("firstname")){ System.out.println("Please enter the firstname of the customer " + "you wish to evaluate"); }else{ System.out.println("Please enter the surname of the customer " + "you wish to evaluate"); } if(in.hasNext()){ outputString = in.next(); }else{ System.out.println("Please enter something"); hasNext = false; in.next(); } } while (!(hasNext)); return outputString; } /** * User response used in main * @param in scanner * @return response of user */ public static String userContinue(Scanner in){ System.out.println("Do you wish to evaluate another csv file? Y for yes anything else for no"); String response = in.next(); return response; } /** * Method which generates the user input to get the inputFile name * @param in the scanner used in the constructor * @return returns the filename */ private static String InputFile(Scanner in) { Boolean fileExists = true; String filename = ""; do{ System.out.println("Please enter the name of the csv ledger input " + "file you wish to evaluate"); if(in.hasNext()){ filename = in.next(); File maybeExists = new File(filename); if (maybeExists.exists() == true){ System.out.println("file has been found"); filename = maybeExists.getName(); fileExists = true; }else{ System.out.println("file " + filename + " has been not " + "found try again"); fileExists = false; } } }while (!fileExists); return filename; } }
package ru.itis.javalab.listeners; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import ru.itis.javalab.config.*; import ru.itis.javalab.services.*; import ru.itis.javalab.services.PostServiceImpl; import ru.itis.javalab.services.UserService; import ru.itis.javalab.services.UserServiceImpl; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; /** * created: 19-11-2020 - 1:25 * project: 07. Fremarker * * @author dinar * @version v0.1 */ @WebListener public class ApplicationContextListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent event) { ServletContext servletContext = event.getServletContext(); ApplicationContext applicationContext = new AnnotationConfigApplicationContext(ApplicationConfig.class); UserService userService = applicationContext.getBean(UserServiceImpl.class); PostService postService = applicationContext.getBean(PostServiceImpl.class); servletContext.setAttribute("userService", userService); servletContext.setAttribute("postService", postService); } }
package com.fleet.jpush.entity; import java.io.Serializable; import java.util.Map; public class JPush implements Serializable { private static final long serialVersionUID = 1L; /** * 目标平台: "all","android","ios","winphone" */ private String platform; private String title; private String alert; private Map<String, String> extras; public String getPlatform() { return platform; } public void setPlatform(String platform) { this.platform = platform; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAlert() { return alert; } public void setAlert(String alert) { this.alert = alert; } public Map<String, String> getExtras() { return extras; } public void setExtras(Map<String, String> extras) { this.extras = extras; } }
package com.ducph.consoledrawing.model; import com.ducph.consoledrawing.util.Utils; import lombok.Data; @Data public class Line implements Entity { private int x1; private int y1; private int x2; private int y2; public Line(int x1, int y1, int x2, int y2) { if (x1 != x2 && y1 != y2) { throw new IllegalArgumentException("Draw line does not support diagonal line at the moment"); } Utils.shouldAllPositive(x1, y1, x2, y2); this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } }
package com.epam.jmp.module.concurency; import com.epam.jmp.module.concurency.bus.*; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.IntStream; import static org.testng.Assert.assertNotNull; public class DeadLockTest { @BeforeMethod public void setUp() { } @Test public void deadlockTest() throws InterruptedException { List<Integer> numbers = new CopyOnWriteArrayList<>(); final AtomicBoolean isActive = new AtomicBoolean(true); List<Thread> threads = Arrays.asList(new Thread(() -> { while (isActive.get()) { numbers.add(ThreadLocalRandom.current().nextInt(0, 10000)); } }), new Thread(() -> { while (isActive.get()) { System.out.println(numbers.stream().reduce(0, Integer::sum)); } }), new Thread(() -> { while (isActive.get()) { System.out.println(numbers.stream().reduce(0, (x, y) -> ((Double) (Math.sqrt(x) + Math.sqrt(y))).intValue())); } })); threads.forEach(Thread::start); TimeUnit.MILLISECONDS.sleep(1000); isActive.set(false); for (Thread thread : threads) { thread.join(); } } @Test public void deadlockTestSynchronized() throws InterruptedException { List<Integer> numbers = new ArrayList<>(); final AtomicBoolean isActive = new AtomicBoolean(true); List<Thread> threads = Arrays.asList(new Thread(() -> { while (isActive.get()) { synchronized (numbers) { numbers.add(ThreadLocalRandom.current().nextInt(0, 10000)); } } }), new Thread(() -> { while (isActive.get()) { synchronized (numbers) { System.out.println(numbers.stream().reduce(0, Integer::sum)); } } }), new Thread(() -> { while (isActive.get()) { synchronized (numbers) { System.out.println(numbers.stream().reduce(0, (x, y) -> ((Double) (Math.sqrt(x) + Math.sqrt(y))).intValue())); } } })); threads.forEach(Thread::start); TimeUnit.MILLISECONDS.sleep(1000); isActive.set(false); for (Thread thread : threads) { thread.join(); } } }
package c523.spark_streaming_eg; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import kafka.serializer.StringDecoder; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.util.Bytes; import org.apache.spark.SparkConf; import org.apache.spark.streaming.Durations; import org.apache.spark.streaming.api.java.JavaDStream; import org.apache.spark.streaming.api.java.JavaPairDStream; import org.apache.spark.streaming.api.java.JavaPairInputDStream; import org.apache.spark.streaming.api.java.JavaStreamingContext; import org.apache.spark.streaming.kafka.KafkaUtils; import scala.Tuple2; import com.google.gson.Gson; public class SparkStreaming { private static Connection connection; private static void initialize() { Configuration config = HBaseConfiguration.create(); try { connection = ConnectionFactory.createConnection(config); } catch(Exception exc) { exc.printStackTrace(); } } private static void saveRDD(String tableName, List<Put> puts) throws IOException { Table hTable = connection.getTable(TableName.valueOf(tableName)); hTable.put(puts); hTable.close(); } private static void saveCounts(JavaPairInputDStream<String, String> stream) { String table = "tweet_counts"; String cf = "countInfo"; JavaPairDStream<Integer, Integer> tweetCounts = stream.map(s -> new Gson().fromJson(s._2, Tweet.class)) .mapToPair(s -> new Tuple2<Integer, Integer>(s.getCreatedAt(), 1)) .reduceByKey(Integer::sum); tweetCounts.foreachRDD(t -> { if (!t.isEmpty()) { List<Tuple2<Integer, Integer>> obj = t.collect(); List<Put> puts = new ArrayList<Put>(); for (Tuple2<Integer, Integer> o : obj) { Put put = new Put(Bytes.toBytes(o._1.toString())); put.addImmutable(Bytes.toBytes(cf), Bytes.toBytes("id"), Bytes.toBytes(o._1.toString())); put.addImmutable(Bytes.toBytes(cf), Bytes.toBytes("elapseTime"), Bytes.toBytes(o._1.toString())); put.addImmutable(Bytes.toBytes(cf), Bytes.toBytes("tweetCount"), Bytes.toBytes(o._2.toString())); puts.add(put); } saveRDD(table, puts); } }); } private static boolean filterWord(String statusText, String[] words) { boolean contained = false; for(String w : words) { contained = contained || statusText.toLowerCase().contains(w); if(contained) { break; } } return contained; } private static void saveWordCounts(JavaPairInputDStream<String, String> stream, String[] filteredWords) { String table = "tweet_words"; String cf = "wordInfo"; JavaDStream<String> tweetStream = stream.map(s -> new Gson().fromJson(s._2, Tweet.class)) .filter(s -> SparkStreaming.filterWord(s.getStatusText(), filteredWords)) .map(s -> s.getStatusText()); tweetStream.foreachRDD(t -> { if(!t.isEmpty()) { List<String> tweets = t.collect(); Map<String, Integer> wordCounts = new HashMap<String, Integer>(); for(String statusText : tweets) { for(String filterW : filteredWords) { if(statusText.toLowerCase().contains(filterW)) { if(wordCounts.containsKey(filterW)) { wordCounts.put(filterW, wordCounts.get(filterW) + 1); } else { wordCounts.put(filterW, 1); } } } } Iterator<Entry<String, Integer>> iterator = wordCounts.entrySet().iterator(); long timeStamp = System.currentTimeMillis() / 1000; List<Put> puts = new ArrayList<Put>(); while(iterator.hasNext()) { Entry<String, Integer> entry = iterator.next(); String id = timeStamp + entry.getKey(); System.out.println(id); Put put = new Put(Bytes.toBytes(id)); put.addImmutable(Bytes.toBytes(cf), Bytes.toBytes("id"), Bytes.toBytes(id)); put.addImmutable(Bytes.toBytes(cf), Bytes.toBytes("word"), Bytes.toBytes(entry.getKey())); put.addImmutable(Bytes.toBytes(cf), Bytes.toBytes("tweetCount"), Bytes.toBytes(entry.getValue().toString())); put.addImmutable(Bytes.toBytes(cf), Bytes.toBytes("createdAt"), Bytes.toBytes(String.valueOf(timeStamp))); puts.add(put); } saveRDD(table, puts); } }); } public static void main(String[] args) throws Exception { if (args.length < 1) { System.err.println("Usage: SparkStreaming <hostname>:<port>"); System.exit(1); } String filteredWords[] = new String[]{"trump", "bitcoin", "football", "snow", "iphone"}; if(args.length == 2) { filteredWords = args[1].split(","); } System.out.println(filteredWords); initialize(); // Create the context with a 1 second batch size SparkConf sparkConf = new SparkConf().setAppName("SparkStreaming").setMaster("local"); JavaStreamingContext ssc = new JavaStreamingContext(sparkConf, Durations.seconds(5)); Map<String, String> kafkaParams = new HashMap<>(); kafkaParams.put("bootstrap.servers", args[0]); kafkaParams.put("group.id", "kafka-spark-streaming-example"); Set<String> topics = new HashSet<String>(); topics.add("sparktest"); JavaPairInputDStream<String, String> stream = KafkaUtils.createDirectStream(ssc, String.class, String.class, StringDecoder.class, StringDecoder.class, kafkaParams, topics); saveCounts(stream); saveWordCounts(stream, filteredWords); ssc.start(); ssc.awaitTermination(); } }
// Sun Certified Java Programmer // Chapter 5, P337_3 // Flow Control, Exceptions, and Assertions class Tester337_3 { public static void main(String[] args) { switch (new Integer(4)) { case 4: System.out.println("boxing is OK"); } } }
/* * 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 forms; import classes.Livro; import java.util.List; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; /** * * @author alunoces */ public class FormConsultaLivroTabela extends javax.swing.JFrame { DefaultTableModel modelo; /** * Creates new form FormConsultaLivro */ public FormConsultaLivroTabela() { initComponents(); //tira o foco btBuscar.setFocusable(false); //cria a tabela this.modelo = (DefaultTableModel) jTable1.getModel(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); btEditar = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); tfCodigo = new javax.swing.JTextField(); btBuscar = new javax.swing.JButton(); ckBuscarTodos = new javax.swing.JCheckBox(); btExcluir = new javax.swing.JButton(); btSair = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Consulta Livro"); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Código", "Titulo", "Fornecedor", "Estoque", "Valor Unitário", "Data publicação" } ) { Class[] types = new Class [] { java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.Float.class, java.lang.String.class }; boolean[] canEdit = new boolean [] { false, false, false, false, false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF); jTable1.getTableHeader().setReorderingAllowed(false); jTable1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jTable1MouseClicked(evt); } }); jScrollPane1.setViewportView(jTable1); if (jTable1.getColumnModel().getColumnCount() > 0) { jTable1.getColumnModel().getColumn(0).setResizable(false); jTable1.getColumnModel().getColumn(0).setPreferredWidth(50); jTable1.getColumnModel().getColumn(1).setResizable(false); jTable1.getColumnModel().getColumn(1).setPreferredWidth(200); jTable1.getColumnModel().getColumn(2).setResizable(false); jTable1.getColumnModel().getColumn(2).setPreferredWidth(150); jTable1.getColumnModel().getColumn(3).setResizable(false); jTable1.getColumnModel().getColumn(3).setPreferredWidth(50); jTable1.getColumnModel().getColumn(4).setResizable(false); jTable1.getColumnModel().getColumn(4).setPreferredWidth(90); jTable1.getColumnModel().getColumn(5).setResizable(false); jTable1.getColumnModel().getColumn(5).setPreferredWidth(90); } btEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/icAtualizar2.png"))); // NOI18N btEditar.setText("Editar"); btEditar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btEditarActionPerformed(evt); } }); jLabel1.setText("Código"); tfCodigo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tfCodigoActionPerformed(evt); } }); btBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/icBuscar.png"))); // NOI18N btBuscar.setText("Buscar"); btBuscar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btBuscarActionPerformed(evt); } }); ckBuscarTodos.setText("Buscar todos"); ckBuscarTodos.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ckBuscarTodosActionPerformed(evt); } }); btExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/icExcluir.png"))); // NOI18N btExcluir.setText("Excluir"); btExcluir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btExcluirActionPerformed(evt); } }); btSair.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/icSair.png"))); // NOI18N btSair.setText("Sair"); btSair.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btSairActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(25, 25, 25) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(20, 20, 20) .addComponent(btEditar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btExcluir) .addGap(117, 117, 117) .addComponent(btSair) .addGap(32, 32, 32)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 600, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addGroup(layout.createSequentialGroup() .addComponent(tfCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(96, 96, 96) .addComponent(btBuscar))) .addGap(95, 95, 95) .addComponent(ckBuscarTodos))) .addContainerGap(20, Short.MAX_VALUE)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(21, 21, 21) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(tfCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btBuscar) .addComponent(ckBuscarTodos)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 37, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 268, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btSair, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btEditar)) .addGap(53, 53, 53)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btEditarActionPerformed // TODO add your handling code here: //pegar o livro da celular selecionada // mesma que fez no excluir. Livro livro = getLivro(); FormLivro frm = new FormLivro(); frm.setVisible(true); frm.livro = livro; //ou fecha a janela ou esconde a janela, pois se esconde não tem que fazer a pesquisa novamente e se fechar terá que fazer a pesquisa novemente //no caso desaparecemos a janela this.dispose(); }//GEN-LAST:event_btEditarActionPerformed private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked // TODO add your handling code here: btEditar.setEnabled(true); btExcluir.setEnabled(true); }//GEN-LAST:event_jTable1MouseClicked private void tfCodigoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfCodigoActionPerformed // TODO add your handling code here: }//GEN-LAST:event_tfCodigoActionPerformed private void btBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btBuscarActionPerformed // TODO add your handling code here: limparTabela(); // limpa area do texto if (ckBuscarTodos.isSelected()) { List<Livro> lista = FormPrincipal.daoLivro.todosLivros(); for (Livro l : lista) { incluirLivroTabela(l); } } else { if (tfCodigo.getText().trim().length() != 0) { int codigo = Integer.parseInt(tfCodigo.getText()); Livro livro = FormPrincipal.daoLivro.buscarLivro(codigo); if (livro != null) { incluirLivroTabela(livro); } else { JOptionPane.showMessageDialog(null, "Livro não encontrado.", "Atenção!", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(null, "Favor preencher o Código do Livro! ", "Atenção!", JOptionPane.ERROR_MESSAGE); tfCodigo.requestFocus(); } } }//GEN-LAST:event_btBuscarActionPerformed private void btSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSairActionPerformed // TODO add your handling code here: int sairSistema = JOptionPane.showConfirmDialog(null, "Sair da Consulta? ", "Sair da Janela", JOptionPane.YES_OPTION, JOptionPane.QUESTION_MESSAGE); if (sairSistema == 0) { this.dispose(); } }//GEN-LAST:event_btSairActionPerformed private void btExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btExcluirActionPerformed // TODO add your handling code here: Livro livro = getLivro(); FormPrincipal.daoLivro.removerLivro(livro.getCodigo()); modelo.removeRow(jTable1.getSelectedRow()); }//GEN-LAST:event_btExcluirActionPerformed private void ckBuscarTodosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ckBuscarTodosActionPerformed // TODO add your handling code here: tfCodigo.setText(""); if(ckBuscarTodos.isSelected()) { tfCodigo.setEnabled(false); } else { tfCodigo.setEnabled(true); tfCodigo.requestFocus(); tfCodigo.setText(""); } }//GEN-LAST:event_ckBuscarTodosActionPerformed private void incluirLivroTabela(Livro livro) { modelo.addRow(new Object[]{livro.getCodigo(), livro.getTitulo(), livro.getFornecedor(), livro.getQtdEstoque(), livro.getDataPublicacao()}); } public void limparTabela() { for (int i = jTable1.getRowCount() - 1; i >= 0; --i) { modelo.removeRow(i); } } private Livro getLivro() { Livro livro = new Livro(); int linha = jTable1.getSelectedRow(); livro.setCodigo((Integer) modelo.getValueAt(linha, 0)); livro.setTitulo((String) modelo.getValueAt(linha, 1)); livro.setFornecedor((String) modelo.getValueAt(linha, 2)); livro.setQtdEstoque((Integer) modelo.getValueAt(linha, 3)); livro.setValorUnitario((Float) modelo.getValueAt(linha, 4)); livro.setDataPublicacao((String) modelo.getValueAt(linha, 5)); return livro; } /** * * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(FormConsultaLivroTabela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(FormConsultaLivroTabela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(FormConsultaLivroTabela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(FormConsultaLivroTabela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new FormConsultaLivroTabela().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btBuscar; private javax.swing.JButton btEditar; private javax.swing.JButton btExcluir; private javax.swing.JButton btSair; private javax.swing.JCheckBox ckBuscarTodos; private javax.swing.JLabel jLabel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable1; private javax.swing.JTextField tfCodigo; // End of variables declaration//GEN-END:variables }
package com.mavi.webirssi.layout; import java.util.List; import com.mavi.IRCConnectionManager; import com.mavi.IRCMessage; import com.vaadin.event.FieldEvents.BlurEvent; import com.vaadin.event.FieldEvents.BlurListener; import com.vaadin.event.FieldEvents.FocusEvent; import com.vaadin.event.FieldEvents.FocusListener; import com.vaadin.event.ShortcutAction; import com.vaadin.event.ShortcutListener; import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.RichTextArea; import com.vaadin.ui.TextArea; import com.vaadin.ui.TextField; import com.vaadin.ui.VerticalLayout; public class ChannelLayout extends VerticalLayout implements TabSheetLayout { private RichTextArea area; private TextArea nickList; private TextField tf; private IRCConnectionManager connectionManager; private String channel; public ChannelLayout(IRCConnectionManager connectionManager, String channel) { this.connectionManager = connectionManager; buildLayout(); this.channel = channel; } private void buildLayout() { setSizeFull(); HorizontalLayout mainLayout = new HorizontalLayout(); mainLayout.setSizeFull(); area = new RichTextArea(); area.addStyleName("no-toolbar-top"); area.addStyleName("no-toolbar-bottom"); // area.setImmediate(true); area.setSizeFull(); mainLayout.addComponent(area); mainLayout.setExpandRatio(area, 1.0f); // TODO: // Update this // Make uneditable nickList = new TextArea(); // nickList.setImmediate(true); nickList.setHeight("100%"); nickList.setEnabled(false); mainLayout.addComponent(nickList); HorizontalLayout submitLayout = new HorizontalLayout(); submitLayout.setWidth("100%"); tf = new TextField(); tf.setSizeFull(); submitLayout.addComponent(tf); submitLayout.setExpandRatio(tf, 1.0f); final EnterListener enterListener = new EnterListener("Shortcut Name", ShortcutAction.KeyCode.ENTER, null); tf.addFocusListener(new FocusListener() { @Override public void focus(FocusEvent event) { tf.addShortcutListener(enterListener); } }); tf.addBlurListener(new BlurListener() { @Override public void blur(BlurEvent event) { tf.removeShortcutListener(enterListener); } }); Button button = new Button("Send"); button.addClickListener(new Button.ClickListener() { public void buttonClick(ClickEvent event) { String msg = tf.getValue(); sendMessage(msg); } }); submitLayout.addComponent(button); addComponent(mainLayout); addComponent(submitLayout); setExpandRatio(mainLayout, 1.0f); } private class EnterListener extends ShortcutListener { public EnterListener(String caption, int keyCode, int... modifierKeys) { super(caption, keyCode, modifierKeys); } @Override public void handleAction(Object sender, Object target) { String msg = tf.getValue(); sendMessage(msg); } } private void sendMessage(String msg) { if (msg != null) { connectionManager.doMessage(channel, msg); tf.setValue(""); } } private String getNick() { return connectionManager.getNick(); } public void refreshContent() { String content = ""; List<IRCMessage> messages = connectionManager.getMessages(channel); // TODO: parse links // http://stackoverflow.com/questions/5713558/detect-and-extract-url-from-a-string String nick = getNick(); for (IRCMessage message : messages) { boolean personal = message.isPersonal(); boolean bold = message.getMsg().contains(nick); int minutes = message.getDate().getMinutes(); String minutesString = (minutes < 10) ? "0" + minutes : "" + minutes; int hours = message.getDate().getHours(); String hoursString = (hours < 10) ? "0" + hours : "" + hours; String line = "[" + hoursString + ":" + minutesString + "] [" + message.getNick() + "]"; if (personal) line += " --> [" + nick + "]"; else line += ":"; line += message.getMsg(); if (bold) { content = content + "<b>" + line + "</b><br>"; } else { content = content + line + "<br>"; } } area.setValue(content); List<String> nicks = connectionManager.getNicks(); String nickContent = ""; for (String listNick : nicks) { nickContent += listNick + "\n"; } nickList.setValue(nickContent); } }
package com.xiaoxiao.tiny.frontline.service.impl; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.xiaoxiao.pojo.XiaoxiaoLeaveMessage; import com.xiaoxiao.pojo.vo.XiaoxiaoLeaveMessageVo; import com.xiaoxiao.tiny.frontline.feign.RedisCacheFeignClient; import com.xiaoxiao.tiny.frontline.mapper.FrontlineTinyLeaveMessageMapper; import com.xiaoxiao.tiny.frontline.service.FrontlineTinyLeaveMessageService; import com.xiaoxiao.tiny.frontline.utils.PageUtils; import com.xiaoxiao.utils.IDUtils; import com.xiaoxiao.utils.PageResult; import com.xiaoxiao.utils.Result; import com.xiaoxiao.utils.StatusCode; import net.bytebuddy.asm.Advice; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.ResourceUtils; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * _ooOoo_ o8888888o 88" . "88 (| -_- |) O\ = /O ____/`---'\____ .' \\| |// `. / \\||| : |||// \ / _||||| -:- |||||- \ | * | \\\ - /// | | | \_| ''\---/'' | | \ .-\__ `-` ___/-. / ___`. .' /--.--\ `. . __ ."" '< `.___\_<|>_/___.' >'"". | | * : `- \`.;`\ _ /`;.`/ - ` : | | \ \ `-. \_ __\ /__ _/ .-` / / ======`-.____`-.___\_____/___.-`____.-'====== `=---=' * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 佛祖保佑 永无BUG 佛曰: 写字楼里写字间,写字间里程序员; 程序人员写程序,又拿程序换酒钱。 酒醒只在网上坐,酒醉还来网下眠; * 酒醉酒醒日复日,网上网下年复年。 但愿老死电脑间,不愿鞠躬老板前; 奔驰宝马贵者趣,公交自行程序员。 别人笑我忒疯癫,我笑自己命太贱; 不见满街漂亮妹,哪个归得程序员? * * @project_name:xiaoxiao_final_blogs * @date:2019/12/19:14:57 * @author:shinelon * @Describe: */ @Service @SuppressWarnings("all") public class FrontlineTinyLeaveMessageServiceImpl implements FrontlineTinyLeaveMessageService { @Autowired private FrontlineTinyLeaveMessageMapper frontlineTinyLeaveMessageMapper; @Autowired private RedisCacheFeignClient client; @Override public Result insert(XiaoxiaoLeaveMessage leaveMessage) { leaveMessage.setMessageId(IDUtils.getUUID()); leaveMessage.setMessageDate(new Date()); leaveMessage.setMessageParentId("-1"); if (this.frontlineTinyLeaveMessageMapper.insert(leaveMessage) > 0) { try { /** * 删除分页缓存 */ this.client.deleteLeaveMessage(); } catch (Exception e) { e.printStackTrace(); } try { /** * 删除缓存留言个数 */ this.client.deleteLeaveMessageSum(); } catch (Exception e) { e.printStackTrace(); } return Result.ok(StatusCode.OK, Result.MARKED_WORDS_SUCCESS); } return Result.ok(StatusCode.OK, Result.MARKED_WORDS_FAULT); } @Override public Result findAllLeaveMessage(Integer page, Integer rows) { try { PageResult leaveMessage = this.client.getLeaveMessage(page); if (leaveMessage != null && leaveMessage.getResult().size() > 0) { return Result.ok(StatusCode.OK, Result.MARKED_WORDS_SUCCESS, leaveMessage); } } catch (Exception e) { e.printStackTrace(); } PageHelper.startPage(page, rows); List<XiaoxiaoLeaveMessage> allLeaveMessage = this.frontlineTinyLeaveMessageMapper.findAllLeaveMessage(); List<XiaoxiaoLeaveMessage> son = getSon(allLeaveMessage); if (allLeaveMessage.size() > 0 && allLeaveMessage != null) { PageResult result = PageUtils.getResult(new PageInfo<XiaoxiaoLeaveMessage>(allLeaveMessage), page); /** * 设置数据 */ result.setResult(son); try { /** * 插入缓存 */ this.client.insertLeaveMessage(result, page); /** * 删除缓存留言个数 */ this.client.deleteLeaveMessageSum(); } catch (Exception e) { e.printStackTrace(); } return Result.ok(StatusCode.OK, true, Result.MARKED_WORDS_SUCCESS, result); } return Result.error(StatusCode.ERROR, Result.MARKED_WORDS_FAULT); } @Override public Result getLeaveMessageSum() { try { XiaoxiaoLeaveMessageVo leaveMessageSum1 = this.client.getLeaveMessageSum(); if (leaveMessageSum1 != null) { return Result.ok(StatusCode.OK, true, Result.MARKED_WORDS_SUCCESS, leaveMessageSum1); } } catch (Exception e) { e.printStackTrace(); } XiaoxiaoLeaveMessageVo leaveMessageSum = this.frontlineTinyLeaveMessageMapper.getLeaveMessageSum(); if (leaveMessageSum != null) { try { this.client.insertLeaveMessageSum(leaveMessageSum); } catch (Exception e) { e.printStackTrace(); } return Result.ok(StatusCode.OK, true, Result.MARKED_WORDS_SUCCESS, leaveMessageSum); } return Result.error(StatusCode.ERROR, Result.MARKED_WORDS_FAULT); } /** * 获取子评论 * * @param messageId * @return */ public List<XiaoxiaoLeaveMessage> getSon(List<XiaoxiaoLeaveMessage> leaveMessages) { ArrayList<XiaoxiaoLeaveMessage> list = new ArrayList<>(); if (leaveMessages == null || leaveMessages.size() < 0) { return leaveMessages; } else { /** * 1.如果 */ for (XiaoxiaoLeaveMessage x : leaveMessages) { if (x.getMessageParentId() != null && x.getMessageParentId() != "") { List<XiaoxiaoLeaveMessage> son = this.frontlineTinyLeaveMessageMapper.getSon(x.getMessageId()); x.setList(son); list.add(x); }else { list.add(x); } } } return list; } }
package de.fu_berlin.inf.archnemesis.core.chralx; public class ChralxUtil { }
package rx.vincent.com.rx; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import rx.Observable; import rx.Subscriber; import rx.functions.Action1; import rx.functions.Func1; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Observable observable = Observable.create(new Observable.OnSubscribe<String>(){ @Override public void call(Subscriber<? super String> subscriber) { subscriber.onNext("Hello World"); subscriber.onCompleted(); } }); Subscriber<String> stringSubscriber = new Subscriber<String>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(String s) { System.out.print(s); } }; observable.subscribe(stringSubscriber); //just 就是创建只发出一个事件的Observable对象 Observable<String> observable1 = Observable.just("Hello World"); Action1<String> onNextAction = new Action1<String>() {// 相当于上面的doNext doError doComplete @Override public void call(String s) { System.out.println(s); } }; observable1.subscribe(onNextAction);// onErrorAction onCompleteAction Observable.just("Hello World") .subscribe(new Action1<String>() { @Override public void call(String s) { System.out.print(s); } }); Observable.just("Hello World")// use lambda .subscribe(s -> System.out.print(s)); // Observable.just("Hello World "+ "Dan") .subscribe(s -> System.out.println(s)); Observable.just("Hello, world!") .subscribe(s -> System.out.println(s + " -Dan")); Observable.just("Hello World")// 差不多就是将just进来的参数做进一步处理 .map(new Func1<String,String>(){ @Override public String call(String s) { return s + "-Dan"; } }) .subscribe(new Action1<String>() { @Override public void call(String s) { System.out.print(s); } }); Observable.just("Hello World")//use lamdba .map(s -> s + " -Dan") .subscribe(s -> System.out.println(s)); // Observable.just("Hello World") .map(new Func1<String, Integer>() { @Override public Integer call(String s) { return s.hashCode(); } }) .subscribe(new Action1<Integer>() { @Override public void call(Integer integer) { System.out.print(Integer.toString(integer)); } }); Observable.just("Hello World") // Use lamdba .map(s -> s.hashCode()) .subscribe(integer -> System.out.print(Integer.toString(integer))); Observable.just("Hello World")//Subscriber做的事情越少越好,我们再增加一个map操作符 .map(s -> s.hashCode()) .map(i -> Integer.toString(i)) .subscribe(s -> System.out.print(s)); // // 1.Observable和Subscriber可以做任何事情 // Observable可以是一个数据库查询,Subscriber用来显示查询结果; // Observable可以是屏幕上的点击事件,Subscriber用来响应点击事件; // Observable可以是一个网络请求,Subscriber用来显示请求结果。 // // 2.Observable和Subscriber是独立于中间的变换过程的。 // 在Observable和Subscriber中间可以增减任何数量的map。 // 整个系统是高度可组合的,操作数据是一个很简单的过程。 } }
/* * 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 laptinhmang; import java.awt.Toolkit; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.UnsupportedFlavorException; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.table.DefaultTableModel; import laptinhmang.ControllDownload; /** * * @author dangn */ public class NewJFrame extends javax.swing.JFrame { String path; IOS ios; ArrayList<LichSu> listLS; DefaultTableModel dfModel; ControllDownload controllDownload; Thread updateUi; int check=0; public NewJFrame() { initComponents(); ios = new IOS(); listLS = ios.readList(); dfModel = new DefaultTableModel(); dfModel.setColumnIdentifiers(loadColumnName()); loadData(); jTable1.setModel(dfModel); controllDownload = new ControllDownload(); } private Object[] loadColumnName() { return new Object[]{"Thời gian", "Tên File", "Link File"}; } private Object[][] loadDataLS() { Object[][] data = new Object[listLS.size()][3]; for (int i = 0; i < listLS.size(); i++) { data[i][0] = listLS.get(i).getDateTime(); data[i][1] = listLS.get(i).getFileName(); data[i][2] = listLS.get(i).getLinkFile(); } return data; } private void loadData() { Object[] data = new Object[3]; for (int i = 0; i < listLS.size(); i++) { data[0] = listLS.get(i).getDateTime(); data[1] = listLS.get(i).getFileName(); data[2] = listLS.get(i).getLinkFile(); dfModel.addRow(data); } } private void saveDataLS() { ios.writeList(listLS); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jTabbedPane1 = new javax.swing.JTabbedPane(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jProgressBar2 = new javax.swing.JProgressBar(); jButton1 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jTextAreaThread = new javax.swing.JTextArea(); JSpeed = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jButton4 = new javax.swing.JButton(); jTimeLeft = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); jScrollPane2 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setText("nhập link file:"); jTextField1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField1ActionPerformed(evt); } }); jButton1.setText("Tải"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton3.setText("Tiếp tục"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jButton2.setText("Tạm dừng"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jTextAreaThread.setColumns(20); jTextAreaThread.setRows(5); jScrollPane1.setViewportView(jTextAreaThread); jLabel2.setText("Thời kết thúc :"); jButton4.setText("Clipboard"); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); jTimeLeft.setText("time"); jLabel3.setText("jLabel3"); jLabel4.setText("jLabel4"); jLabel5.setText("-"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(44, 44, 44) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel1) .addGap(48, 48, 48) .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 460, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel4)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 585, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton1)) .addComponent(jProgressBar2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jButton3) .addGap(109, 109, 109) .addComponent(JSpeed) .addGap(138, 138, 138) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTimeLeft) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton2)))) .addContainerGap(51, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(19, 19, 19) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jLabel5)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1) .addComponent(jButton4)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jLabel4)) .addGap(4, 4, 4) .addComponent(jProgressBar2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton3) .addComponent(jButton2) .addComponent(JSpeed) .addComponent(jLabel2) .addComponent(jTimeLeft)) .addGap(29, 29, 29) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 337, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(38, Short.MAX_VALUE)) ); jTabbedPane1.addTab("Dowload", jPanel1); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Thời gian", "Tên File", "Link File" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.String.class, java.lang.String.class }; boolean[] canEdit = new boolean [] { false, false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jScrollPane2.setViewportView(jTable1); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(50, Short.MAX_VALUE) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 503, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jTabbedPane1.addTab("Lịch sử", jPanel2); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTabbedPane1) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 596, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed controllDownload.pause(); }//GEN-LAST:event_jButton2ActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed controllDownload.start(); }//GEN-LAST:event_jButton3ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: path = jTextField1.getText().trim(); if(path.indexOf("http")==-1){ jLabel5.setText("link tải phải có dạng http:// hoặc https://"); } if (path != ""&&path.indexOf("http")!=-1) { jLabel5.setText(""); controllDownload.setLink(path); controllDownload.start(); updateUI(); LichSu ls = new LichSu(controllDownload.getFileName(), path); listLS.add(ls); dfModel.addRow(new Object[]{ls.getDateTime(), ls.getFileName(), ls.getLinkFile()}); ios.writeList(listLS); } }//GEN-LAST:event_jButton1ActionPerformed private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField1ActionPerformed private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed try { // TODO add your handling code here: path = (String) Toolkit.getDefaultToolkit() .getSystemClipboard().getData(DataFlavor.stringFlavor); path = path.trim(); jTextField1.setText(path); } catch (UnsupportedFlavorException ex) { Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_jButton4ActionPerformed public String TimeToString(int s) { String time = ""; int h = s / 3600; return time; } public void updateUI() { if(updateUi == null){ updateUi = new Thread(new Runnable() { @Override public void run() { int sleep =500; while (true) { JSpeed.setText(controllDownload.getSpeed(sleep)+"kb/s"); jTextAreaThread.setText(controllDownload.infoDownload()); jProgressBar2.setValue((int) ((controllDownload.getCurrent() * 100) / controllDownload.getSize())); jTimeLeft.setText(controllDownload.getTIme()); jLabel3.setText((controllDownload.getCurrent()*100)/controllDownload.getSize()+" %"); jLabel4.setText(100+" %"); checkDownd(sleep); controllDownload.getTIme(); try { Thread.sleep(sleep); } catch (InterruptedException ex) { } } } }); updateUi.start(); } } /** * @param args the command line arguments */ public void checkDownd(int sleep){ if(controllDownload.getSpeed(sleep)==0&&(controllDownload.getDownloadStatus() == ControllDownload.DownladStart)){ check++; } else{ check =0; } if(check>5&&(controllDownload.getCurrent()<controllDownload.getSize())){ // tốc độ download = 0 và file download chưa hoàn thành sau 3 giây sẽ download lại controllDownload.start(); } } public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new NewJFrame().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel JSpeed; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JProgressBar jProgressBar2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTabbedPane jTabbedPane1; private javax.swing.JTable jTable1; private javax.swing.JTextArea jTextAreaThread; private javax.swing.JTextField jTextField1; private javax.swing.JLabel jTimeLeft; // End of variables declaration//GEN-END:variables }
package com.tencent.mm.plugin.fav.a; import android.app.Activity; import android.content.Context; import android.content.Intent; import com.tencent.mm.kernel.c.a; import com.tencent.mm.opensdk.modelmsg.WXMediaMessage; import com.tencent.mm.pluginsdk.ui.applet.q; import com.tencent.mm.y.g; public interface ab extends a { int Bu(String str); int a(WXMediaMessage wXMediaMessage, String str, String str2, String str3); int a(g.a aVar, WXMediaMessage wXMediaMessage, String str); void a(Activity activity, int i, int i2, Intent intent, int i3, int i4); void a(Activity activity, String str, String str2); void a(Context context, String str, g gVar, int i, boolean z, q.a aVar); }
package cn.edu.zucc.music.repository; import cn.edu.zucc.music.entity.BornEntityItem; import org.apache.ibatis.annotations.Param; import org.springframework.data.neo4j.annotation.Query; import org.springframework.data.neo4j.repository.Neo4jRepository; import java.util.List; public interface BornRepository extends Neo4jRepository<BornEntityItem, Long> { @Query(value = "Match(m:artist{artistId: {id}})-[r:born]->(n:BORN ) return n;") List<BornEntityItem> findAByArtistId(@Param("id") String id); }
package day8; public class Task1 { public static void main(String[] args) { StringBuilder numbers = new StringBuilder(); for (int i = 0; i <= 20000;i++) { numbers.append(i).append(" "); } System.out.println(numbers); } }
package com.tencent.mm.ui.base; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.InputMethodManager; import com.tencent.mm.sdk.platformtools.x; class MMTagPanel$6 implements OnClickListener { final /* synthetic */ MMTagPanel txS; MMTagPanel$6(MMTagPanel mMTagPanel) { this.txS = mMTagPanel; } public final void onClick(View view) { x.d("MicroMsg.MMTagPanel", "on panel click, enableEditMode %B", new Object[]{Boolean.valueOf(MMTagPanel.f(this.txS))}); if (MMTagPanel.f(this.txS)) { this.txS.crR(); MMTagPanel.a(this.txS).requestFocus(); MMTagPanel.a(this.txS).setSelection(MMTagPanel.a(this.txS).getText().length()); ((InputMethodManager) this.txS.getContext().getSystemService("input_method")).showSoftInput(MMTagPanel.a(this.txS), 0); x.d("MicroMsg.MMTagPanel", "on content click"); if (MMTagPanel.e(this.txS) != null) { MMTagPanel.e(this.txS).aGt(); } } } }
package com.dollarapi.demo.repository; import com.dollarapi.demo.model.Dollar; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.Date; import java.util.Optional; @Repository public interface DollarRepository extends JpaRepository<Dollar, String> { Optional<Dollar> findByDollarDate(Date date); }
package psk.com.mediaplayerdemo.utils; import java.util.Locale; import java.util.concurrent.TimeUnit; /** * Created by Prashant Kashetti on 9/7/16. */ public class TimeUtils { public static String getDuration(long duration){ return String.format(Locale.ENGLISH,"%02d:%02d", TimeUnit.MILLISECONDS.toMinutes(duration), TimeUnit.MILLISECONDS.toSeconds(duration) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration)) ); } }
package com.example.tagebuch.model.pojo; import androidx.annotation.NonNull; import androidx.room.Entity; import androidx.room.ForeignKey; import androidx.room.PrimaryKey; import androidx.swiperefreshlayout.widget.CircularProgressDrawable; @Entity(tableName = "pensamientos", foreignKeys = {@ForeignKey(entity = Categoria.class, parentColumns = "nombre", childColumns = "categoria", onDelete = ForeignKey.CASCADE)}) public class Pensamiento { private String titulo; private String descripcion; @PrimaryKey @NonNull private String fecha; private String categoria; public String getTitulo() { return titulo; } public void setTitulo(String titulo) { this.titulo = titulo; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public String getCategoria() { return categoria; } public void setCategoria(String categoria) { this.categoria = categoria; } @NonNull public String getFecha() { return fecha; } public void setFecha(@NonNull String fecha) { this.fecha = fecha; } }
package headfirst.com.projectapplication; import android.app.AlertDialog; import android.app.SearchManager; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.support.design.widget.NavigationView; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.MenuItemCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.facebook.login.LoginManager; import com.facebook.login.widget.ProfilePictureView; import com.squareup.picasso.Picasso; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { //Defining Variables private Toolbar toolbar; private NavigationView navigationView; private DrawerLayout drawerLayout; public JSONObject response, profile_pic_data, profile_pic_url; public TextView user_name, user_email; public ImageView user_picture; public NavigationView navigation_view; private LoginManager mLoginManager; public ProfilePictureView profilePictureView; Fragment fragment = null; public String jsondata; public String username; public SharedPreferences sharedPreferences; public static final int pref=0; public SharedPreferences.Editor editor; private Cursor cursor; private Cursor cursor2; private SearchMethods searchMethods; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_screen); Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar); toolbar.setTitle(" " + "ProfessorPedia"); searchMethods = new SearchMethods(this); setSupportActionBar(toolbar); getSupportActionBar().setLogo(R.drawable.toolbarlogo); getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setDisplayUseLogoEnabled(true); Intent intent = getIntent(); String strAr[]=intent.getStringArrayExtra("strArray"); jsondata=strAr[0]; username=strAr[1]; setNavigationHeader(username); // call setNavigationHeader Method. setUserProfile(jsondata); // ca // Initializing Drawer Layout and ActionBarToggle drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.openDrawer, R.string.closeDrawer){ @Override public void onDrawerClosed(View drawerView) { // Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank super.onDrawerClosed(drawerView); } @Override public void onDrawerOpened(View drawerView) { // Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank super.onDrawerOpened(drawerView); } }; //Setting the actionbarToggle to drawer layout drawerLayout.setDrawerListener(actionBarDrawerToggle); //calling sync state is necessay or else your hamburger icon wont show up actionBarDrawerToggle.syncState(); navigation_view.setNavigationItemSelectedListener(this); DatabaseHelper dbHelper = new DatabaseHelper(this); try { dbHelper.createDataBase(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); Log.d("info", "Failed"); } displayView(0); } private void displayView(int position) { fragment = null; // String title = getString(R.string.app_name); switch (position) { case 0: fragment = new HomeFragment(); //title = getString(R.string.title_home); break; default: break; } if (fragment != null) { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.container_body, fragment); fragmentTransaction.commit(); } } public void setNavigationHeader(String logdinUser) { navigation_view = (NavigationView) findViewById(R.id.navigation_view); user_name = (TextView) findViewById(R.id.username); profilePictureView = (ProfilePictureView) findViewById(R.id.profile_image); user_email = (TextView) findViewById(R.id.email); user_name.setText(logdinUser); } public void setUserProfile(String jsondata1) { try { profilePictureView.setPresetSize(ProfilePictureView.NORMAL); profilePictureView.setProfileId(jsondata1); } catch (Exception e) { e.printStackTrace(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu, menu); // Retrieve the SearchView and plug it into SearchManager SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search)); SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { cursor = searchMethods.getCourseListByKeyword(query); cursor2 = searchMethods.getProfListByKeyword(query); Intent in = new Intent(MainActivity.this, prof_detail.class); Intent in2 = new Intent(MainActivity.this, Course_Detail.class); if (cursor == null) { if (cursor2 == null) { final AlertDialog.Builder alertDialog=new AlertDialog.Builder(MainActivity.this); alertDialog.setTitle("Alert!!!"); alertDialog.setMessage("No Records Found"); alertDialog.setCancelable(false); alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); AlertDialog dialog=alertDialog.create(); dialog.show(); } else { in.putExtra("NAME", cursor2.getString(cursor2.getColumnIndex(DatabaseHelper.Prof_name))); in.putExtra("IMAGE", cursor2.getString(cursor2.getColumnIndex(DatabaseHelper.Prof_image))); in.putExtra("INFO", cursor2.getString(cursor2.getColumnIndex(DatabaseHelper.Prof_info))); in.putExtra("COURSE1", cursor2.getInt(cursor2.getColumnIndex(DatabaseHelper.Course1_id))); in.putExtra("COURSE2", cursor2.getInt(cursor2.getColumnIndex(DatabaseHelper.Course2_id))); in.putExtra("ID", cursor2.getInt(cursor2.getColumnIndex(DatabaseHelper.Prof_id))); cursor2.close(); startActivity(in); } } else { in2.putExtra("NAME", cursor.getString(cursor.getColumnIndex(DatabaseHelper.Course_name))); in2.putExtra("ID", cursor.getInt(cursor.getColumnIndex(DatabaseHelper.Course_id))); in2.putExtra("INFO", cursor.getString(cursor.getColumnIndex(DatabaseHelper.Course_info))); in2.putExtra("CRN", cursor.getString(cursor.getColumnIndex(DatabaseHelper.Course_crn))); cursor.close(); startActivity(in2); } return false; } @Override public boolean onQueryTextChange(String newText) { return false; } }); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_search) { return true; } return super.onOptionsItemSelected(item); } public boolean onNavigationItemSelected(MenuItem menuItem) { //Checking if the item is in checked state or not, if not make it in checked state if(menuItem.isChecked()) menuItem.setChecked(false); else menuItem.setChecked(true); //Closing drawer on item click drawerLayout.closeDrawers(); String title = getString(R.string.app_name); //Check to see which item was being clicked and perform appropriate action switch (menuItem.getItemId()) { //Replacing the main content with ContentFragment Which is our Inbox View; case R.id.home: fragment = new HomeFragment(); //title = getString(R.string.title_home); android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.container_body, fragment); fragmentTransaction.commit(); return true; // For rest of the options we just show a toast on click case R.id.AboutUs: fragment = new AboutUsFragment(); android.support.v4.app.FragmentTransaction fragmentTransaction1 = getSupportFragmentManager().beginTransaction(); fragmentTransaction1.replace(R.id.container_body, fragment); fragmentTransaction1.addToBackStack(null); fragmentTransaction1.commit(); return true; case R.id.ContactUs: fragment = new ContactUsFragment(); android.support.v4.app.FragmentTransaction fragmentTransaction2 = getSupportFragmentManager().beginTransaction(); fragmentTransaction2.replace(R.id.container_body, fragment); fragmentTransaction2.addToBackStack(null); fragmentTransaction2.commit(); return true; case R.id.maps: fragment = new MapFragment(); android.support.v4.app.FragmentTransaction fragmentTransaction3 = getSupportFragmentManager().beginTransaction(); fragmentTransaction3.replace(R.id.container_body, fragment); fragmentTransaction3.addToBackStack(null); fragmentTransaction3.commit(); return true; case R.id.reminder: fragment = new AlarmFragment(); android.support.v4.app.FragmentTransaction fragmentTransaction4 = getSupportFragmentManager().beginTransaction(); fragmentTransaction4.replace(R.id.container_body, fragment); fragmentTransaction4.addToBackStack(null); fragmentTransaction4.commit(); return true; case R.id.logoutandexit: jsondata=null; mLoginManager = LoginManager.getInstance(); mLoginManager.logOut(); android.os.Process.killProcess(android.os.Process.myPid()); System.exit(1); return true; default: return true; } } }
package com.iuce.control; import java.util.List; import com.iuce.entity.Diary; public interface IDiaryOperations { //add //remove //list //edit public boolean addDiary(Diary diary); public boolean removeDiary(int id); public boolean updateDiary(int id, Diary diary); public List<Diary> listDiary(); public Diary getDiaryWithDate(String date); public Diary getDiaryWithId(int id); }
package DAO; import java.util.List; import org.hibernate.Criteria; import model.BookInfo; public class BookInfoDAO extends hibernateDAO implements IBookInfoDAO { @Override public void SaveBookInfo(BookInfo book) { // TODO Auto-generated method stub if(book == null) return; super.saveObject(book); } @Override public BookInfo GetBookInfoById(int bookId) { // TODO Auto-generated method stub return null; } @Override public List<BookInfo> GetAllBook() { // TODO Auto-generated method stub //return (List<BookInfo>) super.getObjects("from Book"); Criteria criteria = super.getCurrentSession().createCriteria(BookInfo.class); return criteria.list(); } }
package com.netbanking.model; public class AuthorizePIIPendingRequestModel { String requestStatusString; public String getRequestStatusString() { return requestStatusString; } public void setRequestStatusString(String requestStatusString) { this.requestStatusString = requestStatusString; } public String getRequestIDs() { return requestIDs; } public void setRequestIDs(String requestIDs) { this.requestIDs = requestIDs; } String requestIDs; }
package cn.itcase.demo1; public class Employee { String name; public void work() { System.out.println("employee is working!!!"); } }
package com.woowtodo.entities; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.User; public class CurrentWoowUser extends User { private static final long serialVersionUID = 2211964161401958350L; private WoowUser user; public CurrentWoowUser(WoowUser woowUser) { super(woowUser.getUserEmail(), woowUser.getUserPass(), AuthorityUtils.createAuthorityList(woowUser.getRole().toString())); this.user = woowUser; } public WoowUser getWoowUser() { return this.user; } }
package kimmyeonghoe.cloth.domain.notice; import java.time.LocalDate; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Getter; import lombok.Setter; @Getter @Setter public class AdminNotice { private int noticeNum; private String title; private String content; @JsonFormat(pattern="yyyy-MM-dd", timezone="Asia/Seoul") private LocalDate regDate; }
package in.dailyhunt.internship.userprofile.endpoints; import in.dailyhunt.internship.userprofile.client_model.response.UserResponse; import in.dailyhunt.internship.userprofile.security.services.UserPrinciple; import in.dailyhunt.internship.userprofile.services.interfaces.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @CrossOrigin(origins = "*", maxAge = 3600) @RestController @RequestMapping(UserEndpoint.BASE_URL) public class UserEndpoint { static final String BASE_URL = "api/v1/user_profile"; private final UserService userService; @Autowired public UserEndpoint(UserService userService) { this.userService = userService; } @GetMapping("/info") public ResponseEntity<?> user() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); UserPrinciple user = (UserPrinciple) auth.getPrincipal(); return ResponseEntity.ok().body(UserResponse.from(userService.findUserById(user.getId()))); } }
package com.example.iutassistant.Presenter; import com.example.iutassistant.Model.IdentityModel; import com.google.firebase.database.DataSnapshot; public interface FireBaseIdentityPresenter { public void useFireBaseIdentityModel(IdentityModel identityModel); }
package la.opi.verificacionciudadana.adapters; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentStatePagerAdapter; import com.astuetz.PagerSlidingTabStrip; import java.util.List; import la.opi.verificacionciudadana.R; public class MyPagerAdapter extends FragmentPagerAdapter implements PagerSlidingTabStrip.IconTabProvider { private List<Fragment> fragments; private final int[] ICONS = { R.drawable.icon_selector, R.drawable.icon_selector }; public MyPagerAdapter(FragmentManager fm, List<Fragment> fragments) { super(fm); this.fragments = fragments; } @Override public int getCount() { return ICONS.length; } @Override public android.support.v4.app.Fragment getItem(int position) { return fragments.get(position); } @Override public int getPageIconResId(int i) { return ICONS[i]; } }
package com.google.android.gms.analytics.internal; public interface ah { void mB(); }
import java.util.Arrays; import java.util.HashMap; //两数之和 class _1{ public int[] twoSum(final int[] nums, final int target) { final int[] indexs = new int[2]; final HashMap<Integer, Integer> hash = new HashMap<Integer, Integer>(); for (int i = 0; i < nums.length; i++) { if (!hash.containsKey(target - nums[i])) { hash.put(nums[i], i); } else { indexs[0] = i; indexs[1] = hash.get(target - nums[i]); break; } } return indexs; } public static void main(String args[]) { final _1 t = new _1(); int[] a = t.twoSum(new int[]{2,7,11,15}, 9); System.out.println(Arrays.toString(a)); } }
package com.chat.zipchat.Service; import com.chat.zipchat.BuildConfig; import com.ihsanbal.logging.Level; import com.ihsanbal.logging.LoggingInterceptor; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import okhttp3.internal.platform.Platform; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class ApiClient { private static Retrofit retrofit; private static String API_BASE_URL = BuildConfig.BaseUrl + "api/v1/"; private static String NOTIFICATION_URL = BuildConfig.NotificationUrl; private static String CONVERT_AMOUNT_URL = "https://min-api.cryptocompare.com/data/"; private static String PAYMENT_URL = BuildConfig.PaymentUrl; private static OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(new LoggingInterceptor.Builder() .loggable(BuildConfig.DEBUG) .setLevel(Level.BASIC) .log(Platform.INFO) .request("Request") .response("Response").build()) .connectTimeout(60, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .writeTimeout(60, TimeUnit.SECONDS) .build(); public static Retrofit getClient() { /*HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor) .connectTimeout(60, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .writeTimeout(60, TimeUnit.SECONDS) .build();*/ retrofit = new Retrofit.Builder() .baseUrl(API_BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(client) .build(); return retrofit; } public static Retrofit getClientNotification() { retrofit = new Retrofit.Builder() .baseUrl(NOTIFICATION_URL) .addConverterFactory(GsonConverterFactory.create()) .client(client) .build(); return retrofit; } public static Retrofit getClientPayment() { retrofit = new Retrofit.Builder() .baseUrl(PAYMENT_URL) .addConverterFactory(GsonConverterFactory.create()) .client(client) .build(); return retrofit; } public static Retrofit getClientConvertion() { retrofit = new Retrofit.Builder() .baseUrl(CONVERT_AMOUNT_URL) .addConverterFactory(GsonConverterFactory.create()) .client(client) .build(); return retrofit; } public static Retrofit getAuthClient() { OkHttpClient okHttpClient = new OkHttpClient.Builder() .addInterceptor(new LoggingInterceptor.Builder() .loggable(BuildConfig.DEBUG) .setLevel(Level.BASIC) .log(Platform.INFO) .request("Request") .response("Response") .addHeader("authid", "1") .addHeader("authorization", "2") .build()) .connectTimeout(60, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .writeTimeout(60, TimeUnit.SECONDS) .build(); retrofit = new Retrofit.Builder() .baseUrl(BuildConfig.BaseUrl) .addConverterFactory(GsonConverterFactory.create()) .client(okHttpClient) .build(); return retrofit; } }
package br.com.higornucci.contracheque.dominio.real; import java.math.BigDecimal; import java.text.NumberFormat; import java.util.Locale; public class Real { private BigDecimal valor; public Real(BigDecimal valor) { this.valor = valor.setScale(2, BigDecimal.ROUND_HALF_EVEN); } public Real multiplicarPor(double multiplicador) { return new Real(valor.multiply(new BigDecimal(multiplicador))); } public boolean menorOuIgualQue(BigDecimal valorASerComparado) { return valor.compareTo(valorASerComparado) == -1; } public BigDecimal getValor() { return valor; } public boolean entre(BigDecimal valorInferiorLimite, BigDecimal valorSuperiorLimite) { return valor.compareTo(valorInferiorLimite.setScale(2, BigDecimal.ROUND_HALF_EVEN)) >= 0 && valor.compareTo(valorSuperiorLimite.setScale(2, BigDecimal.ROUND_HALF_EVEN)) <= 0; } public Real menos(Real descontoINSS) { return new Real(valor.subtract(descontoINSS.getValor())); } public String formatado() { Locale ptBR = new Locale("pt", "BR"); return NumberFormat.getCurrencyInstance(ptBR).format(valor).toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Real real = (Real) o; return valor.equals(real.getValor()); } @Override public int hashCode() { return valor.hashCode(); } }
package com.example.healthmanage.ui.activity.my.aboutus; import com.example.healthmanage.base.BaseViewModel; public class AboutUsViewModel extends BaseViewModel { }
package test.main; import java.sql.Connection; import java.sql.PreparedStatement; import test.util.DBConnect; /* * member 테이블에서 * 회원번호가 801 번 회원의 정보를 삭제하는 기능을 완성해 보기 * hint * new DBConnect().getConn(); */ public class MainClass05 { public static void main(String[] args) { //삭제할 회원의 번호 int num=806; //필요한 참조값을 담을 지역 변수 미리 만들고 초기화 하기 Connection conn=null; PreparedStatement pstmt=null; int flag=0; try { //Connection 객체의 참조값 얻어오기 conn=new DBConnect().getConn(); //실행할 sql 문의 뼈대 준비하기 String sql="DELETE FROM member WHERE num=?"; //PreparedStatement 객체의 참조값 얻어오기 pstmt=conn.prepareStatement(sql); //? 에 값 바인딩하기 pstmt.setInt(1, num); //sql 문 실행하고 변화된 row 의 갯수 리턴 받기 flag=pstmt.executeUpdate(); System.out.println("DELETE 문 수행 성공"); }catch(Exception e) { e.printStackTrace(); }finally { //마무리 작업 try { if(pstmt!=null)pstmt.close(); if(conn!=null)conn.close(); }catch(Exception e) {} } if(flag>0) { System.out.println("작업(DELETE) 성공"); }else { System.out.println("작업(DELETE) 실패"); } } }
package staff.menu; import java.io.IOException; import java.net.MalformedURLException; import javafx.beans.property.SimpleFloatProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleStringProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import manager.editmenu.AddIngredientController; import org.apache.commons.lang3.StringUtils; import server.httprequest.HttpRequester; /** * The 'Ingredient' class is used to create ingredient objects 'singleIngredient' , * with data from the database. * @author Svetoslav Mihovski */ public class Ingredient { //Private fields of the class used to create the object. private SimpleIntegerProperty id; private SimpleStringProperty name; private SimpleFloatProperty cost; private SimpleIntegerProperty metricId; private SimpleStringProperty metricName; private SimpleIntegerProperty calories; private SimpleIntegerProperty allergyId; private SimpleStringProperty allergyName; private SimpleFloatProperty quantity; private static HttpRequester httpRequester = new HttpRequester(); /** * Initialise the ingredients fields. This is to be used in conjunction with * all the getters of Ingredient to make it more readable. */ public Ingredient() { this.id = new SimpleIntegerProperty(); this.name = new SimpleStringProperty(); this.cost = new SimpleFloatProperty(); this.metricId = new SimpleIntegerProperty(); this.metricName = new SimpleStringProperty(); this.calories = new SimpleIntegerProperty(); this.allergyId = new SimpleIntegerProperty(); this.allergyName = new SimpleStringProperty(); this.quantity = new SimpleFloatProperty(); } /** * Constructor of 'Ingredient' class is used to initialize the fields in the database such as: * @param id - id of an ingredient. * @param name - name of an ingredient. * @param qty - quantity of an ingredient. */ public Ingredient(int id, String name, float qty) { this.id = new SimpleIntegerProperty(id); this.name = new SimpleStringProperty(name); this.quantity = new SimpleFloatProperty(qty); } /** * Initialise all fields of an ingredient. * * @param name * of the ingredient. * @param cost * of the ingredient. * @param metricName * is the name of the metric id. * @param calories * of the food. * @param allergyName * name of allergy id. * @param quantity * amount of stock. * @throws IOException * In case there is an exception while contacting the server * (Connection exception). * @throws MalformedURLException * In case there is an exception while contacting the server (URL is * malformed). * @throws NumberFormatException * In a case a number is converted to String. */ public Ingredient(String name, float cost, String metricName, int calories, String allergyName, float quantity) throws NumberFormatException, MalformedURLException, IOException { // Assign fields this.name = new SimpleStringProperty(name); this.cost = new SimpleFloatProperty(cost); this.metricName = new SimpleStringProperty(metricName); this.metricId = new SimpleIntegerProperty(findMetricIdFromMetricName(metricName)); this.calories = new SimpleIntegerProperty(calories); this.allergyName = new SimpleStringProperty(allergyName); this.allergyId = new SimpleIntegerProperty(findAllergyIdFromAllergyName(allergyName)); this.quantity = new SimpleFloatProperty(quantity); // Insert ingredient into database String sql = "INSERT INTO ingredients_stock(name, cost, metric_id, calories, allergy_id, quantity) " + "VALUES('" + getName() + "', " + Float.toString(getCost()) + ", " + getMetricId() + ", " + getCalories() + ", " + getAllergyId() + ", " + getQuantity() + ")"; httpRequester.sendPost("/database/insertRow", sql); //get id of ingredient this.id = new SimpleIntegerProperty(Integer.parseInt(httpRequester .sendPost("/database/select", "SELECT MAX(id) FROM ingredients_stock;").split(" \n")[0])); } private static int findAllergyIdFromAllergyName(String allergyName) throws NumberFormatException, MalformedURLException, IOException { String sql = "SELECT id FROM ingredients_allergies WHERE name = '" + StringUtils.capitalize(allergyName) + "';"; return Integer.parseInt(AddIngredientController.selectFromDb(sql)[0]); } private static int findMetricIdFromMetricName(String metricName) throws MalformedURLException, IOException { String sql = "SELECT id FROM metric_unit WHERE name = '" + metricName + "';"; return Integer.parseInt(AddIngredientController.selectFromDb(sql)[0]); } /** * Initialise all fields of an ingredient. * * @param id * of the ingredient. * @param name * of the ingredient. * @param cost * of the ingredient. * @param metricId * its type, whether its in KG or Litres or quantity. * @param metricName * is the name of the metric id. * @param calories * of the food. * @param allergyId * any possible allergies. * @param allergyName * name of allergy id. * @param quantity * amount of stock. */ public Ingredient(int id, String name, float cost, int metricId, String metricName, int calories, int allergyId, String allergyName, float quantity) { this.id = new SimpleIntegerProperty(id); this.name = new SimpleStringProperty(name); this.cost = new SimpleFloatProperty(cost); this.metricId = new SimpleIntegerProperty(metricId); this.metricName = new SimpleStringProperty(metricName); this.calories = new SimpleIntegerProperty(calories); this.allergyId = new SimpleIntegerProperty(allergyId); this.allergyName = new SimpleStringProperty(allergyName); this.quantity = new SimpleFloatProperty(quantity); } /** * Returns a list of all of the specific all ingredient data from the database. * * @return a list of information about an ingredient. * @throws MalformedURLException * In case there is an exception while contacting the server (URL is * malformed). * @throws IOException * In case there is an exception while contacting the server * (Connection exception). */ public ObservableList<Ingredient> getAllIngredients() throws MalformedURLException, IOException { HttpRequester httpRequester = new HttpRequester(); ObservableList<Ingredient> stock = FXCollections.observableArrayList(); String sqlCommand = "SELECT ingredients_stock.id, ingredients_stock.name," + " ingredients_stock.cost," + " ingredients_stock.metric_id, metric_unit.name AS metric_name," + " ingredients_stock.calories," + " ingredients_stock.allergy_id, ingredients_allergies.name AS allergy_name," + " ingredients_stock.quantity" + " FROM ingredients_stock" + " INNER JOIN ingredients_allergies" + " ON (ingredients_stock.allergy_id = ingredients_allergies.id)" + " INNER JOIN metric_unit" + " ON (ingredients_stock.metric_id = metric_unit.id);"; String[] ingredients = httpRequester.sendPost("/database/select", sqlCommand).split("\n"); for (String ingredient : ingredients) { String[] singleIngredient = ingredient.split(" "); if (singleIngredient[8].equals("null")) { singleIngredient[8] = "0"; } Ingredient tempIngredient = new Ingredient(Integer.parseInt(singleIngredient[0]), singleIngredient[1], Float.parseFloat(singleIngredient[2]), Integer.parseInt(singleIngredient[3]), singleIngredient[4], Integer.parseInt(singleIngredient[5]), Integer.parseInt(singleIngredient[6]), singleIngredient[7], Float.parseFloat(singleIngredient[8])); stock.add(tempIngredient); } return stock; } /** * Creates ObservableList of all ingredients within a specific Dish. * * @param dishId The ID of the Dish whose ingredients are to be retrieved * @throws MalformedURLException * In case there is an exception while contacting the server (URL is * malformed). * @throws IOException * In case there is an exception while contacting the server * (Connection exception). */ public ObservableList<Ingredient> getIngredientsById(int dishId) throws MalformedURLException, IOException { ObservableList<Ingredient> viewIngredients = FXCollections.observableArrayList(); String sqlCommand = "SELECT ingredients_stock.id, ingredients_stock.name," + " dishes_ingredients.ingredient_qty" + " FROM dishes_ingredients" + " INNER JOIN ingredients_stock" + " ON dishes_ingredients.ingredient_id = ingredients_stock.id" + " WHERE dishes_ingredients.dish_id = '" + dishId + "'"; String[] ingredients = httpRequester.sendPost("/database/select", sqlCommand).split("\n"); for (String ingredient : ingredients) { String[] singleIngredient = ingredient.split(" "); Ingredient tempIngredient = new Ingredient( Integer.parseInt(singleIngredient[0]), singleIngredient[1], Float.parseFloat(singleIngredient[2])); viewIngredients.add(tempIngredient); } return viewIngredients; } /** * Adds the ingredient to a specific Dish. * * @param dishId The ID of the Dish to which the ingredient is added * @throws MalformedURLException * In case there is an exception while contacting the server (URL is * malformed). * @throws IOException * In case there is an exception while contacting the server * (Connection exception). */ public void addIngredientToDish(int dishId) throws MalformedURLException, IOException { String sqlCommand = null; sqlCommand = "INSERT INTO dishes_ingredients (dish_id, ingredient_id, ingredient_qty)" + " VALUES ('" + dishId + "', '" + this.getId() + "', '0')"; httpRequester.sendPost("/database/select", sqlCommand).split("\n"); } /** * Removes the ingredient to a specific Dish. * * @param dishId The ID of the Dish from which the ingredient is removed * @throws MalformedURLException * In case there is an exception while contacting the server (URL is * malformed). * @throws IOException * In case there is an exception while contacting the server * (Connection exception). */ public void removeIngredientFromDish(int dishId) throws MalformedURLException, IOException { String sqlCommand = null; sqlCommand = "DELETE FROM dishes_ingredients" + " WHERE dish_id = '" + dishId + "' AND ingredient_id = '" + this.getId() + "'"; httpRequester.sendPost("/database/select", sqlCommand).split("\n"); } //Set of getters and setters for the private fields. public int getId() { return id.get(); } public void setId(int id) { this.id.set(id); } public String getName() { return name.get(); } public void setName(String name) { this.name.set(name); } public float getCost() { return cost.get(); } public void setCost(float cost) { this.cost.set(cost); } public int getMetricId() { return metricId.get(); } public void setMetricId(int metricId) { this.metricId.set(metricId); } public String getMetricName() { return metricName.get(); } public void setMetricName(String metricName) { this.metricName.set(metricName); } public int getCalories() { return calories.get(); } public void setCalories(int calories) { this.calories.set(calories); } public int getAllergyId() { return allergyId.get(); } public void setAllergyId(int allergyId) { this.allergyId.set(allergyId); } public String getAllergyName() { return allergyName.get(); } public void setAllergyName(String allergyName) { this.allergyName.set(allergyName); } public float getQuantity() { return quantity.get(); } public void setQuantity(float quantity) { this.quantity.set(quantity); } @Override public String toString() { return getId() + " " + getName() + " " + getMetricId() + " " + getMetricName() + " " + getCalories() + " " + getAllergyId() + " " + getAllergyName() + " " + getQuantity(); } }
import javax.swing.*; import java.awt.*; /** * Created by TAWEESOFT on 4/21/16 AD. */ public class LightButton extends JButton { public LightButton(String text) { super(text); setForeground(Color.red); } public void paint(Graphics g){ g.setColor(Color.pink); g.fillRect(0, 0, getWidth(), getHeight()); super.paint(g); } }
package com.classcheck.panel; import java.awt.BorderLayout; import java.awt.Dimension; import java.io.IOException; import java.util.Iterator; import java.util.List; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTree; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import org.apache.commons.io.FileUtils; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.fife.ui.rsyntaxtextarea.SyntaxConstants; import org.fife.ui.rtextarea.RTextScrollPane; import com.classcheck.autosource.ClassBuilder; import com.classcheck.autosource.ClassNode; import com.classcheck.autosource.MyClass; import com.classcheck.tree.FileNode; import com.classcheck.tree.FileTree; import com.classcheck.window.DebugMessageWindow; public class CodeViewTabPanel extends JPanel{ /** * */ private static final long serialVersionUID = 1L; JSplitPane userHolizontalSplitePane; JSplitPane astahHolizontalSplitePane; JSplitPane verticalSplitePane; JTree userJtree; JTree astahJTree; DefaultMutableTreeNode astahRoot; MutableFileNode userRoot; RSyntaxTextArea userEditor; RSyntaxTextArea skeltonEditor; StatusBar userTreeStatus; StatusBar userSourceStatus; StatusBar astahTreeStatus; StatusBar astahSourceStatus; List<MyClass> myClassList; FileTree userFileTree; public CodeViewTabPanel(ClassBuilder cb, FileTree userFileTree) { this.myClassList = cb.getClasslist(); this.userFileTree = userFileTree; setLayout(new BorderLayout()); initComponent(); initActionEvent(); setVisible(true); } public void setTextAreaEditable(boolean isEditable){ skeltonEditor.setEditable(isEditable); userEditor.setEditable(isEditable); } private void makeFileNodeTree(){ Iterator<FileNode> it = userFileTree.iterator(); FileNode fileNode; MutableFileNode muFileNode; while (it.hasNext()) { fileNode = (FileNode) it.next(); if (fileNode!=null) { if (fileNode.isDirectory()) { }else if(fileNode.isFile()){ muFileNode = new MutableFileNode(fileNode); userRoot.add(muFileNode); } } } } private void initComponent(){ JPanel panel; ClassNode child = null; RTextScrollPane rScrollPane = null; userHolizontalSplitePane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); astahHolizontalSplitePane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); verticalSplitePane = new JSplitPane(JSplitPane.VERTICAL_SPLIT); userEditor = new RSyntaxTextArea(20, 60); skeltonEditor = new RSyntaxTextArea(20, 60); userEditor.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA); userEditor.setBracketMatchingEnabled(false); userEditor.setCodeFoldingEnabled(true); skeltonEditor.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA); skeltonEditor.setCodeFoldingEnabled(true); skeltonEditor.setBracketMatchingEnabled(false); //astah tree logic astahRoot = new DefaultMutableTreeNode("SkeltonCode"); astahJTree = new JTree(astahRoot); astahJTree.setMinimumSize(new Dimension(200,200)); astahJTree.setSize(new Dimension(200,200)); for (MyClass myClass : myClassList) { child = new ClassNode(myClass); astahRoot.add(child); } //user file tree logic userRoot = new MutableFileNode(userFileTree.getRoot()); userJtree = new JTree(userRoot); userJtree.setMinimumSize(new Dimension(200, 200)); userJtree.setSize(new Dimension(200,200)); makeFileNodeTree(); //上の左右パネル //user tree(左) panel = new JPanel(new BorderLayout()); panel.add(userJtree,BorderLayout.CENTER); userTreeStatus = new StatusBar(panel, "Your-Class"); panel.add(userTreeStatus,BorderLayout.SOUTH); JScrollPane treeScrollPane = new JScrollPane(panel); treeScrollPane.setMinimumSize(new Dimension(180, 150)); treeScrollPane.setSize(new Dimension(180, 150)); //user textArea(右) rScrollPane = new RTextScrollPane(userEditor); rScrollPane.setLineNumbersEnabled(true); panel = new JPanel(new BorderLayout()); panel.add(rScrollPane,BorderLayout.CENTER); userSourceStatus = new StatusBar(panel, "Your Source Code"); panel.add(userSourceStatus,BorderLayout.SOUTH); //左右をセット userHolizontalSplitePane.setLeftComponent(treeScrollPane); userHolizontalSplitePane.setRightComponent(panel); userHolizontalSplitePane.setContinuousLayout(true); //下の左右パネル //astah tree(左) panel = new JPanel(new BorderLayout()); panel.add(astahJTree,BorderLayout.CENTER); astahTreeStatus = new StatusBar(panel, "SkeltonCode-Class"); panel.add(astahTreeStatus,BorderLayout.SOUTH); JScrollPane astahTreeScrollPane = new JScrollPane(panel); astahTreeScrollPane.setMinimumSize(new Dimension(180, 150)); astahTreeScrollPane.setSize(new Dimension(180, 150)); //astah textArea(右) rScrollPane = new RTextScrollPane(skeltonEditor); rScrollPane.setLineNumbersEnabled(true); panel = new JPanel(new BorderLayout()); panel.add(rScrollPane,BorderLayout.CENTER); astahSourceStatus = new StatusBar(panel, "Skelton Code"); panel.add(astahSourceStatus,BorderLayout.SOUTH); //左右をセット astahHolizontalSplitePane.setLeftComponent(astahTreeScrollPane); astahHolizontalSplitePane.setRightComponent(panel); astahHolizontalSplitePane.setContinuousLayout(true); //アスタとユーザーソースの上下をセット verticalSplitePane.setTopComponent(astahHolizontalSplitePane); verticalSplitePane.setBottomComponent(userHolizontalSplitePane); verticalSplitePane.setContinuousLayout(true); add(verticalSplitePane,BorderLayout.CENTER); } private void initActionEvent() { userJtree.addTreeSelectionListener(new TreeSelectionListener(){ @Override public void valueChanged(TreeSelectionEvent e) { Object obj = userJtree.getLastSelectedPathComponent(); if (obj instanceof MutableFileNode) { MutableFileNode muFileNode = (MutableFileNode) obj; FileNode fileNode = muFileNode.getFileNode(); try { userEditor.setText(FileUtils.readFileToString(fileNode)); userSourceStatus.setText("Your Source Code : " + fileNode.getName()); userTreeStatus.setText("Your-Class : " + fileNode.getName()) ; } catch (IOException e1) { DebugMessageWindow.clearText(); System.out.println(e1); DebugMessageWindow.msgToTextArea(); } } } }); astahJTree.addTreeSelectionListener(new TreeSelectionListener(){ @Override public void valueChanged(TreeSelectionEvent e) { Object obj = astahJTree.getLastSelectedPathComponent(); if (obj instanceof ClassNode) { ClassNode selectedNode = (ClassNode) obj; Object userObj = selectedNode.getUserObject(); if (userObj instanceof MyClass) { MyClass myClass = (MyClass) userObj; skeltonEditor.setText(myClass.toString()); astahSourceStatus.setText("Skelton Code : " + myClass.getName()); astahTreeStatus.setText("Skelton-Class : " + myClass.getName()) ; } } } }); } }
package de.zarncke.lib.math; import static de.zarncke.lib.math.Intervals.EMPTY; import static de.zarncke.lib.math.Intervals.of; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Random; import junit.framework.TestCase; import de.zarncke.lib.coll.L; import de.zarncke.lib.log.Log; import de.zarncke.lib.math.Intervals.Interval; /** * Test Intervals handling comprehensively. * * @author Gunnar Zarncke * @clean 22.03.2012 */ public class IntervalTest extends TestCase { private static final int a = 0; private static final int b = 10; private static final int c = 20; private static final int d = 30; private static final int e = 40; private static final int f = 50; private static final int g = 60; private static final Interval aa = Interval.of(a, a); private static final Interval bb = Interval.of(b, b); private static final Interval ab = Interval.of(a, b); private static final Interval bc = Interval.of(b, c); private static final Interval cd = Interval.of(c, d); private static final Interval de = Interval.of(d, e); private static final Interval ef = Interval.of(e, f); private static final Interval fg = Interval.of(f, g); private static final Interval ac = Interval.of(a, c); private static final Interval bd = Interval.of(b, d); private static final Interval ce = Interval.of(c, e); private static final Interval df = Interval.of(d, f); private static final Interval eg = Interval.of(e, g); private static final Interval ad = Interval.of(a, d); private static final Interval be = Interval.of(b, e); private static final Interval cf = Interval.of(c, f); private static final Interval ae = Interval.of(a, e); private static final Interval bf = Interval.of(b, f); private static final Interval af = Interval.of(a, f); private static final Interval bg = Interval.of(b, g); private static final Interval ag = Interval.of(a, g); public void testNormalize() { assertEquals(EMPTY, Intervals.ofNormalized()); assertEquals(EMPTY, Intervals.ofNormalized((Interval) null)); assertEquals(of(cd), Intervals.ofNormalized(null, cd, null)); assertEquals(of(ab, cd), Intervals.ofNormalized(cd, ab)); assertEquals(of(ad), Intervals.ofNormalized(ab, bc, bd)); assertEquals(of(ad), Intervals.ofNormalized(ad, bc)); assertEquals(of(ad), Intervals.ofNormalized(bc, ad)); assertEquals(of(ad), Intervals.ofNormalized(ac, bd)); } public void testSimpleJoin() { assertEquals(ab, ab.join(null)); assertEquals(ac, ab.join(bc)); assertEquals(ac, ab.join(ac)); assertEquals(ac, ac.join(ab)); assertEquals(ad, ab.join(cd)); } public void testSimpleIntersect() { assertEquals(null, ab.intersect(null)); assertEquals(ab, ab.intersect(ab)); assertEquals(ab, ab.intersect(ac)); assertEquals(null, ab.intersect(bc)); assertEquals(null, ab.intersect(cd)); assertEquals(bc, ad.intersect(bc)); } public void testIntervalsJoin() { assertEquals(EMPTY, EMPTY.join(EMPTY)); assertEquals(of(ab), of(ab).join(EMPTY)); assertEquals(of(ab), EMPTY.join(of(ab))); assertEquals(of(ab), of(ab).join(of(ab))); assertEquals(of(ab, cd), EMPTY.join(of(ab, cd))); assertEquals(of(ab, cd), of(ab, cd).join(EMPTY)); // separate cases assertEquals(of(ab, cd), EMPTY.join(of(ab, cd))); assertEquals(of(ab, cd), of(ab).join(of(cd))); assertEquals(of(ab, cd), of(cd).join(of(ab))); // neighbor cases assertEquals(of(ac), of(ab).join(of(bc))); assertEquals(of(ac), of(bc).join(of(ab))); // contained cases assertEquals(of(ad), of(ad).join(of(bc))); assertEquals(of(ad), of(bc).join(of(ad))); // overlap cases assertEquals(of(ad), of(bd).join(of(ac))); assertEquals(of(ad), of(ac).join(of(bd))); // multi cases assertEquals(of(ad), of(ab).join(of(cd)).join(of(bc))); assertEquals(of(ab, cd, ef), of(ab, cd).join(of(cd, ef))); assertEquals(of(ae), of(ac, de).join(of(be))); assertEquals(of(af), of(ac, de).join(of(bf))); assertEquals(of(ag), of(ac, de).join(of(bg))); assertEquals(of(af), of(ac, df).join(of(be))); Intervals r = of(de).join(fg); assertEquals(of(de, fg), r); r = r.join(cd); assertEquals(of(ce, fg), r); r = r.join(bc); assertEquals(of(be, fg), r); r = r.join(ab); assertEquals(of(ae, fg), r); r = r.join(ef); assertEquals(of(ag), r); assertEquals(of(ab, cd, ef), of(ef).join(of(ab)).join(of(cd))); } public void testIntervalsJoinStress() { Random rnd = new Random(4711); Interval[] ivs = new Interval[] { ab, bc, cd, de, ef, fg }; for (int i = 0; i < 1000; i++) { Intervals res = EMPTY; List<Intervals.Interval> control = L.l(); Collections.shuffle(Arrays.asList(ivs), rnd); for (Interval iv : ivs) { res = res.join(iv); // the control is created by using the naturally ordered intervals control.add(iv); Collections.sort(control, new Intervals.StartComparator()); assertEquals(Intervals.ofNormalized(control.toArray(new Interval[control.size()])), res); } if (!of(ag).equals(res)) { String msg = "stress try " + i + " with " + Arrays.asList(ivs) + " didn't lead to " + ag + " but " + res; Log.LOG.get().report(msg); fail(msg); } } } public void testIntervalsIntersectSingle() { assertEquals(EMPTY, EMPTY.intersect(EMPTY)); assertEquals(EMPTY, of(ab).intersect(EMPTY)); assertEquals(EMPTY, EMPTY.intersect(of(ab))); assertEquals(EMPTY, of(ab).intersect(of(bc))); assertEquals(EMPTY, of(bc).intersect(of(ab))); assertEquals(EMPTY, of(ab, cd).intersect(of(bc))); // single intersects assertEquals(of(ab), of(ab).intersect(of(ab))); assertEquals(of(ab), of(ab).intersect(of(ac))); assertEquals(of(ab), of(ac).intersect(of(ab))); assertEquals(of(bc), of(bc).intersect(of(ac))); assertEquals(of(bc), of(ac).intersect(of(bc))); assertEquals(of(bc), of(ad).intersect(of(bc))); assertEquals(of(bc), of(bc).intersect(of(ad))); // cut away assertEquals(of(ab), of(ab, cd).intersect(of(ab))); assertEquals(of(ab), of(ac, de).intersect(of(ab))); assertEquals(of(cd), of(cd, ef).intersect(of(ae))); assertEquals(of(bc), of(ac, de).intersect(of(bd))); assertEquals(of(cd), of(ab, cd, ef).intersect(of(be))); // double overlap assertEquals(of(bc, ef), of(ac, eg).intersect(of(bf))); // longer assertEquals(of(ab, cd), of(ab, cd, ef).intersect(of(ae))); } public void testIntervalsIntersectMulti() { assertEquals(EMPTY, of(ab, cd).intersect(of(bc, de, ef))); assertEquals(of(ab, de), of(ac, df).intersect(of(ab, ce))); } public void testIntervalsIntersectStress() { Random rnd = new Random(4711); Interval[] ivs = new Interval[] { ab, bc, cd, de, ef, fg }; for (int i = 0; i < 1000; i++) { Intervals res = of(ag); Collections.shuffle(Arrays.asList(ivs), rnd); for (Interval iv : ivs) { Intervals neg = of(ag).intersect(iv); res = res.intersect(neg); } if (!EMPTY.equals(res)) { String msg = "stress try " + i + " with " + Arrays.asList(ivs) + " didn't lead to " + ag + " but " + res; Log.LOG.get().report(msg); fail(msg); } } } // public void testEmptyIntervals() { // assertEquals(EMPTY, of(aa).simplify()); // // // single intersects // assertEquals(of(ab), of(aa).join(of(ab))); // assertEquals(of(ab), of(ab).join(of(bb))); // // assertEquals(EMPTY, of(aa).intersect(of(ab))); // assertEquals(EMPTY, of(aa).intersect(of(ab))); // assertEquals(EMPTY, of(ab).intersect(of(bb)).simplify()); // } }
/* * Copyright (c) 2019 LINE Corporation. All rights reserved. * LINE Corporation PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package com.libedi.demo.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.libedi.demo.domain.Parent; /** * ParentRepository * * @author Sang-jun, Park (libedi@linecorp.com) * @since 2019. 04. 19 */ public interface ParentRepository extends JpaRepository<Parent, Long> { }
/* * 2012-3 Red Hat Inc. and/or its affiliates and other contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.overlord.rtgov.activity.processor; import static org.junit.Assert.*; import org.junit.Test; import org.overlord.rtgov.activity.processor.AbstractInformationProcessorManager; import org.overlord.rtgov.activity.processor.InformationProcessor; import org.overlord.rtgov.activity.processor.InformationProcessorManager; public class AbstractInformationProcessorManagerTest { private static final String IP_NAME1 = "IPName1"; @Test public void testRegister() { InformationProcessorManager ipm=new AbstractInformationProcessorManager(){}; InformationProcessor ip=new InformationProcessor(); ip.setName(IP_NAME1); ip.setVersion("1"); try { ipm.register(ip); } catch (Exception e) { fail("Failed to register"); } if (ipm.getInformationProcessor(IP_NAME1) == null) { fail("Information processor not registered"); } } @Test public void testRegisterFailed() { InformationProcessorManager ipm=new AbstractInformationProcessorManager(){}; InformationProcessor ip=new InformationProcessor() { public void init() throws Exception { throw new Exception("FAIL"); } }; ip.setName(IP_NAME1); ip.setVersion("1"); try { ipm.register(ip); fail("Should have failed to register"); } catch (Exception e) { } } @Test public void testRegisterNewer() { InformationProcessorManager ipm=new AbstractInformationProcessorManager(){}; InformationProcessor ip1=new InformationProcessor(); ip1.setName(IP_NAME1); ip1.setVersion("1"); try { ipm.register(ip1); } catch (Exception e) { fail("Failed to register"); } if (ipm.getInformationProcessor(IP_NAME1) == null) { fail("Information processor not registered"); } if (!ipm.getInformationProcessor(IP_NAME1).getVersion().equals("1")) { fail("Information processor not version 1: "+ ipm.getInformationProcessor(IP_NAME1).getVersion()); } InformationProcessor ip2=new InformationProcessor(); ip2.setName(IP_NAME1); ip2.setVersion("2"); try { ipm.register(ip2); } catch (Exception e) { fail("Failed to register"); } if (ipm.getInformationProcessor(IP_NAME1) == null) { fail("Information processor not registered"); } if (!ipm.getInformationProcessor(IP_NAME1).getVersion().equals("2")) { fail("Information processor not version 2: "+ ipm.getInformationProcessor(IP_NAME1).getVersion()); } } @Test public void testRegisterOlder() { InformationProcessorManager ipm=new AbstractInformationProcessorManager(){}; InformationProcessor ip1=new InformationProcessor(); ip1.setName(IP_NAME1); ip1.setVersion("2"); try { ipm.register(ip1); } catch (Exception e) { fail("Failed to register"); } if (ipm.getInformationProcessor(IP_NAME1) == null) { fail("Information processor not registered"); } if (!ipm.getInformationProcessor(IP_NAME1).getVersion().equals("2")) { fail("Information processor not version 2: "+ ipm.getInformationProcessor(IP_NAME1).getVersion()); } InformationProcessor ip2=new InformationProcessor(); ip2.setName(IP_NAME1); ip2.setVersion("1"); try { ipm.register(ip2); } catch (Exception e) { fail("Failed to register"); } if (ipm.getInformationProcessor(IP_NAME1) == null) { fail("Information processor not registered"); } // Version should remain 2 if (!ipm.getInformationProcessor(IP_NAME1).getVersion().equals("2")) { fail("Information processor not version 2: "+ ipm.getInformationProcessor(IP_NAME1).getVersion()); } } @Test public void testUnregisterNewerRegisterOlder() { InformationProcessorManager ipm=new AbstractInformationProcessorManager(){}; InformationProcessor ip1=new InformationProcessor(); ip1.setName(IP_NAME1); ip1.setVersion("2"); try { ipm.register(ip1); } catch (Exception e) { fail("Failed to register"); } if (ipm.getInformationProcessor(IP_NAME1) == null) { fail("Information processor not registered"); } if (!ipm.getInformationProcessor(IP_NAME1).getVersion().equals("2")) { fail("Information processor not version 2: "+ ipm.getInformationProcessor(IP_NAME1).getVersion()); } try { ipm.unregister(ip1); } catch (Exception e) { fail("Failed to unregister"); } InformationProcessor ip2=new InformationProcessor(); ip2.setName(IP_NAME1); ip2.setVersion("1"); try { ipm.register(ip2); } catch (Exception e) { fail("Failed to register"); } if (ipm.getInformationProcessor(IP_NAME1) == null) { fail("Information processor not registered"); } if (!ipm.getInformationProcessor(IP_NAME1).getVersion().equals("1")) { fail("Information processor not version 1: "+ ipm.getInformationProcessor(IP_NAME1).getVersion()); } } }
package br.ita.sem2dia1.AprofundandoClassesJava.escola; //passo 1 programamos de forma estruturada para comparar //passo 2 programamos de forma O.O para comparar public class VerificadoraDeNotas { /* Exemplo de como seria estruturado: * Classe movida para dentro de Aluno * public static int mediaAluno(Aluno a){ int total = 0; total += a.bim1; total += a.bim2; total += a.bim3; total += a.bim4; return total /4; } */ /* Exemplo de como seria estruturado: * Classe movida para dentro de Aluno * public static boolean passouDeAno(Aluno a){ int media = a.mediaAluno(a); if(media >= 60) return true; return false; } */ }
package communication.packets.request; import communication.enums.PacketType; import communication.enums.RequestResult; import communication.packets.Packet; import communication.packets.RequestPacket; import communication.packets.ResponsePacket; import communication.packets.response.LoginResponsePacket; import communication.wrapper.Connection; import main.Conference; import user.LoginResponse; import utils.Pair; /** * This packet handles an login request from either an attendee or an admin and responds with an {@link LoginResponsePacket}. */ public class LoginRequestPacket extends RequestPacket { private String username; private String password; /** * @param username the username to login with * @param password the password to use for login */ public LoginRequestPacket(String username, String password) { super(PacketType.LOGIN_REQUEST); this.username = username; this.password = password; } @Override public void handle(Conference conference, Connection connection) { if(password == null) { password = ""; } Pair<LoginResponse, Pair<String, Long>> result; result = conference.login(username, password); Packet response; if(result.first() == LoginResponse.Valid) { response = new LoginResponsePacket(result.second().first(), result.second().second()); } else { response = new ResponsePacket(PacketType.LOGIN_RESPONSE, RequestResult.Failure); } response.send(connection); } }
package com.rofour.baseball.service.manager; import com.rofour.baseball.dao.manager.bean.CityOrderConfBean; import java.util.List; public interface CityOrderConfService { int insert(CityOrderConfBean bean); int updateCostValue(CityOrderConfBean bean); int del(CityOrderConfBean bean); List<CityOrderConfBean> getAll(CityOrderConfBean bean); int selectAllCount(CityOrderConfBean bean); int selectIsExtNameCount(CityOrderConfBean bean); int enable(CityOrderConfBean bean); int disable(CityOrderConfBean bean); }
package com.nt.service; import java.util.Calendar; import org.springframework.stereotype.Service; @Service public class WishService { public String generateWishMsg(String uname){ int hour=0; Calendar cal=null; cal=Calendar.getInstance(); hour=cal.get(Calendar.HOUR_OF_DAY); if(hour<12) return "Good Morning"+uname; else if(hour<16) return "Good AfterNoon " +uname; else if(hour<20) return"Good Evening"+uname; else return "Good Night"+uname; } }
package br.com.rsinet.hub_bdd.teste; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.PageFactory; import com.aventstack.extentreports.ExtentReports; import com.aventstack.extentreports.ExtentTest; import com.aventstack.extentreports.reporter.ExtentHtmlReporter; import br.com.rsinet.hub_bdd.files.Constant; import br.com.rsinet.hub_bdd.files.ExcelUtils; import br.com.rsinet.hub_bdd.files.Screenshot; import br.com.rsinet.hub_bdd.page.DriverElement; import br.com.rsinet.hub_bdd.page.HomePage; import br.com.rsinet.hub_bdd.page.ProductPage; public class ConsultaProdutoBarraDePesquisa { private WebDriver driver; @Before public void Inicializa() throws Exception { driver = DriverElement.getChromeDriver(); } @After public void finaliza() { DriverElement.quitDriver(driver); } @Test public void ConsultarProdutoPelaBarraDePesquisaComSucesso() throws Exception { HomePage homePage = PageFactory.initElements(driver, HomePage.class); ProductPage productPage = PageFactory.initElements(driver, ProductPage.class); ExcelUtils.setExcelFile(Constant.File_DataUserRegister, "Headphone"); homePage.clickIconSearch(); homePage.setSearch(ExcelUtils.getCellData(1, 1)); homePage.findElementLinkText(ExcelUtils.getCellData(1, 1)); productPage.assertEqualsProduct(ExcelUtils.getCellData(1, 1)); Screenshot.getScreenShot(driver, "Consultar Produto Pela Barra de Pesquisa Com Sucesso", "TesteConsultaProdutoPelaBarraDePesquisaComSucesso"); } @Test public void ConsultarProdutoPelaBarraDePesquisaComFalha() throws Exception { HomePage homePage = PageFactory.initElements(driver, HomePage.class); ProductPage productPage = PageFactory.initElements(driver, ProductPage.class); ExcelUtils.setExcelFile(Constant.File_DataUserRegister, "Headphone"); homePage.clickIconSearch(); homePage.setSearch(ExcelUtils.getCellData(6, 1)); productPage.assertEqualsProductFail(ExcelUtils.getCellData(6, 1)); Screenshot.getScreenShot(driver, "Consultar Produto Pela Barra de Pesquisa Com Falha", "TesteConsultaProdutoPelaBarraDePesquisaComFalha"); } }
package com.tencent.mm.plugin.backup.b; import com.tencent.mm.plugin.backup.b.c.b.2; import com.tencent.mm.plugin.backup.f.c; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import junit.framework.Assert; class c$b$2$1 implements Runnable { final /* synthetic */ c gSE; final /* synthetic */ long gSF; final /* synthetic */ 2 gSG; c$b$2$1(2 2, c cVar, long j) { this.gSG = 2; this.gSE = cVar; this.gSF = j; } public final String toString() { return this.gSG.gSD.TAG + ".sendFile"; } public final void run() { Assert.assertTrue(toString() + ", check running. ", this.gSG.gSD.ftu); long VF = bi.VF(); this.gSE.ass(); long VF2 = bi.VF(); x.i(this.gSG.gSD.TAG, "SendFileScene size:%d waitTime:%d netTime:%d [%s]", Integer.valueOf(this.gSE.asz()), Long.valueOf(VF2 - this.gSF), Long.valueOf(VF2 - VF), this.gSE.gXK.hcI); } }
package com.gerray.fmsystem.ManagerModule.Profile; import android.content.Intent; import android.os.Bundle; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import com.gerray.fmsystem.R; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.squareup.picasso.Picasso; import java.util.Objects; public class FacilityProfile extends AppCompatActivity { private TextView facilityName, facilityAuth, facilityManager, facilityPostal, facilityEmail, facilityActivity, facilityOccupancy; private ImageView facilityImage; FirebaseAuth auth; FirebaseDatabase firebaseDatabase; DatabaseReference firebaseDatabaseReference, reference; FirebaseUser firebaseUser; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_facility_profile); facilityName = findViewById(R.id.tv_prof_name); facilityAuth = findViewById(R.id.tv_prof_auth); facilityManager = findViewById(R.id.tv_prof_manager); facilityPostal = findViewById(R.id.tv_prof_postal); facilityEmail = findViewById(R.id.tv_prof_email); facilityActivity = findViewById(R.id.tv_prof_activity); facilityOccupancy = findViewById(R.id.tv_prof_occupancy); facilityImage = findViewById(R.id.facility_imageView); Button btnUpdate = findViewById(R.id.profile_update); btnUpdate.setOnClickListener(v -> startActivity(new Intent(FacilityProfile.this, ProfilePopUp.class))); auth = FirebaseAuth.getInstance(); firebaseDatabase = FirebaseDatabase.getInstance(); firebaseDatabaseReference = firebaseDatabase.getReference(); reference = firebaseDatabase.getReference(); firebaseUser = FirebaseAuth.getInstance().getCurrentUser(); if (firebaseUser != null) { reference.child("Facilities").child(firebaseUser.getUid()) .addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { if (snapshot.child("facilityManager").exists()) { String facManager = Objects.requireNonNull(snapshot.child("facilityManager").getValue()).toString().trim(); facilityManager.setText(facManager); } if (snapshot.child("name").exists()) { String facName = Objects.requireNonNull(snapshot.child("name").getValue()).toString().trim(); facilityName.setText(facName); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); if (firebaseUser != null) { firebaseDatabaseReference.child("Facilities").child(firebaseUser.getUid()).child("Profile") .addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { if (snapshot.child("authorityName").exists()) { String authName = Objects.requireNonNull(snapshot.child("authorityName").getValue()).toString().trim(); facilityAuth.setText(authName); } if (snapshot.child("emailAddress").exists()) { String emailAddress = Objects.requireNonNull(snapshot.child("emailAddress").getValue()).toString().trim(); facilityEmail.setText(emailAddress); } if (snapshot.child("facilityType").exists()) { String facilityType = Objects.requireNonNull(snapshot.child("facilityType").getValue()).toString().trim(); facilityActivity.setText(facilityType); } if (snapshot.child("occupancyNo").exists()) { String occNo = Objects.requireNonNull(snapshot.child("occupancyNo").getValue()).toString().trim(); facilityOccupancy.setText(occNo); } if (snapshot.child("postalAddress").exists()) { String postal = Objects.requireNonNull(snapshot.child("postalAddress").getValue()).toString().trim(); facilityPostal.setText(postal); } if (snapshot.child("facilityImageUrl").exists()) { String imageUrl = Objects.requireNonNull(snapshot.child("facilityImageUrl").getValue()).toString().trim(); Picasso.with(FacilityProfile.this).load(imageUrl).into(facilityImage); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); } } } }
package com.wisape.android.util; import android.net.Uri; import static android.content.ContentResolver.SCHEME_FILE; /** * Created by LeiGuoting on 18/6/15. */ public class FrescoUriUtils { public static Uri fromFilePath(String path){ return new Uri.Builder().scheme(SCHEME_FILE).authority("").path(path).build(); } public static Uri fromResId(int resId){ return new Uri.Builder().scheme("res").path(Integer.toString(resId)).build(); } }
package com.qihoo.finance.chronus.storage.h2.plugin.dao.impl; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.stream.Collectors; import javax.transaction.Transactional; import org.apache.commons.collections4.CollectionUtils; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import com.qihoo.finance.chronus.metadata.api.cluster.dao.ClusterDao; import com.qihoo.finance.chronus.metadata.api.cluster.entity.ClusterEntity; import com.qihoo.finance.chronus.storage.h2.plugin.entity.ClusterH2Entity; import com.qihoo.finance.chronus.storage.h2.plugin.repository.ClusterJpaRepository; import com.qihoo.finance.chronus.storage.h2.plugin.util.H2IdUtil; /** * @author liuronghua * @date 2019年11月19日 下午8:01:26 * @version 5.1.0 */ public class ClusterH2DaoImpl implements ClusterDao { @Autowired private ClusterJpaRepository clusterJpaRepository; private ClusterH2Entity transferH2Entity(ClusterEntity entity) { if (null == entity) { return null; } ClusterH2Entity h2Entity = new ClusterH2Entity(); BeanUtils.copyProperties(entity, h2Entity); h2Entity.setId(H2IdUtil.getId()); h2Entity.setDateCreated(new Date()); h2Entity.setDateUpdated(h2Entity.getDateCreated()); return h2Entity; } private ClusterEntity transferEntity(ClusterH2Entity h2Entity) { if (null == h2Entity) { return null; } ClusterEntity entity = new ClusterEntity(); BeanUtils.copyProperties(h2Entity, entity); return entity; } @Override public void insert(ClusterEntity clusterEntity) { clusterJpaRepository.save(transferH2Entity(clusterEntity)); } @Override @Transactional public void update(ClusterEntity entity) { entity.setDateUpdated(new Date()); clusterJpaRepository.updateEnvDesc(entity.getId(), entity.getClusterDesc()); } @Override public void delete(String cluster) { clusterJpaRepository.deleteByCluster(cluster); } @Override public ClusterEntity selectByCluster(String cluster) { return transferEntity(clusterJpaRepository.findFirstByAndCluster(cluster)); } @Override public List<ClusterEntity> selectListAll() { List<ClusterH2Entity> list = clusterJpaRepository.findAll(); if (CollectionUtils.isEmpty(list)) { return new ArrayList<>(); } return list.stream().map(this::transferEntity).collect(Collectors.toList()); } }
package chinese.parser.implementations.map; import include.learning.perceptron.PackedScoreMap; import include.linguistics.chinese.CTagInt; import chinese.pos.CTag; @SuppressWarnings("serial") public final class CTagIntMap extends PackedScoreMap<CTagInt> { public CTagIntMap(final String input_name, final int table_size) { super(input_name, table_size); } @Override public CTagInt loadKeyFromString(final String str) { String[] args = str.split(" , "); return new CTagInt(new CTag(args[0]), Integer.valueOf(args[1])); } @Override public String generateStringFromKey(final CTagInt key) { return key.first().toString() + " , " + key.second().toString(); } @Override public CTagInt allocate_key(final CTagInt key) { return new CTagInt(key); } }
package com.example.usersessionmanagement; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class Welcome extends AppCompatActivity { TextView tv,tv2; Button b4; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_welcome); tv=findViewById(R.id.textView); tv2=findViewById(R.id.textView2); final UserPref up=new UserPref(Welcome.this); String spname=up.getData("Name"); String sppassword=up.getData("Password"); String address=up.getData("Address"); String mobile=up.getData("Mobile"); String email=up.getData("Email"); tv.setText(spname+"\n"+sppassword+"\n"+address+"\n"+mobile+"\n"+email); b4=findViewById(R.id.button4); b4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { up.addData("status","false"); Intent i=new Intent(Welcome.this,MainActivity.class); startActivity(i); finish(); } }); SharedPreferences sp= PreferenceManager.getDefaultSharedPreferences(this); String uname=sp.getString("uname",""); String password=sp.getString("upassword",""); String country=sp.getString("list",""); boolean chk=sp.getBoolean("chk1",false); boolean sw=sp.getBoolean("sw",false); tv2.setText(uname+"\n"+password+"\n"+country+"\n"+chk+"\n"+sw); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu1,menu); return true; } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { if(item.getItemId()==R.id.settings) { // Toast.makeText(this, "settings selected", Toast.LENGTH_SHORT).show(); Intent i=new Intent(Welcome.this,Settings.class); startActivity(i); finish(); } return true; } }
package fr.lteconsulting.outil; import java.io.IOException; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Outils { public static void callJsp( String name, ServletContext context, HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { context .getRequestDispatcher( "/WEB-INF/" + name + ".jsp" ) .forward( request, response ); } }
package gui; import bbdd.GestionBDFactory; import java.awt.Color; import java.awt.Toolkit; import java.util.List; import java.util.Vector; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import javax.swing.table.JTableHeader; import javax.swing.table.TableColumn; import model.Clientes; public class frmListadoClientes extends javax.swing.JFrame { public frmListadoClientes(List<Clientes> listClientes) { initComponents(); this.setExtendedState(MAXIMIZED_BOTH); this.setLocationRelativeTo(null); this.setIconImage(Toolkit.getDefaultToolkit().getImage("C:/Program Files/Gestion Clientes v3.0/resources/estrella_peque.png")); printListadoClientes(listClientes); formateoTabla(); } private void printListadoClientes(List<Clientes> listClientes) { Clientes cli = null; Vector<String> tableHeaders = new Vector<String>(); Vector tableData = new Vector(); tableHeaders.add("Nombre"); tableHeaders.add("Apellido1"); tableHeaders.add("Apellido2"); tableHeaders.add("Edad"); tableHeaders.add("Sexo"); tableHeaders.add("Tipo Vía"); tableHeaders.add("Dirección"); tableHeaders.add("Teléfono"); tableHeaders.add("Móvil"); tableHeaders.add("E-Mail"); tableHeaders.add("Fecha de Nacimiento"); tableHeaders.add("Comentarios"); tableHeaders.add("Id"); for (Object o : listClientes) { cli = (Clientes) o; Vector<Object> row = new Vector<Object>(); row.add(cli.getNombre()); row.add(cli.getApellido1()); row.add(cli.getApellido2()); row.add(cli.getEdad()); row.add(cli.getSexo()); row.add(cli.getDireccionTipo()); row.add(cli.getDireccion()); row.add(cli.getTelefono()); row.add(cli.getMovil()); row.add(cli.getEmail()); row.add(cli.getFechaNacimiento()); row.add(cli.getComentarios()); row.add(cli.getId()); tableData.add(row); } tablaClientes.setModel(new DefaultTableModel(tableData, tableHeaders)); JTableHeader header = tablaClientes.getTableHeader(); header.setBackground(Color.DARK_GRAY); } private void formateoTabla() { TableColumn column = null; for (int i = 0; i < tablaClientes.getColumnCount(); i++) { column = tablaClientes.getColumnModel().getColumn(i); switch (i) { case 0: column.setPreferredWidth(110); column.setMaxWidth(200); column.sizeWidthToFit(); break; case 1: column.setPreferredWidth(110); column.setMaxWidth(200); column.sizeWidthToFit(); break; case 2: column.setPreferredWidth(110); column.setMaxWidth(200); column.sizeWidthToFit(); break; case 3: column.setPreferredWidth(60); column.setMaxWidth(200); column.sizeWidthToFit(); break; case 4: column.setPreferredWidth(80); column.setMaxWidth(200); column.sizeWidthToFit(); break; case 5: column.setPreferredWidth(75); column.setMaxWidth(200); column.sizeWidthToFit(); break; case 6: column.setPreferredWidth(220); column.sizeWidthToFit(); break; case 7: column.setPreferredWidth(130); column.setMaxWidth(200); column.sizeWidthToFit(); break; case 8: column.setPreferredWidth(130); column.setMaxWidth(200); column.sizeWidthToFit(); break; case 9: column.setPreferredWidth(220); column.sizeWidthToFit(); break; case 10: column.setPreferredWidth(150); column.setMaxWidth(200); column.sizeWidthToFit(); break; case 11: column.setPreferredWidth(200); column.sizeWidthToFit(); break; case 12: column.setPreferredWidth(30); column.setMaxWidth(200); column.sizeWidthToFit(); break; } } } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); lblLogo = new javax.swing.JLabel(); lblListado = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); tablaClientes = new javax.swing.JTable(); btnCerrar = new javax.swing.JButton(); btnMostrarFicha = new javax.swing.JButton(); setTitle("Listado de Clientes"); jPanel1.setBackground(new java.awt.Color(225, 183, 222)); lblLogo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/logo_ambar_transp4.png"))); // NOI18N lblListado.setFont(new java.awt.Font("Ubuntu", 2, 24)); lblListado.setForeground(new java.awt.Color(8, 6, 6)); lblListado.setText("Listado de clientes"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(194, 194, 194) .addComponent(lblListado, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 246, Short.MAX_VALUE) .addComponent(lblLogo) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(lblLogo)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(12, 12, 12) .addComponent(lblListado, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE))) .addContainerGap()) ); tablaClientes.setFont(new java.awt.Font("Verdana", 0, 15)); // NOI18N tablaClientes.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { } )); tablaClientes.setDoubleBuffered(true); tablaClientes.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); tablaClientes.setShowHorizontalLines(false); jScrollPane1.setViewportView(tablaClientes); btnCerrar.setFont(new java.awt.Font("Comic Sans MS", 1, 15)); btnCerrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/Cerrar.png"))); // NOI18N btnCerrar.setText("Cerrar"); btnCerrar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCerrarActionPerformed(evt); } }); btnMostrarFicha.setFont(new java.awt.Font("Comic Sans MS", 1, 15)); btnMostrarFicha.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/Modificar.png"))); // NOI18N btnMostrarFicha.setText("Mostrar Ficha"); btnMostrarFicha.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnMostrarFichaActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(417, Short.MAX_VALUE) .addComponent(btnMostrarFicha) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnCerrar) .addGap(119, 119, 119)) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 796, Short.MAX_VALUE) .addContainerGap())) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 432, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnMostrarFicha) .addComponent(btnCerrar)) .addContainerGap()) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(78, 78, 78) .addComponent(jScrollPane1) .addGap(57, 57, 57))) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnCerrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCerrarActionPerformed this.setVisible(false); }//GEN-LAST:event_btnCerrarActionPerformed private void btnMostrarFichaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnMostrarFichaActionPerformed Object idCliente; try { idCliente = tablaClientes.getModel().getValueAt(tablaClientes.getSelectedRow(), 12); } catch (ArrayIndexOutOfBoundsException ex) { JOptionPane.showMessageDialog(rootPane, "Debe seleccionar el cliente a mostrar!!", "Error!", JOptionPane.ERROR_MESSAGE); return; } try { List<Clientes> cliente = GestionBDFactory.getInstance().getBDMySQL().findCliente(Integer.parseInt(idCliente.toString()), "", "", ""); frmClientes frmCliente = new frmClientes(cliente); frmCliente.setVisible(true); this.setVisible(false); } catch (Exception ex) { JOptionPane.showMessageDialog(rootPane, "Se ha producido un error mostrando la ficha del cliente!!", "Error!", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_btnMostrarFichaActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnCerrar; private javax.swing.JButton btnMostrarFicha; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel lblListado; private javax.swing.JLabel lblLogo; private javax.swing.JTable tablaClientes; // End of variables declaration//GEN-END:variables }