blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
ba6bf2c396ffe25e7fa7cd9efdcf73f86a2a193f
Java
samijan/opsCloud
/cmdb-domain/src/main/java/com/sdg/cmdb/domain/server/ServerVO.java
UTF-8
9,567
1.953125
2
[]
no_license
package com.sdg.cmdb.domain.server; import com.sdg.cmdb.domain.ip.IPDetailVO; import java.io.Serializable; /** * Created by zxxiao on 16/9/23. */ public class ServerVO implements Serializable { private static final long serialVersionUID = -70862472925821073L; private long id; private ServerGroupDO serverGroupDO; private int loginType; private String loginUser; private int envType; /** * 环境 */ private String envTypeStr; private IPDetailVO publicIP; private IPDetailVO insideIP; private int serverType; private String serverName; private String area; private int useType; private String serialNumber; private String ciGroup; private String content; private int zabbixStatus; private int zabbixMonitor; private String tomcatVersion; private String gmtModify; private String gmtCreate; private VmServerDO vmServerDO; private EcsServerDO ecsServerDO; private PhysicalServerDO physicalServerDO; private ServerGroupUseTypeDO serverGroupUseTypeDO; public ServerVO() { } public ServerVO(ServerDO serverDO, ServerGroupDO serverGroupDO, IPDetailVO publicIP, IPDetailVO insideIP) { this.id = serverDO.getId(); this.serverGroupDO = serverGroupDO; this.loginType = serverDO.getLoginType(); this.loginUser = serverDO.getLoginUser(); this.envType = serverDO.getEnvType(); this.envTypeStr = EnvTypeEnum.getDescByCode(envType); this.publicIP = publicIP; this.insideIP = insideIP; this.serverType = serverDO.getServerType(); this.serverName = serverDO.getServerName(); this.area = serverDO.getArea(); this.useType = serverDO.getUseType(); this.serialNumber = serverDO.getSerialNumber(); this.ciGroup = serverDO.getCiGroup(); this.content = serverDO.getContent(); this.zabbixStatus = serverDO.getZabbixStatus(); this.zabbixMonitor = serverDO.getZabbixMonitor(); this.tomcatVersion = serverDO.getExtTomcatVersion(); this.gmtCreate = serverDO.getGmtCreate(); this.gmtModify = serverDO.getGmtModify(); } public ServerVO(ServerDO serverDO, ServerGroupDO serverGroupDO) { this.id = serverDO.getId(); this.serverGroupDO = serverGroupDO; this.loginType = serverDO.getLoginType(); this.loginUser = serverDO.getLoginUser(); this.envType = serverDO.getEnvType(); this.envTypeStr = EnvTypeEnum.getDescByCode(envType); this.serverType = serverDO.getServerType(); this.serverName = serverDO.getServerName(); this.area = serverDO.getArea(); this.useType = serverDO.getUseType(); this.serialNumber = serverDO.getSerialNumber(); this.ciGroup = serverDO.getCiGroup(); this.content = serverDO.getContent(); this.zabbixStatus = serverDO.getZabbixStatus(); this.zabbixMonitor = serverDO.getZabbixMonitor(); this.gmtCreate = serverDO.getGmtCreate(); this.gmtModify = serverDO.getGmtModify(); } public ServerVO(ServerDO serverDO) { this.id = serverDO.getId(); this.loginType = serverDO.getLoginType(); this.loginUser = serverDO.getLoginUser(); this.envType = serverDO.getEnvType(); this.envTypeStr = EnvTypeEnum.getDescByCode(envType); this.serverType = serverDO.getServerType(); this.serverName = serverDO.getServerName(); this.area = serverDO.getArea(); this.useType = serverDO.getUseType(); this.serialNumber = serverDO.getSerialNumber(); this.ciGroup = serverDO.getCiGroup(); this.content = serverDO.getContent(); this.zabbixStatus = serverDO.getZabbixStatus(); this.zabbixMonitor = serverDO.getZabbixMonitor(); this.gmtCreate = serverDO.getGmtCreate(); this.gmtModify = serverDO.getGmtModify(); } public long getId() { return id; } public void setId(long id) { this.id = id; } public ServerGroupDO getServerGroupDO() { return serverGroupDO; } public void setServerGroupDO(ServerGroupDO serverGroupDO) { this.serverGroupDO = serverGroupDO; } public int getLoginType() { return loginType; } public void setLoginType(int loginType) { this.loginType = loginType; } public String getLoginUser() { return loginUser; } public void setLoginUser(String loginUser) { this.loginUser = loginUser; } public int getEnvType() { return envType; } public void setEnvType(int envType) { this.envType = envType; } public String getEnvTypeStr() { return envTypeStr; } public void setEnvTypeStr(String envTypeStr) { this.envTypeStr = envTypeStr; } public IPDetailVO getPublicIP() { return publicIP; } public void setPublicIP(IPDetailVO publicIP) { this.publicIP = publicIP; } public IPDetailVO getInsideIP() { return insideIP; } public void setInsideIP(IPDetailVO insideIP) { this.insideIP = insideIP; } public int getServerType() { return serverType; } public void setServerType(int serverType) { this.serverType = serverType; } public String getServerName() { return serverName; } public void setServerName(String serverName) { this.serverName = serverName; } public String getArea() { return area; } public void setArea(String area) { this.area = area; } public int getUseType() { return useType; } public void setUseType(int useType) { this.useType = useType; } public String getSerialNumber() { return serialNumber; } public void setSerialNumber(String serialNumber) { this.serialNumber = serialNumber; } public String getCiGroup() { return ciGroup; } public void setCiGroup(String ciGroup) { this.ciGroup = ciGroup; } public String getContent() { return content; } public int getZabbixStatus() { return zabbixStatus; } public void setZabbixStatus(int zabbixStatus) { this.zabbixStatus = zabbixStatus; } public int getZabbixMonitor() { return zabbixMonitor; } public void setZabbixMonitor(int zabbixMonitor) { this.zabbixMonitor = zabbixMonitor; } public void setContent(String content) { this.content = content; } public String getGmtModify() { return gmtModify; } public void setGmtModify(String gmtModify) { this.gmtModify = gmtModify; } public String getGmtCreate() { return gmtCreate; } public void setGmtCreate(String gmtCreate) { this.gmtCreate = gmtCreate; } public VmServerDO getVmServerDO() { return vmServerDO; } public void setVmServerDO(VmServerDO vmServerDO) { this.vmServerDO = vmServerDO; } public EcsServerDO getEcsServerDO() { return ecsServerDO; } public void setEcsServerDO(EcsServerDO ecsServerDO) { this.ecsServerDO = ecsServerDO; } public PhysicalServerDO getPhysicalServerDO() { return physicalServerDO; } public void setPhysicalServerDO(PhysicalServerDO physicalServerDO) { this.physicalServerDO = physicalServerDO; } public String getTomcatVersion() { return tomcatVersion; } public void setTomcatVersion(String tomcatVersion) { this.tomcatVersion = tomcatVersion; } public ServerGroupUseTypeDO getServerGroupUseTypeDO() { return serverGroupUseTypeDO; } public void setServerGroupUseTypeDO(ServerGroupUseTypeDO serverGroupUseTypeDO) { this.serverGroupUseTypeDO = serverGroupUseTypeDO; } // public String acqServerName() { // if (this.envType == ServerDO.EnvTypeEnum.prod.getCode()) { // return serverName; // } else { // return serverName + "-" + ServerDO.EnvTypeEnum.getEnvTypeName(envType); // } // } public String acqServerName() { if (this.envType == ServerDO.EnvTypeEnum.prod.getCode()) { return serverName + "-" + serialNumber; } else { return serverName + "-" + ServerDO.EnvTypeEnum.getEnvTypeName(envType) + "-" + serialNumber; } } @Override public String toString() { return "ServerVO{" + "id=" + id + ", serverGroupDO=" + serverGroupDO + ", loginType=" + loginType + ", loginUser='" + loginUser + '\'' + ", envType=" + envType + ", envTypeStr='" + envTypeStr + '\'' + ", publicIP=" + publicIP + ", insideIP=" + insideIP + ", serverType=" + serverType + ", serverName='" + serverName + '\'' + ", area='" + area + '\'' + ", useType=" + useType + ", serialNumber='" + serialNumber + '\'' + ", ciGroup='" + ciGroup + '\'' + ", content='" + content + '\'' + ", zabbixStatus=" + zabbixStatus + ", zabbixMonitor=" + zabbixMonitor + ", gmtModify='" + gmtModify + '\'' + ", gmtCreate='" + gmtCreate + '\'' + '}'; } }
true
8901030581440dd0ef0885fc7586cdc5ea6d744a
Java
bcdasilv/topicxp_extension
/ldaTopics_Bruno_v2/src/edu/wm/LDATopics/LDA/LDATopicMap.java
UTF-8
26,345
1.796875
2
[]
no_license
package edu.wm.LDATopics.LDA; import jgibblda.*; import java.io.*; import java.lang.reflect.Array; import java.net.URI; import java.net.URL; import java.net.URLClassLoader; import java.text.DecimalFormatSymbols; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Locale; import java.util.Scanner; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; import org.apache.lucene.analysis.snowball.SnowballAnalyzer; import org.apache.lucene.analysis.StopAnalyzer; import org.apache.lucene.analysis.Token; import org.apache.lucene.analysis.TokenStream; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jdt.core.IBuffer; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IOpenable; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.MessageBox; import edu.wm.LDATopics.LDATopics; import edu.wm.LDATopics.LDA.Topic; import edu.wm.LDATopics.LDA.TopicMember; import edu.wm.LDATopics.LDA.documents.LDAClassDocument; import edu.wm.LDATopics.LDA.documents.LDADocument; import edu.wm.LDATopics.LDA.documents.LDAMethodDocument; import edu.wm.LDATopics.LDA.documents.LDAPackageDocument; /** * Responsible for representing and generating a set of topics. * @author tcsava * */ public abstract class LDATopicMap { final int METADATA_FORMAT_VERSION = 3; // LDA Analysis Parameters LDAOptions options; public double hellingerThreshold=0.4; public Topic topics[] = null; LDADocument documents[]; boolean updateInProgress = false; boolean loadInProgress = false; public String project; // root that all documents should somehow be children of. can really be a proj, a package, a class... or can it? String basisModelName = ""; // existing topic map to measure this topic's documents by public boolean filterUsingQuery = false; // Should we filter documents using their hellinger distance from a query? /** * Creates a new LDATopicMap for the source of project with name project, * and loads up a topic map with either the last settings used or the default settings. * * @param project project name * @param path path to store LDA information in */ public LDATopicMap (String project, LDAOptions options) { // TODO: should we still allow specifying path? not useful for us, might be useful as a library? this.project = project; this.options = options; File folder = new File(getTopicDirectory()); if (!folder.exists()) folder.mkdirs(); } public LDATopicMap(String project, String basisModelName, LDAOptions options) { this.project = project; this.basisModelName = basisModelName; this.options = options; File folder = new File(getTopicDirectory()); if (!folder.exists()) folder.mkdirs(); // // try { // loadTopicMapInJob(); // // Don't count this load to prevent loads after updates // loadInProgress = false; // } catch (FileNotFoundException e) { // // Couldn't load, so let's try generating the map // updateTopicMap(); // } } protected abstract LDADocument[] getDocuments(); protected abstract String getModelName(); protected String getFullModelName() { String modelName = getModelName(); if (basisModelName != "") modelName += "." + basisModelName; return modelName; } /** * Returns a directory to store lda files in. * * @return Directory for temp LDA files */ String getTopicDirectory() { return LDATopics.getDefault().getStateLocation().append("/"+project+"/").toOSString(); } /** * Checks the modification stamp of the project at the time the last topic map * was generated and compares it to the current modification stamp. * * @return true if current map is current and present, otherwise false. */ public void loadMetadata() { try { options.loadMetadata( getTopicDirectory() + "metadata"); } catch (FileNotFoundException e) { // No options, so use the defaults } } public void saveMetadata() { // Get the project modification stamp of the project at the time of reading the docs IProject projectRep = ResourcesPlugin.getWorkspace().getRoot().getProject(project); long modificationStamp = projectRep.getModificationStamp(); options.saveMetadata(modificationStamp, getTopicDirectory() + "metadata"); } /** * Calls JGibbLDA to generate a new Topic Map using the current settings. */ public void updateTopicMap() { if (basisModelName != "") { updateTopicMapFromExistingTopics(); return; } // Load metadata if it's been saved; information about last LDA settings to use and such //loadMetadata(); // then use jgibblda to generate LDA topics with String args[] = {"-est","-dir", getTopicDirectory(),"-dfile", getModelName(), "-model", getModelName(), "-alpha", Double.toString(options.alpha), "-beta", Double.toString(options.beta), "-ntopics", Integer.toString(options.numberTopics), "-twords", Integer.toString(options.numberWords), "-niters", Integer.toString(options.numberIterations), "-savestep", Integer.toString(options.numberIterations)}; Job generateTopics = new GenerateTopicsJob(args,options.numberIterations, getModelName()); generateTopics.schedule(); // And load the topics into our data structures loadTopicMapInJobWithoutCheck(); } /** * Calls JGibbLDA to generate a new Topic Map using the current settings. * Regenerates the document->topic mapping using the existing topics. */ public void updateTopicMapFromExistingTopics() { // Load metadata if it's been saved; information about last LDA settings to use and such //loadMetadata(); // then use jgibblda to generate LDA topics with String args[] = {"-inf","-dir", getTopicDirectory(), "-model", basisModelName, "-dfile", getModelName(), "-twords", Integer.toString(options.numberWords), "-niters", Integer.toString(20)}; // was numberIterations; locked niters to 20 for restimation Job generateTopics = new GenerateTopicsJob(args, 20, getModelName()); generateTopics.schedule(); // And load the topics into our data structures loadTopicMapInJobWithoutCheck(); } /** * Uses updateTopicMapFromExistingTopics to compute topic probabilities for a use query * (which is treated as any other document), then loads in the results and computes * Hellinger distances between the user query and the documents in this topic map. */ public void userQuery(String query) { filterUsingQuery = true; //TODO, 2010: ever need to set this to false? // Run the query, get the probabilities QueryTopicMap queryTopicMap = new QueryTopicMap(this.project, this.getFullModelName(), this.options, query); queryTopicMap.updateTopicMapFromExistingTopics(); // And compute distanes between the query and all our documents ComputeDistanceJob distanceJob = new ComputeDistanceJob(queryTopicMap); distanceJob.schedule(); } /** * Returns the probabilities of doc with respect to each topic in an array * @param doc * @return */ private Double[] getProbabilities(LDADocument doc) { Double[] probabilities = new Double[topics.length]; //TODO, 2010: make getDocumentByName use full names instead of names? names may not be unique!! for (Topic topic : topics) probabilities[topic.getNumber()-1] = topic.getDocumentByNameFromAllProbabilities(doc.getName()).probability; return probabilities; } public double hellingerDistance(Double probability1[], Double probability2[]) { Double sum = 0.0; for (int i = 0; i < probability1.length; i++) sum += Math.pow(Math.sqrt(probability1[i]) - Math.sqrt(probability2[i]),2); return Math.sqrt(sum); } public boolean existsOnDisk() { String modelName = getFullModelName(); return new File(getTopicDirectory()+modelName+".theta").exists() && new File(getTopicDirectory()+modelName+".twords").exists(); } public void loadTopicMapInJob() throws FileNotFoundException { if (!existsOnDisk()) { // System.out.println("No topic map was available to be loaded for model '"+getModelName()+"'."); throw new FileNotFoundException(); } Job loadTopics = new LoadTopicsJob(getModelName()); loadTopics.schedule(); } public void loadTopicMapInJobWithoutCheck() { Job loadTopics = new LoadTopicsJob(getModelName()); loadTopics.schedule(); } /** * Reads in the last generated topic map for the current project and settings. * @throws FileNotFoundException */ public void loadTopicMap() throws FileNotFoundException { // Load metadata if it's been saved; information about last LDA settings used and such loadMetadata(); String modelName = getFullModelName(); if (!new File(getTopicDirectory()+modelName+".theta").exists()) { // System.out.println("No topic map was available to be loaded for model '"+getModelName()+"'."); throw new FileNotFoundException(); } // Reset topics and such this.documents = getDocuments(); topics = null; // Read in document probabilities for each topic Scanner scanTheta = new Scanner(new FileInputStream(getTopicDirectory()+modelName+".theta")); scanTheta.useLocale(Locale.ENGLISH); for (LDADocument doc : documents) { if (!scanTheta.hasNextLine()) throw new FileNotFoundException();; // Invalid input String line = scanTheta.nextLine(); String topicProbabilities[] = line.split("\\s+"); for (int i = 0; i < topicProbabilities.length; i++) { // Init topics array if ((topics == null) || (topics.length != topicProbabilities.length)) { topics = new Topic[topicProbabilities.length]; for (int j = 0; j < topics.length; j++) { topics[j] = new Topic((j+1), this); } } //new Path(doc).lastSegment() topics[i].documents.add(new TopicMember(doc, Double.valueOf(topicProbabilities[i]))); } } scanTheta.close(); if (topics == null) throw new FileNotFoundException();; // Invalid data! for ( Topic topic : topics) Collections.sort(topic.documents); // Read in top words in each topic Scanner scanTwords = new Scanner(new FileInputStream(getTopicDirectory()+modelName+".twords")); scanTwords.useLocale(Locale.ENGLISH); if (!options.noThresholdOrCutoff) { // this is a hack, but it keeps us from reading twords if this is a queryTopicMap for (int i = 0; i < topics.length; i++) { scanTwords.nextLine(); for (int j = 0; j < options.numberWords; j++) { //System.out.println(scanTwords.next() + ":"+ scanTwords.nextDouble()); topics[i].words.add(new TopicMember(scanTwords.next(), scanTwords.nextDouble())); } scanTwords.nextLine(); } } scanTwords.close(); // TODO, 2010: Didn't close; did that cause issue on XP?? // Save all probabilities for computing MWE cohesion, hellinger distance for (Topic topic : topics) topic.allProbabilities = (ArrayList<TopicMember>) topic.documents.clone(); filter(false); } public void filter(boolean refilter) { // TODO, 2010: detect this automatically? // If filtering's been done before, we need to copy documents back over for (Topic topic : topics) topic.documents = (ArrayList<TopicMember>) topic.allProbabilities.clone(); if (filterUsingQuery) filterUsingQuery(); if (!options.noThresholdOrCutoff) { if (options.useThreshold) limitTopicsPerDocumentWithThreshold(options.topicAssociationThreshold); else // use cutoff limitTopicsPerDocumentWithCutoff(options.topicAssociationCutoff); } } private void filterUsingQuery() { for (LDADocument doc : documents) { for (Topic topic : topics) { TopicMember document = topic.getDocumentByName(doc.getName()); if (doc.hellingerDistance > hellingerThreshold) { topic.documents.remove(document); } } } } public void exportToFile(String filename) throws IOException { // create .zip with all necessary LDA analysis files // All the files? Nah. //String files[] = {"model-final.others", "model-final.phi", "model-final.tassign", "model-final.theta", "model-final.twords", "metadata", "sourcefiles.dat", "wordmap.txt"}; // Just the essential files // later, include some renderings of the visualizations or such? String files[] = {"model-final.theta", "model-final.twords", "metadata"}; FileOutputStream zipFile = new FileOutputStream(filename); ZipOutputStream zip = new ZipOutputStream(zipFile); for (String file : files) { ZipEntry entry = new ZipEntry(file); FileInputStream fileStream = new FileInputStream(getTopicDirectory() + file); zip.putNextEntry(entry); for (int c = fileStream.read(); c != -1; c = fileStream.read()) { zip.write(c); } fileStream.close(); } zip.close(); zipFile.close(); } public void importFromFile(String filename) throws IOException { // load back from an archived topic map // overwrite existing map? GUI should warn about that "this will overwrite your current map for project x, are you sure?" String files[] = {"model-final.theta", "model-final.twords", "metadata"}; // extract files to current map directory, load them up. ZipFile zip = new ZipFile(filename); for (String file : files) { ZipEntry entry = zip.getEntry(file); InputStream entryIn = zip.getInputStream(entry); FileOutputStream entryOut = new FileOutputStream(getTopicDirectory() + file); for (int c = entryIn.read(); c != -1; c = entryIn.read()) { entryOut.write(c); } } loadTopicMapInJob(); } /** * For Snowball. * * @return a list of java and english stop words */ protected String[] getStopWords() { String[] JAVA_STOP_WORDS = { "public", "private", "protected", "interface", "abstract", "implements", "extends", "null", "new", "switch", "case", "default", "synchronized", "do", "if", "else", "break", "continue", "this", "assert", "for", "instanceof", "transient", "final", "static", "void", "catch", "try", "throws", "throw", "class", "finally", "return", "const", "native", "super", "while", "import", "package", "true", "false"}; // these should be good stop words too, right? : String[] GENERIC_STOP_WORDS = { "java", "boolean", "string", "get", "set", ""}; HashSet<String> st = new HashSet<String>(Arrays.asList(StopAnalyzer.ENGLISH_STOP_WORDS)); st.addAll(Arrays.asList(JAVA_STOP_WORDS)); st.addAll(Arrays.asList(GENERIC_STOP_WORDS)); st.addAll(Arrays.asList(options.customStopWords)); // Add any project-specific stop words the user has entered return st.toArray(new String[st.size()]); } /** * Creates a datafile in the LDA directory containing the words in the current list of documents. */ public void createDatafile() { // If project LDA temp dir doesn't exist, create it. File directory = new File(getTopicDirectory()); if (!directory.exists()) directory.mkdir(); // Then create a .dat file in the directory with the words to be analyzed // from all of the source files createDatafile(getTopicDirectory()+getModelName(), documents); } /** * Creates a .dat file containing all the documents in a given corpus. * * @param fileName Location to save datafile. * @param documents List of filenames to save to datafile. */ public void createDatafile(String fileName, LDADocument documents[]) { FileOutputStream dataFile; try { dataFile = new FileOutputStream(fileName); PrintStream out = new PrintStream(dataFile); out.println(documents.length); for (LDADocument document : documents) { out.print(document.getFullName()+ " ="); //oops, this doesn't actually belong there. useful for debugging though. //Scanner scan = new Scanner(new FileInputStream(document)); Reader reader = document.getReader(); // Snowball makes datafiler -> datafil o.O is it supposed to? is that the stem? // Do preprocessing with Snowball TokenStream stream = new SnowballAnalyzer("English", getStopWords()).tokenStream("",reader); Token tok; String whitespace = ""; //Bruno: I modified here as in the ClassTopicMap class. while ((tok = stream.next()) != null) { String text = tok.termText(); if ( (text.length() >= 2) && !(isStringNumeric(text)) ){ out.print(whitespace+tok.termText()); whitespace = " "; } } out.print("\n"); } out.close(); dataFile.close(); } catch (FileNotFoundException e) { System.err.println("File not found: "+fileName); e.printStackTrace(); } catch (IOException e) { System.err.println("Error closing: "+fileName); e.printStackTrace(); } } //Added by Bruno - 06/27/2014 /* * Solution extracted from StackOverFlow post: * http://stackoverflow.com/questions/1102891/how-to-check-if-a-string-is-a-numeric-type-in-java * */ private boolean isStringNumeric( String str ) { DecimalFormatSymbols currentLocaleSymbols = DecimalFormatSymbols.getInstance(); char localeMinusSign = currentLocaleSymbols.getMinusSign(); if ( !Character.isDigit( str.charAt( 0 ) ) && str.charAt( 0 ) != localeMinusSign ) return false; boolean isDecimalSeparatorFound = false; char localeDecimalSeparator = currentLocaleSymbols.getDecimalSeparator(); for ( char c : str.substring( 1 ).toCharArray() ) { if ( !Character.isDigit( c ) ) { if ( c == localeDecimalSeparator && !isDecimalSeparatorFound ) { isDecimalSeparatorFound = true; continue; } return false; } } return true; } /** * Limits documents to only being in one topic at a time, the one that it best fits in. * * @param limit Number of topics to limit a document to. */ public void limitTopicsPerDocument(int limit) { // assume limit = 1 for now int currentDoc = 0; int bestTopic; if (topics == null) return; for (LDADocument doc : documents) { int currentTopic = 0; double bestProbability = -1; bestTopic = -1; for (Topic topic : topics) { TopicMember document = topic.getDocumentByName(doc.getName()); if (document.probability > bestProbability) { bestTopic = currentTopic; bestProbability = document.probability; } currentTopic++; } currentTopic = 0; for (Topic topic : topics) { if (currentTopic != bestTopic) { TopicMember toRemove = topic.getDocumentByName(doc.getName()); if (toRemove != null) { topic.documents.remove(toRemove); } } currentTopic++; } currentDoc++; } } /** * Limits documents to only being in a topic if the associated probability is above a threshold * * @param threshold Threshold required */ public void limitTopicsPerDocumentWithThreshold(double threshold) { if (topics == null) return; for (LDADocument doc : documents) { for (Topic topic : topics) { TopicMember document = topic.getDocumentByName(doc.getName()); if ((document != null) && (document.probability < threshold)) { topic.documents.remove(document); } } } } /** * Limits number of documents that can be associated with one topic to a specific number. * * @param cutoff Cuttoff point. */ public void limitTopicsPerDocumentWithCutoff(int cutoff) { if (topics == null) return; for (Topic topic : topics) { if (topic.documents.size() <= cutoff) continue; // Our work is done for us! No need to cut any thing off. // Otherwise, documents are already sorted so we just need to cut off the bottom size-cutoff documents int totalDocuments = topic.documents.size(); for (int i = cutoff; i < totalDocuments; i++) topic.documents.remove(cutoff); } } public String toString() { String str = ""; int num = 1; for (Topic topic : topics) { str += topic.getName() + ":\n"; str += "words:\n"; for (TopicMember word : topic.words) { str += "\t" + word.name + "\t" + word.probability + "\n"; } str += "\ndocs:\n"; for (TopicMember document: topic.documents) { str += "\t" + document.name + "\t" + document.probability + "\n"; } str += "\n"; num++; } return str; } // Job for generating topic map in public class GenerateTopicsJob extends Job { String[] args; int numberIterations; private String modelName; boolean doNotSchedule = false; public GenerateTopicsJob(String[] args, int numberIterations, String modelName) { super("Extracting Topics from "+modelName+ ""); this.args = args; this.modelName = modelName; this.setPriority(Job.LONG); this.setRule(new LDATopicUpdateRule()); if (modelName.equals("classes")) this.setUser(true); else this.setUser(false); this.numberIterations = numberIterations; // Only schedule one update at a time! if (updateInProgress) doNotSchedule = true; else updateInProgress = true; } @Override public boolean shouldSchedule() { return !doNotSchedule && super.shouldSchedule(); } public IStatus run(IProgressMonitor monitor) { monitor.beginTask("", numberIterations); monitor.subTask("Extracting words from "+modelName+"..."); // Get the documents we're analyzing documents = getDocuments(); // Make sure we have a .dat file for the project, createDatafile(); monitor.subTask("Extracting topics..."); PrintStream newOut = null; try { newOut = new ProgressStream(monitor, new File(getTopicDirectory()+getFullModelName()+".log")); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); return Status.CANCEL_STATUS; } PrintStream oldOut = System.out; System.setOut(newOut); // Do the work LDA.main(args); System.setOut(oldOut); // JGibbLDA always calls the model model-final, so we need to rename the files monitor.subTask("Moving LDA files."); File files[] = new File(getTopicDirectory()).listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { if (name.startsWith("model-final")) return true; else return false; }}); for (File file : files) { File destination = new File(file.getParent() + "/"+getFullModelName() + file.getName().split("model-final")[1]); destination.delete(); Boolean success = file.renameTo(destination); if (!success) System.out.println("LDA Topics ERROR: failed to rename "+file.toString()+ " to:"+file.getParent() + "/"+getModelName() + file.getName().split("model-final")[1]); } // TODO: remove files we don't care to read? // Save metadata about how the topic map was generated monitor.subTask("Saving LDA metadata."); saveMetadata(); updateInProgress = false; return Status.OK_STATUS; } // All writes to this print stream are copied to two print streams public class ProgressStream extends PrintStream { IProgressMonitor monitor; public ProgressStream(IProgressMonitor monitor, File logFile) throws FileNotFoundException { super(new FileOutputStream(logFile)); //super(out); this.monitor = monitor; } public void write(byte buf[], int off, int len) { try { super.write(buf, off, len); } catch (Exception e) { } // And indicate some progress for (byte b : buf) if (b == '\n') monitor.worked(1); } public void flush() { super.flush(); } } } // Job for loading the topic map into our data structures public class LoadTopicsJob extends Job { String[] args; private boolean doNotSchedule; public LoadTopicsJob(String modelName) { super("Loading topic map for "+ modelName); //this.args = args; this.setPriority(Job.LONG); this.setRule(new LDATopicUpdateRule()); // Only schedule one load at a time! if (loadInProgress) doNotSchedule = true; else loadInProgress = true; } @Override public boolean shouldSchedule() { return !doNotSchedule && super.shouldSchedule(); } public IStatus run(IProgressMonitor monitor) { monitor.beginTask("Loading topics...", monitor.UNKNOWN); // Load in the new topic information try { loadTopicMap(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } loadInProgress = false; return Status.OK_STATUS; } } public class ComputeDistanceJob extends Job { QueryTopicMap queryTopicMap; public ComputeDistanceJob(QueryTopicMap queryMap) { super("Computing Hellinger Distances..."); this.queryTopicMap = queryMap; setRule(new LDATopicUpdateRule()); } @Override protected IStatus run(IProgressMonitor monitor) { Double probabilities[] = queryTopicMap.getProbabilities(); boolean allSame = true; for (int i = 0; i < (probabilities.length-1); i++) if (!probabilities[i].equals(probabilities[i+1])) allSame = false; if (!probabilities[0].equals(probabilities[probabilities.length-1])) allSame = false; if (allSame) { // TODO, 2010: message box telling the user about this filterUsingQuery = false; LDATopics.twoDimensionalView.updateToolbar(); return Status.OK_STATUS; } // Now, compute Hellinger distances for each class and store them for (LDADocument doc : documents) { doc.hellingerDistance = hellingerDistance(probabilities, getProbabilities(doc)); } filter(true); return Status.OK_STATUS; } } }
true
6516fd821fc42d5a22c1115327cbeddc06cc3a92
Java
mwhitlock1219/Backend-Springboot_Capstone
/src/main/java/com/tts/stream/service/UserService.java
UTF-8
370
1.960938
2
[]
no_license
package com.tts.stream.service; import java.util.List; import com.tts.stream.model.Movie; import com.tts.stream.model.User; import org.springframework.stereotype.Service; @Service public class UserService { public void addMovieToWatchlist(User user, Movie movie) { // List<Movie> watchList = user.getWatchList(); // watchList.add(movie); } }
true
4f965720e3fe0faab5b6571550b1eba0853a6eb0
Java
7nights/smgpapi
/src/cn/com/zjtelecom/smgp/message/ActiveTestRespMessage.java
UTF-8
719
2.03125
2
[]
no_license
package cn.com.zjtelecom.smgp.message; import cn.com.zjtelecom.smgp.protocol.RequestId; import cn.com.zjtelecom.util.TypeConvert; public class ActiveTestRespMessage extends Message{ public ActiveTestRespMessage(){ int len = 12; this.buf = new byte[len]; TypeConvert.int2byte(len, this.buf, 0); TypeConvert.int2byte(RequestId.ActiveTest_Resp, this.buf, 4); } public ActiveTestRespMessage(int seq){ int len = 12; this.buf = new byte[len]; TypeConvert.int2byte(len, this.buf, 0); TypeConvert.int2byte(RequestId.ActiveTest_Resp, this.buf, 4);//requestID TypeConvert.int2byte(this.sequence_Id, this.buf, 8); // sequence_Id } }
true
21a1ec932a82e4b0709359112e3318bdd361949e
Java
roq-messaging/RoQ
/roq-clientlib/src/main/java/org/roqmessaging/clientlib/factory/IRoQConnectionFactory.java
UTF-8
1,721
2.3125
2
[ "Apache-2.0" ]
permissive
/** * Copyright 2012 EURANOVA * 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.roqmessaging.clientlib.factory; import org.roqmessaging.client.IRoQConnection; import org.roqmessaging.client.IRoQSubscriberConnection; /** * Interface IRoQConnectionFactory * <p> Description: factory that create the RoQConnection. * * @author sskhiri */ public interface IRoQConnectionFactory { /** * Instantiates a connection. Notice that the connection will need to connect to an active Exchange. At startup this * could take few seconds before beefing ready. * @param qn the name of the logical queue * @return a connection that can be used to send messages. */ public IRoQConnection createRoQConnection(String qName) throws IllegalStateException; /** * Instantiates a connection. Notice that the connection will need to connect to an active Exchange. At startup this * could take few seconds before being ready. * @param qName the queue logical name to bind * @param key the subscription key * @return a connection that can be used to receive messages. */ public IRoQSubscriberConnection createRoQSubscriberConnection(String qName, String key) throws IllegalStateException; }
true
b3bcd6ff00d976eb85bb35b48776366a34161ae5
Java
magefree/mage
/Mage.Sets/src/mage/cards/a/AwakenTheErstwhile.java
UTF-8
2,760
2.765625
3
[ "MIT" ]
permissive
package mage.cards.a; import mage.abilities.Ability; import mage.abilities.effects.OneShotEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Outcome; import mage.game.Game; import mage.game.permanent.token.ZombieToken; import mage.players.Player; import java.util.HashMap; import java.util.Map; import java.util.UUID; /** * @author JayDi85 */ public final class AwakenTheErstwhile extends CardImpl { public AwakenTheErstwhile(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{3}{B}{B}"); // Each player discards all the cards in their hand, then creates that many 2/2 black Zombie creature tokens. this.getSpellAbility().addEffect(new AwakenTheErstwhileEffect()); } private AwakenTheErstwhile(final AwakenTheErstwhile card) { super(card); } @Override public AwakenTheErstwhile copy() { return new AwakenTheErstwhile(this); } } class AwakenTheErstwhileEffect extends OneShotEffect { public AwakenTheErstwhileEffect() { super(Outcome.Detriment); this.staticText = "each player discards all the cards in their hand, then creates that many 2/2 black Zombie creature tokens"; } public AwakenTheErstwhileEffect(final AwakenTheErstwhileEffect effect) { super(effect); } @Override public AwakenTheErstwhileEffect copy() { return new AwakenTheErstwhileEffect(this); } @Override public boolean apply(Game game, Ability source) { Player controller = game.getPlayer(source.getControllerId()); if (controller != null) { // discard hands Map<UUID, Integer> cardsAmount = new HashMap<>(); for (UUID playerId : game.getState().getPlayersInRange(controller.getId(), game)) { Player player = game.getPlayer(playerId); if (player != null) { int cardsInHand = player.getHand().size(); if (cardsInHand > 0) { player.discard(cardsInHand, false, false, source, game); cardsAmount.put(playerId, cardsInHand); } } } // create tokens cardsAmount.entrySet().forEach(discardedHand -> { Player player = game.getPlayer(discardedHand.getKey()); int tokensCount = discardedHand.getValue(); if (player != null && tokensCount > 0) { new ZombieToken().putOntoBattlefield(tokensCount, game, source, player.getId()); } }); return true; } return false; } }
true
f5901a69fcf98b35bc14730dda5f81946695f0a8
Java
Noah981107/FootballMatching_API
/src/main/java/domain/Comment.java
UTF-8
1,934
2.28125
2
[]
no_license
package domain; import javax.validation.constraints.NotNull; public class Comment { @NotNull(groups = {ValidationGroups.commentModification.class, ValidationGroups.commentDeletion.class }, message = "댓글 번호는 비워둘 수 없습니다.") protected String id; protected String writer; @NotNull(groups = {ValidationGroups.commentRegistration.class, ValidationGroups.commentModification.class, ValidationGroups.commentDeletion.class}, message = "게시글 번호는 비워둘 수 없습니다.") protected String boardNumber; protected String postDate; protected String modifiedDate; @NotNull(groups = {ValidationGroups.commentRegistration.class, ValidationGroups.commentModification.class}, message = "내용은 비워둘 수 없습니다.") protected String content; protected Boolean is_deleted; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getWriter() { return writer; } public void setWriter(String writer) { this.writer = writer; } public String getBoardNumber() { return boardNumber; } public void setBoardNumber(String boardNumber) { this.boardNumber = boardNumber; } public String getPostDate() { return postDate; } public void setPostDate(String postDate) { this.postDate = postDate; } public String getModifiedDate() { return modifiedDate; } public void setModifiedDate(String modifiedDate) { this.modifiedDate = modifiedDate; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Boolean getIs_deleted() { return is_deleted; } public void setIs_deleted(Boolean is_deleted) { this.is_deleted = is_deleted; } }
true
49f5900db5c77862fa7e9ca2009b7dd21ae8f783
Java
bucsistvan/vehicle
/vehicle-frontend/src/main/java/hu/ulyssys/java/course/javaee/demo/mbean/PlaneCRUDMBean.java
UTF-8
986
2.0625
2
[]
no_license
package hu.ulyssys.java.course.javaee.demo.mbean; import hu.ulyssys.java.course.javaee.demo.vehicle.entity.Owner; import hu.ulyssys.java.course.javaee.demo.vehicle.entity.Plane; import hu.ulyssys.java.course.javaee.demo.vehicle.service.OwnerService; import hu.ulyssys.java.course.javaee.demo.vehicle.service.PlaneService; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.faces.view.ViewScoped; import javax.inject.Inject; import javax.inject.Named; import java.io.Serializable; import java.util.List; @Named @ViewScoped public class PlaneCRUDMBean extends OwnerAwareCRUDMBean<Plane> implements Serializable { @Inject public PlaneCRUDMBean(PlaneService planeService, OwnerService ownerService) { super(planeService, ownerService); } @Override protected String dialogName() { return "planeDialog"; } @Override protected Plane initNewEntity() { return new Plane(); } }
true
038fce9e718e3a45d16bb3bde040446451a35f43
Java
EricGerry/Code
/牛客/BullMarket.java
UTF-8
1,651
3.890625
4
[]
no_license
/** * @Author:Eric * @Date:2020/4/12 22:47 */ /* * 风口的猪-中国牛市 * * 风口之下,猪都能飞。当今中国股市牛市,真可谓“错过等七年”。 * 给你一个回顾历史的机会,已知一支股票连续n天的价格走势,以长度为n的整数数组表示,数组中第i个元素(prices[i])代表该股票第i天的股价。 * 假设你一开始没有股票,但有至多两次买入1股而后卖出1股的机会,并且买入前一定要先保证手上没有股票。 * 若两次交易机会都放弃,收益为0。 设计算法,计算你能获得的最大收益。 * 输入数值范围:2<=n<=100,0<=prices[i]<=100 * 示例1 * 输入 * 3,8,5,1,7,8 * 输出 * 12 * */ public class BullMarket { /** * 计算你能获得的最大收益 * * @param prices Prices[i]即第i天的股价 * @return 整型 */ public int calculateMax(int[] prices) { int sum = 0,temp; for(int i=0; i<prices.length; i++){ temp = getMax(prices,0,i) + getMax(prices,i,prices.length-1); if(temp > sum) { sum = temp; } } return sum; } // 求最大start到end之间的最大利润函数 public int getMax(int[] prices, int start, int end){ int max = 0; int min = prices[start]; for(int i=start+1; i<=end; i++){ if(prices[i] < min) { min = prices[i]; } if(prices[i]-min > max) { max = prices[i] - min; } } return max; } }
true
6640f9dde7493c5194ef873b7e85619e6881fb57
Java
inchara1990/TextEditor_JAVA
/Savelistener.java
UTF-8
2,654
3.0625
3
[]
no_license
/* * Author: Inchara Diwakar * Date: November 17th * Class: Savelistener * Description: This class implements Actionlistener interface and performs the file save operation */ import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.StringReader; import javax.swing.JFileChooser; public class Savelistener implements ActionListener { private TextEditor.Textreaderwindow text; Savelistener(TextEditor.Textreaderwindow text) { this.text = text; } /* method parameters */ File file = null; BufferedWriter fw = null; BufferedReader reader = null; JFileChooser filesaver = new JFileChooser(); int check = 0; int returnval = 999; public void actionPerformed(ActionEvent e) { /* setting default path */ /* filesaver.setCurrentDirectory(new File(TextEditor.DEFAULT_PATH)); */ filesaver.setDialogTitle("Save"); /* get file method to get the file to written onto */ get_file(); if (returnval == JFileChooser.APPROVE_OPTION) { file = filesaver.getSelectedFile(); text.filename = file.getName(); write_file(); } else if (returnval == 999) { write_file(); } else { return; } } int get_file() { /* * if the last file name is null, or it equals the current filename * label show save dialog */ if ((text.lastfileopened == null || text.lastfileopened.isEmpty()) || (text.file_name == text.lastfileopened)) { returnval = filesaver.showSaveDialog(null); } /* else treat the last file as the file to be edited */ else { file = new File(text.lastfilepath); check = 1; text.filename = text.lastfileopened; } return returnval; } void write_file() { /* get text from textarea */ String string = text.textarea.getText(); StringReader stringReader = new StringReader(string); try { /* append .txt if it is a new file */ if (text.filename.contains("txt")) { fw = new BufferedWriter(new FileWriter(file)); } else { fw = new BufferedWriter(new FileWriter(file + ".txt")); } /* read each line from textarea */ reader = new BufferedReader(stringReader); for (String line = reader.readLine(); line != null; line = reader.readLine()) { fw.write(line); fw.write("\n"); } /* close reader, writer and set labels */ reader.close(); fw.close(); /* set label accordingly */ text.label.setText( (text.filename.contains("txt") ? text.filename : text.filename + ".txt") + " succesfully saved"); } catch (IOException e1) { e1.printStackTrace(); } } }
true
f78777fdd2e982c2e5e1f12cfed842522df6df94
Java
TristanMauvieux/sgp-api
/src/main/java/dta/sgp/controller/CollaborateurController.java
UTF-8
3,110
2.28125
2
[]
no_license
package dta.sgp.controller; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import dta.sgp.entite.Banque; import dta.sgp.entite.Collaborateur; import dta.sgp.repository.CollaborateurRepository; import dta.sgp.repository.DepartementRepository; import dta.sgp.service.InitialisationDonneeService; @RestController @RequestMapping("/api/collaborateurs") public class CollaborateurController { private DepartementRepository depRepo; private CollaborateurRepository colRepo; private InitialisationDonneeService init; @Autowired public CollaborateurController(DepartementRepository depRepo, CollaborateurRepository colRepo, InitialisationDonneeService init) { super(); this.depRepo = depRepo; this.colRepo = colRepo; this.init = init; init.initialiser(); } @GetMapping public List<Collaborateur> allCollaborateur() { return colRepo.findAll(); } @GetMapping(params = { "departementId" }) public List<Collaborateur> colByDep(@RequestParam("departementId") int id) { return colRepo.findByDepartementId(id).get(); } @GetMapping(path = "/{matricule}") public Collaborateur oneCollaborateur(@PathVariable String matricule) { return colRepo.findByMatricule(matricule).get(); } @PutMapping(path = "/{matricule}") public ResponseEntity<String> modifierMatricule(@PathVariable String matricule, @RequestBody Collaborateur collab) { Optional<Collaborateur> col = colRepo.findByMatricule(matricule); ResponseEntity<String> rep; if (col.isPresent()) { rep = new ResponseEntity<>(HttpStatus.OK); collab.setMatricule(matricule); collab.setId(col.get().getId()); colRepo.save(collab); } else { rep = new ResponseEntity<>(HttpStatus.NO_CONTENT); } return rep; } @GetMapping(path = "/{matricule}/banque") public Banque oneBanque(@PathVariable String matricule) { Optional<Collaborateur> col = colRepo.findByMatricule(matricule); return col.get().getBanque(); } @PutMapping(path = "/{matricule}/banque") public ResponseEntity<String> modifierBanque(@PathVariable String matricule, @RequestBody Collaborateur collab) { Optional<Collaborateur> col = colRepo.findByMatricule(matricule); ResponseEntity<String> rep; if (col.isPresent()) { rep = new ResponseEntity<>(HttpStatus.OK); Banque nouvelle = col.get().getBanque(); collab.setId(col.get().getId()); collab.setMatricule(col.get().getMatricule()); collab.setBanque(nouvelle); colRepo.save(collab); } else { rep = new ResponseEntity<>(HttpStatus.NO_CONTENT); } return rep; } }
true
a50df64c28bd70b0936e7bcf7b01062985c3fafa
Java
kayresbug/onorder_admin_dnk
/app/src/main/java/com/daon/admin_onorder/ServiceDialog.java
UTF-8
3,766
2.1875
2
[]
no_license
package com.daon.admin_onorder; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import com.google.gson.JsonObject; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class ServiceDialog extends Dialog implements View.OnClickListener { private Button mPositiveButton; private Button mNegativeButton; private TextView service_body; private ServiceDialogListener _listener ; String body; String num; public ServiceDialog(@NonNull Context context, String body, String num) { super(context); this.body = body; this.num = num; } public interface ServiceDialogListener { public void onDismissListener(String s); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //다이얼로그 밖의 화면은 흐리게 만들어줌 WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(); layoutParams.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND; layoutParams.dimAmount = 0.8f; getWindow().setAttributes(layoutParams); setContentView(R.layout.service_dialog); service_body = findViewById(R.id.service_dialog_body); service_body.setText(body); mPositiveButton = findViewById(R.id.service_pbutton); mNegativeButton = findViewById(R.id.service_nbutton); mPositiveButton.setOnClickListener(this); mNegativeButton.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.service_pbutton: Log.d("daon", "pbutton"); Toast.makeText(getContext(), "확인", Toast.LENGTH_SHORT).show(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://15.164.232.164:5000/") .addConverterFactory(new NullOnEmptyConverterFactory()) .addConverterFactory(GsonConverterFactory.create()) .build(); InterfaceApi interfaceApi = retrofit.create(InterfaceApi.class); interfaceApi.updateService("krgg0002", num).enqueue(new Callback<JsonObject>() { @Override public void onResponse(Call<JsonObject> call, Response<JsonObject> response) { if (response.isSuccessful()) { Log.d("daon", String.valueOf(response.body().get("StatusCode"))); if (String.valueOf(response.body().get("StatusCode")).equals("\"200\"")){ _listener.onDismissListener("ok_dismiss"); } }else{ } } @Override public void onFailure(Call<JsonObject> call, Throwable t) { Log.d("daon", "fail = "+t.getMessage()); } }); break; case R.id.service_nbutton: Toast.makeText(getContext(), "취소", Toast.LENGTH_SHORT).show(); _listener.onDismissListener("dismiss"); break; } } public void setOnDismissListener(ServiceDialogListener listener ) { _listener = listener ; } }
true
5d5f74ed3509e1b42d4641101b0ca0a0cbee1410
Java
remotesyssupport/platformlayer
/services/service-jenkins/src/main/java/org/platformlayer/service/jenkins/ops/HudsonScrambler.java
UTF-8
532
2.40625
2
[]
no_license
package org.platformlayer.service.jenkins.ops; import org.platformlayer.crypto.CryptoUtils; /** * Supports password obfuscation in the way that Hudson does it */ public class HudsonScrambler { public static String scramble(String secret) { if (secret == null) { return null; } return CryptoUtils.toBase64(CryptoUtils.toBytesUtf8(secret)); } public static String descramble(String scrambled) { if (scrambled == null) { return null; } return CryptoUtils.toStringUtf8(CryptoUtils.fromBase64(scrambled)); } }
true
f1a8357a275da77d578d398df3a54d43cb0bb190
Java
thecheesynachos/zork_game
/src/main/java/muic/ooc/zork/character/monsters/BossMonster.java
UTF-8
1,380
3.140625
3
[]
no_license
package muic.ooc.zork.character.monsters; import muic.ooc.zork.character.Character; import muic.ooc.zork.gameplay.AttackObject; import muic.ooc.zork.gameplay.Observation; public class BossMonster extends Monster { private static final int BOSS_MAX_HEALTH = 40; private static final int BOSS_MAX_ATTACK = 9; private static final double BOSS_STUN_PROB = 0.15; private static final int BOSS_CRITICAL_LEVEL = 10; private static final int BOSS_STUN_TURNS = 1; public BossMonster(){ super(); this.potionAvailable = 1; } public Observation doTurn(Character c) { if(stunTurnLeft > 0){ stunTurnLeft -= 1; return new Observation("Monster cannot attack because it is stunned!"); } else { Observation ob; if(health <= BOSS_CRITICAL_LEVEL && potionAvailable > 0){ usePotion(); return new Observation("Monster uses potion to restore its health."); } else if (rand.nextDouble() < BOSS_STUN_PROB){ ob = new Observation("Monster stuns you! Your attacks will be useless in the next turn!"); AttackObject ao = new AttackObject.Builder().stunTurn(BOSS_STUN_TURNS).build(); c.getAttacked(ao, ob); return ob; } else { ob = new Observation("Big boi attacks."); basicAttack(c, ob); return ob; } } } public int getMaxHealth() { return BOSS_MAX_HEALTH; } protected int getMaxAttack() { return BOSS_MAX_ATTACK; } }
true
10a4015d14d9532304d95cbd8c355ff113394040
Java
ashwani29/Sensors
/src/main/java/com/example/coding/sensor/MainActivity.java
UTF-8
3,019
2.28125
2
[]
no_license
package com.example.coding.sensor; import android.content.Context; import android.content.DialogInterface; import android.graphics.Color; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.support.constraint.ConstraintLayout; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import java.util.List; import static java.lang.Math.abs; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final ConstraintLayout constraintLayout= (ConstraintLayout) findViewById(R.id.constraint); final SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); List<Sensor> sensor = sensorManager.getSensorList(Sensor.TYPE_ALL); for(Sensor s : sensor){ Log.e("TAG", s.getName()); } final SensorEventListener sensorEventListener = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent event) { float [] arr= event.values; int x,y,z; x= (int) (abs(arr[0]/9.8)*255); y= (int) (abs(arr[1]/9.8)*255); z= (int) (abs(arr[2]/9.8)*255); constraintLayout.setBackgroundColor(Color.rgb(x,y,z)); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }; final Sensor acc = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); Button button = (Button) findViewById(R.id.b); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).setTitle("Do u want to register listener") .setMessage("Please Select").setPositiveButton("YES", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { sensorManager.registerListener(sensorEventListener, acc, SensorManager.SENSOR_DELAY_NORMAL); } }).setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).setCancelable(false) .create(); alertDialog.show(); } }); } }
true
6d101de4d63abe53b5ef09b6759ca623be1a7d29
Java
vhavryk/videostore
/src/main/java/com/test/domain/MovieTypePrice.java
UTF-8
2,834
2.4375
2
[]
no_license
package com.test.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import javax.persistence.*; import java.io.Serializable; /** * A MovieTypePrice. */ @Entity @Table(name = "movie_type_price") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class MovieTypePrice implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "days") private Integer days; @Column(name = "next_days") private Integer nextDays; @ManyToOne @JsonIgnoreProperties(value = "movieTypePrices", allowSetters = true) private MovieType movieType; @ManyToOne @JsonIgnoreProperties(value = "moviewTypePrices", allowSetters = true) private Price price; private Integer bonus; // jhipster-needle-entity-add-field - JHipster will add fields here public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Integer getDays() { return days; } public MovieTypePrice days(Integer days) { this.days = days; return this; } public void setDays(Integer days) { this.days = days; } public Integer getNextDays() { return nextDays; } public MovieTypePrice nextDays(Integer nextDays) { this.nextDays = nextDays; return this; } public void setNextDays(Integer nextDays) { this.nextDays = nextDays; } public MovieType getMovieType() { return movieType; } public MovieTypePrice movieType(MovieType movieType) { this.movieType = movieType; return this; } public void setMovieType(MovieType movieType) { this.movieType = movieType; } public Price getPrice() { return price; } public MovieTypePrice price(Price price) { this.price = price; return this; } public void setPrice(Price price) { this.price = price; } // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof MovieTypePrice)) { return false; } return id != null && id.equals(((MovieTypePrice) o).id); } @Override public int hashCode() { return 31; } // prettier-ignore @Override public String toString() { return "MovieTypePrice{" + "id=" + getId() + ", days=" + getDays() + ", nextDays=" + getNextDays() + "}"; } }
true
553e73ac20bfe50e559c53d12d8a16cf0afaf3b0
Java
Abrahamlong/MyBatis-Study
/mybatis-07/src/main/java/com/longg/mapper/StudentMapper.java
UTF-8
482
2.171875
2
[]
no_license
package com.longg.mapper; import com.longg.pojo.Student; import java.util.List; /** * @author long * @date 2020/9/25 */ public interface StudentMapper { /** * 查询所有学生的信息,以及对于老师的信息 方式一:按照查询嵌套处理 */ public List<Student> getStudent1(); /** * 查询所有学生的信息,以及对于老师的信息 方式二:按照结果嵌套处理 */ public List<Student> getStudent2(); }
true
e80a947f7b67f737cc097fcc140c38c4562c44c7
Java
mP1/walkingkooka-tree-json
/src/main/java/walkingkooka/tree/json/marshall/JsonNodeMarshallContexts.java
UTF-8
1,349
2
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2019 Miroslav Pokorny (github.com/mP1) * * 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 walkingkooka.tree.json.marshall; import walkingkooka.reflect.PublicStaticHelper; /** * Collection of static factory methods for numerous {@link JsonNodeMarshallContext}. */ public final class JsonNodeMarshallContexts implements PublicStaticHelper { /** * {@see BasicJsonNodeMarshallContext} */ public static JsonNodeMarshallContext basic() { return BasicJsonNodeMarshallContext.INSTANCE; } /** * {@see FakeJsonNodeMarshallContext} */ public static JsonNodeMarshallContext fake() { return new FakeJsonNodeMarshallContext(); } /** * Stops creation */ private JsonNodeMarshallContexts() { throw new UnsupportedOperationException(); } }
true
92f4c0571a2e932f476012f125beb39bbda7ce2d
Java
rprasathg/cdgen
/src/org/eclipse/app4mc/cdgen/utils/fileUtil.java
UTF-8
9,461
1.859375
2
[]
no_license
/******************************************************************************* * Copyright (c) 2019 Dortmund University of Applied Sciences and Arts and others. * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Dortmund University of Applied Sciences and Arts - initial API and implementation *******************************************************************************/ package org.eclipse.app4mc.cdgen.utils; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.stream.Collectors; import org.eclipse.app4mc.amalthea.model.Amalthea; import org.eclipse.app4mc.amalthea.model.Label; import org.eclipse.app4mc.amalthea.model.PeriodicStimulus; import org.eclipse.app4mc.amalthea.model.ProcessingUnit; import org.eclipse.app4mc.amalthea.model.Stimulus; import org.eclipse.app4mc.amalthea.model.Task; import org.eclipse.app4mc.amalthea.model.Time; import org.eclipse.app4mc.amalthea.model.util.SoftwareUtil; import org.eclipse.app4mc.cdgen.LabelFileCreation; /** * Implementation of Common API for CDGen. * */ public class fileUtil { @SuppressWarnings({ "null", "resource" }) public static void fileMainHeader(final File f) throws IOException { FileWriter fr = null; try { fr = new FileWriter(f); fr.write("/******************************************************************\n"); fr.write("******************************************************************\n"); fr.write("**************#####**####*****#####**######*###****##*************\n"); fr.write("*************##******#***##**##******##*****##*#***##*************\n"); fr.write("*************#*******#****#**#****##*######*##**#**##*************\n"); fr.write("*************##******#***##**##***##*##*****##***#*##*************\n"); fr.write("**************#####**####*****######*######*##****###*************\n"); fr.write("******************************************************************\n"); fr.write("******************************************************************\n"); fr.write("*Author : Ram Prasath Govindarajan\n"); fr.write("*Tool : CDGen_GSoC\n"); fr.write("*Version : V1.0.0\n"); } catch (final IOException e) { e.printStackTrace(); } fr.close(); } public static void FreeRTOSConfigFileHeader(final File f1) { try { final File fn = f1; @SuppressWarnings("resource") final FileWriter fw = new FileWriter(fn, true); fw.write("*Title : FreeRTOSConfig\n"); fw.write("*Description : Holds configuration for the FreeRTOS Software\n"); fw.write("******************************************************************\n"); fw.write("******************************************************************/\n\n\n"); fw.close(); } catch (final IOException ioe) { System.err.println("IOException: " + ioe.getMessage()); } } public static String getFileExtension(final File file) { final String fileName = file.getName(); String fileExtension = null; if (fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0) { fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1); // return fileName.substring(fileName.lastIndexOf(".") + 1); } return fileExtension; } public static String datatype(final String string) { String type = null; switch (string) { case "8 bit": type = "uint8_t"; break; case "16 bit": type = "uint16_t"; break; case "32 bit": type = "uint32_t"; break; case "64 bit": type = "uint64_t"; break; default: type = "int"; break; } return type; } public static String datatypeSize(final String string) { String type = null; switch (string) { case "8 bit": type = "8"; break; case "16 bit": type = "16"; break; case "32 bit": type = "32"; break; case "64 bit": type = "64"; break; default: type = "00"; break; } return type; } /** * Shared Label definition and initialization structure. * * @param tasks * * @param file * @param labellist * @return */ public static List<Label> CoreSpecificLabel(final Amalthea model, final List<Task> tasks) { List<Label> SharedLabelList = new ArrayList<Label>(); for (final Task ta : tasks) { SharedLabelList.addAll(SoftwareUtil.getReadLabelSet(ta, null)); } SharedLabelList = SharedLabelList.stream().distinct().collect(Collectors.toList()); final List<Label> SharedLabelListSortCore = new ArrayList<Label>(); if (SharedLabelList.size() == 0) { System.out.println("Shared Label size 0"); } else { // System.out.println("Shared Label size "+SharedLabelList.size()); final HashMap<Label, HashMap<Task, ProcessingUnit>> sharedLabelTaskMap = LabelFileCreation .LabelTaskMap(model, SharedLabelList); for (final Label share : SharedLabelList) { final HashMap<Task, ProcessingUnit> TaskMap = sharedLabelTaskMap.get(share); final Set<Task> taskList = TaskMap.keySet(); final Collection<ProcessingUnit> puList = TaskMap.values(); final List<ProcessingUnit> puListUnique = puList.stream().distinct().collect(Collectors.toList()); if (puListUnique.size() == 1 && taskList.size() > 1) { SharedLabelListSortCore.add(share); } } } return SharedLabelListSortCore; } /** * Shared Label definition and initialization structure. * * @param tasks * * @param file * @param labellist * @return */ // public static List<Label> SharedLabelDeclarationHead(Amalthea model, // List<Task> tasks) { public static List<Label> SharedLabelDeclarationHead(final Amalthea model, final List<Task> tasks) { final List<Label> SharedLabelList = LabelFileCreation.SharedLabelFinder(model); final List<Label> SharedLabelListSortCore = new ArrayList<Label>(); final List<Label> SharedLabel = new ArrayList<Label>(); if (SharedLabelList.size() == 0) { // System.out.println("Shared Label size 0"); } else { // System.out.println("Shared Label size "+SharedLabelList.size()); final HashMap<Label, HashMap<Task, ProcessingUnit>> sharedLabelTaskMap = LabelFileCreation .LabelTaskMap(model, SharedLabelList); for (final Label share : SharedLabelList) { final HashMap<Task, ProcessingUnit> TaskMap = sharedLabelTaskMap.get(share); final Collection<ProcessingUnit> puList = TaskMap.values(); final List<ProcessingUnit> puListUnique = puList.stream().distinct().collect(Collectors.toList()); if (puListUnique.size() > 1) { SharedLabelListSortCore.add(share); } } } final HashMap<Label, String> SharedLabelTypeMap = new HashMap<Label, String>(); for (final Label share : SharedLabelListSortCore) { SharedLabelTypeMap.put(share, share.getSize().toString()); } final List<String> SharedTypeMapList = new ArrayList<>( SharedLabelTypeMap.values().stream().distinct().collect(Collectors.toList())); final List<Label> SharedLabelMapList = new ArrayList<Label>(SharedLabelTypeMap.keySet()); for (int k = 0; k < SharedTypeMapList.size(); k++) { final String sh = SharedTypeMapList.get(k); for (final Label s : SharedLabelMapList) { final String ShTy = SharedLabelTypeMap.get(s); if (sh.equals(ShTy)) { SharedLabel.add(s); } } } return SharedLabel; } public static long intialisation(final String string) { long init = 0; switch (string) { case "8 bit": init = 255; break; case "16 bit": init = 65535; break; // case "32 bit": init =4294967295; break; // case "64 bit": init =18446744073709551615; break; default: init = 0000; break; } return init; } public static void defineMain(final File f1) { try { final File fn = f1; @SuppressWarnings("resource") final FileWriter fw = new FileWriter(fn, true); // the true will // append the new // data fw.write("#define DELAY_MULT 100"); fw.write("\n"); fw.close(); } catch (final IOException ioe) { System.err.println("IOException: " + ioe.getMessage()); } } public static Time getRecurrence(final Task t) { final List<Stimulus> lStimuli = t.getStimuli(); for (final Stimulus s : lStimuli) { if (s instanceof PeriodicStimulus) { return ((PeriodicStimulus) s).getRecurrence(); } System.out.println("ERR: Unsupported Stimulus in Task " + t + " -> " + s); } return null; } // This code is form stackoverflow https://stackoverflow.com/a/2581754 public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(final Map<K, V> map) { final List<Entry<K, V>> list = new ArrayList<>(map.entrySet()); list.sort(Entry.comparingByValue()); final Map<K, V> result = new LinkedHashMap<>(); for (final Entry<K, V> entry : list) { result.put(entry.getKey(), entry.getValue()); } return result; } }
true
4c919c5786b20cfede97887934b96f5418fa936f
Java
smartictcoop/SmartDental
/src/main/java/com/smict/all/model/PatFileModel.java
UTF-8
379
2.125
2
[ "Unlicense" ]
permissive
package com.smict.all.model; import com.smict.person.model.BranchModel; public class PatFileModel extends BranchModel { String patHn, fileId; public String getPatHn() { return patHn; } public void setPatHn(String patHn) { this.patHn = patHn; } public String getFileId() { return fileId; } public void setFileId(String fileId) { this.fileId = fileId; } }
true
d0b962779387012039c811ac14b905f03e6e4d01
Java
sergeibux/bankonetAdvanced
/src/main/java/com/CESI/accessingdatamysql/Entity/CompteEpargne.java
UTF-8
1,004
2.3125
2
[]
no_license
package main.java.com.CESI.accessingdatamysql.Entity; import main.java.com.CESI.accessingdatamysql.Entity.Compte; import main.java.com.CESI.accessingdatamysql.Repository.ClientRepository; import main.java.com.CESI.accessingdatamysql.Repository.CompteCourantRepository; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import java.util.Optional; @Entity // This tells Hibernate to make a table out of this class public class CompteEpargne extends Compte { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer IdComteEpargne; public double getTauxInteret() { return tauxInteret; } public void setTauxInteret(double tauxInteret) { this.tauxInteret = tauxInteret; } private double tauxInteret; public Integer getId() { return IdComteEpargne; } public void setId(Integer id) { this.IdComteEpargne = id; } }
true
91da316bda75a17b145415056ef90b6976cf2b10
Java
nguyentrungngoc1997/Cong2So
/src/test/java/MyBigNumberTest.java
UTF-8
277
2.75
3
[]
no_license
package myjava.mybignumber; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; class MyBigNumberTest { @Test void testSum() { MyBigNumber myClass = new MyBigNumber(); String sum = myClass.sum("1", "2"); assertEquals("3", sum); } }
true
07cbc78a6a670517af30f2d4b0cc033c99367aaa
Java
Rovanion/AinORM
/main/java/gov/polisen/orm/examples/CaseExample.java
UTF-8
38,954
2.140625
2
[]
no_license
package gov.polisen.orm.examples; import java.util.ArrayList; import java.util.Date; import java.util.List; public class CaseExample { /** * This field was generated by MyBatis Generator. * This field corresponds to the database table cases * * @mbggenerated Fri Apr 25 17:12:46 CEST 2014 */ protected String orderByClause; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table cases * * @mbggenerated Fri Apr 25 17:12:46 CEST 2014 */ protected boolean distinct; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table cases * * @mbggenerated Fri Apr 25 17:12:46 CEST 2014 */ protected List<Criteria> oredCriteria; /** * This method was generated by MyBatis Generator. * This method corresponds to the database table cases * * @mbggenerated Fri Apr 25 17:12:46 CEST 2014 */ public CaseExample() { oredCriteria = new ArrayList<Criteria>(); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table cases * * @mbggenerated Fri Apr 25 17:12:46 CEST 2014 */ public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table cases * * @mbggenerated Fri Apr 25 17:12:46 CEST 2014 */ public String getOrderByClause() { return orderByClause; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table cases * * @mbggenerated Fri Apr 25 17:12:46 CEST 2014 */ public void setDistinct(boolean distinct) { this.distinct = distinct; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table cases * * @mbggenerated Fri Apr 25 17:12:46 CEST 2014 */ public boolean isDistinct() { return distinct; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table cases * * @mbggenerated Fri Apr 25 17:12:46 CEST 2014 */ public List<Criteria> getOredCriteria() { return oredCriteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table cases * * @mbggenerated Fri Apr 25 17:12:46 CEST 2014 */ public void or(Criteria criteria) { oredCriteria.add(criteria); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table cases * * @mbggenerated Fri Apr 25 17:12:46 CEST 2014 */ public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table cases * * @mbggenerated Fri Apr 25 17:12:46 CEST 2014 */ public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table cases * * @mbggenerated Fri Apr 25 17:12:46 CEST 2014 */ protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table cases * * @mbggenerated Fri Apr 25 17:12:46 CEST 2014 */ public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table cases * * @mbggenerated Fri Apr 25 17:12:46 CEST 2014 */ protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andDeviceIdIsNull() { addCriterion("device_id is null"); return (Criteria) this; } public Criteria andDeviceIdIsNotNull() { addCriterion("device_id is not null"); return (Criteria) this; } public Criteria andDeviceIdEqualTo(Integer value) { addCriterion("device_id =", value, "deviceId"); return (Criteria) this; } public Criteria andDeviceIdNotEqualTo(Integer value) { addCriterion("device_id <>", value, "deviceId"); return (Criteria) this; } public Criteria andDeviceIdGreaterThan(Integer value) { addCriterion("device_id >", value, "deviceId"); return (Criteria) this; } public Criteria andDeviceIdGreaterThanOrEqualTo(Integer value) { addCriterion("device_id >=", value, "deviceId"); return (Criteria) this; } public Criteria andDeviceIdLessThan(Integer value) { addCriterion("device_id <", value, "deviceId"); return (Criteria) this; } public Criteria andDeviceIdLessThanOrEqualTo(Integer value) { addCriterion("device_id <=", value, "deviceId"); return (Criteria) this; } public Criteria andDeviceIdIn(List<Integer> values) { addCriterion("device_id in", values, "deviceId"); return (Criteria) this; } public Criteria andDeviceIdNotIn(List<Integer> values) { addCriterion("device_id not in", values, "deviceId"); return (Criteria) this; } public Criteria andDeviceIdBetween(Integer value1, Integer value2) { addCriterion("device_id between", value1, value2, "deviceId"); return (Criteria) this; } public Criteria andDeviceIdNotBetween(Integer value1, Integer value2) { addCriterion("device_id not between", value1, value2, "deviceId"); return (Criteria) this; } public Criteria andCaseIdIsNull() { addCriterion("case_id is null"); return (Criteria) this; } public Criteria andCaseIdIsNotNull() { addCriterion("case_id is not null"); return (Criteria) this; } public Criteria andCaseIdEqualTo(Integer value) { addCriterion("case_id =", value, "caseId"); return (Criteria) this; } public Criteria andCaseIdNotEqualTo(Integer value) { addCriterion("case_id <>", value, "caseId"); return (Criteria) this; } public Criteria andCaseIdGreaterThan(Integer value) { addCriterion("case_id >", value, "caseId"); return (Criteria) this; } public Criteria andCaseIdGreaterThanOrEqualTo(Integer value) { addCriterion("case_id >=", value, "caseId"); return (Criteria) this; } public Criteria andCaseIdLessThan(Integer value) { addCriterion("case_id <", value, "caseId"); return (Criteria) this; } public Criteria andCaseIdLessThanOrEqualTo(Integer value) { addCriterion("case_id <=", value, "caseId"); return (Criteria) this; } public Criteria andCaseIdIn(List<Integer> values) { addCriterion("case_id in", values, "caseId"); return (Criteria) this; } public Criteria andCaseIdNotIn(List<Integer> values) { addCriterion("case_id not in", values, "caseId"); return (Criteria) this; } public Criteria andCaseIdBetween(Integer value1, Integer value2) { addCriterion("case_id between", value1, value2, "caseId"); return (Criteria) this; } public Criteria andCaseIdNotBetween(Integer value1, Integer value2) { addCriterion("case_id not between", value1, value2, "caseId"); return (Criteria) this; } public Criteria andAuthorIsNull() { addCriterion("author is null"); return (Criteria) this; } public Criteria andAuthorIsNotNull() { addCriterion("author is not null"); return (Criteria) this; } public Criteria andAuthorEqualTo(Integer value) { addCriterion("author =", value, "author"); return (Criteria) this; } public Criteria andAuthorNotEqualTo(Integer value) { addCriterion("author <>", value, "author"); return (Criteria) this; } public Criteria andAuthorGreaterThan(Integer value) { addCriterion("author >", value, "author"); return (Criteria) this; } public Criteria andAuthorGreaterThanOrEqualTo(Integer value) { addCriterion("author >=", value, "author"); return (Criteria) this; } public Criteria andAuthorLessThan(Integer value) { addCriterion("author <", value, "author"); return (Criteria) this; } public Criteria andAuthorLessThanOrEqualTo(Integer value) { addCriterion("author <=", value, "author"); return (Criteria) this; } public Criteria andAuthorIn(List<Integer> values) { addCriterion("author in", values, "author"); return (Criteria) this; } public Criteria andAuthorNotIn(List<Integer> values) { addCriterion("author not in", values, "author"); return (Criteria) this; } public Criteria andAuthorBetween(Integer value1, Integer value2) { addCriterion("author between", value1, value2, "author"); return (Criteria) this; } public Criteria andAuthorNotBetween(Integer value1, Integer value2) { addCriterion("author not between", value1, value2, "author"); return (Criteria) this; } public Criteria andModificationTimeIsNull() { addCriterion("modification_time is null"); return (Criteria) this; } public Criteria andModificationTimeIsNotNull() { addCriterion("modification_time is not null"); return (Criteria) this; } public Criteria andModificationTimeEqualTo(Date value) { addCriterion("modification_time =", value, "modificationTime"); return (Criteria) this; } public Criteria andModificationTimeNotEqualTo(Date value) { addCriterion("modification_time <>", value, "modificationTime"); return (Criteria) this; } public Criteria andModificationTimeGreaterThan(Date value) { addCriterion("modification_time >", value, "modificationTime"); return (Criteria) this; } public Criteria andModificationTimeGreaterThanOrEqualTo(Date value) { addCriterion("modification_time >=", value, "modificationTime"); return (Criteria) this; } public Criteria andModificationTimeLessThan(Date value) { addCriterion("modification_time <", value, "modificationTime"); return (Criteria) this; } public Criteria andModificationTimeLessThanOrEqualTo(Date value) { addCriterion("modification_time <=", value, "modificationTime"); return (Criteria) this; } public Criteria andModificationTimeIn(List<Date> values) { addCriterion("modification_time in", values, "modificationTime"); return (Criteria) this; } public Criteria andModificationTimeNotIn(List<Date> values) { addCriterion("modification_time not in", values, "modificationTime"); return (Criteria) this; } public Criteria andModificationTimeBetween(Date value1, Date value2) { addCriterion("modification_time between", value1, value2, "modificationTime"); return (Criteria) this; } public Criteria andModificationTimeNotBetween(Date value1, Date value2) { addCriterion("modification_time not between", value1, value2, "modificationTime"); return (Criteria) this; } public Criteria andFirstRevisionCaseIdIsNull() { addCriterion("first_revision_case_id is null"); return (Criteria) this; } public Criteria andFirstRevisionCaseIdIsNotNull() { addCriterion("first_revision_case_id is not null"); return (Criteria) this; } public Criteria andFirstRevisionCaseIdEqualTo(Integer value) { addCriterion("first_revision_case_id =", value, "firstRevisionCaseId"); return (Criteria) this; } public Criteria andFirstRevisionCaseIdNotEqualTo(Integer value) { addCriterion("first_revision_case_id <>", value, "firstRevisionCaseId"); return (Criteria) this; } public Criteria andFirstRevisionCaseIdGreaterThan(Integer value) { addCriterion("first_revision_case_id >", value, "firstRevisionCaseId"); return (Criteria) this; } public Criteria andFirstRevisionCaseIdGreaterThanOrEqualTo(Integer value) { addCriterion("first_revision_case_id >=", value, "firstRevisionCaseId"); return (Criteria) this; } public Criteria andFirstRevisionCaseIdLessThan(Integer value) { addCriterion("first_revision_case_id <", value, "firstRevisionCaseId"); return (Criteria) this; } public Criteria andFirstRevisionCaseIdLessThanOrEqualTo(Integer value) { addCriterion("first_revision_case_id <=", value, "firstRevisionCaseId"); return (Criteria) this; } public Criteria andFirstRevisionCaseIdIn(List<Integer> values) { addCriterion("first_revision_case_id in", values, "firstRevisionCaseId"); return (Criteria) this; } public Criteria andFirstRevisionCaseIdNotIn(List<Integer> values) { addCriterion("first_revision_case_id not in", values, "firstRevisionCaseId"); return (Criteria) this; } public Criteria andFirstRevisionCaseIdBetween(Integer value1, Integer value2) { addCriterion("first_revision_case_id between", value1, value2, "firstRevisionCaseId"); return (Criteria) this; } public Criteria andFirstRevisionCaseIdNotBetween(Integer value1, Integer value2) { addCriterion("first_revision_case_id not between", value1, value2, "firstRevisionCaseId"); return (Criteria) this; } public Criteria andFirstRevisionDeviceIdIsNull() { addCriterion("first_revision_device_id is null"); return (Criteria) this; } public Criteria andFirstRevisionDeviceIdIsNotNull() { addCriterion("first_revision_device_id is not null"); return (Criteria) this; } public Criteria andFirstRevisionDeviceIdEqualTo(Integer value) { addCriterion("first_revision_device_id =", value, "firstRevisionDeviceId"); return (Criteria) this; } public Criteria andFirstRevisionDeviceIdNotEqualTo(Integer value) { addCriterion("first_revision_device_id <>", value, "firstRevisionDeviceId"); return (Criteria) this; } public Criteria andFirstRevisionDeviceIdGreaterThan(Integer value) { addCriterion("first_revision_device_id >", value, "firstRevisionDeviceId"); return (Criteria) this; } public Criteria andFirstRevisionDeviceIdGreaterThanOrEqualTo(Integer value) { addCriterion("first_revision_device_id >=", value, "firstRevisionDeviceId"); return (Criteria) this; } public Criteria andFirstRevisionDeviceIdLessThan(Integer value) { addCriterion("first_revision_device_id <", value, "firstRevisionDeviceId"); return (Criteria) this; } public Criteria andFirstRevisionDeviceIdLessThanOrEqualTo(Integer value) { addCriterion("first_revision_device_id <=", value, "firstRevisionDeviceId"); return (Criteria) this; } public Criteria andFirstRevisionDeviceIdIn(List<Integer> values) { addCriterion("first_revision_device_id in", values, "firstRevisionDeviceId"); return (Criteria) this; } public Criteria andFirstRevisionDeviceIdNotIn(List<Integer> values) { addCriterion("first_revision_device_id not in", values, "firstRevisionDeviceId"); return (Criteria) this; } public Criteria andFirstRevisionDeviceIdBetween(Integer value1, Integer value2) { addCriterion("first_revision_device_id between", value1, value2, "firstRevisionDeviceId"); return (Criteria) this; } public Criteria andFirstRevisionDeviceIdNotBetween(Integer value1, Integer value2) { addCriterion("first_revision_device_id not between", value1, value2, "firstRevisionDeviceId"); return (Criteria) this; } public Criteria andDeletionTimeIsNull() { addCriterion("deletion_time is null"); return (Criteria) this; } public Criteria andDeletionTimeIsNotNull() { addCriterion("deletion_time is not null"); return (Criteria) this; } public Criteria andDeletionTimeEqualTo(Date value) { addCriterion("deletion_time =", value, "deletionTime"); return (Criteria) this; } public Criteria andDeletionTimeNotEqualTo(Date value) { addCriterion("deletion_time <>", value, "deletionTime"); return (Criteria) this; } public Criteria andDeletionTimeGreaterThan(Date value) { addCriterion("deletion_time >", value, "deletionTime"); return (Criteria) this; } public Criteria andDeletionTimeGreaterThanOrEqualTo(Date value) { addCriterion("deletion_time >=", value, "deletionTime"); return (Criteria) this; } public Criteria andDeletionTimeLessThan(Date value) { addCriterion("deletion_time <", value, "deletionTime"); return (Criteria) this; } public Criteria andDeletionTimeLessThanOrEqualTo(Date value) { addCriterion("deletion_time <=", value, "deletionTime"); return (Criteria) this; } public Criteria andDeletionTimeIn(List<Date> values) { addCriterion("deletion_time in", values, "deletionTime"); return (Criteria) this; } public Criteria andDeletionTimeNotIn(List<Date> values) { addCriterion("deletion_time not in", values, "deletionTime"); return (Criteria) this; } public Criteria andDeletionTimeBetween(Date value1, Date value2) { addCriterion("deletion_time between", value1, value2, "deletionTime"); return (Criteria) this; } public Criteria andDeletionTimeNotBetween(Date value1, Date value2) { addCriterion("deletion_time not between", value1, value2, "deletionTime"); return (Criteria) this; } public Criteria andClassificationIsNull() { addCriterion("classification is null"); return (Criteria) this; } public Criteria andClassificationIsNotNull() { addCriterion("classification is not null"); return (Criteria) this; } public Criteria andClassificationEqualTo(Short value) { addCriterion("classification =", value, "classification"); return (Criteria) this; } public Criteria andClassificationNotEqualTo(Short value) { addCriterion("classification <>", value, "classification"); return (Criteria) this; } public Criteria andClassificationGreaterThan(Short value) { addCriterion("classification >", value, "classification"); return (Criteria) this; } public Criteria andClassificationGreaterThanOrEqualTo(Short value) { addCriterion("classification >=", value, "classification"); return (Criteria) this; } public Criteria andClassificationLessThan(Short value) { addCriterion("classification <", value, "classification"); return (Criteria) this; } public Criteria andClassificationLessThanOrEqualTo(Short value) { addCriterion("classification <=", value, "classification"); return (Criteria) this; } public Criteria andClassificationIn(List<Short> values) { addCriterion("classification in", values, "classification"); return (Criteria) this; } public Criteria andClassificationNotIn(List<Short> values) { addCriterion("classification not in", values, "classification"); return (Criteria) this; } public Criteria andClassificationBetween(Short value1, Short value2) { addCriterion("classification between", value1, value2, "classification"); return (Criteria) this; } public Criteria andClassificationNotBetween(Short value1, Short value2) { addCriterion("classification not between", value1, value2, "classification"); return (Criteria) this; } public Criteria andStatusIsNull() { addCriterion("status is null"); return (Criteria) this; } public Criteria andStatusIsNotNull() { addCriterion("status is not null"); return (Criteria) this; } public Criteria andStatusEqualTo(Short value) { addCriterion("status =", value, "status"); return (Criteria) this; } public Criteria andStatusNotEqualTo(Short value) { addCriterion("status <>", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThan(Short value) { addCriterion("status >", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThanOrEqualTo(Short value) { addCriterion("status >=", value, "status"); return (Criteria) this; } public Criteria andStatusLessThan(Short value) { addCriterion("status <", value, "status"); return (Criteria) this; } public Criteria andStatusLessThanOrEqualTo(Short value) { addCriterion("status <=", value, "status"); return (Criteria) this; } public Criteria andStatusIn(List<Short> values) { addCriterion("status in", values, "status"); return (Criteria) this; } public Criteria andStatusNotIn(List<Short> values) { addCriterion("status not in", values, "status"); return (Criteria) this; } public Criteria andStatusBetween(Short value1, Short value2) { addCriterion("status between", value1, value2, "status"); return (Criteria) this; } public Criteria andStatusNotBetween(Short value1, Short value2) { addCriterion("status not between", value1, value2, "status"); return (Criteria) this; } public Criteria andPriorityIsNull() { addCriterion("priority is null"); return (Criteria) this; } public Criteria andPriorityIsNotNull() { addCriterion("priority is not null"); return (Criteria) this; } public Criteria andPriorityEqualTo(Short value) { addCriterion("priority =", value, "priority"); return (Criteria) this; } public Criteria andPriorityNotEqualTo(Short value) { addCriterion("priority <>", value, "priority"); return (Criteria) this; } public Criteria andPriorityGreaterThan(Short value) { addCriterion("priority >", value, "priority"); return (Criteria) this; } public Criteria andPriorityGreaterThanOrEqualTo(Short value) { addCriterion("priority >=", value, "priority"); return (Criteria) this; } public Criteria andPriorityLessThan(Short value) { addCriterion("priority <", value, "priority"); return (Criteria) this; } public Criteria andPriorityLessThanOrEqualTo(Short value) { addCriterion("priority <=", value, "priority"); return (Criteria) this; } public Criteria andPriorityIn(List<Short> values) { addCriterion("priority in", values, "priority"); return (Criteria) this; } public Criteria andPriorityNotIn(List<Short> values) { addCriterion("priority not in", values, "priority"); return (Criteria) this; } public Criteria andPriorityBetween(Short value1, Short value2) { addCriterion("priority between", value1, value2, "priority"); return (Criteria) this; } public Criteria andPriorityNotBetween(Short value1, Short value2) { addCriterion("priority not between", value1, value2, "priority"); return (Criteria) this; } public Criteria andLongitudeIsNull() { addCriterion("longitude is null"); return (Criteria) this; } public Criteria andLongitudeIsNotNull() { addCriterion("longitude is not null"); return (Criteria) this; } public Criteria andLongitudeEqualTo(Float value) { addCriterion("longitude =", value, "longitude"); return (Criteria) this; } public Criteria andLongitudeNotEqualTo(Float value) { addCriterion("longitude <>", value, "longitude"); return (Criteria) this; } public Criteria andLongitudeGreaterThan(Float value) { addCriterion("longitude >", value, "longitude"); return (Criteria) this; } public Criteria andLongitudeGreaterThanOrEqualTo(Float value) { addCriterion("longitude >=", value, "longitude"); return (Criteria) this; } public Criteria andLongitudeLessThan(Float value) { addCriterion("longitude <", value, "longitude"); return (Criteria) this; } public Criteria andLongitudeLessThanOrEqualTo(Float value) { addCriterion("longitude <=", value, "longitude"); return (Criteria) this; } public Criteria andLongitudeIn(List<Float> values) { addCriterion("longitude in", values, "longitude"); return (Criteria) this; } public Criteria andLongitudeNotIn(List<Float> values) { addCriterion("longitude not in", values, "longitude"); return (Criteria) this; } public Criteria andLongitudeBetween(Float value1, Float value2) { addCriterion("longitude between", value1, value2, "longitude"); return (Criteria) this; } public Criteria andLongitudeNotBetween(Float value1, Float value2) { addCriterion("longitude not between", value1, value2, "longitude"); return (Criteria) this; } public Criteria andLatitudeIsNull() { addCriterion("latitude is null"); return (Criteria) this; } public Criteria andLatitudeIsNotNull() { addCriterion("latitude is not null"); return (Criteria) this; } public Criteria andLatitudeEqualTo(Float value) { addCriterion("latitude =", value, "latitude"); return (Criteria) this; } public Criteria andLatitudeNotEqualTo(Float value) { addCriterion("latitude <>", value, "latitude"); return (Criteria) this; } public Criteria andLatitudeGreaterThan(Float value) { addCriterion("latitude >", value, "latitude"); return (Criteria) this; } public Criteria andLatitudeGreaterThanOrEqualTo(Float value) { addCriterion("latitude >=", value, "latitude"); return (Criteria) this; } public Criteria andLatitudeLessThan(Float value) { addCriterion("latitude <", value, "latitude"); return (Criteria) this; } public Criteria andLatitudeLessThanOrEqualTo(Float value) { addCriterion("latitude <=", value, "latitude"); return (Criteria) this; } public Criteria andLatitudeIn(List<Float> values) { addCriterion("latitude in", values, "latitude"); return (Criteria) this; } public Criteria andLatitudeNotIn(List<Float> values) { addCriterion("latitude not in", values, "latitude"); return (Criteria) this; } public Criteria andLatitudeBetween(Float value1, Float value2) { addCriterion("latitude between", value1, value2, "latitude"); return (Criteria) this; } public Criteria andLatitudeNotBetween(Float value1, Float value2) { addCriterion("latitude not between", value1, value2, "latitude"); return (Criteria) this; } public Criteria andTimeOfCrimeIsNull() { addCriterion("time_of_crime is null"); return (Criteria) this; } public Criteria andTimeOfCrimeIsNotNull() { addCriterion("time_of_crime is not null"); return (Criteria) this; } public Criteria andTimeOfCrimeEqualTo(Date value) { addCriterion("time_of_crime =", value, "timeOfCrime"); return (Criteria) this; } public Criteria andTimeOfCrimeNotEqualTo(Date value) { addCriterion("time_of_crime <>", value, "timeOfCrime"); return (Criteria) this; } public Criteria andTimeOfCrimeGreaterThan(Date value) { addCriterion("time_of_crime >", value, "timeOfCrime"); return (Criteria) this; } public Criteria andTimeOfCrimeGreaterThanOrEqualTo(Date value) { addCriterion("time_of_crime >=", value, "timeOfCrime"); return (Criteria) this; } public Criteria andTimeOfCrimeLessThan(Date value) { addCriterion("time_of_crime <", value, "timeOfCrime"); return (Criteria) this; } public Criteria andTimeOfCrimeLessThanOrEqualTo(Date value) { addCriterion("time_of_crime <=", value, "timeOfCrime"); return (Criteria) this; } public Criteria andTimeOfCrimeIn(List<Date> values) { addCriterion("time_of_crime in", values, "timeOfCrime"); return (Criteria) this; } public Criteria andTimeOfCrimeNotIn(List<Date> values) { addCriterion("time_of_crime not in", values, "timeOfCrime"); return (Criteria) this; } public Criteria andTimeOfCrimeBetween(Date value1, Date value2) { addCriterion("time_of_crime between", value1, value2, "timeOfCrime"); return (Criteria) this; } public Criteria andTimeOfCrimeNotBetween(Date value1, Date value2) { addCriterion("time_of_crime not between", value1, value2, "timeOfCrime"); return (Criteria) this; } public Criteria andDescriptionIsNull() { addCriterion("description is null"); return (Criteria) this; } public Criteria andDescriptionIsNotNull() { addCriterion("description is not null"); return (Criteria) this; } public Criteria andDescriptionEqualTo(String value) { addCriterion("description =", value, "description"); return (Criteria) this; } public Criteria andDescriptionNotEqualTo(String value) { addCriterion("description <>", value, "description"); return (Criteria) this; } public Criteria andDescriptionGreaterThan(String value) { addCriterion("description >", value, "description"); return (Criteria) this; } public Criteria andDescriptionGreaterThanOrEqualTo(String value) { addCriterion("description >=", value, "description"); return (Criteria) this; } public Criteria andDescriptionLessThan(String value) { addCriterion("description <", value, "description"); return (Criteria) this; } public Criteria andDescriptionLessThanOrEqualTo(String value) { addCriterion("description <=", value, "description"); return (Criteria) this; } public Criteria andDescriptionLike(String value) { addCriterion("description like", value, "description"); return (Criteria) this; } public Criteria andDescriptionNotLike(String value) { addCriterion("description not like", value, "description"); return (Criteria) this; } public Criteria andDescriptionIn(List<String> values) { addCriterion("description in", values, "description"); return (Criteria) this; } public Criteria andDescriptionNotIn(List<String> values) { addCriterion("description not in", values, "description"); return (Criteria) this; } public Criteria andDescriptionBetween(String value1, String value2) { addCriterion("description between", value1, value2, "description"); return (Criteria) this; } public Criteria andDescriptionNotBetween(String value1, String value2) { addCriterion("description not between", value1, value2, "description"); return (Criteria) this; } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table cases * * @mbggenerated do_not_delete_during_merge Fri Apr 25 17:12:46 CEST 2014 */ public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table cases * * @mbggenerated Fri Apr 25 17:12:46 CEST 2014 */ public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
true
f4b63c0d5a900e14b37cebdd8fe38bd214927bb3
Java
dmsthf2605/Object-Oriented-Programming-Java
/Workshop3/lab3/mandatory/TestUncheckedException.java
UTF-8
1,565
3.984375
4
[]
no_license
package lab3.mandatory; class UnexpectedUserInputException extends Exception{ public UnexpectedUserInputException(){ super(); } public UnexpectedUserInputException(String msg){ super(msg); } } public class TestUncheckedException { public static void test(int num) throws UnexpectedUserInputException{ int x = 10; int[] ia1 = null, ia2 = new int[2]; try { if (num == 0) { x = 20 / num; } else if (num == 1) { x = ia1.length; } else if (num == 2) { x = ia2[2]; } else { x = num; throw new UnexpectedUserInputException("Unexpected User Exception!"); } } catch (ArithmeticException e) { System.out.println("Arithmetic Exception"); } catch(NullPointerException e){ System.out.println("Null Pointer Exception"); } catch (ArrayIndexOutOfBoundsException e){ System.out.println("Array Index Out Of Bounds Exception"); } finally { System.out.println("Value of variable x = " + x); } } public static void main(String[] args) { System.out.println("Please enter 0, 1, 2 or any other number: "); java.util.Scanner sc = new java.util.Scanner(System.in); try { test(sc.nextInt()); } catch (UnexpectedUserInputException e){ System.out.println(e.getMessage()); } } }
true
732be47bc871bb2201b22295024091709ca5f07d
Java
guoguocai/Design-Pattern
/src/com/guoguocai/decorator/demo/Client.java
UTF-8
1,468
3.34375
3
[]
no_license
package com.guoguocai.decorator.demo; import com.guoguocai.decorator.demo.component.Person; import com.guoguocai.decorator.demo.fineryimp.*; /** * 客户端 * * @auther guoguocai * @date 2018/12/25 22:35 */ public class Client { public static void main(String[] args) { Person person = new Person("Chaser"); /** * 可以发现,每种打扮方式都是可以灵活组合的, * 能动态的添加装扮。 * * 虽说装饰的先后顺序可以任意组合,但是在实际应用 * 中装饰的顺序是非常重要的,比如加密数据和过滤词 * 汇都可以是数据持久化前的装饰功能,但是如果是先 * 加密后过滤,最后肯定是会出问题的。就像先穿西装 * 外套后再穿 T 恤一样奇怪。 */ System.out.println("第一种打扮:"); BigTrouser big = new BigTrouser(); Suit suit = new Suit(); Sneaker sneaker = new Sneaker(); big.decorate(person); suit.decorate(big); sneaker.decorate(suit); sneaker.show(); System.out.println("第二种打扮:"); LeatherShoe shoe = new LeatherShoe(); Tie tie = new Tie(); TShirts shirt = new TShirts(); shoe.decorate(person); tie.decorate(shoe); shirt.decorate(tie); shirt.show(); } }
true
e08132fd0fe126ab8ecf172bdcd89163de88aa95
Java
alexdaixin2010/AndroidStudioProjects
/BusinessApp/app/src/main/java/com/foodymon/businessapp/service/PaymentService.java
UTF-8
3,275
2.046875
2
[]
no_license
package com.foodymon.businessapp.service; import android.support.annotation.Nullable; import com.foodymon.businessapp.constant.Constants; import com.foodymon.businessapp.datastructure.LiteOrderList; import com.foodymon.businessapp.datastructure.LitePaymentList; import com.foodymon.businessapp.datastructure.Order; import com.foodymon.businessapp.datastructure.Payment; import com.foodymon.businessapp.main.BusinessApplication; import com.foodymon.businessapp.utils.HttpUtils; import java.util.HashMap; /** * Created by alexdai on 5/22/16. */ public class PaymentService { public static void getPaymentList(final String storeId, final String status, final UICallBack<LitePaymentList> callBack, final BusinessApplication app) { new TaskRunner<String, LitePaymentList>(new Task<String, LitePaymentList>() { @Override public void onPreExecute() { callBack.onPreExecute(); } @Override @Nullable public LitePaymentList doInBackground(String[] params) { HashMap<String, String> paramMap = new HashMap<>(); paramMap.put("storeId", storeId); paramMap.put("status", status); LitePaymentList payList = HttpUtils.get("/bp/paymentList", paramMap, null, LitePaymentList.class, app); return payList; } @Override public void onPostExecute(@Nullable LitePaymentList payList) { callBack.onPostExecute(payList); } }).execute(null); } public static void getPaidRequestList(String storeId, final UICallBack<LitePaymentList> callBack, BusinessApplication app) { getPaymentList(storeId, Constants.ORDER_REQUEST_PAY, callBack, app); } public static void getPaidList(String storeId, final UICallBack<LitePaymentList> callBack, BusinessApplication app) { getPaymentList(storeId, Constants.ORDER_PAID, callBack, app); } public static void getUnPaidList(String storeId, final UICallBack<LitePaymentList> callBack, BusinessApplication app) { getPaymentList(storeId, Constants.ORDER_UNPAID, callBack, app); } public static void getAllLiteOrderList(String storeId, final UICallBack<LitePaymentList> callBack, BusinessApplication app) { getPaymentList(storeId, null, callBack, app); } public static <T> void getPayment(final String paymentId, final UICallBack<Payment> callBack, final BusinessApplication app) { new TaskRunner<String, Order>(new Task<String, Payment>() { @Override public void onPreExecute() { callBack.onPreExecute(); } @Override @Nullable public Payment doInBackground(String[] params) { HashMap<String, String> paramMap = new HashMap<>(); paramMap.put("paymentId", paymentId); Payment payment = HttpUtils.get("/bp/paymentDetails", paramMap, null, Payment.class, app); return payment; } @Override public void onPostExecute(@Nullable Payment payment) { callBack.onPostExecute(payment); } }).execute(null); } }
true
4906f5c84755dbcc45302239e71b74f23be106c4
Java
fabiocasado/Capstone
/app/src/main/java/com/fcasado/betapp/participants/BetParticipantsActivity.java
UTF-8
4,280
1.960938
2
[]
no_license
package com.fcasado.betapp.participants; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.util.Pair; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.Toast; import com.fcasado.betapp.utils.FirebaseUtils; import com.fcasado.betapp.R; import com.fcasado.betapp.data.Bet; import com.fcasado.betapp.data.User; import com.hannesdorfmann.mosby.mvp.MvpActivity; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; public class BetParticipantsActivity extends MvpActivity<ParticipantsView, ParticipantsPresenter>implements ParticipantsView, SwipeRefreshLayout.OnRefreshListener { private static final String TAG = "BetParticipantsActivity"; public static final String EXTRA_CURRENT_BET = "extra_current_bet"; public static final String EXTRA_BET_WINNERS = "extra_bet_winners"; protected ParticipantsAdapter adapter; @BindView(R.id.recyclerView) RecyclerView recyclerView; @BindView(R.id.swiperefresh) SwipeRefreshLayout swipeRefreshLayout; private Bet bet; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_friends); ButterKnife.bind(this); FirebaseUtils.logEvent(this, FirebaseUtils.PARTICIPANTS_SHOW_ACTIVITY, null); if (bet == null && getIntent().hasExtra(EXTRA_CURRENT_BET)) { bet = getIntent().getParcelableExtra(EXTRA_CURRENT_BET); } adapter = new ParticipantsAdapter(bet.getWinners()); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.setAdapter(adapter); swipeRefreshLayout.setOnRefreshListener(this); } @Override protected void onStart() { super.onStart(); swipeRefreshLayout.post(new Runnable() { @Override public void run() { // Workaround since indicator is not showing properly swipeRefreshLayout.setRefreshing(true); } }); loadParticipants(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.participants_activity, menu); if (bet.getWinners() != null && bet.getWinners().size() > 0) { menu.findItem(R.id.winners).setVisible(false); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.winners: if (!adapter.canSelectWinner()) { adapter.setCanSelectWinner(true); item.setIcon(R.drawable.ic_save_white); } else { Intent data = new Intent(); data.putStringArrayListExtra(EXTRA_BET_WINNERS, adapter.getSelectedWinners()); setResult(RESULT_OK, data); finish(); } return true; default: return super.onOptionsItemSelected(item); } } @NonNull @Override public ParticipantsPresenter createPresenter() { return new ParticipantsPresenter(); } @Override public void loadParticipants() { if (bet != null) { getPresenter().loadParticipants(bet.getParticipants()); } } @Override public void showLoadParticipantsFailed() { adapter.clearPredictions(); Toast.makeText(this, R.string.load_participants_failed, Toast.LENGTH_SHORT).show(); } @Override public void onRefresh() { loadParticipants(); } @Override public void showParticipants(List<User> participants) { List<Pair<User, String>> predictions = new ArrayList<>(); if (bet != null) { List<String> betParticipants = bet.getParticipants(); List<String> betPredictions = bet.getPredictions(); // Add friends predictions for (int i = 0; i < participants.size(); i++) { int participantIndex = betParticipants.indexOf(participants.get(i).getUid()); if (participantIndex >= 0) { predictions.add(Pair.create(participants.get(i), betPredictions.get(participantIndex))); } } } adapter.setPredictions(predictions); swipeRefreshLayout.setRefreshing(false); } @Override public Intent getParentActivityIntent() { return super.getParentActivityIntent().addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); } }
true
c80c4bb42fe3ddae2f63385720533e4900878604
Java
DeepKandey/design-patterns
/src/main/java/com/seleniumdesign/executearound/MainPage.java
UTF-8
1,542
2.375
2
[]
no_license
package com.seleniumdesign.executearound; import java.util.function.Consumer; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; public class MainPage { private final WebDriver driver; @FindBy(id = "a") private WebElement a; @FindBy(id = "b") private WebElement b; @FindBy(id = "c") private WebElement c; private FrameA frameA; private FrameB frameB; private FrameC frameC; public MainPage(WebDriver driver) { this.driver = driver; PageFactory.initElements(driver, this); this.frameA = PageFactory.initElements(driver, FrameA.class); this.frameB = PageFactory.initElements(driver, FrameB.class); this.frameC = PageFactory.initElements(driver, FrameC.class); } public void goTo() { this.driver.get("https://vins-udemy.s3.amazonaws.com/ds/main.html"); } public void onFrameA(Consumer<FrameA> frameAConsumer) { this.driver.switchTo().frame(a); frameAConsumer.accept(this.frameA); this.driver.switchTo().defaultContent(); } public void onFrameB(Consumer<FrameB> frameBConsumer) { this.driver.switchTo().frame(b); frameBConsumer.accept(this.frameB); this.driver.switchTo().defaultContent(); } public void onFrameC(Consumer<FrameC> frameCConsumer) { this.driver.switchTo().frame(c); frameCConsumer.accept(this.frameC); this.driver.switchTo().defaultContent(); } }
true
7c29c473fce7035f03ecdfabd24970a41f050cd6
Java
liujie1206/1712
/src/main/java/com/liujie/beans/Goods.java
UTF-8
2,265
2.40625
2
[]
no_license
package com.liujie.beans; public class Goods { private Integer gid ; private String gname; private String ename; private Integer size; private double price; private Integer num; private String label; private String picture; private Brand brand; private Goodskind goodskind ; public Goods(Integer gid, String gname, String ename, Integer size, double price, Integer num, String label, String picture, Brand brand, Goodskind goodskind) { super(); this.gid = gid; this.gname = gname; this.ename = ename; this.size = size; this.price = price; this.num = num; this.label = label; this.picture = picture; this.brand = brand; this.goodskind = goodskind; } public Goods() { super(); // TODO Auto-generated constructor stub } public Integer getGid() { return gid; } public void setGid(Integer gid) { this.gid = gid; } public String getGname() { return gname; } public void setGname(String gname) { this.gname = gname; } public String getEname() { return ename; } public void setEname(String ename) { this.ename = ename; } public Integer getSize() { return size; } public void setSize(Integer size) { this.size = size; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public Integer getNum() { return num; } public void setNum(Integer num) { this.num = num; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public String getPicture() { return picture; } public void setPicture(String picture) { this.picture = picture; } public Brand getBrand() { return brand; } public void setBrand(Brand brand) { this.brand = brand; } public Goodskind getGoodskind() { return goodskind; } public void setGoodskind(Goodskind goodskind) { this.goodskind = goodskind; } @Override public String toString() { return "Goods [gid=" + gid + ", gname=" + gname + ", ename=" + ename + ", size=" + size + ", price=" + price + ", num=" + num + ", label=" + label + ", picture=" + picture + ", brand=" + brand + ", goodskind=" + goodskind + "]"; } }
true
19de7bbb1474a39fee61ea722c69430f9fa07a61
Java
ping2ravi/jpmorgan-test1
/CodingInterviewQuestions/src/main/java/com/jpmorgan/gce/interview/batch/PrintingDownloader.java
UTF-8
562
2.5
2
[]
no_license
package com.jpmorgan.gce.interview.batch; public class PrintingDownloader implements Downloader { public void download(DownloadRequest request) { if(request.getGroupID() == null){ System.out.println("Downloading request for account: " + request.getAccountID().getAccountCode() + ", group: null" ); }else{ System.out.println("Downloading request for account: " + request.getAccountID().getAccountCode() + ", group: " + request.getGroupID().toString()); } } }
true
428be3eec95c63801e6bbac510837ce33633c328
Java
SuFarther/spring-example
/spring-aop-aspectj/src/main/java/com/company/aspect1/MyAspect.java
UTF-8
10,802
3.015625
3
[]
no_license
package com.company.aspect1; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import java.util.Date; /** * @author 苏东坡 * @version 1.0 * @ClassName MyAspect * @company 公司 * @Description 切面类 * @Aspect: 是aspect框架中的注解 * 作用: 表示当前类是切面类 * 切面类: 是用来给业务方法增加功能的类,在这个类中有切面的功能代码 * 位置: 在类的定义上面 * * @createTime 2021年10月17日 14:47:47 */ @Aspect public class MyAspect { /** * 定义方法,方法是实现切面功能的 * 方法的定义要求: * 1、公共方法 public * 2、方法没有返回值 * 3、方法名称自定义 * 4、方法可以有参数,也可以没有参数 * 如果有参数,参数不是自定义的,有几个参数类型可以使用 */ /** * @Before 前置通知注解 * 属性:value, 是切入点表达式,表示切面的功能执行位置 * 位置: 在方法的上面 * 特点: * 1、在目标方法之前先执行的 * 2、不会改变目标方法的执行结果 * 3、不会影响目标方法的执行 */ // @Before("execution(public void com.company.aspect1.impl.SomeServiceImpl.doSomething(String,Integer))") // public void myBefore(){ // //就是你切面要执行的功能代码 // System.out.println("前置通知,切面功能:在目标方法之前输出执行时间:"+new Date()); // } // @Before("execution(void com.company.aspect1.impl.SomeServiceImpl.doSomething(String,Integer))") // public void myBefore(){ // //就是你切面要执行的功能代码 // System.out.println("前置通知,切面功能:在目标方法之前输出执行时间:"+new Date()); // } // @Before("execution(* *..SomeServiceImpl.doSomething(String,Integer))") // public void myBefore(){ // //就是你切面要执行的功能代码 // System.out.println("前置通知,切面功能:在目标方法之前输出执行时间:"+new Date()); // } // @Before("execution(* *..SomeServiceImpl.doSomething(..))") // public void myBefore(){ // //就是你切面要执行的功能代码 // System.out.println("前置通知,切面功能:在目标方法之前输出执行时间:"+new Date()); // } // @Before("execution(* *..SomeServiceImpl.do*(..))") // public void myBefore(){ // //就是你切面要执行的功能代码 // System.out.println("前置通知,切面功能:在目标方法之前输出执行时间:"+new Date()); // } // @Before("execution(* com.company.aspect1.impl.*.*(..))") // public void myBefore(){ // //就是你切面要执行的功能代码 // System.out.println("前置通知,切面功能:在目标方法之前输出执行时间:"+new Date()); // } /** * 指定通知方法中的参数: JoinPoint * JoinPoint: 业务方法,要加入切面功能的业务方法 * 作用是: 可以在通知方法中获取方法执行时的信息,例如方法名称,方法的实参 * 如果你的切面功能中需要用到的方法的信息,就加入JoinPoint * 这个JoinPoint参数的值是由框架赋予,必须是第一个位置的参数 * */ @Before("execution(public void com.company.aspect1.impl.SomeServiceImpl.doSomething(String,Integer))") public void myBefore(JoinPoint joinPoint){ //获取方法的完整定义 System.out.println("方法的签名(定义)="+joinPoint.getSignature()); System.out.println("方法的名称="+joinPoint.getSignature().getName()); //获取方法的实参 Object args [] = joinPoint.getArgs(); for (Object arg:args){ System.out.println("参数="+arg); } //就是你切面要执行的功能代码 System.out.println("前置通知,切面功能:在目标方法之前输出执行时间:"+new Date()); } /** * 后置通知定义方法,方法是实现切面功能的 * 方法的定义要求: * 1、公共方法 public * 2、方法没有返回值 * 3、方法名字自定义 * 4、方法有参数的,推荐是Object,参数名自定义 */ /** * @AfterReturning:后置通知 * 属性: 1、value 切入点表达式 * 2、returning 自定义的变量,表示目标方法的返回值的 * 自定义变量名必须和通知方法的形参名一样 * 位置: 在方法定义的上面 * 特点: * 1、在目标方法之后执行的 * 2、能够获取到目标方法的返回值,可以根据这个返回值做不同的处理功能 * Object res = doOther(); * 3、可以修改这个返回值 * * * 后置通知的执行 * Object res = doOther(); * 参数传参: 传值,传引用 * myAfterReturning(res); * @param res */ @AfterReturning(value = "execution(* *..SomeServiceImpl.doOther(..))",returning = "res") public void myAfterReturning(JoinPoint jp,Object res){ System.out.println("后置通知: 方法的定义"+jp.getSignature()); //Object res:是目标方法执行后的返回值,根据返回值做你的切面的功能处理 System.out.println("后置通知: 在目标方法之后执行的,获取的返回值是:"+res); } /** * 环绕通知方法的定义格式 * 1、public * 2、必须有一个返回值,推荐使用Object * 3、方法的名称自定义 * 4、方法有参数,固定的参数 ProceedingJoinPoint */ /** * @Around: 环绕通知 * 属性: value 切入点表达式 * 位置: 在方法的定义什么 * 特点: * 1、它是功能最强的通知 * 2、在目标方法的前和后都能增强功能 * 3、控制目标方法是否被调用执行 * 4、修改原来的目标方法的执行结果。 影响最后的调用结果 * * 环绕通知,等同于jdk动态代理的,InvocationHandler接口 * * 参数: ProceedingJoinPoint 就等同于Method * 作用: 执行目标方法的 * 返回值: 就是目标方法的执行结果,可以被修改 * * 环绕通知:经常做事务,在目标方法之前前启事务,执行目标方法,在目标方法之后提交事务 * * @param pjp * @return */ @Around("execution(* *..SomeServiceImpl.doFirst(..))") public Object myAround(ProceedingJoinPoint pjp) throws Throwable { //获取第一个参数值 String name=""; //获取第一个参数值 Object[] args = pjp.getArgs(); if(args!=null && args.length > 1){ Object arg = args[0]; name = (String) arg; } //实现环绕通知 Object result = null; System.out.println("环绕通知,在目标方法之前,输出时间:"+new Date()); //1、目标方法调用 //method.invoke();Object result = doFirst(); //目标方法执行 if("zhangsan".equals(name)){ result = pjp.proceed(); } System.out.println("环绕通知,在目标方法之后,提交事务"); //修改目标方法的执行结果,影响方法最后的调用结果 if(result != null){ result = "Hello AspectJ AOP"; } //返回目标方法的执行结果 return result; } /** * 异常通知方法的定义格式 * 1.public * 2.没有返回值 * 3.方法名称自定义 * 4.方法有个一个Exception, 如果还有是JoinPoint, */ /** * @AfterThrowing:异常通知 * 属性:1. value 切入点表达式 * 2. throwing 自定义的变量,表示目标方法抛出的异常对象。 * 变量名必须和方法的参数名一样 * 特点: * 1. 在目标方法抛出异常时执行的 * 2. 可以做异常的监控程序, 监控目标方法执行时是不是有异常。 * 如果有异常,可以发送邮件,短信进行通知 * * 执行就是: * try{ * SomeServiceImpl.doSecond(..) * }catch(Exception e){ * myAfterThrowing(e); * } */ @AfterThrowing(value = "execution(* *..SomeServiceImpl.doSecond(..))", throwing = "ex") public void myAfterThrowing(Exception ex) { System.out.println("异常通知:方法发生异常时,执行:"+ex.getMessage()); //发送邮件,短信,通知开发人员 } /** * 最终通知方法的定义格式 * 1.public * 2.没有返回值 * 3.方法名称自定义 * 4.方法没有参数, 如果还有是JoinPoint, */ /** * @After :最终通知 * 属性: value 切入点表达式 * 位置: 在方法的上面 * 特点: * 1.总是会执行 * 2.在目标方法之后执行的 * * try{ * SomeServiceImpl.doThird(..) * }catch(Exception e){ * * }finally{ * myAfter() * } * */ // @After(value = "execution(* *..SomeServiceImpl.doThird(..))") // public void myAfter(){ // System.out.println("执行最终通知,总是会被执行的代码"); // //一般做资源清除工作的。 // } // // // @Before(value = "execution(* *..SomeServiceImpl.doThird(..))") // public void myBefore(){ // System.out.println("前置通知,在目标方法之前先执行的"); // //一般做资源清除工作的。 // } @After(value = "mypt()") public void myAfter(){ System.out.println("执行最终通知,总是会被执行的代码"); //一般做资源清除工作的。 } @Before(value = "mypt()") public void myBefore(){ System.out.println("前置通知,在目标方法之前先执行的"); //一般做资源清除工作的。 } /** * @Pointcut: 定义和管理切入点, 如果你的项目中有多个切入点表达式是重复的,可以复用的。 * 可以使用@Pointcut * 属性:value 切入点表达式 * 位置:在自定义的方法上面 * 特点: * 当使用@Pointcut定义在一个方法的上面 ,此时这个方法的名称就是切入点表达式的别名。 * 其它的通知中,value属性就可以使用这个方法名称,代替切入点表达式了 */ @Pointcut(value = "execution(* *..SomeServiceImpl.doThird(..))" ) private void mypt(){ //无需代码, } }
true
2bb83ac55d278cc14589e5862045d542b08d79d7
Java
TruiGo/AndroidDevelopSpace
/StudyProject/src/com/gtr/studyproject/nfc/NFCAsyncReaderNdef.java
UTF-8
1,399
2.3125
2
[]
no_license
package com.gtr.studyproject.nfc; import java.io.UnsupportedEncodingException; import java.util.Arrays; import android.nfc.NdefMessage; import android.nfc.NdefRecord; import android.nfc.Tag; import android.nfc.tech.Ndef; import com.xiaotian.framework.common.Mylog; /** * @version 1.0.0 * @author XiaoTian * @name NFCAsyncReaderNDEF * @description NDEF 类型读取器 * @date 2014-5-13 * @link gtrstudio@qq.com * @copyright Copyright © 2010-2014 小天天 Studio, All Rights Reserved. */ public class NFCAsyncReaderNdef extends NFCAsyncReader { @Override protected String doInBackground(Tag... params) { Tag tag = params[0]; Ndef ndef = Ndef.get(tag); if (ndef == null) { // 本Tag 不包含 NDEF协议头 return null; } NdefMessage ndefMessage = ndef.getCachedNdefMessage(); NdefRecord[] records = ndefMessage.getRecords(); for (NdefRecord ndefRecord : records) { // TNF if (ndefRecord.getTnf() == NdefRecord.TNF_WELL_KNOWN // TNF-short && Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT) // RTD-Byte[] ) { try { return readText(ndefRecord); } catch (UnsupportedEncodingException e) { // 不支持的语言编码 e.printStackTrace(); } } } return null; } @Override protected void onPostExecute(String result) { Mylog.info("读取内容完成 Text=" + result); } }
true
07b54ee5584b73684b56ef80b7dda00760f09160
Java
YOUSSEFHARGAM/Gestion-de-Stock-en-JAVA
/cachier.java
UTF-8
36,606
1.804688
2
[]
no_license
/* * 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 projet_youtube_produit; import BDD.Parameter; import BDD.ResultSetTableModel; import BDD.db_connection; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; /** * * @author liamsi */ public class cachier extends javax.swing.JFrame { /** * Creates new form cachier */ ResultSet rs; db_connection db; int old, dec, now; public cachier() { db = new db_connection(new Parameter().HOST_DB, new Parameter().USERNAME_DB, new Parameter().PASSWORD_DB, new Parameter().IPHOST, new Parameter().PORT); initComponents(); table(); jam(); } public void table() { String colon[] = {"code_produit","reference","deseignation","rangement","fournisseur","remise","prix","stock"}; rs = db.querySelect(colon, "produit"); tbl_res.setModel(new ResultSetTableModel(rs)); } public void importer() { String colon[] = {"num_facture","code_produit","reference","prix_vente","stock_sortie","subtotal"}; rs = db.fcSelectCommand(colon, "vente", "num_facture='" + txtfac.getText() + "'"); tbl_ven.setModel(new ResultSetTableModel(rs)); } public void jam() { Date s = new Date(); SimpleDateFormat tgl = new SimpleDateFormat("EEEE-dd-MMM-yyyy"); SimpleDateFormat jam = new SimpleDateFormat("HH:mm"); lbl1.setText(jam.format(s)); lbl2.setText(tgl.format(s));} /** * 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() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); tbl_res = new javax.swing.JTable(); jButton7 = new javax.swing.JButton(); jButton8 = new javax.swing.JButton(); jPanel2 = new javax.swing.JPanel(); jLabel5 = new javax.swing.JLabel(); comrech = new javax.swing.JComboBox(); txtrech = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); txtcod = new javax.swing.JTextField(); txtref = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); txtran = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); txtfou = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); txtpri = new javax.swing.JTextField(); jLabel8 = new javax.swing.JLabel(); txtrem = new javax.swing.JTextField(); txtnou = new javax.swing.JTextField(); jLabel9 = new javax.swing.JLabel(); txtsto = new javax.swing.JTextField(); jLabel10 = new javax.swing.JLabel(); jButton2 = new javax.swing.JButton(); jLabel13 = new javax.swing.JLabel(); lbltot1 = new javax.swing.JLabel(); jButton5 = new javax.swing.JButton(); jPanel3 = new javax.swing.JPanel(); jLabel14 = new javax.swing.JLabel(); txtfac = new javax.swing.JTextField(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jScrollPane2 = new javax.swing.JScrollPane(); tbl_ven = new javax.swing.JTable(); lbltot2 = new javax.swing.JLabel(); jLabel18 = new javax.swing.JLabel(); jLabel19 = new javax.swing.JLabel(); txtpay = new javax.swing.JTextField(); jLabel20 = new javax.swing.JLabel(); txtcas = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jPanel4 = new javax.swing.JPanel(); jLabel16 = new javax.swing.JLabel(); lbl1 = new javax.swing.JLabel(); lbl2 = new javax.swing.JLabel(); jLabel21 = new javax.swing.JLabel(); jButton6 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setPreferredSize(new java.awt.Dimension(1029, 745)); getContentPane().setLayout(null); jPanel1.setBackground(new java.awt.Color(248, 249, 250)); jPanel1.setLayout(null); jLabel1.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N jLabel1.setText("resultat"); jLabel1.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 0, 1, 0, new java.awt.Color(0, 0, 0))); jPanel1.add(jLabel1); jLabel1.setBounds(460, 10, 100, 24); tbl_res.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null} }, new String [] { "code_produit", "reference", "deseignation", "rangement", "fournisseur", "remise", "prix", "stock " } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); tbl_res.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tbl_resMouseClicked(evt); } }); jScrollPane1.setViewportView(tbl_res); jPanel1.add(jScrollPane1); jScrollPane1.setBounds(0, 40, 990, 90); jButton7.setText("actualiser"); jButton7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton7ActionPerformed(evt); } }); jPanel1.add(jButton7); jButton7.setBounds(840, 0, 80, 20); jButton8.setText("sortire"); jButton8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton8ActionPerformed(evt); } }); jPanel1.add(jButton8); jButton8.setBounds(920, 0, 70, 20); getContentPane().add(jPanel1); jPanel1.setBounds(10, 10, 990, 140); jPanel2.setBackground(new java.awt.Color(239, 252, 253)); jPanel2.setLayout(null); jLabel5.setFont(new java.awt.Font("Tahoma", 3, 18)); // NOI18N jLabel5.setText("recherche par catégorie :"); jPanel2.add(jLabel5); jLabel5.setBounds(50, 0, 250, 20); comrech.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "code_produit", "reference", "deseignation", "rangement", "fournisseur", "remise", "prix", "stock" })); jPanel2.add(comrech); comrech.setBounds(50, 30, 240, 30); jPanel2.add(txtrech); txtrech.setBounds(150, 70, 180, 30); jLabel2.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N jLabel2.setText("code_produit :"); jPanel2.add(jLabel2); jLabel2.setBounds(30, 130, 100, 17); txtcod.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtcodActionPerformed(evt); } }); jPanel2.add(txtcod); txtcod.setBounds(150, 120, 160, 30); txtref.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtrefActionPerformed(evt); } }); jPanel2.add(txtref); txtref.setBounds(150, 160, 160, 30); jLabel3.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N jLabel3.setText("reference :"); jPanel2.add(jLabel3); jLabel3.setBounds(30, 170, 100, 17); txtran.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtranActionPerformed(evt); } }); jPanel2.add(txtran); txtran.setBounds(150, 200, 160, 30); jLabel4.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N jLabel4.setText("Prix :"); jPanel2.add(jLabel4); jLabel4.setBounds(30, 290, 100, 17); jLabel6.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N jLabel6.setText("rangement :"); jPanel2.add(jLabel6); jLabel6.setBounds(30, 210, 100, 17); txtfou.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtfouActionPerformed(evt); } }); jPanel2.add(txtfou); txtfou.setBounds(150, 240, 160, 30); jLabel7.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N jLabel7.setText("fournisseur :"); jPanel2.add(jLabel7); jLabel7.setBounds(30, 250, 100, 17); txtpri.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtpriActionPerformed(evt); } }); jPanel2.add(txtpri); txtpri.setBounds(150, 280, 160, 30); jLabel8.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N jLabel8.setText("remise :"); jPanel2.add(jLabel8); jLabel8.setBounds(30, 340, 100, 17); txtrem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtremActionPerformed(evt); } }); jPanel2.add(txtrem); txtrem.setBounds(150, 330, 160, 30); txtnou.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtnouActionPerformed(evt); } }); jPanel2.add(txtnou); txtnou.setBounds(150, 370, 160, 30); jLabel9.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N jLabel9.setText("nouveau Prix :"); jPanel2.add(jLabel9); jLabel9.setBounds(30, 380, 100, 17); txtsto.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtstoActionPerformed(evt); } }); txtsto.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { txtstoKeyReleased(evt); } }); jPanel2.add(txtsto); txtsto.setBounds(150, 410, 160, 30); jLabel10.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N jLabel10.setText("Stock sortire :"); jPanel2.add(jLabel10); jLabel10.setBounds(30, 420, 100, 17); jButton2.setFont(new java.awt.Font("Times New Roman", 3, 18)); // NOI18N jButton2.setText("Ajouter au vente"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jPanel2.add(jButton2); jButton2.setBounds(40, 500, 260, 40); jLabel13.setFont(new java.awt.Font("Tahoma", 3, 18)); // NOI18N jLabel13.setText("RP : "); jPanel2.add(jLabel13); jLabel13.setBounds(60, 460, 50, 30); lbltot1.setFont(new java.awt.Font("Tahoma", 3, 18)); // NOI18N lbltot1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lbltot1.setText("0"); jPanel2.add(lbltot1); lbltot1.setBounds(110, 460, 170, 30); jButton5.setFont(new java.awt.Font("Tahoma", 3, 18)); // NOI18N jButton5.setText("recherche "); jButton5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton5ActionPerformed(evt); } }); jPanel2.add(jButton5); jButton5.setBounds(10, 70, 133, 30); getContentPane().add(jPanel2); jPanel2.setBounds(10, 150, 360, 550); jPanel3.setBackground(new java.awt.Color(240, 249, 252)); jPanel3.setLayout(null); jLabel14.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N jLabel14.setText("Num de facture :"); jPanel3.add(jLabel14); jLabel14.setBounds(20, 130, 100, 17); txtfac.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtfacActionPerformed(evt); } }); jPanel3.add(txtfac); txtfac.setBounds(140, 120, 160, 30); jButton3.setFont(new java.awt.Font("Times New Roman", 3, 14)); // NOI18N jButton3.setText("recherche "); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jPanel3.add(jButton3); jButton3.setBounds(310, 120, 120, 27); jButton4.setFont(new java.awt.Font("Times New Roman", 3, 14)); // NOI18N jButton4.setText("Supprimer"); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); jPanel3.add(jButton4); jButton4.setBounds(440, 120, 110, 27); tbl_ven.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null} }, new String [] { "num_facture", "code_produit", "reference", "Prix de vente", "Stock sortire", "total " } ) { Class[] types = new Class [] { java.lang.Object.class, java.lang.Integer.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Integer.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); jScrollPane2.setViewportView(tbl_ven); jPanel3.add(jScrollPane2); jScrollPane2.setBounds(0, 170, 630, 110); lbltot2.setFont(new java.awt.Font("Tahoma", 3, 18)); // NOI18N lbltot2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lbltot2.setText("0"); jPanel3.add(lbltot2); lbltot2.setBounds(380, 310, 190, 30); jLabel18.setFont(new java.awt.Font("Tahoma", 3, 14)); // NOI18N jLabel18.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel18.setText("payé aprés :"); jPanel3.add(jLabel18); jLabel18.setBounds(290, 380, 90, 30); jLabel19.setFont(new java.awt.Font("Tahoma", 3, 18)); // NOI18N jLabel19.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel19.setText("Rp"); jPanel3.add(jLabel19); jLabel19.setBounds(300, 310, 70, 30); jPanel3.add(txtpay); txtpay.setBounds(400, 380, 130, 30); jLabel20.setFont(new java.awt.Font("Tahoma", 3, 14)); // NOI18N jLabel20.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel20.setText("cash :"); jPanel3.add(jLabel20); jLabel20.setBounds(80, 380, 50, 30); txtcas.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { txtcasKeyReleased(evt); } }); jPanel3.add(txtcas); txtcas.setBounds(140, 380, 130, 30); jButton1.setFont(new java.awt.Font("Tahoma", 3, 18)); // NOI18N jButton1.setText("imprimer"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jPanel3.add(jButton1); jButton1.setBounds(140, 440, 350, 30); jPanel4.setBackground(new java.awt.Color(253, 230, 250)); jLabel16.setFont(new java.awt.Font("Tahoma", 3, 18)); // NOI18N jLabel16.setText("Vente"); jLabel16.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 0, 1, 0, new java.awt.Color(0, 0, 0))); lbl1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N lbl1.setText("jLabel12"); lbl2.setText("jLabel17"); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addGap(264, 264, 264) .addComponent(jLabel16, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 75, Short.MAX_VALUE) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lbl2, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel4Layout.createSequentialGroup() .addGap(10, 10, 10) .addComponent(lbl1, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(50, 50, 50)) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(jLabel16, javax.swing.GroupLayout.DEFAULT_SIZE, 48, Short.MAX_VALUE) .addContainerGap()) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(lbl2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(lbl1) .addGap(0, 0, Short.MAX_VALUE)))) ); jPanel3.add(jPanel4); jPanel4.setBounds(0, 0, 630, 70); jLabel21.setFont(new java.awt.Font("Tahoma", 3, 18)); // NOI18N jLabel21.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel21.setText("Total "); jPanel3.add(jLabel21); jLabel21.setBounds(160, 310, 110, 30); jButton6.setFont(new java.awt.Font("Tahoma", 3, 18)); // NOI18N jButton6.setText("annuler"); jButton6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton6ActionPerformed(evt); } }); jPanel3.add(jButton6); jButton6.setBounds(140, 480, 350, 30); getContentPane().add(jPanel3); jPanel3.setBounds(370, 150, 630, 550); pack(); }// </editor-fold>//GEN-END:initComponents private void tbl_resMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbl_resMouseClicked txtcod.setText(String.valueOf(tbl_res.getValueAt(tbl_res.getSelectedRow(), 0))); txtref.setText(String.valueOf(tbl_res.getValueAt(tbl_res.getSelectedRow(), 1))); txtran.setText(String.valueOf(tbl_res.getValueAt(tbl_res.getSelectedRow(), 3))); txtfou.setText(String.valueOf(tbl_res.getValueAt(tbl_res.getSelectedRow(), 4))); txtrem.setText(String.valueOf(tbl_res.getValueAt(tbl_res.getSelectedRow(), 5))); txtpri.setText(String.valueOf(tbl_res.getValueAt(tbl_res.getSelectedRow(), 6))); cout(); }//GEN-LAST:event_tbl_resMouseClicked private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed Recu n = new Recu(); n.setVisible(true); payaprés(); }//GEN-LAST:event_jButton1ActionPerformed private void txtcodActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtcodActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtcodActionPerformed private void txtrefActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtrefActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtrefActionPerformed private void txtranActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtranActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtranActionPerformed private void txtfouActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtfouActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtfouActionPerformed private void txtpriActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtpriActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtpriActionPerformed private void txtremActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtremActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtremActionPerformed private void txtnouActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtnouActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtnouActionPerformed private void txtstoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtstoActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtstoActionPerformed private void txtfacActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtfacActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtfacActionPerformed private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed if (txtrech.getText().equals("")) { JOptionPane.showMessageDialog(this, "SVP complete le champ de recherche"); } else { if (comrech.getSelectedItem().equals("code_produit")) { String colon[] = {"code_produit","reference","deseignation","rangement","fournisseur","remise","prix","stock"}; rs = db.fcSelectCommand(colon, "produit", "code_produit LIKE '" + txtrech.getText() + "' "); tbl_res.setModel(new ResultSetTableModel(rs)); } else if (comrech.getSelectedItem().equals("reference")) { String colon[] = {"code_produit","reference","deseignation","rangement","fournisseur","remise","prix","stock"}; rs = db.fcSelectCommand(colon, "produit", "reference LIKE '" + txtrech.getText() + "' "); tbl_res.setModel(new ResultSetTableModel(rs)); } else if (comrech.getSelectedItem().equals("deseignation")) { String colon[] = {"code_produit","reference","deseignation","rangement","fournisseur","remise","prix","stock"}; rs = db.fcSelectCommand(colon, "produit", "deseignation LIKE '" + txtrech.getText() + "' "); tbl_res.setModel(new ResultSetTableModel(rs)); } else if (comrech.getSelectedItem().equals("rangement")) { String colon[] = {"code_produit","reference","deseignation","rangement","fournisseur","remise","prix","stock"}; rs = db.fcSelectCommand(colon, "produit", "rangement LIKE '" + txtrech.getText() + "' "); tbl_res.setModel(new ResultSetTableModel(rs)); } else if (comrech.getSelectedItem().equals("fournisseur")) { String colon[] = {"code_produit","reference","deseignation","rangement","fournisseur","remise","prix","stock"}; rs = db.fcSelectCommand(colon, "produit", "fournisseur LIKE '" + txtrech.getText() + "' "); tbl_res.setModel(new ResultSetTableModel(rs)); } else if (comrech.getSelectedItem().equals("remise")) { String colon[] = {"code_produit","reference","deseignation","rangement","fournisseur","remise","prix","stock"}; rs = db.fcSelectCommand(colon, "produit", "remise LIKE '" + txtrech.getText() + "' "); tbl_res.setModel(new ResultSetTableModel(rs)); } else if (comrech.getSelectedItem().equals("prix")) { String colon[] = {"code_produit","reference","deseignation","rangement","fournisseur","remise","prix","stock"}; rs = db.fcSelectCommand(colon, "produit", "prix LIKE '" + txtrech.getText() + "' "); tbl_res.setModel(new ResultSetTableModel(rs)); } else if (comrech.getSelectedItem().equals("stock")) { String colon[] = {"code_produit","reference","deseignation","rangement","fournisseur","remise","prix","stock"}; rs = db.fcSelectCommand(colon, "produit", "stock LIKE '" + txtrech.getText() + "' "); tbl_res.setModel(new ResultSetTableModel(rs)); } } }//GEN-LAST:event_jButton5ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed if (txtcod.getText().equals("") || txtref.getText().equals("") || txtran.getText().equals("") || txtfou.getText().equals("") || txtrem.getText().equals("") || txtpri.getText().equals("") || txtnou.getText().equals("")|| txtsto.getText().equals("")) { JOptionPane.showMessageDialog(this, "SVP entrer vos donneé"); } else if (txtfac.getText().equals("")) { JOptionPane.showMessageDialog(this, "SVP entrer le num de facture"); } else { String[] colon = {"num_facture","code_produit", "reference", "prix_vente", "stock_sortie", "subtotal"}; String[] isi = {txtfac.getText(), txtcod.getText(), txtref.getText(), txtnou.getText(), txtsto.getText(), lbltot1.getText()}; System.out.println(db.queryInsert("vente", colon, isi)); try { if (!test_stock()) { JOptionPane.showMessageDialog(this, "le stock est Limiter"); } else { def(); //true table(); //true } } catch (SQLException ex) { Logger.getLogger(cachier.class.getName()).log(Level.SEVERE, null, ex); System.err.println("\n"+ex); } subtotal(); importer(); total(); } }//GEN-LAST:event_jButton2ActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed importer(); total(); }//GEN-LAST:event_jButton3ActionPerformed private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed String id = String.valueOf(tbl_ven.getValueAt(tbl_ven.getSelectedRow(), 0)); if (JOptionPane.showConfirmDialog(this, "est ce que tu es sure que tu veux supprimer ", "Attention", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) { db.queryDelete("vente", "id=" + id); } else { return; } importer(); total(); }//GEN-LAST:event_jButton4ActionPerformed private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed String invoice = txtfac.getText(); if (JOptionPane.showConfirmDialog(this,"est ce que tu es sure que tu veux supprimer ","attention", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) { db.queryDelete("vente", "num_facture=" + invoice); } else { return; } importer(); total(); }//GEN-LAST:event_jButton6ActionPerformed private void txtstoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtstoKeyReleased subtotal(); // TODO add your handling code here: }//GEN-LAST:event_txtstoKeyReleased private void txtcasKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtcasKeyReleased payaprés(); // TODO add your handling code here: }//GEN-LAST:event_txtcasKeyReleased private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed table(); // TODO add your handling code here: }//GEN-LAST:event_jButton7ActionPerformed private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed Login l = new Login(); l.setVisible(true); this.dispose(); }//GEN-LAST:event_jButton8ActionPerformed /** * @param args the command line arguments */ public void cout() { double a = Double.parseDouble(txtpri.getText()); double b = Double.parseDouble(txtrem.getText()); double c = a - a * (b / 100); txtnou.setText(String.valueOf(c)); } public void subtotal() { double a = Double.parseDouble(txtnou.getText()); double b = Double.parseDouble(txtsto.getText()); double c = a * b; lbltot1.setText(String.valueOf(c));} public void total() { rs = db.exécutionQuery("SELECT SUM(subtotal) as subtotal FROM vente WHERE num_facture = '" + txtfac.getText() + "'"); try { rs.next(); lbltot2.setText(rs.getString("subtotal")); } catch (SQLException ex) { Logger.getLogger(cachier.class.getName()).log(Level.SEVERE, null, ex); } } public boolean test_stock() throws SQLException { boolean teststock; rs = db.querySelectAll("produit","code_produit='" + txtcod.getText() + "'"); while (rs.next()) { old = rs.getInt("stock"); } dec = Integer.parseInt(txtsto.getText()); if (old < dec) { teststock = false; } else { teststock = true; } return teststock; } public void def() throws SQLException { rs = db.querySelectAll("produit", "code_produit='" + txtcod.getText() + "'"); while (rs.next()) { old = rs.getInt("stock"); } dec = Integer.parseInt(txtsto.getText()); now = old - dec; String nvstock = Integer.toString(now); String a = String.valueOf(nvstock); String[] colon = {"stock"}; String[] isi = {a}; System.out.println(db.queryUpdate("produit", colon, isi, "code_produit='" + txtcod.getText() + "'")); } public void payaprés() { int a = Integer.parseInt(lbltot2.getText()); int b = Integer.parseInt(txtcas.getText()); int c = b - a; txtpay.setText(Integer.toString(c)); } 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(cachier.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(cachier.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(cachier.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(cachier.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 cachier().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables public static javax.swing.JComboBox comrech; public static javax.swing.JButton jButton1; public static javax.swing.JButton jButton2; public static javax.swing.JButton jButton3; public static javax.swing.JButton jButton4; public static javax.swing.JButton jButton5; public static javax.swing.JButton jButton6; public static javax.swing.JButton jButton7; public static javax.swing.JButton jButton8; public static javax.swing.JLabel jLabel1; public static javax.swing.JLabel jLabel10; public static javax.swing.JLabel jLabel13; public static javax.swing.JLabel jLabel14; public static javax.swing.JLabel jLabel16; public static javax.swing.JLabel jLabel18; public static javax.swing.JLabel jLabel19; public static javax.swing.JLabel jLabel2; public static javax.swing.JLabel jLabel20; public static javax.swing.JLabel jLabel21; public static javax.swing.JLabel jLabel3; public static javax.swing.JLabel jLabel4; public static javax.swing.JLabel jLabel5; public static javax.swing.JLabel jLabel6; public static javax.swing.JLabel jLabel7; public static javax.swing.JLabel jLabel8; public static javax.swing.JLabel jLabel9; public static javax.swing.JPanel jPanel1; public static javax.swing.JPanel jPanel2; public static javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; public static javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; public static javax.swing.JLabel lbl1; public static javax.swing.JLabel lbl2; public static javax.swing.JLabel lbltot1; public static javax.swing.JLabel lbltot2; public static javax.swing.JTable tbl_res; public static javax.swing.JTable tbl_ven; public static javax.swing.JTextField txtcas; public static javax.swing.JTextField txtcod; public static javax.swing.JTextField txtfac; public static javax.swing.JTextField txtfou; public static javax.swing.JTextField txtnou; public static javax.swing.JTextField txtpay; public static javax.swing.JTextField txtpri; public static javax.swing.JTextField txtran; public static javax.swing.JTextField txtrech; public static javax.swing.JTextField txtref; public static javax.swing.JTextField txtrem; public static javax.swing.JTextField txtsto; // End of variables declaration//GEN-END:variables }
true
e4bbea7d6b20d8d2806d828013344871237c6574
Java
mpriyankdev/socialmedia
/src/main/java/com/socialmedia/service/IFollowerFolloweeHandlingService.java
UTF-8
273
1.890625
2
[]
no_license
package com.socialmedia.service; import java.util.Set; public interface IFollowerFolloweeHandlingService { boolean follow(String followerId, String followeeId); boolean unfollow(String followerId, String followeeId); Set<String> followees(String userId); }
true
35acc45389df457ecc54a0feccb91f996e0b0574
Java
MaNarOdEh/Institute-Management-Project
/app/src/main/java/com/example/pccorner/finalproject/methodsRequiredMoreThanOnce.java
UTF-8
988
3.15625
3
[]
no_license
package com.example.pccorner.finalproject; import java.util.Random; public class methodsRequiredMoreThanOnce { public static String generatePassword(){ String pass=""; String ALLPossible="aAbBEeRrTtYyUu$%&#*123896574JjKkLlMmNnBbVvCcXxZz"; int index=0; for(int i=0;i<6;i++){ index=new Random().nextInt(ALLPossible.length()); pass+=ALLPossible.charAt(index); } return pass; } public static boolean isCorrectName(String name){ if(name.length()>3){ return false; } for(int i=0;i<name.length();i++){ if(!Character.isAlphabetic(name.charAt(i))){ return false; } } return true; } public static boolean isNumber(String number){ for(int i=0;i<number.length();i++){ if(!Character.isDigit(number.charAt(i))){ return false; } } return true; } }
true
e7aef4ac0acfbe61713e91b193b0688f83b3dabc
Java
adwait140/SchemaManager
/src/main/java/com/unbxd/SchemaManager/services/SchemaService.java
UTF-8
799
2.171875
2
[]
no_license
package com.unbxd.SchemaManager.services; import com.unbxd.SchemaManager.exceptions.SchemaServiceException; import com.unbxd.SchemaManager.models.Field; import com.unbxd.SchemaManager.models.SiteSchema; public interface SchemaService { public void addNewSchema(SiteSchema schema) throws SchemaServiceException; public SiteSchema getSchemaForSite(String siteKey) throws SchemaServiceException; public Field getFieldInSite(String SiteKey, String fieldName) throws SchemaServiceException; public void updateFieldInSite(String SiteKey,String fieldName, Field field) throws SchemaServiceException; public void updateSchemaForSite(String SiteKey, SiteSchema schema) throws SchemaServiceException; public void deleteSchemaForSite(String SiteKey) throws SchemaServiceException; }
true
e0257d812982db3e3aef3585eb77cc573ac6adf7
Java
folio-org/mod-quick-marc
/src/main/java/org/folio/qm/service/ChangeManagerService.java
UTF-8
741
1.601563
2
[ "Apache-2.0" ]
permissive
package org.folio.qm.service; import java.util.UUID; import org.folio.qm.domain.dto.InitJobExecutionsRqDto; import org.folio.qm.domain.dto.InitJobExecutionsRsDto; import org.folio.qm.domain.dto.ParsedRecordDto; import org.folio.qm.domain.dto.ProfileInfo; import org.folio.qm.domain.dto.RawRecordsDto; public interface ChangeManagerService { ParsedRecordDto getParsedRecordByExternalId(String externalId); void putParsedRecordByInstanceId(UUID id, ParsedRecordDto recordDto); InitJobExecutionsRsDto postJobExecution(InitJobExecutionsRqDto jobExecutionDto); void putJobProfileByJobExecutionId(UUID jobExecutionId, ProfileInfo jobProfile); void postRawRecordsByJobExecutionId(UUID jobExecutionId, RawRecordsDto rawRecords); }
true
2ec5ff4e70672bca98573f4325de843c2ceb641f
Java
CVAndroid/CVAndroid
/app/src/main/java/com/soulmatexd/cvandroid/SlidingMain/SlidingMain.java
UTF-8
3,392
2.46875
2
[]
no_license
package com.soulmatexd.cvandroid.SlidingMain; import android.content.Context; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.view.MotionEvent; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.LinearLayout; import android.widget.ScrollView; /** * Created by SoulMateXD on 2017/4/23. */ public class SlidingMain extends ScrollView{ private LinearLayout mWrapper; private ViewGroup photoLayout; private ViewGroup albumLayout; private SlidingScrollListener listener; //屏幕高度 private int mScreenHeight; private int halfScreenHeight; //onMeasure是否被调用过了 private boolean once; public SlidingMain(Context context) { this(context, null); } public SlidingMain(Context context, AttributeSet attrs) { this(context, attrs, 0); } public SlidingMain(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initView(context, attrs, defStyleAttr); } public void setSlidingScrollListener(SlidingScrollListener listener) { this.listener = listener; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (!once){ mWrapper = (LinearLayout) getChildAt(0); photoLayout = (ViewGroup) mWrapper.getChildAt(0); albumLayout = (ViewGroup) mWrapper.getChildAt(1); photoLayout.getLayoutParams().height = albumLayout.getLayoutParams().height = mScreenHeight; once = true; } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); if (changed){ this.scrollTo(0, halfScreenHeight); } } @Override public boolean onTouchEvent(MotionEvent ev) { int action = ev.getAction(); switch (action){ case MotionEvent.ACTION_UP: int scaleY = getScrollY(); if (scaleY >= (halfScreenHeight + halfScreenHeight/4)){ this.smoothScrollTo(0, mScreenHeight); listener.onDownPage(); }else if (scaleY <= (halfScreenHeight - halfScreenHeight/4)){ this.smoothScrollTo(0, 0); listener.onUpPage(); }else { this.smoothScrollTo(0, halfScreenHeight); } return false; } return super.onTouchEvent(ev); } public void showTakePhoto(){ this.smoothScrollTo(0, 0); } public void showAlbum(){ this.smoothScrollTo(0, mScreenHeight); } public void initSliding(){ this.scrollTo(0, halfScreenHeight); } private void initView(Context context, AttributeSet attrs, int defStyleAttr) { WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); DisplayMetrics metrics = new DisplayMetrics(); windowManager.getDefaultDisplay().getMetrics(metrics); mScreenHeight = metrics.heightPixels; halfScreenHeight = mScreenHeight/2; this.setVerticalScrollBarEnabled(false); this.setHorizontalScrollBarEnabled(false); } }
true
5d86a4d13d3ee0778abe6132bf2d526c26353794
Java
newtonker/wechat6.5.3
/app/src/main/wechat6.5.3/com/tencent/mm/c/b/f.java
UTF-8
541
1.695313
2
[]
no_license
package com.tencent.mm.c.b; public abstract class f { protected boolean aUP = false; protected int aUQ = 0; protected int aUc = -123456789; protected a aUt; public interface a { void c(int i, byte[] bArr); } public abstract void an(boolean z); public abstract void oT(); public abstract boolean pj(); public final void a(a aVar) { this.aUt = aVar; } public final void cM(int i) { this.aUc = i; } public final int pl() { return this.aUQ; } }
true
754b795a07b77291d5d0d24c334c14e638b1a7cd
Java
bitrise-io/trace-android-sdk
/trace-test-application/src/main/java/io/bitrise/trace/testapp/network/BaseNetworkActivity.java
UTF-8
3,485
2.40625
2
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package io.bitrise.trace.testapp.network; import android.annotation.SuppressLint; import android.os.Bundle; import android.widget.Button; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import io.bitrise.trace.testapp.R; /** * Base common class for networking related Activities, such as OkHttp, UrlStreamHandler. */ public abstract class BaseNetworkActivity extends AppCompatActivity { protected String httpEndpoint = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/significant_hour.geojson"; protected String httpsEndpoint = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/significant_hour.geojson"; protected TextView lblTitle; protected Button btnConnectHttp; protected Button btnConnectHttps; protected TextView lblResponseCode; protected TextView lblResponseBody; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_base_network); lblTitle = findViewById(R.id.lbl_title); btnConnectHttp = findViewById(R.id.btn_connect_http); btnConnectHttps = findViewById(R.id.btn_connect_https); lblResponseCode = findViewById(R.id.lbl_response_status_code); lblResponseBody = findViewById(R.id.lbl_response_body); initViews(); } /** * Initialises the views. */ protected void initViews() { lblTitle.setText(getTitleContent()); btnConnectHttp.setOnClickListener(v -> sendHttpRequest()); btnConnectHttps.setOnClickListener(v -> sendHttpsRequest()); } /** * Displays an error on the screen by clearing the response code, and setting the body to the * error message. * * @param error the error to display. */ protected void displayError(@NonNull final String error) { runOnUiThread(() -> { enableSending(true); lblResponseCode.setText(""); lblResponseBody.setText(error); }); } /** * Displays the response on the screen, by setting the response code and body TextViews. * * @param statusCode the HTTP status code to display. * @param response the body of the response. */ @SuppressLint("SetTextI18n") protected void displayResponse(final int statusCode, @NonNull final String response) { runOnUiThread(() -> { enableSending(true); lblResponseCode.setText(Integer.toString(statusCode)); lblResponseBody.setText(response); }); } /** * Enables the sending by enabling clicking on buttons {@link #btnConnectHttp} and * {@link #btnConnectHttps}. * * @param state {@code true} to enable, {@code false} otherwise. */ protected void enableSending(final boolean state) { btnConnectHttp.setEnabled(state); btnConnectHttps.setEnabled(state); } /** * Clears the text from {@link #lblResponseBody} and {@link #lblResponseCode}. */ protected void clearTexts() { lblResponseBody.setText(""); lblResponseCode.setText(""); } /** * Gets the title content for {@link #lblTitle}. The title should be the given networking * library's name. * * @return the title. */ @NonNull protected abstract String getTitleContent(); /** * Executes the sending of an HTTP request. */ protected abstract void sendHttpRequest(); /** * Executes the sending of an HTTPS request. */ protected abstract void sendHttpsRequest(); }
true
e0f7f5af109d32541beffdeb18792fc711b38531
Java
plenio/TC
/app/src/main/java/com/example/transcamb/MainActivity.java
UTF-8
3,040
2.015625
2
[]
no_license
package com.example.transcamb; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import androidx.viewpager.widget.ViewPager; import com.example.transcamb.costantes.Constants; import com.example.transcamb.utils.SharedPref; import com.google.android.material.appbar.AppBarLayout; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.tabs.TabLayout; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseReference; public class MainActivity extends AppCompatActivity { private TabLayout tabLayout; private AppBarLayout appBarLayout; private ViewPager viewPager; private FirebaseAuth mAuth; private DatabaseReference databaseReference; private FirebaseAuth.AuthStateListener authStateListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tabLayout = findViewById(R.id.tablayout_id); // appBarLayout = findViewById(R.id.appbarid); viewPager = findViewById(R.id.viewpager_id); FloatingActionButton fb_login = findViewById(R.id.fb_login); mAuth = FirebaseAuth.getInstance(); ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager()); Bundle bundle = new Bundle(); SharedPref pref = new SharedPref(getBaseContext()); String statusPref = pref.readPreference(); bundle.putString("fragment", "passageiro"); Bundle bundle1 = new Bundle(); bundle1.putString("fragment", "passageiro"); Passageiro passageiro = new Passageiro(); passageiro.setArguments(bundle); Transportador transportador = new Transportador(); transportador.setArguments(bundle1); if (statusPref != null && statusPref.equals(Constants.PASSAGEIRO)){ adapter.addFrag(passageiro, "passageiro"); }else if (statusPref != null && statusPref.equals(Constants.TRANSPORTADOR)){ adapter.addFrag(transportador, "transportador"); }else { adapter.addFrag(passageiro, "passageiro"); adapter.addFrag(transportador, "transportador"); } if (mAuth.getCurrentUser() != null){ fb_login.setImageResource(R.drawable.ic_car); } viewPager.setAdapter(adapter); tabLayout.setupWithViewPager(viewPager); fb_login.setOnClickListener(view -> { if (tabLayout.getSelectedTabPosition() == 0) { Intent intent = new Intent(MainActivity.this, LogIn.class); intent.putExtra("status", "pass"); startActivity(intent); } else { Intent intent = new Intent(MainActivity.this, LogIn.class); intent.putExtra("status", "trans"); startActivity(intent); } }); } }
true
4a194efba020b9d0f520ccd1ed1c4ab7d2c5512a
Java
swapnilbera/Chat-App
/app/src/main/java/com/example/chatapp/myadapter.java
UTF-8
1,961
2.265625
2
[]
no_license
package com.example.chatapp; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.firebase.ui.database.FirebaseRecyclerAdapter; import com.firebase.ui.database.FirebaseRecyclerOptions; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import de.hdodenhof.circleimageview.CircleImageView; public class myadapter extends FirebaseRecyclerAdapter<model,myadapter.myViewholder> { /** * Initialize a {@link RecyclerView.Adapter} that listens to a Firebase query. See * {@link FirebaseRecyclerOptions} for configuration options. * * @param options */ public myadapter(@NonNull @NotNull FirebaseRecyclerOptions<model> options) { super(options); } @Override protected void onBindViewHolder(@NonNull @NotNull myadapter.myViewholder holder, int position, @NonNull @NotNull model model) { holder.name.setText(model.getName()); holder.status.setText(model.getStatus()); //Glide.with(holder.image.getContext()).load(model.getImage()).into(holder.image); } @NonNull @NotNull @Override public myViewholder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) { View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.singlerow,parent,false); return new myViewholder(view); } class myViewholder extends RecyclerView.ViewHolder{ CircleImageView image; TextView name,status; public myViewholder(@NonNull @NotNull View itemView) { super(itemView); // image=itemView.findViewById(R.id.profile_image); name=itemView.findViewById(R.id.textView5); status=itemView.findViewById(R.id.textView6); } } }
true
17164656faf6a24e82c8d32a002ba30e8394b18f
Java
ansar010/Fundoo-BackEnd
/FundooNote/src/main/java/com/bridgelabz/fundoo/note/services/NoteServiceImp.java
UTF-8
23,979
1.632813
2
[]
no_license
/**************************************************************************************** * purpose : . * *@author Ansar *@version 1.2 *@since 18/12/2018 ****************************************************************************************/ package com.bridgelabz.fundoo.note.services; import java.io.IOException; import java.net.MalformedURLException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; //import com.bridgelabz.fundoo.elasticqueue.ElasticQueueProducer; import com.bridgelabz.fundoo.exception.CollaboratorException; import com.bridgelabz.fundoo.note.dao.ILabelRepository; import com.bridgelabz.fundoo.note.dao.INoteRepository; import com.bridgelabz.fundoo.note.dto.CollabUserInfo; import com.bridgelabz.fundoo.note.dto.ElasticDto; import com.bridgelabz.fundoo.note.dto.NoteDTO; import com.bridgelabz.fundoo.note.model.Label; import com.bridgelabz.fundoo.note.model.Note; import com.bridgelabz.fundoo.rabbitmq.MessageProducer; import com.bridgelabz.fundoo.response.Response; import com.bridgelabz.fundoo.user.dao.IUserRepository; import com.bridgelabz.fundoo.user.model.User; import com.bridgelabz.fundoo.util.StatusHelper; import com.bridgelabz.fundoo.util.UserToken; import lombok.extern.slf4j.Slf4j; @Slf4j @Service("noteService") @PropertySource("classpath:message.properties") public class NoteServiceImp implements INoteService { @Autowired private INoteRepository noteRepository; @Autowired private Environment environment; @Autowired private IUserRepository userRepository; @Autowired private ILabelRepository labelRepository; @Autowired private UserToken userToken; @Autowired private ModelMapper modelMapper; @Autowired private MessageProducer messageProducer; @Autowired private ElasticDto elasticDto; @Autowired private ElasticSearchService elasticService; private final Path fileLocation = Paths.get("/home/admin1/FundooFile"); // private final Path fileLocation = Paths.get("G:\\FundooFile"); @Override public Response createNote(NoteDTO noteDTO, String token) { log.info("user note->"+noteDTO.toString()); log.info("Token->"+token); long userId = userToken.tokenVerify(token); log.info(Long.toString(userId)); System.out.println(noteDTO.isPin()); //transfer DTO data into Model Note note = modelMapper.map(noteDTO, Note.class); System.out.println(noteDTO.getTitle()); Optional<User> user = userRepository.findById(userId); note.setUser(user.get()); note.setCreateStamp(LocalDateTime.now()); Note savedNote = noteRepository.save(note); elasticDto.setData(savedNote); elasticDto.setType("save"); messageProducer.sendMsgToElasticQueue(elasticDto); // messageProducer.sendMsgToElasticQueue(savedNote); // elasticService.save(savedNote); // elasticQueueProducer.sendMessageToElasticQueue("Elastic search worked"); // User user2 = note.getUser(); // System.out.println(user2.toString()); Response response = StatusHelper.statusInfo(environment.getProperty("status.noteCreate.successMsg"), Integer.parseInt(environment.getProperty("status.success.code"))); return response; } @Override public Response updateNote(Note note, String token) { log.info("user note->"+note.toString()); log.info("Token->"+token); long userId = userToken.tokenVerify(token); log.info(Long.toString(userId)); //User user = userRepository.findById(userId).orElse(th) note.setUpdateStamp(LocalDateTime.now()); Optional<Note> dbNote = noteRepository.findById(note.getId()); long dbUserId = dbNote.get().getUser().getUserId(); if(dbUserId==userId&&dbNote.isPresent()) { Note updatedNote = noteRepository.save(note); elasticDto.setData(updatedNote); elasticDto.setType("update"); messageProducer.sendMsgToElasticQueue(elasticDto); Response response = StatusHelper.statusInfo(environment.getProperty("status.noteUpdate.successMsg"), Integer.parseInt(environment.getProperty("status.success.code"))); return response; } Response response = StatusHelper.statusInfo(environment.getProperty("status.noteUpdateError.errorMsg"), Integer.parseInt(environment.getProperty("status.noteUpdateError.errorcode"))); return response; } // @Override // public Response updateNote(long noteId,NoteDTO noteDTO, String token) { // log.info("note id->"+noteId); // log.info("noteDto->"+noteDTO); // log.info("token->"+token); // // long userId = userToken.tokenVerify(token); // // Note note = modelMapper.map(noteDTO, Note.class); // // Optional<Note> dbNote = noteRepository.findById(noteId); // long dbUserId = dbNote.get().getUser().getUserId(); // // if(dbUserId==userId&&dbNote.isPresent()) // { // // note.setUpdateStamp(LocalDateTime.now()); // // note.setId(noteId); // // Note status = noteRepository.save(note); // dbNote.get().setUpdateStamp(LocalDateTime.now()); // dbNote.get().setTitle(noteDTO.getTitle()); // dbNote.get().setDescription(noteDTO.getDescription()); // dbNote.get().setColor(noteDTO.getColor()); // Note status = noteRepository.save(dbNote.get()); // if(status.equals(null)) // { // Response response = StatusHelper.statusInfo(environment.getProperty("status.noteUpdateError.errorMsg"), // Integer.parseInt(environment.getProperty("status.noteUpdateError.errorcode"))); // return response; // } // Response response = StatusHelper.statusInfo(environment.getProperty("status.noteUpdate.successMsg"), // Integer.parseInt(environment.getProperty("status.success.code"))); // // return response; // // } // // return null; // } @Override public List<Note> getAllNoteLists(String token, String isArchive, String isTrash) { log.info("Token->"+token); log.info("isArchive->"+isArchive); log.info("isTrash->"+isTrash); long userId = userToken.tokenVerify(token); Optional<User> dbUser = userRepository.findById(userId); List<Note> collabedNotes = dbUser.get().getCollabedNotes().stream().collect(Collectors.toList()); Optional<List<Note>> list_of_notes = noteRepository.findAllById(userId, Boolean.valueOf(isArchive),Boolean.valueOf(isTrash)); // list_of_notes.get().addAll(collabedNotes); collabedNotes.addAll(list_of_notes.get()); // return list_of_notes.get(); return collabedNotes; } @Override public Response deleteForever(long noteId, String token) { log.info("Note id->"+noteId); log.info("Token->"+token); long userId = userToken.tokenVerify(token); log.info(Long.toString(userId)); Optional<Note> note = noteRepository.findById(noteId); log.info(String.valueOf(note.isPresent())); System.out.println("cehck sds"+note.isPresent()); long dbuserId = note.get().getUser().getUserId(); log.info("user id->"+dbuserId); boolean trash = note.get().isTrash(); log.info("Trash->"+trash); if(note.isPresent()&&dbuserId==userId&&note.get().isTrash()==true) { log.info("user validation done"); // note.get().getLabels().stream().filter(label->label.getNotes().remove(note.get())); note.get().getLabels().forEach(label->label.getNotes().remove(note.get())); note.get().getCollabedUsers().forEach(user->user.getCollabedNotes().remove(note.get())); noteRepository.delete(note.get()); elasticDto.getData().setId(noteId); elasticDto.setType("delete"); messageProducer.sendMsgToElasticQueue(elasticDto); Response response = StatusHelper.statusInfo(environment.getProperty("status.deleteForever.successMsg"), Integer.parseInt(environment.getProperty("status.success.code"))); return response; } Response response = StatusHelper.statusInfo(environment.getProperty("status.deleteForever.errorMsg"), Integer.parseInt(environment.getProperty("status.deleteForever.errorCode"))); return response; } @Override public Response trashStatus(long noteId, String token) { log.info("Note id->"+noteId); log.info("Token->"+token); long userId = userToken.tokenVerify(token); log.info(Long.toString(userId)); Optional<Note> note = noteRepository.findById(noteId); long dbuserId = note.get().getUser().getUserId(); if(dbuserId==userId) { if(note.get().isTrash()==true) { note.get().setTrash(false); noteRepository.save(note.get()); Response response = StatusHelper.statusInfo(environment.getProperty("status.restore.successMsg"), Integer.parseInt(environment.getProperty("status.success.code"))); return response; } else { note.get().setTrash(true); } noteRepository.save(note.get()); } // Response response = StatusHelper.statusInfo(environment.getProperty("status.moveTrash.errorMsg"), // Integer.parseInt(environment.getProperty("status.deleteForever.errorCode"))); // return response; Response response = StatusHelper.statusInfo(environment.getProperty("status.moveTrash.successMsg"), Integer.parseInt(environment.getProperty("status.success.code"))); return response; } @Override public Response pinStatus(long noteId, String token) { log.info("Note id->"+noteId); log.info("Token->"+token); long userId = userToken.tokenVerify(token); log.info(Long.toString(userId)); Optional<Note> note = noteRepository.findById(noteId); long dbuserId = note.get().getUser().getUserId(); if(dbuserId==userId) { if(note.get().isPin()==true) { note.get().setPin(false); noteRepository.save(note.get()); Response response = StatusHelper.statusInfo(environment.getProperty("status.unpin.successMsg"), Integer.parseInt(environment.getProperty("status.success.code"))); return response; } else { note.get().setPin(true); } noteRepository.save(note.get()); } // Response response = StatusHelper.statusInfo(environment.getProperty("status.moveTrash.errorMsg"), // Integer.parseInt(environment.getProperty("status.deleteForever.errorCode"))); // return response; Response response = StatusHelper.statusInfo(environment.getProperty("status.pinned.successMsg"), Integer.parseInt(environment.getProperty("status.success.code"))); return response; } @Override public Response archiveStatus(long noteId, String token) { log.info("Note id->"+noteId); log.info("Token->"+token); long userId = userToken.tokenVerify(token); log.info(Long.toString(userId)); Optional<Note> note = noteRepository.findById(noteId); long dbuserId = note.get().getUser().getUserId(); if(dbuserId==userId) { if(note.get().isArchive()==true) { note.get().setArchive(false); noteRepository.save(note.get()); Response response = StatusHelper.statusInfo(environment.getProperty("status.unarchive.successMsg"), Integer.parseInt(environment.getProperty("status.success.code"))); return response; } else { note.get().setArchive(true); } noteRepository.save(note.get()); } // Response response = StatusHelper.statusInfo(environment.getProperty("status.moveTrash.errorMsg"), // Integer.parseInt(environment.getProperty("status.deleteForever.errorCode"))); // return response; Response response = StatusHelper.statusInfo(environment.getProperty("status.archive.successMsg"), Integer.parseInt(environment.getProperty("status.success.code"))); return response; } @Override public List<Note> getAllNote(String token) { log.info("Token->"+token); long userId = userToken.tokenVerify(token); log.info(Long.toString(userId)); // List<Note> noteRepository.findByUser_id(userId); List<Note> listNote = noteRepository.findAll(); List<Note> list = new ArrayList<>(); for (int i = 0; i < listNote.size(); i++) { if(listNote.get(i).getUser().getUserId()==userId) { list.add(listNote.get(i)); } } return list; // List<Note> notes = noteRepository.findAllByUserId(userId); // System.out.println("notes"+notes); } @Override public List<Note> getlabeledNote(String token, String labelName) { // Optional<Long> labelId = labelRepository.findIdByLabelName(labelName); Optional<Label> label = labelRepository.findBylabelName(labelName); long userId = userToken.tokenVerify(token); if(label.get().getUser().getUserId()==userId) { // List<Note> labeledNotesList = labelRepository.findById(label.get().getId()).get().getNotes().stream().collect(Collectors.toList()); List<Note> labeledNotesList = label.get().getNotes().stream().collect(Collectors.toList()); return labeledNotesList; } return null; } //method to store file @Override public Response saveNoteImage(String token, MultipartFile file, Long noteId) { Note note = noteRepository.findById(noteId).get(); long userId = userToken.tokenVerify(token); // generate random universal unique id UUID uuid = UUID.randomUUID(); String uniqueStringId = uuid.toString(); //copying file stream in target file try { Files.copy(file.getInputStream(), fileLocation.resolve(uniqueStringId),StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { e.printStackTrace(); } if(note.getUser().getUserId()==userId) { note.setImage(uniqueStringId); noteRepository.save(note); Response response = StatusHelper.statusInfo(environment.getProperty("status.imageUpload.successMsg"), Integer.parseInt(environment.getProperty("status.success.code"))); return response; } Response response = StatusHelper.statusInfo(environment.getProperty("status.imageUpload.errorMsg"), Integer.parseInt(environment.getProperty("status.error.code"))); return response; } @Override public Resource getNoteImage(Long noteId) { Note note = noteRepository.findById(noteId).get(); // get image name from database Path imagePath = fileLocation.resolve(note.getImage()); try { //creating url resource based on uri object Resource resource = new UrlResource(imagePath.toUri()); if(resource.exists() || resource.isReadable()) { return resource; } } catch (MalformedURLException e) { e.printStackTrace(); } return null; } @Override public Response addCollab(long noteId, String userMailId, String token) { log.info("collab Service noteId->"+noteId); log.info("collab Service userMailId->"+userMailId); log.info("collab Service token->"+token); long userId = userToken.tokenVerify(token); User collabUserDetails = userRepository.findByEmail(userMailId).orElseThrow( ()->new CollaboratorException(environment.getProperty("status.invalidAc.errorMsg"), Integer.parseInt(environment.getProperty("status.error.code")))); Optional<Note> collabNoteDetails = noteRepository.findById(noteId); Optional<User> OwnerUser = userRepository.findById(userId); // validation to add userhimself //boolean ownerValidation = OwnerUser.get().getEmail().equals(userMailId); // validating user already added List<User> checkUserPresence = collabNoteDetails.get().getCollabedUsers().stream().filter(user->user.getEmail().equals(userMailId)).collect(Collectors.toList()); // if(checkUserPresence.isEmpty()&&!ownerValidation&&collabNoteDetails.get().getUser().getUserId()==userId) if(checkUserPresence.isEmpty()) { collabNoteDetails.get().getCollabedUsers().add(collabUserDetails); collabUserDetails.getCollabedNotes().add(collabNoteDetails.get()); noteRepository.save(collabNoteDetails.get()); userRepository.save(collabUserDetails); Response response = StatusHelper.statusInfo(environment.getProperty("status.addCollab.successMsg"), Integer.parseInt(environment.getProperty("status.success.code"))); return response; }else{ throw new CollaboratorException(environment.getProperty("status.addCollab.errorMsg"), Integer.parseInt(environment.getProperty("status.error.code"))); } } @Override public Response removeCollab(long noteId, String userMailId, String token) { log.info("collab Service noteId->"+noteId); log.info("collab Service userMailId->"+userMailId); log.info("collab Service token->"+token); // long userId = userToken.tokenVerify(token); Optional<User> collabUserDetails = userRepository.findByEmail(userMailId); Optional<Note> collabNoteDetails = noteRepository.findById(noteId); List<User> checkUserPresence = collabNoteDetails.get().getCollabedUsers().stream().filter(user->user.getEmail().equals(userMailId)).collect(Collectors.toList()); if(!checkUserPresence.isEmpty()) { collabNoteDetails.get().getCollabedUsers().remove(collabUserDetails.get()); collabUserDetails.get().getCollabedNotes().remove(collabNoteDetails.get()); noteRepository.save(collabNoteDetails.get()); userRepository.save(collabUserDetails.get()); Response response = StatusHelper.statusInfo(environment.getProperty("status.removeCollab.successMsg"), Integer.parseInt(environment.getProperty("status.success.code"))); return response; }else{ throw new CollaboratorException(environment.getProperty("status.removeCollab.errorMsg"), Integer.parseInt(environment.getProperty("status.error.code"))); } } @Override public List<Note> searchNotes(String searchText,String token) { long userId = userToken.tokenVerify(token); Map<String,Float> fields = new HashMap<>(); fields.put("title", 3.0f); fields.put("description", 2.0f); List<Note> searchedNotes = elasticService.searchedNotes("fundoo_note", "note_info", fields, searchText ,userId); return searchedNotes; } @Override // public Set<User> getCollabedUser(long noteId, String token) public Set<CollabUserInfo> getCollabedUser(long noteId, String token) { log.info("collab Service noteId->"+noteId); log.info("collab Service token->"+token); long userId = userToken.tokenVerify(token); Optional<Note> note = noteRepository.findById(noteId); // Optional<User> ownerUser = userRepository.findById(userId); // if(note.get().getUser().getUserId()==userId) // { // Set<User> collabedUsers = note.get().getCollabedUsers(); // collabedUsers.add(ownerUser.get()); Set<CollabUserInfo> collabUserInfos=note.get().getCollabedUsers().stream().map(user->modelMapper.map(user, CollabUserInfo.class)).collect(Collectors.toSet()); // CollabUserInfo collabUserInfo = modelMapper.map(collabedUsers, CollabUserInfo.class); // return collabUserInfos; // } // return null; } // @Override // public List<SendingNotes> listLabelNotes(String token,String label)throws NoteException { // long labelId=labelRepository.findIdByLabelName(label).get(); // TokenVerify.tokenVerifing(token); // List<Notes> list=labelRepository.findById(labelId).get().getNotes().stream().collect(Collectors.toList()); // List<SendingNotes> xyz = new ArrayList<SendingNotes>(); // list.stream().forEach( x -> xyz.add(new SendingNotes(x, new ArrayList<CollabUserDetails>()))); // return xyz; //} // Note note; // @Override // public Response addNote(NoteDTO noteDTO, String token) // { // log.info("user note->"+noteDTO.toString()); // log.info("Token->"+token); // // long userId = userToken.tokenVerify(token); // log.info(Long.toString(userId)); // // //transfer DTO data into Model // Note note = modelMapper.map(noteDTO, Note.class); // // //user details // Optional<User> user = userRepository.findById(userId); // // note.setCreateStamp(LocalDateTime.now()); // note.setUserId(user.get()); // //add note to list in user table // user.get().getNotes().add(note); // userRepository.save(user.get()); // // long userId2 = note.getUserId().getUserId(); // System.out.println("Ansar"+userId2); // Response response = StatusHelper.statusInfo(environment.getProperty("status.noteCreate.successMsg"), // Integer.parseInt(environment.getProperty("status.success.code"))); // // return response; // // } // // @Override //// public Response updateNote(NoteDTO noteDTO, String token,long noteId) // public Response updateNote(NoteDTO noteDTO, String token) // { // log.info("user note->"+noteDTO.toString()); // log.info("Token->"+token); // // long userId = userToken.tokenVerify(token); // log.info(Long.toString(userId)); // // Note note = modelMapper.map(noteDTO, Note.class); // // // Optional<User> user = userRepository.findById(userId); //// if(userId==id) //// { //// note.setUpdateStamp(LocalDateTime.now()); //// //// noteRepository.save(note); //// //// Response response = StatusHelper.statusInfo(environment.getProperty("status.noteUpdate.successMsg"), //// Integer.parseInt(environment.getProperty("status.success.code"))); // // //// return response; //// } // //// for (int i = 0; i < user.get().getNotes().size(); i++) { //// if(note.getNoteId()==user.get().getNotes().iterator().hasNext().has) //// { //// user.get().getNotes().add(note) //// } //// } // //// //// //transfer DTO data into Model //// Note note = modelMapper.map(noteDTO, Note.class); //// note.setNoteId(noteId); //// //// Optional<Note> dbNote = noteRepository.findById(note.getNoteId()); //// //// User user = dbNote.get().getUserId(); //// //// System.out.println("sdfsdf"+user.toString()); //// //// long id = user.getUserId(); //// // // // Response response = StatusHelper.statusInfo(environment.getProperty("status.noteUpdateError.successMsg"), // Integer.parseInt(environment.getProperty("status.noteUpdateError.errorcode"))); // return response; // } // //// private List<Note> listOfNotes(long id) //// { //// log.info("Note id->"+id); //// //// Optional<User> user = userRepository.findById(id); //// List<Note> notes = user.get().getNotes(); //// //// log.info("List of Note ->"+notes.toString()); //// //// System.out.println("Notes --->"+notes.toString()); //// //// return notes; //// } // // // // // @Override // // public boolean updateNote(NoteDTO noteDTO, String token) // // { // // log.info("user note->"+noteDTO.toString()); // // log.info("Token->"+token); // // // // long userId = userToken.tokenVerify(token); // // // // log.info(Long.toString(userId)); // // // // Note note = modelMapper.map(noteDTO, Note.class); // // Optional<User> userDeatils = userRepository.findById(userId); // // // // System.out.println(userDeatils.get()); // // // //// note.setUser(userDeatils.get()); // // note.setCreateStamp(LocalDate.now()); // // noteRepository.save(note); // // // // return true; // // } // }
true
a44cdea90538dc0b3c406794b4e976eeff6902f5
Java
IntelNetwork/taskcenter
/taskcenter-dal/src/main/java/org/smartwork/dal/entity/ZGTaskTag.java
UTF-8
1,229
2.015625
2
[]
no_license
package org.smartwork.dal.entity; import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.core.enums.SqlKeyword; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import org.forbes.comm.annotations.QueryColumn; import org.forbes.comm.annotations.ValidUnique; import org.forbes.comm.constant.SaveValid; import org.forbes.comm.constant.UpdateValid; import org.forbes.comm.entity.BaseEntity; import javax.validation.constraints.NotEmpty; /** * Table: fb_zg_task_tag */ @Data @ApiModel(description = "任务标签") @TableName("fb_zg_task_tag") public class ZGTaskTag extends BaseEntity { private static final long serialVersionUID = -1450874657154153994L; /** * 标签名称 * <p> * Table: fb_zg_task_tag * Column: name * Nullable: true */ @ApiModelProperty(value = "标签名称",example="",required = true) @NotEmpty(message = "标签名称为空",groups ={UpdateValid.class, SaveValid.class} ) @QueryColumn(column = "name",sqlKeyword = SqlKeyword.LIKE) @ValidUnique(column = "name",bizCode = "005006001",bizErrorMsg = "%s标签名称已经存在") private String name; }
true
07a70142a16c444e123c318a1154bcb37c838402
Java
gabrielsr/ltsa
/stoch-fsp/src/main/java/ic/doc/simulation/sim/ClockCondition.java
UTF-8
4,536
2.59375
3
[]
no_license
/****************************************************************************** * LTSA (Labelled Transition System Analyser) - LTSA is a verification tool * * for concurrent systems. It mechanically checks that the specification of a * * concurrent system satisfies the properties required of its behaviour. * * Copyright (C) 2001-2004 Jeff Magee (with additions by Robert Chatley) * * * * This program is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public License * * as published by the Free Software Foundation; either version 2 * * of the License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA * * * * The authors can be contacted by email at {jnm,rbc}@doc.ic.ac.uk * * * ******************************************************************************/ package ic.doc.simulation.sim; import ic.doc.ltsa.lts.StochasticAutomata; /** * This class represents clock conditions that may guard * transitions. The condition refers to a particular clock and * sense. The sense of the condition determines whether the clock must * have expired or not - if the sense is true, the clock must have * expired. * * @author Thomas Ayles * @version $Revision: 1.1 $ $Date: 2005/02/14 14:09:30 $ */ public class ClockCondition implements Condition, Cloneable { private int clock; private boolean sense; /** * Creates a new clock condition referring to the specified clock * in the given sense. The sense determines whether the clock must * have or must have not expired in order for the condition to be * met. * @param clock The identifier of the clock that this condition * refers to. * @param sense The sense of the condition - if <code>true</code> * the clock must have expired (have a value less than zero) for * the condition to be met. */ public ClockCondition( int clock, boolean sense ) { this.clock = clock; this.sense = sense; } public boolean evaluate( SimulationState s ) { return sense ? s.getClock( clock ) <= 0 : s.getClock( clock ) > 0; } public double timeUntilTrue( SimulationState s ) { if( sense ) return s.clockRunning(clock) ? s.getClock( clock ) : Double.POSITIVE_INFINITY; else return s.getClock( clock ) > 0 ? 0 : Double.POSITIVE_INFINITY; } public void addClockOffset( int offset ) { clock += offset; } public int getMaxClockIdentifier() { return clock; } /** * Returns the identifier of the clock that this condition refers to. * @return The identifier of the clock this condition refers to. */ public int getClockIdentifier() { return clock; } public String toString() { return ( sense ? "" : "!" ) + clock; } public boolean equals( Object o ) { try { ClockCondition c = (ClockCondition) o; return c.getClass().equals( this.getClass() ) && c.clock == this.clock && c.sense == this.sense; } catch( ClassCastException e ) { return false; } } public int hashCode() { return getClass().hashCode() ^ clock ^ (sense?0xFF:0x00); } public Condition cloneCondition() { try { return (Condition) super.clone(); } catch( CloneNotSupportedException e ) { throw new RuntimeException( e.getMessage() ); } } public String prettyPrint( StochasticAutomata m ) { return (sense?"":"!") + clock; } }
true
8934104cfaec0c67dd977e2c2f1f0a9c3ccbe24b
Java
ilyasziyaoglu/andriambavy-backend
/src/main/java/com/andriambavy/ecom/common/property/db/repository/PropertyRepository.java
UTF-8
383
1.59375
2
[]
no_license
package com.andriambavy.ecom.common.property.db.repository; import com.andriambavy.ecom.common.basemodel.db.repository.BaseRepository; import com.andriambavy.ecom.common.property.db.entity.Property; import org.springframework.stereotype.Repository; /** * @author Ilyas Ziyaoglu * @date 2020-04-18 */ @Repository public interface PropertyRepository extends BaseRepository<Property> { }
true
a9a22979946337a614273c7261890f5d6658634c
Java
kevinarditya/graphql
/src/main/java/com/btpn/chips/mskevingraphql/wallets/WalletService.java
UTF-8
1,384
2.1875
2
[]
no_license
package com.btpn.chips.mskevingraphql.wallets; import com.btpn.chips.mskevingraphql.kafka.model.WalletCreationModel; import com.btpn.chips.mskevingraphql.kafka.service.KafkaProducerService; import com.btpn.chips.mskevingraphql.users.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class WalletService { private final WalletRepository walletRepository; private final KafkaProducerService kafkaProducerService; @Autowired public WalletService(WalletRepository walletRepository, KafkaProducerService kafkaProducerService) { this.walletRepository = walletRepository; this.kafkaProducerService = kafkaProducerService; } public void clear() { walletRepository.deleteAll(); } public Wallet create(Long balance, User user) { Wallet wallet = new Wallet(balance, user); WalletCreationModel walletCreationModel = new WalletCreationModel(user.getId(), wallet.getId(), user.getName(), wallet.getBalance()); kafkaProducerService.sendData("test", walletCreationModel); return walletRepository.save(wallet); } public List<Wallet> fetchAll() { return walletRepository.findAll(); } public Wallet fetch(int id) { return walletRepository.findWalletById(id); } }
true
a08ba76ea264b3f641aa0472f2e6799c707f59f6
Java
rashadsaif/aden-univ
/src/main/java/com/adenuniv/repo/YearRepository.java
UTF-8
208
1.585938
2
[]
no_license
package com.adenuniv.repo; import org.springframework.data.jpa.repository.JpaRepository; import com.adenuniv.model.Year; public interface YearRepository extends JpaRepository<Year, Long>{ }
true
9890fca6950f35e6bce43544cc1fd68249c48177
Java
Bkonuskan/Java2021
/src/day35/C01_RentApartments.java
UTF-8
1,197
2.875
3
[]
no_license
package day35; public class C01_RentApartments { private String name; private int roomCount; private boolean balconyOrNo; private int kira; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getRoomCount() { return roomCount; } public void setRoomCount(int roomCount) { this.roomCount = roomCount; } public boolean isBalconyOrNo() { return balconyOrNo; } public void setBalconyOrNo(boolean balconyOrNo) { this.balconyOrNo = balconyOrNo; } public int kiraHesapla(int roomCount) { if (roomCount==0) { this.kira=1400; }else if (roomCount==1) { this.kira=1700; }else if (roomCount==2) { this.kira=2200; }else if (roomCount==3) { this.kira=2700; }else { System.out.println("hatali veri girdiniz :( "); } return this.kira; } public int balkonSor (boolean balconyOrNo) { if (balconyOrNo==true) { this.kira+=200; } return this.kira; } }
true
2d03df4753dc164498f52b747db96c8e36971a12
Java
sunilreddyg/Project_184_10AM_Sep_2020
/Project_184/src/ui_verification_commands/Runtime_page_Source.java
UTF-8
2,017
2.78125
3
[]
no_license
package ui_verification_commands; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class Runtime_page_Source { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "Drivers\\chromedriver.exe"); WebDriver driver=new ChromeDriver(); driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS); driver.get("http://facebook.com"); driver.manage().window().maximize(); //Method capture entirepage source into String.. String PageSource=driver.getPageSource(); /* * Note:--> In this line when element not found at [DOM] webdriver throw * exception and suspend your run [NosuchElementException] */ WebElement Email=driver.findElement(By.cssSelector("input[data-testid='royal_email']")); Email.clear(); Email.sendKeys("9030248855"); /* * Note:--> In this line when element not found at Pagesource * it prevent action to perform on location and lest us know * element not available at source without throwing exception.. */ if(PageSource.contains("royal_email")) { System.out.println("Element Presented at source"); WebElement Email_EB=driver.findElement(By.cssSelector("input[data-testid='royal_email']")); Email_EB.clear(); Email_EB.sendKeys("9030248855"); } else { System.out.println("Element Not presented at source"); } /* * Verify Element presented at source using try-catch block.. */ try { driver.findElement(By.cssSelector("input[data-testid='royal_emai']")); System.out.println("Element presented at source"); } catch (NoSuchElementException e) { System.out.println(e.getMessage()); } System.out.println("Completed run"); } }
true
a321c7e5bb579799b18afe8d577592bbe8b25189
Java
pph-zhiyi/app-server
/src/test/java/com/pph/demo/effective/other/entity/stack/Stack.java
UTF-8
1,829
3.421875
3
[]
no_license
package com.pph.demo.effective.other.entity.stack; import java.util.Arrays; import java.util.Collections; import java.util.EmptyStackException; import java.util.List; /** * @author PPH * @date 2019-06-10 18:21 * @description */ public class Stack { // public static final String[] STRINGS_ARR = {}; private static final String[] STRING_DEF = {"Demo", "b", "c"}; // 不可改变 List 的值,否则抛出异常:java.lang.UnsupportedOperationException public static final List<String> STRING_LIST = Collections.unmodifiableList(Arrays.asList(STRING_DEF)); public static final String[] getStringDef() { return STRING_DEF.clone(); } private Object[] elements; private int size; private static final int DEFAULT_INITIAL_CAPACITY = 16; public Stack() { this.elements = new Object[DEFAULT_INITIAL_CAPACITY]; } public void push(Object e) { ensureCapacity(); elements[size++] = e; } public Object pop() { if (size == 0) throw new EmptyStackException(); Object result = elements[size--]; // Eliminate obsolete reference elements[size] = null; return result; } /** * Ensure space for at least one more element. */ private void ensureCapacity() { if (elements.length == size) elements = Arrays.copyOf(elements, 2 * size + 1); } /** * Clone method for class with references to mutable state * * @return */ @Override protected Stack clone() { try { Stack stack = (Stack) super.clone(); stack.elements = elements.clone(); return stack; } catch (CloneNotSupportedException e) { throw new AssertionError(e.getMessage()); } } }
true
45cb06d454157cf016b82b9433895fddc32d844e
Java
Hiteshsukhwani29/Shopkart
/src/main/java/com/example/shopkart/Main3Activity.java
UTF-8
3,817
1.984375
2
[]
no_license
package com.example.shopkart; import android.app.Notification; import android.app.NotificationManager; import android.content.Intent; 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.CardView; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Toast; public class Main3Activity extends AppCompatActivity { private DrawerLayout mDrawerLayout; private ActionBarDrawerToggle mToogle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main3); NotificationManager notificationManager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE); Notification notification= new Notification.Builder(Main3Activity.this) .setContentTitle("Shopkart") .setContentText("Thank you for Downloading the app") .setSmallIcon(R.drawable.thu) .setAutoCancel(true) .build(); notificationManager.notify(4129,notification); CardView cv1, cv2, cv3; mDrawerLayout=(DrawerLayout) findViewById(R.id.ly); mToogle=new ActionBarDrawerToggle(this,mDrawerLayout,R.string.open,R.string.close); mDrawerLayout.addDrawerListener(mToogle); mToogle.syncState(); getSupportActionBar().setDisplayHomeAsUpEnabled(true); cv1 = findViewById(R.id.card_view4); cv3 = findViewById(R.id.card_view2); cv1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openActivity(); } }); cv2 = findViewById(R.id.card_view5); cv2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openActivity2(); } }); cv3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openActivity3(); } }); } public void openActivity() { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); finish(); } public void openActivity2() { Intent intent = new Intent(this, Main5Activity.class); startActivity(intent); finish(); } public void openActivity3() { Intent intent = new Intent(this, Main4Activity.class); startActivity(intent); finish(); } @Override public boolean onCreateOptionsMenu (Menu menu){ MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.abc, menu); return true; } @Override public boolean onOptionsItemSelected (MenuItem item){ if(mToogle.onOptionsItemSelected(item)){ return true; } switch (item.getItemId()) { case R.id.item3: Intent intent3 = new Intent(this, MainActivity.class); startActivity(intent3); return true; case R.id.item4: Intent intent1 = new Intent(this, Main4Activity.class); startActivity(intent1); return true; case R.id.item5: Intent intent2 = new Intent(this, Main5Activity.class); startActivity(intent2); return true; default: return super.onOptionsItemSelected(item); } } }
true
a588d05e3ed6a431be8e402780b762e371ae7b6f
Java
It-fang/Optimize
/TeacherAppointmentSystem/src/com/itfang/www/ui/BaseServlet.java
UTF-8
3,356
2.53125
3
[]
no_license
package com.itfang.www.ui; import com.fasterxml.jackson.databind.ObjectMapper; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * @Description: 用于对servlet共用的方法进行抽取 * @Author: it-fang * @Date: 2019-04-29 */ public class BaseServlet extends HttpServlet { /** * @Description: 用于对用户请求的方法进行分发与执行 * @Param: [request, response] * @return: void * @Date: 2019-04-29 */ @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置编码格式为UTF-8 request.setCharacterEncoding("utf-8"); // 获取请求的路径 String uri = request.getRequestURI(); // 获取请求的方法名称 String requestName = uri.substring(uri.lastIndexOf('/')+ 1); try { // 获取方法的对象 Method method = this.getClass().getMethod(requestName , HttpServletRequest.class , HttpServletResponse.class); // 执行这个方法 Object invokeResponse = method.invoke(this, request, response); if(requestName.contains("queryTeacher")){ request.getRequestDispatcher("/queryteacher.jsp").forward(request,response); return; } if (requestName.contains("toApply")){ response.sendRedirect("/TeacherAppointmentSystem_war_exploded/application.jsp"); return; } if(requestName.contains("queryApplication")){ request.getRequestDispatcher("/queryapplication.jsp").forward(request,response); return; } if (requestName.contains("toAgree")){ request.getRequestDispatcher("/agree.jsp").forward(request,response); return; } if (requestName.contains("toModify")){ request.getRequestDispatcher("/modify.jsp").forward(request,response); return; } if (requestName.contains("queryRegister")){ request.getRequestDispatcher("/queryregister.jsp").forward(request,response); return; } if (requestName.contains("studentEnterChatRoom") || requestName.contains("teacherEnterChatRoom")){ response.sendRedirect("/TeacherAppointmentSystem_war_exploded/chatroom.jsp"); return; } if (requestName.contains("checkDetail")){ response.sendRedirect("/TeacherAppointmentSystem_war_exploded/checkdetail.jsp"); return; } ObjectMapper objectMapper = new ObjectMapper(); // 设置编码格式 response.setContentType("application/json;charset=utf-8"); // 将数据传回客户端 objectMapper.writeValue( response.getOutputStream(), invokeResponse); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } }
true
1219d6302daee2f35c547fdc52013e9dff8a504e
Java
jmrives/Zillow
/src/main/java/com/spiral/zillow/formatter/XmlFormatter.java
UTF-8
521
2.484375
2
[]
no_license
package com.spiral.zillow.formatter; public abstract class XmlFormatter { private int indentation; public XmlFormatter(int indentation) { this.indentation = indentation; } public abstract String format(String xml); public String format(String xml, int indentation) { setIndentation(indentation); return format(xml); } protected int getIndentation() { return indentation; } protected void setIndentation(int indentation) { this.indentation = indentation; } }
true
30a9dfa31d9f8cce8aac7a5970ae02586582c6df
Java
prameshmca5/javatestprog
/src/main/java/com/ramesh/springboot/designpattern/Prototype/PrototypeDesignPattern.java
UTF-8
1,023
3.84375
4
[]
no_license
package com.ramesh.springboot.designpattern.Prototype; public class PrototypeDesignPattern { public static void main(String[] args) throws CloneNotSupportedException { System.out.println("***Prototype Pattern Demo***\n"); BasicCar nano = new NanoCar(); nano.setModelName("Nano Car"); nano.basePrice=100000; BasicCar maruthi = new MaruthiCar(); maruthi.setModelName("Maruthi Car"); maruthi.basePrice=50000; BasicCar bc1; bc1 =nano.clone(); System.out.println(nano.getModelName()); bc1.onRoadPrice = nano.basePrice+BasicCar.setAdditionalPrice(); System.out.println("Car is: "+ bc1.modelName+" and it's price is Rs."+bc1.onRoadPrice); BasicCar bc2; bc2 = maruthi.clone(); System.out.println(maruthi.getModelName()); bc2.onRoadPrice = maruthi.basePrice+BasicCar.setAdditionalPrice(); System.out.println("Car is: "+ bc2.modelName+" and it's price is Rs."+bc2.onRoadPrice); } }
true
0dd6d25d43ce6d4a4881d51bd6543f508bb71f04
Java
BrotherJ/texture
/src/texture/client/TextureParam.java
GB18030
12,112
1.671875
2
[]
no_license
package texture.client; import java.util.List; import texture.domain.Material; public class TextureParam { public TextureParam(){ } public TextureParam(String zcz, String luhao, Double zc, Double zsi, Double zmn, Double zp, Double zs, Double zcr, Double zni, Double zmo, Double zcu, Double zv, Double zal, Double znb, Double zw, Double zzn, Double zti, Double zzr, Double zn, Double zta1, Double zfe, Double zb, Double zsn, Double zsb, Double zas, Double co,Double zzfe,Double zca,Double zh,Double zo, Double zta,Double zts, Double zys, Double ze, Double zr, Double zhb, String zj, String zj1, String zj2, String vt, String pt, String mt, String rt, String ut, String temper1, String time1, String temper2, String time2, String temper3, String time3, String temper4, String time4, String cj, String cj_avg, String cj_min, String furn1,String furn2,String furn3,String pren,String ce,String userAccount,String supplier_code,List<Material> materials, Double gts,Double gys,Double ge,Double gr,String zgwls) { super(); this.zcz = zcz; this.luhao = luhao; this.zc = zc; this.zsi = zsi; this.zmn = zmn; this.zp = zp; this.zs = zs; this.zcr = zcr; this.zni = zni; this.zmo = zmo; this.zcu = zcu; this.zv = zv; this.zal = zal; this.znb = znb; this.zw = zw; this.zzn = zzn; this.zti = zti; this.zzr = zzr; this.zn = zn; this.zta1 = zta1; this.zfe = zfe; this.zb = zb; this.zsn = zsn; this.zsb = zsb; this.zas = zas; this.co = co; this.zzfe=zzfe; this.zca=zca; this.zh=zh; this.zo=zo; this.zta=zta; this.zts = zts; this.zys = zys; this.ze = ze; this.zr = zr; this.zhb = zhb; this.zj = zj; this.zj1 = zj1; this.zj2 = zj2; this.vt = vt; this.pt = pt; this.mt = mt; this.rt = rt; this.ut = ut; this.temper1 = temper1; this.time1 = time1; this.temper2 = temper2; this.time2 = time2; this.temper3 = temper3; this.time3 = time3; this.temper4 = temper4; this.time4 = time4; this.cj = cj; this.cj_avg = cj_avg; this.cj_min = cj_min; this.furn1 = furn1; this.furn2 = furn2; this.furn3 = furn3; this.pren =pren; this.ce =ce; this.userAccount = userAccount; this.supplier_code=supplier_code; this.materials=materials; this.gts=gts; this.gys=gys; this.ge=ge; this.gr=gr; this.zgwls=zgwls; } /****/ private String zcz; /**¯**/ private String luhao; /**̼**/ private Double zc; /**躬**/ private Double zsi; /**̺**/ private Double zmn; /**׺**/ private Double zp; /****/ private Double zs; /****/ private Double zcr; /****/ private Double zni; /**⺬**/ private Double zmo; /**ͭ**/ private Double zcu; /****/ private Double zv; /****/ private Double zal; /**꺬**/ private Double znb; /**ٺ**/ private Double zw; /**п**/ private Double zzn; /**Ѻ**/ private Double zti; /**ﯺ**/ private Double zzr; /****/ private Double zn; /**Cb/Nb+Ta**/ private Double zta1; /****/ private Double zfe; /****/ private Double zb; /****/ private Double zsn; /**ຬ**/ private Double zsb; /**麬**/ private Double zas; /**ܺ**/ private Double co; /****/ private Double zzfe; /**Ԫ**/ private Double zca; /**Ԫ**/ private Double zh; /**Ԫ**/ private Double zo; /**Ԫ**/ private Double zta; /****/ private Double zts; /****/ private Double zys; /****/ private Double ze; /****/ private Double zr; /**Ӳ**/ private Double zhb; /**ֵ**/ private String zj; /**ֵ1**/ private String zj1; /**ֵ2**/ private String zj2; /****/ private Double gts; /****/ private Double gys; /****/ private Double ge; /**½**/ private Double gr; /**¶**/ private String zgwls; /**vt**/ private String vt; /**pt**/ private String pt; /**mt**/ private String mt; /**rt**/ private String rt; /**ut**/ private String ut; /**¶1**/ private String temper1; /**ʱ1**/ private String time1; /**¶2**/ private String temper2; /**ʱ2**/ private String time2; /**¶3**/ private String temper3; /**ʱ3**/ private String time3; /**¶4**/ private String temper4; /**ʱ4**/ private String time4; /**¶**/ private String cj; /**ƽֵ **/ private String cj_avg; /**Сֵ **/ private String cj_min; /**¯1**/ private String furn1; /**¯2**/ private String furn2; /**¯3**/ private String furn3; /**prenֵ**/ private String pren; /**̼CE**/ private String ce; /**û˺**/ private String userAccount; /**Ӧ̴**/ private String supplier_code; /**嵥--ڴű֤غϢ**/ private List<Material>materials; public String getPren() { return pren; } public void setPren(String pren) { this.pren = pren; } public String getZcz() { return zcz; } public void setZcz(String zcz) { this.zcz = zcz; } public String getLuhao() { return luhao; } public void setLuhao(String luhao) { this.luhao = luhao; } public Double getZc() { return zc; } public void setZc(Double zc) { this.zc = zc; } public Double getZsi() { return zsi; } public void setZsi(Double zsi) { this.zsi = zsi; } public Double getZmn() { return zmn; } public void setZmn(Double zmn) { this.zmn = zmn; } public Double getZp() { return zp; } public void setZp(Double zp) { this.zp = zp; } public Double getZs() { return zs; } public void setZs(Double zs) { this.zs = zs; } public Double getZcr() { return zcr; } public void setZcr(Double zcr) { this.zcr = zcr; } public Double getZni() { return zni; } public void setZni(Double zni) { this.zni = zni; } public Double getZmo() { return zmo; } public void setZmo(Double zmo) { this.zmo = zmo; } public Double getZcu() { return zcu; } public void setZcu(Double zcu) { this.zcu = zcu; } public Double getZv() { return zv; } public void setZv(Double zv) { this.zv = zv; } public Double getZal() { return zal; } public void setZal(Double zal) { this.zal = zal; } public Double getZnb() { return znb; } public void setZnb(Double znb) { this.znb = znb; } public Double getZw() { return zw; } public void setZw(Double zw) { this.zw = zw; } public Double getZzn() { return zzn; } public void setZzn(Double zzn) { this.zzn = zzn; } public Double getZti() { return zti; } public void setZti(Double zti) { this.zti = zti; } public Double getZzr() { return zzr; } public void setZzr(Double zzr) { this.zzr = zzr; } public Double getZn() { return zn; } public void setZn(Double zn) { this.zn = zn; } public Double getZta1() { return zta1; } public void setZta1(Double zta1) { this.zta1 = zta1; } public Double getZfe() { return zfe; } public void setZfe(Double zfe) { this.zfe = zfe; } public Double getZb() { return zb; } public void setZb(Double zb) { this.zb = zb; } public Double getZsn() { return zsn; } public void setZsn(Double zsn) { this.zsn = zsn; } public Double getZsb() { return zsb; } public void setZsb(Double zsb) { this.zsb = zsb; } public Double getZas() { return zas; } public void setZas(Double zas) { this.zas = zas; } public Double getCo() { return co; } public void setCo(Double co) { this.co = co; } public Double getZts() { return zts; } public void setZts(Double zts) { this.zts = zts; } public Double getZys() { return zys; } public void setZys(Double zys) { this.zys = zys; } public Double getZe() { return ze; } public void setZe(Double ze) { this.ze = ze; } public Double getZr() { return zr; } public void setZr(Double zr) { this.zr = zr; } public Double getZhb() { return zhb; } public void setZhb(Double zhb) { this.zhb = zhb; } public String getZj() { return zj; } public void setZj(String zj) { this.zj = zj; } public String getZj1() { return zj1; } public void setZj1(String zj1) { this.zj1 = zj1; } public String getZj2() { return zj2; } public void setZj2(String zj2) { this.zj2 = zj2; } public String getVt() { return vt; } public void setVt(String vt) { this.vt = vt; } public String getPt() { return pt; } public void setPt(String pt) { this.pt = pt; } public String getMt() { return mt; } public void setMt(String mt) { this.mt = mt; } public String getRt() { return rt; } public void setRt(String rt) { this.rt = rt; } public String getUt() { return ut; } public void setUt(String ut) { this.ut = ut; } public String getTemper1() { return temper1; } public void setTemper1(String temper1) { this.temper1 = temper1; } public String getTime1() { return time1; } public void setTime1(String time1) { this.time1 = time1; } public String getTemper2() { return temper2; } public void setTemper2(String temper2) { this.temper2 = temper2; } public String getTime2() { return time2; } public void setTime2(String time2) { this.time2 = time2; } public String getTemper3() { return temper3; } public void setTemper3(String temper3) { this.temper3 = temper3; } public String getTime3() { return time3; } public void setTime3(String time3) { this.time3 = time3; } public String getTemper4() { return temper4; } public void setTemper4(String temper4) { this.temper4 = temper4; } public String getTime4() { return time4; } public void setTime4(String time4) { this.time4 = time4; } public String getCj() { return cj; } public void setCj(String cj) { this.cj = cj; } public String getCj_avg() { return cj_avg; } public void setCj_avg(String cj_avg) { this.cj_avg = cj_avg; } public String getCj_min() { return cj_min; } public void setCj_min(String cj_min) { this.cj_min = cj_min; } public String getFurn1() { return furn1; } public void setFurn1(String furn1) { this.furn1 = furn1; } public String getUserAccount() { return userAccount; } public void setUserAccount(String userAccount) { this.userAccount = userAccount; } public String getFurn2() { return furn2; } public void setFurn2(String furn2) { this.furn2 = furn2; } public String getFurn3() { return furn3; } public void setFurn3(String furn3) { this.furn3 = furn3; } public String getSupplier_code() { return supplier_code; } public void setSupplier_code(String supplier_code) { this.supplier_code = supplier_code; } public List<Material> getMaterials() { return materials; } public void setMaterials(List<Material> materials) { this.materials = materials; } public Double getZzfe() { return zzfe; } public void setZzfe(Double zzfe) { this.zzfe = zzfe; } public Double getZca() { return zca; } public void setZca(Double zca) { this.zca = zca; } public Double getZh() { return zh; } public void setZh(Double zh) { this.zh = zh; } public Double getZo() { return zo; } public void setZo(Double zo) { this.zo = zo; } public Double getZta() { return zta; } public void setZta(Double zta) { this.zta = zta; } public String getCe() { return ce; } public void setCe(String ce) { this.ce = ce; } public Double getGts() { return gts; } public void setGts(Double gts) { this.gts = gts; } public Double getGys() { return gys; } public void setGys(Double gys) { this.gys = gys; } public Double getGe() { return ge; } public void setGe(Double ge) { this.ge = ge; } public Double getGr() { return gr; } public void setGr(Double gr) { this.gr = gr; } public String getZgwls() { return zgwls; } public void setZgwls(String zgwls) { this.zgwls = zgwls; } }
true
6058ff68f611dcb5ec8135bcd57ae8eba2327d99
Java
Harry12901/OOP_PROJECT
/Controller.java
UTF-8
16,112
3.125
3
[]
no_license
import java.util.ArrayList; import java.util.Scanner; public class Controller { // //ARRAY LIST: static ArrayList<Road> Roads = new ArrayList<>(); static ArrayList<Junction> Junctions = new ArrayList<>(); static ArrayList<Traffic_Police> TrafficPolice = new ArrayList<>(); static ArrayList<Police_Station> PoliceStations = new ArrayList<>(); //RETURN FUNCTIONS - checks if the required object exists public static Road return_road(int RID){ for(int i=0;i<Roads.size();i++){ if(RID == Roads.get(i).RoadId){ return Roads.get(i); } } return null; } public static Junction return_jn(int JID){ for(int i=0;i<Junctions.size();i++){ if(JID == Junctions.get(i).JunctionID){ return Junctions.get(i); } } return null; } public static Traffic_Police return_police(Police_Station ps, int PID){ ArrayList<Traffic_Police> TrafficPolice = ps.Personnel; for(int i=0;i<TrafficPolice.size();i++){ if(PID == TrafficPolice.get(i).PoliceID){ return TrafficPolice.get(i); } } return null; } public static Police_Station return_police_station(int SID){ for(int i=0;i<PoliceStations.size();i++){ if(SID == PoliceStations.get(i).StationID){ return PoliceStations.get(i); } } return null; } public static int return_police_station_index(int SID){ for(int i=0;i<PoliceStations.size();i++){ if(SID == PoliceStations.get(i).StationID){ return i; } } return -1; } //ADD: public static void addRoad(int RID,String Name,double Length){ Roads.add(new Road(RID,Name,Length)); } public static void addJunction(int JID, String Name,String Type, ArrayList<Road> conn_roads){ Junctions.add(new Junction(JID,Name,Type,conn_roads)); } public static Traffic_Police addPolice(int PID,String Name,int age,int salary,int yoe,String address){ return new Traffic_Police(PID,Name,age,salary,yoe,address); } public static void addPoliceStation(int SID,String Name,ArrayList<Traffic_Police> police,ArrayList<Junction> junctions,int pinCode){ PoliceStations.add(new Police_Station(SID,Name,police,junctions,pinCode)); } public static void addPolice1(Police_Station ps,int i, int PID,String pName,int age, int salary,int yoe,String address){ PoliceStations.remove(ps); ps.Personnel.add(new Traffic_Police(PID,pName,age,salary,yoe,address)); PoliceStations.add(i,ps); } //DISPLAY public static void listJunctions(){ System.out.println("--------------------------"); System.out.println(); System.out.println("List of Junctions : \n"); for(int i = 0;i<Junctions.size();i++){ System.out.print("Junction ID : "); System.out.println(Junctions.get(i).JunctionID); System.out.print("Junction Name : "); System.out.println(Junctions.get(i).JunctionName); System.out.print("Junction Type : "); System.out.println(Junctions.get(i).JunctionType); System.out.println(); } System.out.println("--------------------------"); } public static void listRoads(){ System.out.println("--------------------------"); System.out.println(); System.out.println("List of Roads : \n"); for(int i = 0;i<Roads.size();i++){ System.out.print("Road ID : "); System.out.println(Roads.get(i).RoadId); System.out.print("Road Name : "); System.out.println(Roads.get(i).RoadName); System.out.print("Road Length : "); System.out.println(Roads.get(i).Length); System.out.println(); } System.out.println("--------------------------"); } public static void listStations(){ System.out.println("--------------------------"); System.out.println(); System.out.println("List of Police Stations : \n"); for(int i = 0;i<PoliceStations.size();i++){ System.out.print("Police Station ID : "); System.out.println(PoliceStations.get(i).StationID); System.out.print("Name : "); System.out.println(PoliceStations.get(i).StationName); System.out.println(); } System.out.println("--------------------------"); } public static void listPolice(int SID){ Police_Station PS = return_police_station(SID); if(PS == null){ System.err.println("Station Does Not Exist"); } else { for(int i =0;i<PS.Personnel.size();i++){ System.out.print("Police ID : "); System.out.println(PS.Personnel.get(i).PoliceID); System.out.print("Police Name : "); System.out.println(PS.Personnel.get(i).Name); System.out.println(); } } System.out.println("--------------------------"); } //DELETE public static void deleteRoad(Road rd){ Roads.remove(rd); System.out.println("Road Successfully deleted"); } public static void deleteJunction(Junction jn){ Junctions.remove(jn); System.out.println("Junction Successfully deleted"); } public static void deletePoliceStation(Police_Station ps){ PoliceStations.remove(ps); System.out.println("Police Station Successfully deleted"); } public static void deletePolice(Police_Station ps,int i, Traffic_Police police){ PoliceStations.remove(ps); ps.Personnel.remove(police); PoliceStations.add(i, ps); } //public static void deletePolice(){ // System.out.println("--------------------------"); // System.out.println(); // Scanner input = new Scanner(System.in); // System.out.print("Enter Police Station ID : "); // int SID = input.nextInt(); // Police_Station ps = return_police_station(SID); // if(ps == null){ // System.err.println("Police Station does not exist"); // } // else{ // System.out.println("Enter Police ID : "); // int pid = input.nextInt(); // Traffic_Police police = return_police(ps,pid); // if(police == null){ // System.out.println("Traffic Police does not exist"); // } // else{ // ps.Personnel.remove(police); // } // System.out.println("Police Successfully deleted"); // } // System.out.println(); // System.out.println("--------------------------"); // // input.close(); // //} // //ARRAY LIST static ArrayList<Logs> log = new ArrayList<>(); static ArrayList<AccidentLog> alog = new ArrayList<>(); static ArrayList<TrafficViolationLog> vlog = new ArrayList<>(); static ArrayList<Vehicle> vehicle = new ArrayList<>(); //RETURN FUNCTIONS - checks if the required object exists public static Logs return_log(int LID){ for(int i=0;i<log.size();i++){ if(LID == log.get(i).LogID){ return log.get(i); } } return null; } public static AccidentLog return_accident(int AID){ for(int i=0;i<alog.size();i++){ if(AID == alog.get(i).AccID){ return alog.get(i); } } return null; } public static TrafficViolationLog return_violation(int VID){ for(int i=0;i<vlog.size();i++){ if(VID == vlog.get(i).VID){ return vlog.get(i); } } return null; } public static Vehicle return_vehicle(String regno){ for(int i=0;i<vehicle.size();i++){ if(regno.equals(vehicle.get(i).Regno) ){ return vehicle.get(i); } } return null; } //ADD: public static void addVehicle(String name,String regno) { vehicle.add(new Vehicle(regno,name)); } public static void addViolation(int VID,double penalty,String reason,String regno,double speed,int RID,int PID,int SID){ vlog.add(new TrafficViolationLog(VID,penalty,reason,regno,speed,RID,PID,SID,"Violation")); } public static void addAccident(int AID,String damage,String reason,int ni,int nov,ArrayList<String> vehicles,int RID,int PID,int SID){ alog.add(new AccidentLog(AID,damage,reason,ni,nov,vehicles,RID,PID,SID,"Accident")); } //DISPLAY: public static void listVehicle(){ System.out.println("--------------------------"); System.out.println(); System.out.println("List of Vehicles : \n"); for(int i = 0;i<vehicle.size();i++){ System.out.print("Regno : "); System.out.println(vehicle.get(i).Regno); System.out.print("Name : "); System.out.println(vehicle.get(i).Name); } System.out.println("--------------------------"); } public static void listViolation(){ System.out.println("--------------------------"); System.out.println(); System.out.println("List of Violations : \n"); for(int i = 0;i<vlog.size();i++){ System.out.print("Violation ID : "); System.out.println(vlog.get(i).VID); System.out.print("Registration Number : "); System.out.println(vlog.get(i).regno); System.out.print("Reason : "); System.out.println(vlog.get(i).Reason); System.out.print("Speed : "); System.out.println(vlog.get(i).speed); System.out.print("Penalty amount : "); System.out.println(vlog.get(i).PenaltyAmount); System.out.print("Road ID : "); System.out.println(vlog.get(i).RoadID); System.out.print("Police ID : "); System.out.println(vlog.get(i).PoliceID); System.out.print("Station ID : "); System.out.println(vlog.get(i).StationID); System.out.print("Date : "); System.out.println(vlog.get(i).date); System.out.print("Time : "); System.out.println(vlog.get(i).time); System.out.println(); } System.out.println("--------------------------"); } public static void listAccident(){ System.out.println("--------------------------"); System.out.println(); System.out.println("List of Accidents : \n"); for(int i = 0;i<alog.size();i++){ System.out.print("Accident ID : "); System.out.println(alog.get(i).AccID); System.out.print("Number of people injured : "); System.out.println(alog.get(i).NoofPersonsInjured); System.out.print("Damage Caused : "); System.out.println(alog.get(i).DamageCaused); System.out.print("Reason for the accident : "); System.out.println(alog.get(i).AccReason); System.out.print("Number of Vehicles involved : "); System.out.println(alog.get(i).NoofVehicles); System.out.print("Vehicles involved : "); System.out.println(alog.get(i).regnos); System.out.print("Road ID : "); System.out.println(alog.get(i).RoadID); System.out.print("Police ID : "); System.out.println(alog.get(i).PoliceID); System.out.print("Station ID : "); System.out.println(alog.get(i).StationID); System.out.print("Date : "); System.out.println(alog.get(i).date); System.out.print("Time : "); System.out.println(alog.get(i).time); System.out.println(); } System.out.println("--------------------------"); } //DELETE public static void deleteVehicle(Vehicle v) { vehicle.remove(v); System.out.println("Vehicle Successfully deleted"); System.out.println(); System.out.println("--------------------------"); } public static void deleteViolation(){ System.out.println("--------------------------"); System.out.println(); Scanner input = new Scanner(System.in); System.out.print("Enter Violation ID : "); int VID = input.nextInt(); //input.close(); TrafficViolationLog v = return_violation(VID); Logs l = return_log(VID); if(v == null){ System.err.println("Violation log does not exist"); } else{ vlog.remove(v); log.remove(l); System.out.println("Violation Successfully deleted"); } // if(l == null){ // System.err.println("Log does not exist"); // } // else{ // log.remove(l); // System.out.println("Log Successfully deleted"); // } // System.out.println(); System.out.println("--------------------------"); } public static void deleteAccident(int AID){ AccidentLog a = return_accident(AID); Logs l = return_log(AID); if(a == null){ System.err.println("Accident log does not exist"); } else{ alog.remove(a); log.remove(l); System.out.println("Accident log Successfully deleted"); } // if(l == null){ // System.err.println("Log does not exist"); // } // else{ // log.remove(l); // System.out.println("Log Successfully deleted"); // } System.out.println(); System.out.println("--------------------------"); } //CHECK VIOLATION AND PENALTY PAY public static void CheckViolation(String reg){ Scanner input = new Scanner(System.in); int flag=0; for(int i = 0;i<vlog.size();i++){ if(reg.equals(vlog.get(i).regno) ) { System.out.print("Violation ID : "); System.out.println(vlog.get(i).VID); System.out.print("Registration Number : "); System.out.println(vlog.get(i).regno); System.out.print("Reason : "); System.out.println(vlog.get(i).Reason); System.out.print("Speed : "); System.out.println(vlog.get(i).speed); System.out.print("Penalty amount : "); System.out.println(vlog.get(i).PenaltyAmount); System.out.print("Road ID : "); System.out.println(vlog.get(i).RoadID); System.out.print("Police ID : "); System.out.println(vlog.get(i).PoliceID); System.out.print("Station ID : "); System.out.println(vlog.get(i).StationID); System.out.print("Date : "); System.out.println(vlog.get(i).date); System.out.print("Time : "); System.out.println(vlog.get(i).time); System.out.println("--------------------------"); System.out.println("Pay Penalty (y/n) :"); String inp = input.next(); if(inp.equals("y")) { deleteViolation(); System.out.println("Penalty removed"); } System.out.println(); flag=1; } } if(flag==0) { System.out.println("No Violation record found"); } System.out.println("--------------------------"); } }
true
15ea180faaa1ab1cde5b8bb02283528ecd5a80f3
Java
amalatesta/OAFramework
/tutorial/jdevhome/jdev/myprojects/oracle/apps/fnd/framework/toolbox/samplelib/server/PurchaseOrderHeadersVORowImpl.java
UTF-8
5,025
1.78125
2
[]
no_license
/*===========================================================================+ | Copyright (c) 2001 Oracle Corporation, Redwood Shores, CA, USA | | All rights reserved. | +===========================================================================+ | HISTORY | +===========================================================================*/ // javadoc_private package oracle.apps.fnd.framework.toolbox.samplelib.server; import oracle.jbo.domain.Number; import oracle.jbo.server.AttributeDefImpl; import oracle.apps.fnd.common.VersionInfo; import oracle.apps.fnd.framework.server.OAViewRowImpl; public class PurchaseOrderHeadersVORowImpl extends OAViewRowImpl { public static final int HEADERID = 0; public static final String RCS_ID="$Header: PurchaseOrderHeadersVORowImpl.java 120.2 2006/07/03 17:20:08 atgops1 noship $"; public static final boolean RCS_ID_RECORDED = VersionInfo.recordClassVersion(RCS_ID, "oracle.apps.fnd.framework.toolbox.samplelib.server"); public static final int DESCRIPTION = 1; public static final int STATUSCODE = 2; public static final int SUPPLIERID = 3; public static final int SUPPLIERSITEID = 4; /** * * This is the default constructor (do not remove) */ public PurchaseOrderHeadersVORowImpl() { } /** * * Gets PurchaseOrderHeaderEO entity object. */ public oracle.apps.fnd.framework.toolbox.schema.server.PurchaseOrderHeaderEOImpl getPurchaseOrderHeaderEO() { return (oracle.apps.fnd.framework.toolbox.schema.server.PurchaseOrderHeaderEOImpl)getEntity(0); } /** * * Gets the attribute value for HEADER_ID using the alias name HeaderId */ public Number getHeaderId() { return (Number)getAttributeInternal(HEADERID); } /** * * Sets <code>value</code> as attribute value for HEADER_ID using the alias name HeaderId */ public void setHeaderId(Number value) { setAttributeInternal(HEADERID, value); } /** * * Gets the attribute value for DESCRIPTION using the alias name Description */ public String getDescription() { return (String)getAttributeInternal(DESCRIPTION); } /** * * Sets <code>value</code> as attribute value for DESCRIPTION using the alias name Description */ public void setDescription(String value) { setAttributeInternal(DESCRIPTION, value); } /** * * Gets the attribute value for STATUS_CODE using the alias name StatusCode */ public String getStatusCode() { return (String)getAttributeInternal(STATUSCODE); } /** * * Sets <code>value</code> as attribute value for STATUS_CODE using the alias name StatusCode */ public void setStatusCode(String value) { setAttributeInternal(STATUSCODE, value); } /** * * Gets the attribute value for SUPPLIER_ID using the alias name SupplierId */ public Number getSupplierId() { return (Number)getAttributeInternal(SUPPLIERID); } /** * * Sets <code>value</code> as attribute value for SUPPLIER_ID using the alias name SupplierId */ public void setSupplierId(Number value) { setAttributeInternal(SUPPLIERID, value); } /** * * Gets the attribute value for SUPPLIER_SITE_ID using the alias name SupplierSiteId */ public Number getSupplierSiteId() { return (Number)getAttributeInternal(SUPPLIERSITEID); } /** * * Sets <code>value</code> as attribute value for SUPPLIER_SITE_ID using the alias name SupplierSiteId */ public void setSupplierSiteId(Number value) { setAttributeInternal(SUPPLIERSITEID, value); } // Generated method. Do not modify. protected Object getAttrInvokeAccessor(int index, AttributeDefImpl attrDef) throws Exception { switch (index) { case HEADERID: return getHeaderId(); case DESCRIPTION: return getDescription(); case STATUSCODE: return getStatusCode(); case SUPPLIERID: return getSupplierId(); case SUPPLIERSITEID: return getSupplierSiteId(); default: return super.getAttrInvokeAccessor(index, attrDef); } } // Generated method. Do not modify. protected void setAttrInvokeAccessor(int index, Object value, AttributeDefImpl attrDef) throws Exception { switch (index) { case HEADERID: setHeaderId((Number)value); return; case DESCRIPTION: setDescription((String)value); return; case STATUSCODE: setStatusCode((String)value); return; case SUPPLIERID: setSupplierId((Number)value); return; case SUPPLIERSITEID: setSupplierSiteId((Number)value); return; default: super.setAttrInvokeAccessor(index, value, attrDef); return; } } }
true
b263c57c9d6b45059c0171596915798fbde84401
Java
beomhyun/homework
/hw_algo_08/hwalgo08.java
UTF-8
1,708
3.15625
3
[]
no_license
package hwalgo08_3반_김범현; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; public class hwalgo08 { public static Node nn = null; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); for (int test = 1; test <= 10; test++) { int N = Integer.parseInt(br.readLine()); boolean check = true; for (int i = 0; i < N; i++) { String str = br.readLine(); StringTokenizer st = new StringTokenizer(str); int a = Integer.parseInt(st.nextToken()); char c = st.nextToken().charAt(0); if((c <48 || c > 57)) { if(!st.hasMoreTokens()) { check = false; } }else { if(st.hasMoreTokens()) { check = false; } } } if(check == true) { System.out.println("#"+test+" 1"); }else { System.out.println("#"+test+" 0"); } } } public static void addNode(Node node,int d,Node son) { if(node.data == d){ if(node.left ==null) { node.left = son; return; }else if(node.right == null) { node.right = son; return; } }else { if(node.left!=null) { addNode(node.left,d,son); } if(node.right!=null) { addNode(node.right,d,son); } } } public static void find(Node node, int index) { if(node.index == index) { nn= node; return; }else { if(node.left!= null) { find(node.left, index); } if(node.right!= null) { find(node.right,index); } } } } class Node { int index; char data; Node left; Node right; public Node(int index, char data) { this.data = data; } }
true
4c771e29fb54767c323723404c8010a2241f3022
Java
lovehoroscoper/multi-engine
/src/main/java/com/baidu/unbiz/multiengine/endpoint/EndpointPool.java
UTF-8
4,291
2.234375
2
[ "Apache-2.0" ]
permissive
package com.baidu.unbiz.multiengine.endpoint; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.collections.CollectionUtils; import org.slf4j.Logger; import org.springframework.util.Assert; import com.baidu.unbiz.multiengine.exception.MultiEngineException; import com.baidu.unbiz.multiengine.transport.client.TaskClient; import com.baidu.unbiz.multiengine.transport.client.TaskClientFactory; import com.baidu.unbiz.multitask.log.AopLogFactory; /** * Created by wangchongjie on 16/4/14. */ public class EndpointPool { private static final Logger LOG = AopLogFactory.getLogger(EndpointPool.class); private static List<TaskClient> pool = new CopyOnWriteArrayList<TaskClient>(); private static TaskClientFactory clientFactory = new TaskClientFactory(); private static AtomicInteger index = new AtomicInteger(); private static CountDownLatch hasInit = new CountDownLatch(1); private static AtomicBoolean initing = new AtomicBoolean(false); public static void init(List<HostConf> serverList) { if (initing.compareAndSet(false, true)) { doInit(serverList); hasInit.countDown(); } } public static boolean exist(HostConf hostConf) { for (TaskClient taskClient : pool) { if (taskClient.getHostConf().equals(hostConf)) { return true; } } return false; } public static TaskClient find(HostConf hostConf) { for (TaskClient taskClient : pool) { if (taskClient.getHostConf().equals(hostConf)) { return taskClient; } } return null; } public static void beInvalid(List<HostConf> serverList) { for (HostConf hostConf : serverList) { TaskClient taskClient = find(hostConf); if (taskClient == null) { continue; } taskClient.setInvalid(true); } } private static void internalAdd(List<HostConf> serverList) { for (HostConf hostConf : serverList) { if (exist(hostConf)) { continue; } TaskClient endpoint = clientFactory.createTaskClient(hostConf); boolean success = endpoint.start(); endpoint.setInvalid(!success); pool.add(endpoint); } } public static void add(List<HostConf> serverList) { try { hasInit.await(); } catch (InterruptedException e) { // do nothing } internalAdd(serverList); } public static List<HostConf> getTaskHostConf() { List<HostConf> hostConfs = new ArrayList<HostConf>(); for (TaskClient taskServer : pool) { hostConfs.add(taskServer.getHostConf()); } return hostConfs; } private static void doInit(List<HostConf> serverList) { if (CollectionUtils.isEmpty(serverList)) { LOG.error("serverList is empty"); } internalAdd(serverList); } public static void stop() { if (CollectionUtils.isEmpty(pool)) { return; } for (TaskClient client : pool) { client.stop(); } } public static TaskClient selectEndpoint() { return selectEndpoint(pool.size(), true); } private static TaskClient selectEndpoint(int retry, boolean first) { try { hasInit.await(); } catch (InterruptedException e) { LOG.error("select endpoint:", e); } if (retry < 0) { throw new MultiEngineException("select endpoint retry fail"); } Assert.isTrue(pool.size() > 0); int idx = retry; if (first) { idx = index.addAndGet(1); } TaskClient endpoint = pool.get((Math.abs(idx) % pool.size())); if (endpoint.getInvalid().get()) { return selectEndpoint(retry - 1, false); } return endpoint; } public static List<TaskClient> getPool() { return pool; } }
true
4f83ee20b1f4832ad618e07a9a4ba1405fef422e
Java
SimoneBaselicePolimi/ingswAM2021-Baselice-Bagnoli-Brugnano
/src/main/java/it/polimi/ingsw/server/modelrepresentation/gameitemsrepresentation/leadercardrepresentation/ServerDevelopmentCardColourAndLevelRequirementRepresentation.java
UTF-8
1,262
2.5625
3
[]
no_license
package it.polimi.ingsw.server.modelrepresentation.gameitemsrepresentation.leadercardrepresentation; import com.fasterxml.jackson.annotation.JsonProperty; import it.polimi.ingsw.server.model.gameitems.developmentcard.DevelopmentCardColour; import it.polimi.ingsw.server.model.gameitems.developmentcard.DevelopmentCardLevel; public class ServerDevelopmentCardColourAndLevelRequirementRepresentation extends ServerLeaderCardRequirementRepresentation { public final DevelopmentCardColour cardColour; public final DevelopmentCardLevel cardLevel; public final int numberOfCards; /** * DevelopmentCardColourAndLevelRequirementRepresentation constructor * @param cardColour colour of development cards required * @param cardLevel level of development cards required * @param numberOfCards number of development cards required */ public ServerDevelopmentCardColourAndLevelRequirementRepresentation( @JsonProperty("cardColour") DevelopmentCardColour cardColour, @JsonProperty("cardLevel") DevelopmentCardLevel cardLevel, @JsonProperty("numberOfCards") int numberOfCards ) { this.cardColour=cardColour; this.cardLevel=cardLevel; this.numberOfCards=numberOfCards; } }
true
aebb3151b2778ac62a9019db99eae71281970120
Java
GhqstMC/FreeRPG
/src/main/java/mc/carlton/freerpg/gameTools/ActionBarMessages.java
UTF-8
646
2.46875
2
[ "MIT" ]
permissive
package mc.carlton.freerpg.gameTools; import net.md_5.bungee.api.ChatMessageType; import net.md_5.bungee.api.chat.TextComponent; import org.bukkit.entity.Player; public class ActionBarMessages { private Player p; public ActionBarMessages(Player p) { this.p = p; } public void sendMessage(String message) { try { p.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(message)); } catch (NoSuchMethodError e) { //This occurs when using craft bukkit p.sendMessage(message); //In this case, we'll just send the player the message } } }
true
a0af807eb8d6cb9ea41da558b0d9363a5af5f1e6
Java
jimmyfever/Algorithms
/TopInterviews/CopyListWithRandomPointer138.java
UTF-8
1,136
3.65625
4
[]
no_license
import java.util.*; public class CopyListWithRandomPointer138 { public static void main(String[] args){ } class RandomListNode { int label; RandomListNode next, random; RandomListNode(int x) { this.label = x; } } public RandomListNode copy(RandomListNode head){ if(head == null){ return head; } copyNext(head); copyRandom(head); return splitList(head); } private void copyNext(RandomListNode head){ // 1 → 1' → 2 → 2' while(head != null){ RandomListNode newNode = new RandomListNode(head.label); newNode.random = head.random; newNode.next = head.next; head.next = newNode; head = head.next.next; } } private void copyRandom(RandomListNode head){ while(head != null){ if(head.next.random != null){ head.next.random = head.random.next; } head = head.next.next; } } private RandomListNode splitList(RandomListNode head){ RandomListNode newHead = head.next; while(head != null){ RandomListNode tmp = head.next; head.next = tmp.next; head = head.next; if(tmp.next != null){ tmp.next = tmp.next.next; } } return newHead; } }
true
f4b4b9838357137f6d1db048ef6254a4943a5c30
Java
hcen1997/web-car
/java/src/main/java/cc/hcen/model/U.java
UTF-8
115
1.671875
2
[ "MIT" ]
permissive
package cc.hcen.model; public class U { public static String getImg(String img){return C.imgDir+"/"+img;} }
true
0bfb9314b19d8a539671d69b15af431e05b70613
Java
VizPass/vizpass-android
/app/src/main/java/com/google/android/gms/samples/vision/face/facetracker/User.java
UTF-8
560
2.359375
2
[]
no_license
package com.google.android.gms.samples.vision.face.facetracker; /** * Created by jonahchin on 2017-12-02. */ public class User { private String first_name; private String key; private String title; public User(String firstName, String key, String title) { this.first_name = firstName; this.key = key; this.title = title; } public String getFirst_name() { return first_name; } public String getKey() { return key; } public String getTitle() { return title; } }
true
0981bc5f4963b17963ad9fba65ea914d26e0af33
Java
zhiyanglu/LeetCode-Java
/GasStation.java
UTF-8
1,301
3.65625
4
[]
no_license
/** * There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. * You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations. * Return the starting gas station's index if you can travel around the circuit once, otherwise return -1. * @author Lu * */ public class GasStation { public static void main(String[] args) { // TODO Auto-generated method stub } public int canCompleteCircuit(int[] gas, int[] cost) { // write your code here for(int i = 0; i < gas.length; i++){ gas[i] -= cost[i]; } int cur = 0; int start = 0; boolean neg = false; for(int i = 0; i < gas.length * 2; i++){ cur += gas[i % gas.length]; if(cur < 0){ //already tried all the start point and meet the situation that remain gas < 0, fail if(i > gas.length - 1) return -1; //else suppose next index to be the start point start = i + 1; cur = 0; } } return start; } }
true
c504acdfa12d81bae51148081a71da55e8ad2316
Java
lixinye99/Travel
/src/main/java/cn/itcast/travel/web/servlet/MyFavoriteServlet.java
UTF-8
2,241
2.21875
2
[]
no_license
package cn.itcast.travel.web.servlet; import cn.itcast.travel.domain.Route; import cn.itcast.travel.service.impl.FavoriteService; import cn.itcast.travel.service.impl.RouteDetailService; import com.alibaba.fastjson.JSONObject; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; /** * Create by lixinye */ @WebServlet("/myFavorite") public class MyFavoriteServlet extends HttpServlet { private FavoriteService favoriteService = new FavoriteService(); private RouteDetailService routeDetailService = new RouteDetailService(); @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { int uid = -1; boolean flag = true; JSONObject jsonObject = new JSONObject(); int pageNum = Integer.parseInt(req.getParameter("pageNum")); if(req.getSession().getAttribute("uid")== "" || req.getSession().getAttribute("uid") == null ){ jsonObject.put("unlogin","你还没有登录!快去进行登录吧!"); flag = false; }else{ uid = Integer.parseInt(req.getSession().getAttribute("uid").toString()); } int pageCount = favoriteService.queryPageCount(uid); if(pageCount<pageNum){ jsonObject.put("pageerror","选择页码有误!请检查页码!"); flag = false; }else{ jsonObject.put("pageCount",pageCount); } if(flag) { List<Integer> list = favoriteService.queryByUidAndPageNum(uid, pageNum); List<Route> routeList = routeDetailService.queryByList(list); jsonObject.put("favoriteList",routeList); } resp.setContentType("text/html;charset=utf-8"); resp.setHeader("Cache-Control", "no-cache"); resp.getWriter().write(String.valueOf(jsonObject)); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doGet(req, resp); } }
true
e9e7633659a78149439fa1ee1c80e8a24e0b2c20
Java
zhn-github/next_film
/src/main/java/com/next/zhn/film/dao/mapper/FilmHallFilmInfoTMapper.java
UTF-8
398
1.570313
2
[]
no_license
package com.next.zhn.film.dao.mapper; import com.next.zhn.film.dao.entity.FilmHallFilmInfoT; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.springframework.stereotype.Repository; /** * <p> * 影厅电影信息表 Mapper 接口 * </p> * * @author zhn * @since 2020-03-27 */ @Repository public interface FilmHallFilmInfoTMapper extends BaseMapper<FilmHallFilmInfoT> { }
true
e80f7505fb67de0b05d5bf5b1a66937bb15d471f
Java
yerayfl/MoneyCalculater
/src/Control/CalculateCommand.java
UTF-8
1,706
2.859375
3
[]
no_license
package Control; import Model.Currency; import Model.ExchangeRate; import UserInterface.MoneyDialog; import UserInterface.MoneyViewer; import UserInterface.CurrencyDialog; import Model.Money; import Model.Number; import Persistence.ExchangeRateLoader; import Persistence.FileExchangeRateLoader; public class CalculateCommand extends Command { private final MoneyDialog moneyDialog; private final CurrencyDialog currencyDialog; private final MoneyViewer moneyViewer; public CalculateCommand(MoneyDialog moneyDialog, CurrencyDialog currencyDialog, MoneyViewer moneyViewer) { this.moneyDialog = moneyDialog; this.currencyDialog = currencyDialog; this.moneyViewer = moneyViewer; } @Override public void execute() { moneyViewer.show(new Money(calculateAmount(), currencyDialog.getCurrency())); } private double getExchangeRate() { String file = "C:\\Users\\Yeray\\Documents\\NetBeansProjects\\MoneyCalculator\\ExchangeRate.txt"; if (moneyDialog.getMoney().getCurrency().equals(new Currency("EUR"))) { ExchangeRate change = new FileExchangeRateLoader(file).load(currencyDialog.getCurrency()); return change.getRate(); } else { ExchangeRate change = new FileExchangeRateLoader(file).load(currencyDialog.getCurrency()); change.multirate(new FileExchangeRateLoader(file).load(moneyDialog.getMoney().getCurrency()).getRate()); return change.getRate(); } } private Number calculateAmount() { return (moneyDialog.getMoney().getAmount()).multiplicationNumber(getExchangeRate()); } }
true
f7dc2a112598b8b14ed2f2ed92bc8d195c27d403
Java
RaymondCC123/geo_enrichment_tweet
/src/resources/crf/Corpus.java
UTF-8
2,666
2.671875
3
[]
no_license
/** * */ package crf; /** * Load corpus from files */ import java.io.File; import java.io.IOException; import java.text.ParseException; import edu.cmu.minorthird.text.*; public class Corpus { private MutableTextBase tb; private MutableTextLabels tl; /** * Load a labeled corpus without specified tokenizer(i.e a default regex tokenizer will be * used) * * @param textDir * @param labelDir * @throws IOException * @throws ParseException */ public Corpus(String textDir, String labelDir) throws IOException, ParseException { File textFile = new File(textDir); File labelFile = new File(labelDir); TextBaseLoader tbl = new TextBaseLoader(TextBaseLoader.DOC_PER_FILE); this.tb = tbl.load(textFile); TextLabelsLoader tll = new TextLabelsLoader(); this.tl = tll.loadOps(tb, labelFile); } /** * Load a labeld corpus using a specified tokenizer; in this project, it is recommended to use * crf.TwitterTokenizer * * @param textDir * @param labelDir * @param tok * @throws IOException * @throws ParseException */ public Corpus(String textDir, String labelDir, Tokenizer tok) throws IOException, ParseException { File textFile = new File(textDir); File labelFile = new File(labelDir); TextBaseLoader tbl = new TextBaseLoader(TextBaseLoader.DOC_PER_FILE); this.tb = tbl.load(textFile, tok); TextLabelsLoader tll = new TextLabelsLoader(); this.tl = tll.loadOps(tb, labelFile); } /** * Load an unlabeled corpus, using specified tokenizer * * @param textDir * @param tok * @throws IOException * @throws ParseException */ public Corpus(String textDir, Tokenizer tok) throws IOException, ParseException { File textFile = new File(textDir); TextBaseLoader tbl = new TextBaseLoader(TextBaseLoader.DOC_PER_FILE); this.tb = tbl.load(textFile, tok); this.tl = new BasicTextLabels(tb); } /** * Load an unlabeled corpus without specifying a tokenizer * * @param textDir * @throws IOException * @throws ParseException */ public Corpus(String textDir) throws IOException, ParseException { File textFile = new File(textDir); TextBaseLoader tbl = new TextBaseLoader(TextBaseLoader.DOC_PER_FILE); this.tb = tbl.load(textFile); this.tl = new BasicTextLabels(tb); } public MutableTextBase getTextBase() { return this.tb; } public MutableTextLabels getTextLabels() { return tl; } }
true
37d2b909f8dda478998acfcbbaf75beeeb7a29d1
Java
junzLiu/BaseAndroid2
/src/com/baseandroid/assist/tools/NetUtil.java
UTF-8
4,437
2.6875
3
[]
no_license
package com.baseandroid.assist.tools; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.util.Log; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; /** * net util * Created by Mark on 2015/11/3. */ public class NetUtil { /** * 是否联网 * * @param context * @return true为有联网反之没有联网 */ public static boolean isNetworkAvailable(Context context) { ConnectivityManager mgr = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (mgr != null) { NetworkInfo[] info = mgr.getAllNetworkInfo(); if (info != null) { for (int i = 0; i < info.length; i++) { if (info[i].getState() == NetworkInfo.State.CONNECTED) { return true; } } } } else { return false; } return false; } public static boolean isNetworkConnected(Context context) { if (context != null) { ConnectivityManager mConnectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo(); if (mNetworkInfo != null) { return mNetworkInfo.isAvailable() && mNetworkInfo.isConnected(); } } return false; } public static boolean isWifiConnected(Context context) { if (context != null) { ConnectivityManager mConnectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mWiFiNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (mWiFiNetworkInfo != null) { return mWiFiNetworkInfo.isAvailable() && mWiFiNetworkInfo.isConnected(); } } return false; } public static boolean isMobileConnected(Context context) { if (context != null) { ConnectivityManager mConnectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mMobileNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if (mMobileNetworkInfo != null) { return mMobileNetworkInfo.isAvailable() && mMobileNetworkInfo.isConnected(); } } return false; } public static final boolean ping() { String result = null; try { String ip = "www.baidu.com";// 除非百度挂了,否则用这个应该没问题~ Process p = Runtime.getRuntime().exec("ping -c 3 -w 100 " + ip);// ping3次 // 读取ping的内容,可不加。 InputStream input = p.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(input)); StringBuffer stringBuffer = new StringBuffer(); String content = ""; while ((content = in.readLine()) != null) { stringBuffer.append(content); } Log.i("TTT", "result content : " + stringBuffer.toString()); // PING的状态 int status = p.waitFor(); if (status == 0) { result = "successful~"; return true; } else { result = "failed~ cannot reach the IP address"; } } catch (IOException e) { result = "failed~ IOException"; } catch (InterruptedException e) { result = "failed~ InterruptedException"; } finally { Log.i("TTT", "result = " + result); } return false; } public static int getConnectedType(Context context) { if (context != null) { ConnectivityManager mConnectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo(); if (mNetworkInfo != null && mNetworkInfo.isAvailable()) { return mNetworkInfo.getType(); } } return -1; } }
true
4494418b9ae307148ace404d235d0af99d351e91
Java
TestCodeDZ/CompareCode
/Sistema/SGTMTR/src/sgtmtr/vehiculos.java
UTF-8
43,191
2.171875
2
[]
no_license
/* * 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 sgtmtr; import static claseConectar.ConexionConBaseDatos.conexion; import java.awt.Toolkit; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.Color; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import static sgtmtr.Principal.jdpescritorio; /** * * @author ZuluCorp */ public class vehiculos extends javax.swing.JInternalFrame { ValidarCaracteres validarLetras = new ValidarCaracteres(); bmarcas bm = new bmarcas(); //crear el nuevo formulario bcliente bc = new bcliente(); //crear el nuevo formulario /** * Creates new form vehiculos */ public vehiculos() { initComponents(); setTitle("Mantenedor de Vehículos"); this.setLocation(280, 15); txtnm.setEnabled(false); txtrutdueño.setEnabled(false); mostrardatos(""); anchocolumnas(); bloquear(); } void mostrardatos(String valor) { DefaultTableModel modelo = new DefaultTableModel(); modelo.addColumn("Patente"); modelo.addColumn("Marca"); modelo.addColumn("Modelo"); modelo.addColumn("Año"); modelo.addColumn("Color"); modelo.addColumn("RUT del Dueño"); tbvehiculos.setModel(modelo); String sql = ""; if (valor.equals("")) { sql = "SELECT * FROM vehiculo"; } else { sql = "SELECT * FROM vehiculo WHERE Patente='" + txtpatente.getText() + "'"; } String[] datos = new String[6]; try { conexion = claseConectar.ConexionConBaseDatos.getConexion(); Statement st = conexion.createStatement(); ResultSet rs = st.executeQuery(sql); while (rs.next()) { datos[0] = rs.getString(1); datos[1] = rs.getString(2); datos[2] = rs.getString(3); datos[3] = rs.getString(4); datos[4] = rs.getString(5); datos[5] = rs.getString(6); modelo.addRow(datos); } tbvehiculos.setModel(modelo); //tbvehiculos.setEnabled(false); } catch (Exception e) { JOptionPane.showMessageDialog(this, "Error " + e.getMessage().toString()); } finally { claseConectar.ConexionConBaseDatos.metodoCerrarConexiones(conexion); } } void anchocolumnas() { tbvehiculos.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF); tbvehiculos.getColumnModel().getColumn(0).setWidth(100); tbvehiculos.getColumnModel().getColumn(0).setMaxWidth(100); tbvehiculos.getColumnModel().getColumn(0).setMinWidth(100); tbvehiculos.getColumnModel().getColumn(1).setWidth(100); tbvehiculos.getColumnModel().getColumn(1).setMaxWidth(100); tbvehiculos.getColumnModel().getColumn(1).setMinWidth(100); tbvehiculos.getColumnModel().getColumn(2).setWidth(100); tbvehiculos.getColumnModel().getColumn(2).setMaxWidth(100); tbvehiculos.getColumnModel().getColumn(2).setMinWidth(100); tbvehiculos.getColumnModel().getColumn(3).setWidth(120); tbvehiculos.getColumnModel().getColumn(3).setMaxWidth(120); tbvehiculos.getColumnModel().getColumn(3).setMinWidth(120); tbvehiculos.getColumnModel().getColumn(4).setWidth(90); tbvehiculos.getColumnModel().getColumn(4).setMaxWidth(90); tbvehiculos.getColumnModel().getColumn(4).setMinWidth(90); tbvehiculos.getColumnModel().getColumn(5).setWidth(200); tbvehiculos.getColumnModel().getColumn(5).setMaxWidth(200); tbvehiculos.getColumnModel().getColumn(5).setMinWidth(200); } private String validarVacios() { String errores = ""; if (txtpatente.getText().equals("")) { errores += "Por favor digite la patente \n"; } if (txtnm.getText().equals("")) { errores += "Por favor seleccione la marca \n"; } if (txtmodelo.getText().trim().isEmpty()) { errores += "El campo modelo está vacio \n"; } if (txtaño.getText().trim().isEmpty()) { errores += "Por favor escriba el año del vehìculo \n"; } if (txtcolor.getText().trim().isEmpty()) { errores += "Por favor escriba el color \n"; } if (txtrutdueño.getText().trim().isEmpty()) { errores += "Por favor seleccione el RUT del dueño \n"; } return errores; } private String validarPatenteVacia() { String errores = ""; if (txtpatente.getText().equals("")) { errores += "Por favor digite la patente \n"; } return errores; } void desbloquear() { txtpatente.setEnabled(true); txtmodelo.setEnabled(true); txtaño.setEnabled(true); txtcolor.setEnabled(true); btbuscar.setEnabled(true); btingresar.setEnabled(true); btmodificar.setEnabled(false); btborrar.setEnabled(false); btlimpiar.setEnabled(true); txtpatente.requestFocus(); btbusca1.setEnabled(true); btbusca2.setEnabled(true); } void bloquear() { txtpatente.setEnabled(false); txtmodelo.setEnabled(false); txtaño.setEnabled(false); txtcolor.setEnabled(false); btbuscar.setEnabled(false); btingresar.setEnabled(false); btmodificar.setEnabled(false); btborrar.setEnabled(false); btlimpiar.setEnabled(false); btbusca1.setEnabled(false); btbusca2.setEnabled(false); } void limpiar() { txtpatente.setText(""); txtnm.setText(""); txtmodelo.setText(""); txtaño.setText(""); txtcolor.setText(""); txtrutdueño.setText(""); } /** * 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() { panelImage1 = new elaprendiz.gui.panel.PanelImage(); panelTranslucido1 = new elaprendiz.gui.panel.PanelTranslucido(); jLabel3 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); txtpatente = new javax.swing.JTextField(); txtnm = new javax.swing.JTextField(); btbusca1 = new javax.swing.JButton(); txtmodelo = new javax.swing.JTextField(); txtaño = new javax.swing.JTextField(); txtcolor = new javax.swing.JTextField(); txtrutdueño = new javax.swing.JTextField(); btbusca2 = new javax.swing.JButton(); panelTranslucido2 = new elaprendiz.gui.panel.PanelTranslucido(); btnuevo = new javax.swing.JButton(); btbuscar = new javax.swing.JButton(); btlimpiar = new javax.swing.JButton(); panelTranslucido3 = new elaprendiz.gui.panel.PanelTranslucido(); btborrar = new javax.swing.JButton(); btmodificar = new javax.swing.JButton(); btingresar = new javax.swing.JButton(); panelTranslucido4 = new elaprendiz.gui.panel.PanelTranslucido(); jsp = new javax.swing.JScrollPane(); tbvehiculos = new javax.swing.JTable(); setClosable(true); panelImage1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/fondoazulceleste.jpg"))); // NOI18N panelTranslucido1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Datos del vehículo", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Arial", 1, 14), java.awt.Color.white)); // NOI18N panelTranslucido1.setForeground(new java.awt.Color(255, 255, 255)); jLabel3.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N jLabel3.setForeground(new java.awt.Color(255, 255, 255)); jLabel3.setText("Modelo"); jLabel5.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N jLabel5.setForeground(new java.awt.Color(255, 255, 255)); jLabel5.setText("Color"); jLabel2.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N jLabel2.setForeground(new java.awt.Color(255, 255, 255)); jLabel2.setText("Marca"); jLabel4.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N jLabel4.setForeground(new java.awt.Color(255, 255, 255)); jLabel4.setText("Año"); jLabel6.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N jLabel6.setForeground(new java.awt.Color(255, 255, 255)); jLabel6.setText("Dueño"); jLabel1.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setText("Patente"); txtpatente.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N txtpatente.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { txtpatenteKeyTyped(evt); } }); txtnm.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N btbusca1.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N btbusca1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/eject.png"))); // NOI18N btbusca1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btbusca1ActionPerformed(evt); } }); txtmodelo.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N txtmodelo.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { txtmodeloKeyTyped(evt); } }); txtaño.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N txtaño.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txtañoKeyPressed(evt); } public void keyTyped(java.awt.event.KeyEvent evt) { txtañoKeyTyped(evt); } }); txtcolor.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N txtcolor.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { txtcolorKeyTyped(evt); } }); txtrutdueño.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N btbusca2.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N btbusca2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/eject.png"))); // NOI18N btbusca2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btbusca2ActionPerformed(evt); } }); javax.swing.GroupLayout panelTranslucido1Layout = new javax.swing.GroupLayout(panelTranslucido1); panelTranslucido1.setLayout(panelTranslucido1Layout); panelTranslucido1Layout.setHorizontalGroup( panelTranslucido1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelTranslucido1Layout.createSequentialGroup() .addContainerGap() .addGroup(panelTranslucido1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(jLabel3) .addComponent(jLabel4) .addComponent(jLabel5) .addComponent(jLabel6) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(panelTranslucido1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelTranslucido1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(txtpatente, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtmodelo) .addComponent(txtaño, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtcolor, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(panelTranslucido1Layout.createSequentialGroup() .addComponent(txtrutdueño, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btbusca2, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(panelTranslucido1Layout.createSequentialGroup() .addComponent(txtnm, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btbusca1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(22, 22, 22)) ); panelTranslucido1Layout.setVerticalGroup( panelTranslucido1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addGroup(panelTranslucido1Layout.createSequentialGroup() .addComponent(txtpatente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(panelTranslucido1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(btbusca1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelTranslucido1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtnm, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(panelTranslucido1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtmodelo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(panelTranslucido1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtaño, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(panelTranslucido1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtcolor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(panelTranslucido1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelTranslucido1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtrutdueño, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6)) .addComponent(btbusca2, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))) ); btnuevo.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N btnuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/add-icon.png"))); // NOI18N btnuevo.setText("Nuevo"); btnuevo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnuevoActionPerformed(evt); } }); btbuscar.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N btbuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/busquedadetodo.png"))); // NOI18N btbuscar.setText("Buscar"); btbuscar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btbuscarActionPerformed(evt); } }); btlimpiar.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N btlimpiar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/limpiar.png"))); // NOI18N btlimpiar.setText("Limpiar"); btlimpiar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btlimpiarActionPerformed(evt); } }); javax.swing.GroupLayout panelTranslucido2Layout = new javax.swing.GroupLayout(panelTranslucido2); panelTranslucido2.setLayout(panelTranslucido2Layout); panelTranslucido2Layout.setHorizontalGroup( panelTranslucido2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelTranslucido2Layout.createSequentialGroup() .addContainerGap() .addGroup(panelTranslucido2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(btnuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btbuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btlimpiar, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); panelTranslucido2Layout.setVerticalGroup( panelTranslucido2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelTranslucido2Layout.createSequentialGroup() .addContainerGap() .addComponent(btnuevo) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btbuscar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btlimpiar) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); btborrar.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N btborrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/delete.png"))); // NOI18N btborrar.setText("Borrar"); btborrar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btborrarActionPerformed(evt); } }); btmodificar.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N btmodificar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/update.png"))); // NOI18N btmodificar.setText("Modificar"); btmodificar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btmodificarActionPerformed(evt); } }); btingresar.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N btingresar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/accept.png"))); // NOI18N btingresar.setText("Ingresar"); btingresar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btingresarActionPerformed(evt); } }); javax.swing.GroupLayout panelTranslucido3Layout = new javax.swing.GroupLayout(panelTranslucido3); panelTranslucido3.setLayout(panelTranslucido3Layout); panelTranslucido3Layout.setHorizontalGroup( panelTranslucido3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelTranslucido3Layout.createSequentialGroup() .addContainerGap() .addComponent(btingresar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btmodificar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btborrar) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); panelTranslucido3Layout.setVerticalGroup( panelTranslucido3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelTranslucido3Layout.createSequentialGroup() .addContainerGap() .addGroup(panelTranslucido3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btingresar) .addComponent(btmodificar) .addComponent(btborrar)) .addContainerGap(12, Short.MAX_VALUE)) ); panelTranslucido4.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Navegación Tabla Vehículos", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Arial", 1, 14), java.awt.Color.white)); // NOI18N //Deshabilitar edicion de tabla tbvehiculos = new javax.swing.JTable(){ public boolean isCellEditable(int rowIndex, int colIndex) { return false; //Disallow the editing of any cell } }; //cambiar color de fila tbvehiculos.setSelectionBackground(Color.LIGHT_GRAY); tbvehiculos.setSelectionForeground(Color.blue); tbvehiculos.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N tbvehiculos.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { } )); tbvehiculos.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); tbvehiculos.getTableHeader().setResizingAllowed(false); tbvehiculos.getTableHeader().setReorderingAllowed(false); tbvehiculos.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tbvehiculosMouseClicked(evt); } }); jsp.setViewportView(tbvehiculos); javax.swing.GroupLayout panelTranslucido4Layout = new javax.swing.GroupLayout(panelTranslucido4); panelTranslucido4.setLayout(panelTranslucido4Layout); panelTranslucido4Layout.setHorizontalGroup( panelTranslucido4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jsp, javax.swing.GroupLayout.PREFERRED_SIZE, 384, javax.swing.GroupLayout.PREFERRED_SIZE) ); panelTranslucido4Layout.setVerticalGroup( panelTranslucido4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelTranslucido4Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jsp, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)) ); jsp.getAccessibleContext().setAccessibleParent(panelTranslucido4); javax.swing.GroupLayout panelImage1Layout = new javax.swing.GroupLayout(panelImage1); panelImage1.setLayout(panelImage1Layout); panelImage1Layout.setHorizontalGroup( panelImage1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelImage1Layout.createSequentialGroup() .addGroup(panelImage1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelImage1Layout.createSequentialGroup() .addGap(22, 22, 22) .addGroup(panelImage1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(panelTranslucido3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(panelImage1Layout.createSequentialGroup() .addComponent(panelTranslucido1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(panelTranslucido2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGroup(panelImage1Layout.createSequentialGroup() .addContainerGap() .addComponent(panelTranslucido4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); panelImage1Layout.setVerticalGroup( panelImage1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelImage1Layout.createSequentialGroup() .addContainerGap() .addGroup(panelImage1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(panelTranslucido1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(panelTranslucido2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(panelTranslucido3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(panelTranslucido4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(panelImage1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(panelImage1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnuevoActionPerformed desbloquear(); limpiar(); txtpatente.requestFocus(); }//GEN-LAST:event_btnuevoActionPerformed private void btbusca1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btbusca1ActionPerformed if (!bm.isVisible()) { boolean mostrar = true; for (int a = 0; a < jdpescritorio.getComponentCount(); a++) { // verificar si es instancia de algun componente que ya este en el jdesktoppane if (bm.getClass().isInstance(jdpescritorio.getComponent(a))) { System.out.println("Búsqueda Marcas: Esto no se volverá a mostrar porque ya está abierta la ventana"); mostrar = false; } else { System.out.println("Búsqueda Marcas: No lo es, puede mostrarse"); } } if (mostrar) { jdpescritorio.add(bm); } bm.show(); bm.toFront(); } else { System.out.println("Búsqueda Marcas: Esto no se volverá a mostrar porque ya está abierta la ventana"); } }//GEN-LAST:event_btbusca1ActionPerformed private void txtañoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtañoKeyPressed }//GEN-LAST:event_txtañoKeyPressed private void txtañoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtañoKeyTyped validarLetras.soloNumeros(evt); //limite de caracteres if (txtaño.getText().length() == 4) { evt.consume(); Toolkit.getDefaultToolkit().beep(); } }//GEN-LAST:event_txtañoKeyTyped private void btbusca2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btbusca2ActionPerformed if (!bc.isVisible()) { boolean mostrar = true; for (int a = 0; a < jdpescritorio.getComponentCount(); a++) { // verificar si es instancia de algun componente que ya este en el jdesktoppane if (bc.getClass().isInstance(jdpescritorio.getComponent(a))) { System.out.println("Búsqueda Dueño: Esto no se volverá a mostrar porque ya está abierta la ventana"); mostrar = false; } else { System.out.println("Búsqueda Dueño: No lo es, puede mostrarse"); } } if (mostrar) { jdpescritorio.add(bc); } bc.show(); bc.toFront(); } else { System.out.println("Búsqueda Dueño: Esto no se volverá a mostrar porque ya está abierta la ventana"); } }//GEN-LAST:event_btbusca2ActionPerformed private void btingresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btingresarActionPerformed String errores = validarVacios(); if (errores.equals("")) { try { conexion = claseConectar.ConexionConBaseDatos.getConexion(); //Crear consulta Statement st = conexion.createStatement(); String sql = "INSERT INTO vehiculo (Patente,Marca,Modelo,Año,Color,Dueño)" + "VALUES('" + txtpatente.getText() + "','" + txtnm.getText() + "','" + txtmodelo.getText() + "'," + "'" + txtaño.getText() + "','" + txtcolor.getText() + "'," + "'" + txtrutdueño.getText() + "')"; //Ejecutar la consulta st.executeUpdate(sql); if (String.valueOf(txtpatente.getText()).compareTo("") == 0 && String.valueOf(txtrutdueño.getText()).compareTo("") == 0) { validarVacios(); } else { JOptionPane.showMessageDialog(this, "Vehìculo Ingresado", "Ingreso", JOptionPane.INFORMATION_MESSAGE); txtpatente.requestFocus(); mostrardatos(""); //Limpiar limpiar(); anchocolumnas(); } } catch (Exception e) { JOptionPane.showMessageDialog(rootPane, "La patente ya existe", "Patente existente", JOptionPane.ERROR_MESSAGE); } finally { claseConectar.ConexionConBaseDatos.metodoCerrarConexiones(conexion); } } else { JOptionPane.showMessageDialog(null, errores); } }//GEN-LAST:event_btingresarActionPerformed private void btlimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btlimpiarActionPerformed limpiar(); mostrardatos(""); txtpatente.setEnabled(true); txtpatente.requestFocus(); }//GEN-LAST:event_btlimpiarActionPerformed private void btmodificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btmodificarActionPerformed String errores = validarVacios(); if (errores.equals("")) { try { conexion = claseConectar.ConexionConBaseDatos.getConexion(); PreparedStatement pst = (PreparedStatement) conexion.prepareStatement("UPDATE vehiculo SET Marca='" + txtnm.getText() + "',Modelo='" + txtmodelo.getText() + "',Año='" + txtaño.getText() + "',Color='" + txtcolor.getText() + "',Dueño='" + txtrutdueño.getText() + "' WHERE Patente='" + txtpatente.getText() + "'"); pst.executeUpdate(); if (String.valueOf(txtpatente.getText()).compareTo("") == 0 && String.valueOf(txtrutdueño.getText()).compareTo("") == 0) { validarVacios(); } else { JOptionPane.showMessageDialog(this, "Datos del Vehículo Actualizados", "Actualización de Datos", JOptionPane.INFORMATION_MESSAGE); btingresar.setEnabled(true); //limpiar textfields limpiar(); mostrardatos(""); anchocolumnas(); } } catch (Exception e) { JOptionPane.showMessageDialog(rootPane, "La patente ya existe", "Patente existente", JOptionPane.ERROR_MESSAGE); } finally { claseConectar.ConexionConBaseDatos.metodoCerrarConexiones(conexion); } } else { JOptionPane.showMessageDialog(null, errores); } }//GEN-LAST:event_btmodificarActionPerformed private void btbuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btbuscarActionPerformed String error = validarPatenteVacia(); if (error.equals("")) { // Buscar registro en la base de datos try { conexion = claseConectar.ConexionConBaseDatos.getConexion(); //Crear consulta Statement st = conexion.createStatement(); String sql = sql = "SELECT * FROM vehiculo WHERE Patente='" + txtpatente.getText() + "'"; //Ejecutar la consulta ResultSet rs = st.executeQuery(sql); mostrardatos(sql); if (rs.next()) { //existe txtnm.setText(rs.getObject("Marca").toString()); txtmodelo.setText(rs.getObject("Modelo").toString()); txtaño.setText(rs.getObject("Año").toString()); txtcolor.setText(rs.getObject("Color").toString()); txtrutdueño.setText(rs.getObject("Dueño").toString()); txtpatente.setEnabled(false); btborrar.setEnabled(true); btmodificar.setEnabled(true); } else { //no existe if (String.valueOf(txtpatente.getText()).compareTo("") == 0) { validarVacios(); } else { JOptionPane.showMessageDialog(this, "El vehículo que busca no existe", "Vehículo Inexistente", JOptionPane.ERROR_MESSAGE); txtpatente.setEnabled(true); btborrar.setEnabled(false); btmodificar.setEnabled(false); limpiar(); anchocolumnas(); } } } catch (Exception e) { JOptionPane.showMessageDialog(this, "Error " + e.getMessage().toString()); } finally { claseConectar.ConexionConBaseDatos.metodoCerrarConexiones(conexion); } } else { JOptionPane.showMessageDialog(null, error); } }//GEN-LAST:event_btbuscarActionPerformed private void btborrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btborrarActionPerformed String error = validarPatenteVacia(); if (error.equals("")) { try { conexion = claseConectar.ConexionConBaseDatos.getConexion(); PreparedStatement pst = (PreparedStatement) conexion.prepareStatement("DELETE FROM vehiculo WHERE Patente='" + txtpatente.getText() + "'"); pst.executeUpdate(); if (String.valueOf(txtpatente.getText()).compareTo("") == 0 && String.valueOf(txtrutdueño.getText()).compareTo("") == 0) { validarVacios(); } else { JOptionPane.showMessageDialog(this, "Vehículo Eliminado", "Eliminación vehículo", JOptionPane.INFORMATION_MESSAGE); btmodificar.setEnabled(false); btborrar.setEnabled(false); limpiar(); mostrardatos(""); anchocolumnas(); btingresar.setEnabled(true); } } catch (Exception e) { JOptionPane.showMessageDialog(this, "Error " + e.getMessage().toString()); } finally { claseConectar.ConexionConBaseDatos.metodoCerrarConexiones(conexion); } } else { JOptionPane.showMessageDialog(null, error); } }//GEN-LAST:event_btborrarActionPerformed private void txtmodeloKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtmodeloKeyTyped validarLetras.LNE(evt); if (txtmodelo.getText().length() == 50) { evt.consume(); Toolkit.getDefaultToolkit().beep(); } }//GEN-LAST:event_txtmodeloKeyTyped private void txtcolorKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtcolorKeyTyped validarLetras.soloLetras(evt); //limite de caracteres if (txtcolor.getText().length() == 12) { evt.consume(); Toolkit.getDefaultToolkit().beep(); } }//GEN-LAST:event_txtcolorKeyTyped private void txtpatenteKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtpatenteKeyTyped validarLetras.soloLetrasyNumeros(evt); //limite de caracteres if (txtpatente.getText().length() == 6) { evt.consume(); Toolkit.getDefaultToolkit().beep(); } }//GEN-LAST:event_txtpatenteKeyTyped private void tbvehiculosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbvehiculosMouseClicked //al momento de hacer click derecho aparecerá el menu modificar //que se irá directamente con los valores de la BD a sus respectivos //textfields para hacer las respectivas modificaciones int fila = tbvehiculos.getSelectedRow(); btingresar.setEnabled(false); if (fila >= 0) { txtpatente.setText(tbvehiculos.getValueAt(fila, 0).toString()); txtnm.setText(tbvehiculos.getValueAt(fila, 1).toString()); txtmodelo.setText(tbvehiculos.getValueAt(fila, 2).toString()); txtaño.setText(tbvehiculos.getValueAt(fila, 3).toString()); txtcolor.setText(tbvehiculos.getValueAt(fila, 4).toString()); txtrutdueño.setText(tbvehiculos.getValueAt(fila, 5).toString()); btmodificar.setEnabled(true); btborrar.setEnabled(true); } else { JOptionPane.showMessageDialog(null, "No ha seleccionado fila"); } }//GEN-LAST:event_tbvehiculosMouseClicked // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btborrar; private javax.swing.JButton btbusca1; private javax.swing.JButton btbusca2; private javax.swing.JButton btbuscar; private javax.swing.JButton btingresar; private javax.swing.JButton btlimpiar; private javax.swing.JButton btmodificar; private javax.swing.JButton btnuevo; 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.JLabel jLabel6; private javax.swing.JScrollPane jsp; private elaprendiz.gui.panel.PanelImage panelImage1; private elaprendiz.gui.panel.PanelTranslucido panelTranslucido1; private elaprendiz.gui.panel.PanelTranslucido panelTranslucido2; private elaprendiz.gui.panel.PanelTranslucido panelTranslucido3; private elaprendiz.gui.panel.PanelTranslucido panelTranslucido4; public static javax.swing.JTable tbvehiculos; private javax.swing.JTextField txtaño; private javax.swing.JTextField txtcolor; private javax.swing.JTextField txtmodelo; public static javax.swing.JTextField txtnm; private javax.swing.JTextField txtpatente; public static javax.swing.JTextField txtrutdueño; // End of variables declaration//GEN-END:variables }
true
b7fe4ddc6ffe2c98fc2c56561ebba07520938b11
Java
natann4755/oldGibuy
/Java - 6/Lesson 3/Functions/src/com/homWork/src/com/company/Other/Main2.java
UTF-8
312
2.59375
3
[]
no_license
package com.company.Other; import com.company.Animal; import com.company.Dog; public class Main2 { public static void main(String[] args) { Dog S=new Dog(); S.setAge(7); System.out.println(S); Cat K=new Cat(); K.setAge(7); System.out.println(K); } }
true
e9472bf37ccf44c0f4571594420782cdd9649cef
Java
koksharov1998/IWatched
/src/main/java/com/example/IWatched/services/RatingService.java
UTF-8
1,129
2.21875
2
[]
no_license
package com.example.IWatched.services; import com.example.IWatched.db.Movie; import com.example.IWatched.db.Rating; import com.example.IWatched.repos.RatingRepository; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class RatingService implements BdService<Rating> { private RatingRepository ratingRepository; @Autowired private UserService userService; @Override public List<Rating> findAll() { return (List<Rating>) ratingRepository.findAll(); } @Override public Rating findById(int id) { return ratingRepository.findById(id).get(); } @Override public Rating save(Rating rating) { return ratingRepository.save(rating); } @Autowired public void DataInit(RatingRepository ratingRepository) { this.ratingRepository = ratingRepository; } public Rating[] findByUsername(String username) { return ratingRepository.findByUser(userService.loadUserByUsername(username)); } public Rating[] findByMovie(Movie movie) { return ratingRepository.findByMovie(movie); } }
true
011043d3301aef27630ded9ec6f09deb4a0ae7fa
Java
ArmanMikayelovich/java-io
/src/main/java/com/energizeglobal/internship/FileServiceImpl.java
UTF-8
3,900
3.015625
3
[]
no_license
package com.energizeglobal.internship; import java.io.*; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.Date; import java.util.Objects; public class FileServiceImpl implements FileService { @Override public String seeProperties(String filename) { File file = new File(filename); if (file.exists()) { return new StringBuilder().append("Type: ").append(file.isDirectory() ? "Directory\n" : " File\n") .append("Name: ").append(file.getName()).append(".\n") .append("Absolute path: ").append(file.getAbsolutePath()).append(".\n") .append("Size: ").append(file.length()).append("Bytes.\n") .append("Last modified: ") .append(new Date(file.lastModified())).append(".\n").toString(); } else { return "File/Directory not found"; } } @Override public String seeTree(String directoryName, int tabCount) { File directory = new File(directoryName); if (!directory.exists()) { return "Directory not exist."; } StringBuilder treeBuilder = new StringBuilder(); if (directory.isDirectory()) { treeBuilder.append(directory.getName()).append("\n"); tabCount++; for (File file : Objects.requireNonNull(directory.listFiles())) { if (!file.isDirectory()) { appendMinuses(treeBuilder, tabCount); treeBuilder.append(file.getName()).append("\n"); } else { appendMinuses(treeBuilder, tabCount); treeBuilder.append(seeTree(file.getAbsolutePath(), tabCount)).append("\n"); } } } else { treeBuilder.append("Not a directory"); } return treeBuilder.toString(); } @Override public void copyFile(String fileName, String destinationFileName) throws IOException { File src = new File(fileName); if (src.exists()) { File dest = new File(destinationFileName); Files.copy(src.toPath(), dest.toPath()); } else { throw new FileNotFoundException(src.getAbsolutePath() + " not found."); } } @Override public void moveFile(String fileName, String destinationName) throws IOException { File src = new File(fileName); if (src.exists()) { File dest = new File(destinationName); Files.move(src.toPath(), dest.toPath(), StandardCopyOption.ATOMIC_MOVE); } else { throw new FileNotFoundException(src.getAbsolutePath() + " not found."); } } @Override public void renameFile(String fileName, String newName) throws IOException { moveFile(fileName, newName); } @Override public String readDataFromFile(String filename) throws IOException { File src = new File(filename); if (src.exists()) { try (BufferedReader bufferedReader = new BufferedReader(new FileReader(src))) { StringBuilder builder = new StringBuilder(); bufferedReader.lines().forEach(line -> builder.append(line).append('\n')); return builder.toString(); } } else { throw new FileNotFoundException(src.getAbsolutePath() + " not found."); } } @Override public void writeDataToFile(String fileName, String data) throws IOException { File dest = new File(fileName); try (PrintWriter printWriter = new PrintWriter(new FileOutputStream(dest), true);) { printWriter.write(data); } } private void appendMinuses(StringBuilder builder, int count) { for (int x = 0; x < count; x++) { builder.append("--"); } } }
true
78e9e235d5ffae31c1ffc742ba551e8f96b296ef
Java
Camavilca/anayacitamedica
/src/main/java/com/camavilca/controllers/citamedica/CitaMedicaController.java
UTF-8
4,005
2.125
2
[]
no_license
package com.camavilca.controllers.citamedica; import com.camavilca.model.CitaMedica; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import pe.albatross.octavia.dynatable.DynatableFilter; import pe.albatross.octavia.dynatable.DynatableResponse; import pe.albatross.zelpers.miscelanea.ExceptionHandler; import pe.albatross.zelpers.miscelanea.JsonHelper; import pe.albatross.zelpers.miscelanea.JsonResponse; import pe.albatross.zelpers.miscelanea.PhobosException; @Controller @RequestMapping("citamedica") public class CitaMedicaController { @Autowired CitaMedicaService service; @RequestMapping(method = RequestMethod.GET) public String getIndex() { return "citamedicaadmin/citamedica"; } @ResponseBody @RequestMapping("save") public JsonResponse save(@RequestBody CitaMedica citaMedica) { JsonResponse response = new JsonResponse(); try { if (citaMedica.getId() == null) { response.setMessage("Cita Medica Guardado"); } else { response.setMessage("Cita Medica Actualizado"); } service.save(citaMedica); response.setSuccess(Boolean.TRUE); } catch (PhobosException e) { ExceptionHandler.handlePhobosEx(e, response); } catch (Exception e) { ExceptionHandler.handleException(e, response); } return response; } @ResponseBody @RequestMapping("allDynatable") public DynatableResponse all(DynatableFilter filter) { DynatableResponse json = new DynatableResponse(); List<CitaMedica> citas = service.allDynatable(filter); ArrayNode array = new ArrayNode(JsonNodeFactory.instance); citas.forEach((cita) -> { ObjectNode node = JsonHelper.createJson(cita, JsonNodeFactory.instance, new String[]{"*", "medico.*"}); array.add(node); }); json.setData(array); json.setTotal(filter.getTotal()); json.setFiltered(filter.getFiltered()); return json; } @ResponseBody @RequestMapping("all") public JsonResponse all() { JsonResponse response = new JsonResponse(); JsonNodeFactory jsonFactory = JsonNodeFactory.instance; ArrayNode arrayNode = new ArrayNode(jsonFactory); try { List<CitaMedica> pasientes = service.all(); for (CitaMedica pasiente : pasientes) { ObjectNode node = JsonHelper.createJson(pasiente, jsonFactory, new String[]{"*", "medico.*", "usuario.*"}); arrayNode.add(node); } response.setData(arrayNode); response.setSuccess(Boolean.TRUE); } catch (PhobosException e) { ExceptionHandler.handlePhobosEx(e, response); } catch (Exception e) { ExceptionHandler.handleException(e, response); } return response; } @ResponseBody @RequestMapping("delete") public JsonResponse delete(@RequestBody CitaMedica citaMedica) { JsonResponse response = new JsonResponse(); try { service.delete(citaMedica); response.setMessage("Cita Medica Eliminado"); response.setSuccess(Boolean.TRUE); } catch (PhobosException e) { ExceptionHandler.handlePhobosEx(e, response); } catch (Exception e) { ExceptionHandler.handleException(e, response); } return response; } }
true
bad7849c6898bbdee53138304f9856384ef0f91c
Java
vinodjagwani/xyz-vehicle-monitoring
/vehicle-monitoring-consumer/src/main/java/com/xyz/vehicle/monitoring/entity/redis/CurrentVehicleStatusEntity.java
UTF-8
557
1.703125
2
[]
no_license
package com.xyz.vehicle.monitoring.entity.redis; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.data.redis.core.RedisHash; import java.io.Serializable; /** * Created by vinodjagwani on 22/01/19. */ @Data @RedisHash @NoArgsConstructor @AllArgsConstructor public class CurrentVehicleStatusEntity implements Serializable { private static final long serialVersionUID = 4497026996490363658L; private Long vehicleId; private Long customerId; private boolean status; }
true
f41243d1d391a936d0c01acae11e1fbe505003a5
Java
GourishettySairam/GourishettySairam_DesignPatterns
/DesignPatterns/src/main/java/com/epam/behavioralPatterns/IChoice.java
UTF-8
86
2.015625
2
[]
no_license
package com.epam.behavioralPatterns; public interface IChoice { void MyChoice(); }
true
baf2bb9d060d39e4573cfb36f18915ef8c8966ab
Java
anacosic85/Java-GUI
/EstateAgentsGUI.java
WINDOWS-1252
13,988
2.984375
3
[]
no_license
/*GUI program to add, view and search properties */ import javafx.application.Application; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.Stage; import javafx.event.ActionEvent; import java.util.*; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; public class EstateAgentsGUI extends Application { ArrayList<Property> propertyList = new ArrayList<>(); Alert a = new Alert(AlertType.NONE); //Make some GUI controls public(visible) TextField txtPropertyID; TextField txtStreet; TextField txtTown; TextField txtCounty; TextField txtBeds; TextField txtReceptions; TextField txtBaths; TextField txtType; TextField txtPrice; TextArea txtWindow; //second GUI window controls TextField txtTerm; TextField txtRepayment; TextField txtPropertyPrice; public void start(Stage stage)//calling start() method to develop a window { //Create all labels Label lblEnter = new Label("***Enter Property Details***"); Label lblPropertyID = new Label("Property ID"); Label lblStreet = new Label("Street"); Label lblTown = new Label("Town"); Label lblCounty = new Label("County"); Label lblBeds = new Label("Beds"); Label lblReceptions = new Label("Receptions"); Label lblBaths = new Label("Baths"); Label lblType = new Label("Type"); Label lblPrice = new Label("Price"); Label lblSearch = new Label("***Property Search***"); //Create all TextFields and give them size txtPropertyID = new TextField(); txtPropertyID.setMaxWidth(100); txtStreet = new TextField(); txtStreet.setMaxWidth(150); txtTown = new TextField(); txtTown.setMaxWidth(150); txtCounty = new TextField(); txtCounty.setMaxWidth(150); txtBeds = new TextField(); txtBeds.setMaxWidth(50); txtReceptions = new TextField(); txtReceptions.setMaxWidth(50); txtBaths = new TextField(); txtBaths.setMaxWidth(50); txtType = new TextField(); txtType.setMaxWidth(100); txtPrice = new TextField(); txtPrice.setMaxWidth(100); //Create Buttons + set Lambda expressions for each button Button btnAddProperty = new Button("Add Property"); btnAddProperty.setOnAction(e -> addProperty(e)); Button btnViewProperties = new Button("View All Properties"); btnViewProperties.setOnAction(e -> viewProperties(e)); Button btnSearchType = new Button("Search by Type"); btnSearchType.setOnAction(e -> searchType(e)); Button btnSearchNoBedrooms = new Button("Search by Number of Bedrooms"); btnSearchNoBedrooms.setOnAction(e -> searchBedrooms(e)); Button btnSearchPriceRange = new Button("Search by Price Range"); btnSearchPriceRange.setOnAction(e -> searchPrice(e)); Button btnDeleteProperty = new Button("Delete Property"); btnDeleteProperty.setOnAction(e -> deleteProperty(e)); Button btnMortgageCalculator = new Button("Mortgage Calculator"); txtWindow = new TextArea(); txtWindow.setMaxSize(630,480); txtWindow.setEditable(false); //HBOx HBox propID = new HBox(8); propID.getChildren().addAll(lblPropertyID, txtPropertyID); propID.setAlignment(Pos.CENTER); //HBox HBox input1 = new HBox(8); input1.getChildren().addAll(lblStreet, txtStreet, lblTown, txtTown, lblCounty, txtCounty); input1.setAlignment(Pos.CENTER); //HBox HBox input2 = new HBox(8); input2.getChildren().addAll(lblBeds, txtBeds, lblReceptions, txtReceptions, lblBaths, txtBaths, lblType, txtType, lblPrice, txtPrice); input2.setAlignment(Pos.CENTER); //HBox HBox buttons = new HBox(30); //spacing between each controls in this HBox buttons.getChildren().addAll(btnViewProperties, btnSearchType, btnSearchNoBedrooms, btnSearchPriceRange); buttons.setAlignment(Pos.CENTER); //HBox HBox functions = new HBox(30); functions.getChildren().addAll(btnDeleteProperty, btnMortgageCalculator); functions.setAlignment(Pos.CENTER); //Create VBox and add all HBoxes to it + TextArea VBox root = new VBox(8); root.getChildren().addAll(lblEnter, propID, input1, input2, btnAddProperty, lblSearch, buttons, txtWindow, functions); root.setAlignment(Pos.CENTER); //Create Scene and add VBox to the scene Scene scene = new Scene(root, 800, 600); stage.setScene(scene); stage.setTitle("Estate Agents"); stage.show(); //Creating controls for separate scene (when "Calculate mortgage" button is clicked) Label lblPropertyPrice = new Label("Insert Property Price"); Label lblTerm = new Label("Insert Repayment In Years"); txtPropertyPrice = new TextField(); txtPropertyPrice.setMaxWidth(100); txtTerm = new TextField(); txtTerm.setMaxWidth(100); Button btnRepayment = new Button("Calculate Mortgage"); btnRepayment.setOnAction(e -> mortgageRepayment(e)); Button btnReturn = new Button("Return to the main window"); btnReturn.setStyle("-fx-background-color: #ADD8E6; "); //looked online how to style with color, hope its ok btnReturn.setOnAction(e -> stage.setScene(scene)); HBox inp = new HBox(8); inp.getChildren().addAll(lblPropertyPrice, txtPropertyPrice); inp.setAlignment(Pos.CENTER); HBox inpt = new HBox(8); inpt.getChildren().addAll(lblTerm, txtTerm); inpt.setAlignment(Pos.CENTER); HBox repayment = new HBox(8); repayment.getChildren().addAll(btnRepayment); repayment.setAlignment(Pos.CENTER); VBox root2 = new VBox(15); root2.getChildren().addAll(inp, inpt, repayment, btnReturn); root2.setAlignment(Pos.CENTER); //Create scene and add root2 to the scene Scene scene2 = new Scene(root2, 500, 300); btnMortgageCalculator.setOnAction(e -> stage.setScene(scene2)); //Lambda expression for mortgage calculator button that will open separete(second) scene when clicked }//close start method //Method to add properties public void addProperty(ActionEvent e) { try { //Check if TextFields are empty if(txtPropertyID.getText().isEmpty() || txtStreet.getText().isEmpty() || txtTown.getText().isEmpty() || txtCounty.getText().isEmpty() || txtBeds.getText().isEmpty() || txtReceptions.getText().isEmpty() || txtBaths.getText().isEmpty() || txtType.getText().isEmpty() || txtPrice.getText().isEmpty()) { txtWindow.setText("You must enter all property values"); } else //get the values from all TextFields { int id = Integer.parseInt(txtPropertyID.getText()); String street = txtStreet.getText(); String town = txtTown.getText(); String county = txtCounty.getText(); int beds = Integer.parseInt(txtBeds.getText()); int receptions = Integer.parseInt(txtReceptions.getText()); int baths = Integer.parseInt(txtBaths.getText()); String type = txtType.getText(); double price = Double.parseDouble(txtPrice.getText()); //Create object and add it to ArrayList propertyList propertyList.add(new Property(id, street, town, county, beds, receptions, baths, type, price)); a.setAlertType(AlertType.INFORMATION);//message window a.setContentText("Property Successfully Added"); a.show(); //Clear the TextFields after employee is added txtPropertyID.clear(); txtStreet.clear(); txtTown.clear(); txtCounty.clear(); txtBeds.clear(); txtReceptions.clear(); txtBaths.clear(); txtType.clear(); txtPrice.clear(); }//close else }//close try catch(IllegalArgumentException ex)//Output message if wrong input in the code above { a.setAlertType(AlertType.INFORMATION); a.setContentText("Property ID, number of beds/receptions/baths and price \ncan not be negative numbers or letters.\nPlease check your input."); a.show(); } }//Close method //Method to view all properties public void viewProperties(ActionEvent e) { txtWindow.clear(); for(Property p: propertyList) { txtWindow.appendText(p +"\n"); } }//close method //Method to search by property's type public void searchType(ActionEvent e) { txtWindow.clear(); //Clear TextArea of any previous output String searchType = txtType.getText(); //get property type the from user //search for every element in the ArrayList for possible match of property type boolean isFound = false; for(int i = 0; i < propertyList.size(); i++)//to get the position of each element { //checking if any of the values entered matches property type if(searchType.equalsIgnoreCase(propertyList.get(i).type())) { txtWindow.appendText(propertyList.get(i).toString()+"\n"); isFound = true; //Change variable isFound from false to true } }//Close for loop if(isFound == false) //if the variable isFound is still False(no match found) then output message to the user { txtWindow.setText("No property found matching that type"); } txtType.clear(); }//Close method //Method to search by number od bedrooms public void searchBedrooms(ActionEvent e) { txtWindow.clear(); int searchBedrooms = Integer.parseInt(txtBeds.getText()); //get number of beds the from the user //search for every element in the ArrayList for possible match boolean isFound = false; for(int i = 0; i < propertyList.size(); i++) { //checking if any values entered matches if(propertyList.get(i).bed() == searchBedrooms) { txtWindow.appendText(propertyList.get(i).toString()+"\n"); isFound = true; } }//Close for loop if(isFound == false) //if no match found - output message to the user { txtWindow.setText("No property found with " + txtBeds.getText() + " bedrooms"); } txtBeds.clear(); }//Close method //Method to search by price public void searchPrice(ActionEvent e) { txtWindow.clear(); //Get price for property from the user double propertyPrice = Double.parseDouble(txtPrice.getText()); //search for every element in the ArrayList for possible match boolean isFound = false; for(int i = 0; i < propertyList.size(); i++) { //checking if any of the values entered matches property price if(propertyList.get(i).viewPrice() <= propertyPrice) { txtWindow.appendText(propertyList.get(i).toString()+"\n"); isFound = true; } }//Close for loop if(isFound == false) //Output message to the user if no matches { txtWindow.setText("No property found for " + txtPrice.getText()); } }//Close method //Method to delete property public void deleteProperty(ActionEvent e) { txtWindow.clear(); //Get user to enter propertyID they wish to delete int propertyID = Integer.parseInt(txtPropertyID.getText()); //Check entire ArrayList to see if inserted ID exists for(int i = 0; i < propertyList.size(); i++) { if(propertyID == propertyList.get(i).getId()) { //Remove that property from the arrayList (at that position) propertyList.remove(i); txtWindow.setText("Property successfully deleted"); } } //Clear property ID text field txtPropertyID.clear(); } //Method to calculate mortgage for the property public void mortgageRepayment(ActionEvent e) { txtWindow.clear(); //Get user to enter property price and term length double propertyPrice = Double.parseDouble(txtPropertyPrice.getText()); if (propertyPrice <= 0)//check for positive input for price { a.setAlertType(AlertType.INFORMATION); a.setContentText("Error - Property price has to be positive number"); a.show(); } else { int termYears = Integer.parseInt(txtTerm.getText()); double monthly, repayment; int months = termYears * 12; monthly = (propertyPrice / months); repayment = monthly + monthly * 0.03; a.setAlertType(AlertType.INFORMATION); a.setContentText("Monthly repayment over " +termYears+ " years is " + repayment); a.show(); } } public static void main(String[]args) { launch(args); } }
true
2b17d8df24d16faeece35a9ae022ca1b8a6d346b
Java
betul-sahin/patika-java-backend-web-development
/java101/src/kosulluifadeler/SinifiGecmeDurumu.java
UTF-8
1,119
2.9375
3
[]
no_license
package kosulluifadeler; import java.util.Scanner; public class SinifiGecmeDurumu { public static void main(String[] args) { int matematik, fizik, kimya, turkce, muzik; Scanner scan = new Scanner(System.in); System.out.println("Ders sayisini ve " + "sirasiyla notlarinizi(matematik, fizik, kimya, turkce, tarih, muzik) giriniz..."); int n = scan.nextInt(); scan.nextLine(); matematik = scan.nextInt(); fizik = scan.nextInt(); kimya = scan.nextInt(); turkce = scan.nextInt(); muzik = scan.nextInt(); double ortalama = 0.0; if((matematik>0 && matematik<=100) || (fizik>0 && fizik<=100) || (kimya>0 && kimya <=100) || (turkce>0 && turkce<=100) || (muzik>0 && muzik<=100)) ortalama = (matematik + fizik + kimya + turkce + muzik) / n; if(ortalama <= 55){ System.out.println("Sınıfta kaldınız."); } else{ System.out.println("Tebrikler geçtiniz!"); } System.out.print("Ortalamanız : " + ortalama); } }
true
1863a39e916b93e295017df8855023729e76cda8
Java
SigmaVEC/OAS
/WEB-INF/src/signoutServlet.java
UTF-8
730
2.390625
2
[]
no_license
import javax.servlet.http.*; import javax.servlet.*; import java.io.*; public class signoutServlet extends HttpServlet{ public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { res.setContentType("text/html");//setting the content type HttpSession session = req.getSession(true); PrintWriter out=res.getWriter();//get the stream to write the data try{ session.invalidate(); }catch(Exception e){} //writing html in the stream res.setStatus(res.SC_MOVED_TEMPORARILY); res.setHeader("Location", "index.html"); out.println("redirect to home page"); out.close();//closing the stream } }
true
beedad1c6fb9f643a3bc05e6e8d50f27576afc90
Java
Bekz7/design-patterns
/src/main/java/pl/bekz/factories/fruitmarket_abstractfactory/FruitMarket.java
UTF-8
1,378
3.3125
3
[]
no_license
package pl.bekz.factories.fruitmarket_abstractfactory; import pl.bekz.factories.fruitmarket_abstractfactory.exception.NoSuchFruit; import pl.bekz.factories.fruitmarket_abstractfactory.factories.FruitFactory; import pl.bekz.factories.fruitmarket_abstractfactory.fruits.*; public class FruitMarket { private String orderedFruit; void orderFruit(FruitTypes fruitTypes, FruitFactory fruitFactory) { Fruit fruit = pickFruit(fruitTypes, fruitFactory); orderedFruit = fruit.toString(); prepare(); box(); } Fruit pickFruit(FruitTypes fruitTypes, FruitFactory fruitFactory) { switch (fruitTypes) { case APPLE: return fruitFactory.createApple(); case WATERMELON: return fruitFactory.createWatermelon(); case ORANGE: return fruitFactory.createOrange(); case GRAPES: return fruitFactory.createGrapes(); case BANANA: return fruitFactory.createBanana(); default: throw new NoSuchFruit("We don't have this fruit in our market"); } } private void prepare() { System.out.println("We're polishing " + orderedFruit); } private void box() { System.out.println("We're packing in cardboard bag " + orderedFruit + "\n"); } }
true
48b68dfc65148971288ee1bb836c9bd0367bd555
Java
suggitpe/java-gui
/mercury/src/test/java/org/suggs/apps/mercury/model/util/xml/DomParserTest.java
UTF-8
6,314
2.4375
2
[ "Apache-2.0" ]
permissive
/* * DomParserTest.java created on 9 Dec 2008 19:35:38 by suggitpe for project GUI - Mercury * */ package org.suggs.apps.mercury.model.util.xml; import org.suggs.apps.mercury.model.util.MercuryUtilityException; import org.suggs.apps.mercury.model.util.file.impl.FileManager; import org.suggs.apps.mercury.model.util.xml.impl.DomParserUtil; import java.io.File; import java.io.IOException; import junit.framework.Assert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * This test will test the DomParser utility. * * @author suggitpe * @version 1.0 9 Dec 2008 */ public class DomParserTest { private static final Logger LOG = LoggerFactory.getLogger( DomParserTest.class ); private static final String TEST_ROOT = "/tmp"; private static final String TEST_DIR = TEST_ROOT + "/test/xmltest"; private static final String TEST_FILE = TEST_DIR + "/dummyXml.xml"; private IDomParserUtil mDomParser_; private FileManager mFileManager_; /** * This is run before all of the tests so that they are correctly * set up * * @throws Exception */ @Before public void setUp() throws Exception { LOG.debug( "------------------- DomParserTest" ); mDomParser_ = new DomParserUtil(); mFileManager_ = new FileManager(); } /** * This is run after each test so that we do not polute the local * drives with our crap. * * @throws Exception */ @After public void teardown() throws Exception { LOG.debug( "Deleting file [" + TEST_FILE + "]" ); File file = new File( TEST_FILE ); file.delete(); LOG.debug( "Deleting directory [" + TEST_DIR + "]" ); File dir = new File( TEST_DIR ); if ( dir.isDirectory() ) { dir.delete(); } else { dir.deleteOnExit(); } LOG.debug( "------------------- end of TearDown" ); } /** * This will test the parsing of a file that is valid for the * schema. * * @throws IOException * @throws MercuryUtilityException */ @Test public void testParseValidXmlFile() throws IOException, MercuryUtilityException { // created good xml StringBuffer buff = new StringBuffer(); buff.append( "<?xml version=\"1.0\"?>\n" ) .append( "<xmlroot xmlns=\"http://www.suggs.org.uk/UnitTestSchema\">\n" ); buff.append( "<testlayer1/>" ); buff.append( "<testlayer2/>" ); buff.append( "<testlayer3/>" ); buff.append( "</xmlroot>" ); // persist the data to a file LOG.debug( "Creating test file [" + TEST_FILE + "]" ); mFileManager_.persistClobToFile( buff.toString(), new File( TEST_FILE ) ); // no we do the actual parse LOG.debug( "Parsing file [" + TEST_FILE + "]" ); Document doc = mDomParser_.createDocFromXmlFile( TEST_FILE, "xml/unit-test-schema.xsd" ); Node docElem = doc.getDocumentElement(); Assert.assertEquals( docElem.getNodeName(), "xmlroot" ); NodeList list = docElem.getChildNodes(); LOG.debug( "Checking parsed elements are correct from [" + list.getLength() + "] child nodes" ); for ( int i = 0; i < list.getLength(); ++i ) { if ( list.item( i ) instanceof Element ) { LOG.debug( "Checking [" + list.item( i ).getNodeName() + "]" ); Assert.assertEquals( list.item( i ).getNodeName().substring( 0, 9 ), "testlayer" ); } } } /** * This will test the parsing of a file that is not valid for the * schema. * * @throws IOException * @throws MercuryUtilityException */ @Test(expected = IllegalStateException.class) public void testParseInvalidXmlFile() throws IOException, MercuryUtilityException { // created good xml StringBuffer buff = new StringBuffer(); buff.append( "<?xml version=\"1.0\"?>\n" ) .append( "<xmlroot xmlns=\"http://www.suggs.org.uk/UnitTestSchema\">\n" ); buff.append( "</xmlroot>" ); // persist the data to a file LOG.debug( "Creating test file [" + TEST_FILE + "]" ); mFileManager_.persistClobToFile( buff.toString(), new File( TEST_FILE ) ); // no we do the actual parse LOG.debug( "Parsing file [" + TEST_FILE + "]" ); mDomParser_.createDocFromXmlFile( TEST_FILE, "xml/unit-test-schema.xsd" ); } /** * This will test the parsing of a file that is not valid for the * schema. * * @throws IOException * @throws MercuryUtilityException */ @Test(expected = IllegalStateException.class) public void testParseBadXmlFile() throws IOException, MercuryUtilityException { // created good xml StringBuffer buff = new StringBuffer(); buff.append( "<?xml version=\"1.0\"?>\n" ) .append( "<xmlroot xmlns=\"http://www.suggs.org.uk/UnitTestSchema\">\n" ); buff.append( "" ); // persist the data to a file LOG.debug( "Creating test file [" + TEST_FILE + "]" ); mFileManager_.persistClobToFile( buff.toString(), new File( TEST_FILE ) ); // no we do the actual parse LOG.debug( "Parsing file [" + TEST_FILE + "]" ); mDomParser_.createDocFromXmlFile( TEST_FILE, "xml/unit-test-schema.xsd" ); } /** * This will try and run the parser but without finding a schema * and thus will throw an exception. * * @throws MercuryUtilityException */ @Test(expected = MercuryUtilityException.class) public void testCantFindXsd() throws MercuryUtilityException { LOG.debug( "Calling the dom parser with no valid schema" ); mDomParser_.createDocFromXmlFile( new String(), "you-cant-find-me.xsd" ); } }
true
c391a2ae50d081ca2316717982ed3af201ca90fd
Java
alexandrefett/Vendi
/app/src/main/java/com/vendi/Utils.java
UTF-8
1,524
2.59375
3
[]
no_license
package com.vendi; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.RectF; import java.io.InputStream; import java.io.OutputStream; /** * Created by Alexandre on 19/07/2016. */ public class Utils { public static void CopyStream(InputStream is, OutputStream os) { final int buffer_size=1024; try { byte[] bytes=new byte[buffer_size]; for(;;) { int count=is.read(bytes, 0, buffer_size); if(count==-1) break; os.write(bytes, 0, count); } } catch(Exception ex){} } public static Bitmap scaleCenterCrop(Bitmap source, int newHeight, int newWidth) { int sourceWidth = source.getWidth(); int sourceHeight = source.getHeight(); float xScale = (float) newWidth / sourceWidth; float yScale = (float) newHeight / sourceHeight; float scale = Math.max(xScale, yScale); float scaledWidth = scale * sourceWidth; float scaledHeight = scale * sourceHeight; float left = (newWidth - scaledWidth) / 2; float top = (newHeight - scaledHeight) / 2; RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight); Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, source.getConfig()); Canvas canvas = new Canvas(dest); canvas.drawBitmap(source, null, targetRect, null); return dest; } }
true
69ad0c3fe850a3649f8fc759d70a9f5721db81cb
Java
yusupscopes/java-name-sorter
/SortLastNames.java
UTF-8
2,683
3.75
4
[]
no_license
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.io.IOException; import java.io.FileNotFoundException; import java.util.Scanner; public class SortLastNames { /** * Sort names by last name. * @param al ArrayList of names. * @return Sorted ArrayList of names. */ public ArrayList<String> sortLast(ArrayList<String> al) { Collections.sort(al, new Comparator<String>() { @Override public int compare(String o1, String o2) { String[] split1 = o1.split(" "); String[] split2 = o2.split(" "); String lastName1 = split1[1]; String lastName2 = split2[1]; if (lastName1.compareTo(lastName2) > 0) { return 1; } else { return -1; } } }); return al; } /** * Write sorted ArrayList of names to file. * @param al Sorted ArrayList of names. * @return void */ public static void writeFile(ArrayList<String> al) throws IOException { String path = System.getProperty("user.dir"); String SEPARATOR = System.getProperty("file.separator"); FileWriter fileWriter = new FileWriter(path + SEPARATOR + "sorted-names-list.txt"); PrintWriter printWriter = new PrintWriter(fileWriter); for (String str: al) { printWriter.println(str); } printWriter.close(); } /** * Read file that contains unsorted names. * @param args String of filename. * @return ArrayList of names (unsorted). */ public ArrayList<String> readFile(String args) { ArrayList<String> listName = new ArrayList<String>(); try { String path = System.getProperty("user.dir"); String SEPARATOR = System.getProperty("file.separator"); Scanner scanner = new Scanner(new File(path + SEPARATOR + args)); while (scanner.hasNextLine()) { listName.add(scanner.nextLine()); } scanner.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } return listName; } public static void main(String[] args) { ArrayList<String> unsortedNames; ArrayList<String> sortedNames; SortLastNames obj = new SortLastNames(); // call readfile method and pass the filename from arguments. unsortedNames = obj.readFile(args[0]); System.out.println("Sorted using Last Name"); // Call sortLast method to sort the names in that file. sortedNames = obj.sortLast(unsortedNames); // Write sorted names to the file try { SortLastNames.writeFile(sortedNames); } catch (IOException e) { e.printStackTrace(); } // Print out sorted names to the screen. for (int i = 0; i < sortedNames.size(); i++) { System.out.println(sortedNames.get(i)); } } }
true
25489587a1c06a9058dc5a3f87f2d37a6ea02dfe
Java
afique13/Data-Structure
/src/main/java/TUT02/Q1.java
UTF-8
1,217
3.484375
3
[]
no_license
/* * 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 TUT02; /** * * @author Owner */ //public class Q1<K,V> { // // private K a; // private K b; // // public static <K,V> void q1(K a, V b){ // if (a instanceof Integer && b instanceof Integer){ // System.out.print("The sum is : "); // System.out.println(((Integer)a)+((Number)b).intValue()); // } // else if (a instanceof Double && b instanceof Double){ // System.out.print("The sum is : "); // System.out.println(((Number)a).doubleValue()+((Number)b).doubleValue()); // } // else if(a instanceof String && b instanceof String){ // if(((String)a).contentEquals((String)b)==true){ // System.out.println("They are the same"); // } // else{ // System.out.println("They are not the same"); // } // } // else{ // System.out.println("These types are incompatible"); // } // } //}
true
68d404627044cb3082cf0ae0329c7ad30c811c46
Java
aj2694/Java-Programs
/Seedbook/src/tcp/Tcp_server.java
UTF-8
2,078
2.984375
3
[]
no_license
package tcp; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; public class Tcp_server implements Runnable { ServerSocket sc; Socket connection; BufferedReader br; Thread t1; public Tcp_server(){ t1=new Thread(this, "thread1"); t1.start(); } @Override public void run() { try { sc=new ServerSocket(2000); connection=sc.accept(); System.out.println("server ready"); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // TODO Auto-generated method stub BufferedReader dc; try { dc = new BufferedReader(new InputStreamReader(connection.getInputStream())); String filename=null; System.out.println("before wait"); while((filename=dc.readLine())!=null){ System.out.println(filename); break; } System.out.println("here"); //DataOutputStream dout=new DataOutputStream(connection.getOutputStream()); File fp=new File(filename); if(fp.exists()){ System.out.println("file found"); BufferedWriter wr=new BufferedWriter(new OutputStreamWriter(connection.getOutputStream())); wr.write("name"+fp.getName()); wr.write(fp.getAbsolutePath()); wr.close(); Thread.sleep(1000); } else{ System.out.println("not found"); } } catch (IOException | InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ try { connection.close(); System.out.println("connectionserverclosed"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
true
b3af1d9a1e2f3e1b5415119019a390ebf47bf5b7
Java
nevercaution/cachedTest
/src/main/java/com/nevercaution/cached_test/controller/PersonController.java
UTF-8
710
2.34375
2
[]
no_license
package com.nevercaution.cached_test.controller; import com.nevercaution.cached_test.model.Person; import com.nevercaution.cached_test.service.PersonService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController public class PersonController { @Autowired private PersonService personService; @GetMapping("/person/{name}") public ResponseEntity getPerson(@PathVariable(value = "name") String name) { Person person = personService.getPerson(name); System.out.println("getPerson = " + person); return ResponseEntity.ok().body(person); } }
true
db888698b8fa0872e3721e4e506a1d42f2170f7e
Java
scarlet25151/leetcodesolution
/binaryNumberInLinkedList.java
UTF-8
401
3.140625
3
[]
no_license
public class binaryNumberInLinkedList { public class SinglyLinkedListNode { int data; SinglyLinkedListNode next; } public long getNumber(SinglyLinkedListNode binary) { // Write your code here long res = 0; while (binary != null) { res = (res << 1) + binary.data; binary = binary.next; } return res; } }
true
d871f8ef1a70f7a25f1ca7d3271c4086b3fded83
Java
daymou/CLPN
/PIPE-4.3.2/src/main/java/pipe/modules/reachability/ReachabilityGraphGenerator.java
UTF-8
24,428
2.1875
2
[]
no_license
package pipe.modules.reachability; import java.awt.Checkbox; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.*; import java.text.DecimalFormat; import java.util.*; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JOptionPane; import net.sourceforge.jpowergraph.Edge; import net.sourceforge.jpowergraph.Node; import net.sourceforge.jpowergraph.defaults.DefaultGraph; import net.sourceforge.jpowergraph.defaults.DefaultNode; import net.sourceforge.jpowergraph.defaults.TextEdge; import pipe.calculations.*; import pipe.exceptions.MarkingNotIntegerException; import pipe.exceptions.TimelessTrapException; import pipe.exceptions.TreeTooBigException; import pipe.extensions.jpowergraph.*; import pipe.gui.ApplicationSettings; import pipe.gui.widgets.*; import pipe.io.ImmediateAbortException; import pipe.io.IncorrectFileFormatException; import pipe.io.ReachabilityGraphFileHeader; import pipe.io.StateRecord; import pipe.io.TransitionRecord; import pipe.modules.interfaces.IModule; import pipe.utilities.Expander; import pipe.utilities.writers.PNMLWriter; import pipe.views.MarkingView; import pipe.views.PetriNetView; import pipe.views.PlaceView; import pipe.views.LogicalTransitionView; /** * @author Matthew Worthington / Edwin Chung / Will Master * Created module to produce the reachability graph representation of a Petri * net. This module makes use of modifications that were made to the state space * generator to produce a list of possible states (both tangible and non * tangible) which are then transformed into a dot file. * The file is then translated into its graphical layout using * www.research.att.com hosting of Graphviz. It should therefore be noted that * a live internet connection is required. (Feb/March,2007) */ public class ReachabilityGraphGenerator implements IModule { private static final String MODULE_NAME = "Reachability/Coverability Graph"; private PetriNetChooserPanel sourceFilePanel; private static ResultsHTMLPane results; private final EscapableDialog guiDialog = new EscapableDialog(ApplicationSettings.getApplicationView(), MODULE_NAME, true); private static final Checkbox checkBox1 = new Checkbox("Display initial state(S0) in a different shape", false); private static String dataLayerName; private static Vector<Vector<String>> HazardousState=new Vector<Vector<String>>(); private static GraphHazardousFrame frame = new GraphHazardousFrame(); private static GraphFrame gframe=new GraphFrame(); //测试用 private PetriNetView pn; public void start() { PetriNetView pnmlData = ApplicationSettings.getApplicationView().getCurrentPetriNetView(); pn=pnmlData; // Check if this net is a CGSPN. If it is, then this // module won't work with it and we must convert it. if(pnmlData.getEnabledTokenClassNumber() > 1){ //if(pnmlData.getTokenViews().size() > 1) Expander expander = new Expander(pnmlData); pnmlData = expander.unfold(); JOptionPane.showMessageDialog(null, "This is CGSPN. The analysis will only apply to default color (black)", "Information", JOptionPane.INFORMATION_MESSAGE); } // Build interface // 1 Set layout Container contentPane = guiDialog.getContentPane(); contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.PAGE_AXIS)); // 2 Add file browser sourceFilePanel = new PetriNetChooserPanel("Source net", pnmlData); contentPane.add(sourceFilePanel); // 3 Add results pane results = new ResultsHTMLPane(pnmlData.getPNMLName()); contentPane.add(results); // 4 Add button's contentPane.add(new ButtonBar("Generate Reachability/Coverability Graph", generateGraph, guiDialog.getRootPane())); contentPane.add(new ButtonBar("Add Hazardous State", AddHazardous, guiDialog.getRootPane())); contentPane.add(checkBox1); // 5 Make window fit contents' preferred size guiDialog.pack(); // 6 Move window to the middle of the screen guiDialog.setLocationRelativeTo(null); checkBox1.setState(false); guiDialog.setModal(false); guiDialog.setVisible(false); guiDialog.setVisible(true); } //测试用 public void start(PetriNetView pnmlData) { pn=pnmlData; // Check if this net is a CGSPN. If it is, then this // module won't work with it and we must convert it. if(pnmlData.getEnabledTokenClassNumber() > 1){ //if(pnmlData.getTokenViews().size() > 1) Expander expander = new Expander(pnmlData); pnmlData = expander.unfold(); JOptionPane.showMessageDialog(null, "This is CGSPN. The analysis will only apply to default color (black)", "Information", JOptionPane.INFORMATION_MESSAGE); } // Build interface // 1 Set layout Container contentPane = guiDialog.getContentPane(); contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.PAGE_AXIS)); // 2 Add file browser sourceFilePanel = new PetriNetChooserPanel("Source net", pnmlData); contentPane.add(sourceFilePanel); // 3 Add results pane results = new ResultsHTMLPane(pnmlData.getPNMLName()); contentPane.add(results); // 4 Add button's contentPane.add(new ButtonBar("Generate Reachability/Coverability Graph", generateGraph, guiDialog.getRootPane())); contentPane.add(new ButtonBar("Add Hazardous State", AddHazardous, guiDialog.getRootPane())); contentPane.add(checkBox1); // 5 Make window fit contents' preferred size guiDialog.pack(); // 6 Move window to the middle of the screen guiDialog.setLocationRelativeTo(null); checkBox1.setState(false); guiDialog.setModal(false); guiDialog.setVisible(false); guiDialog.setVisible(true); } private final ActionListener generateGraph = new ActionListener() { public void actionPerformed(ActionEvent arg0) { long start = new Date().getTime(); long gfinished; long allfinished; double graphtime; double constructiontime; double totaltime; //data layer corrected, so that we could have the correct calculation //PetriNetView sourcePetriNetView = ApplicationSettings.getApplicationView().getCurrentPetriNetView();//sourceFilePanel.getDataLayer(); PetriNetView sourcePetriNetView=pn; dataLayerName = sourcePetriNetView.getPNMLName(); // This will be used to store the reachability graph data File reachabilityGraph = new File("results.rg"); File fullreachabilityGraph=new File("temp.rg"); // This will be used to store the steady state distribution String s = "<h2>Reachability/Coverability Graph Results</h2>"; if(sourcePetriNetView == null) { JOptionPane.showMessageDialog(null, "Please, choose a source net", "Error", JOptionPane.ERROR_MESSAGE); return; } if(!sourcePetriNetView.hasPlaceTransitionObjects()) { s += "No Petri net objects defined!"; } else { try { PNMLWriter.saveTemporaryFile(sourcePetriNetView, this.getClass().getName()); String graph = "Reachability graph"; boolean generateCoverability = false; try { //生成可达图 StateSpaceGenerator.generate2(sourcePetriNetView, fullreachabilityGraph); StateSpaceGenerator.generate(sourcePetriNetView, reachabilityGraph); } catch(OutOfMemoryError e) { // net seems to be unbounded, let's try to generate the // coverability graph generateCoverability = true; } LinkedList<MarkingView>[] markings = sourcePetriNetView.getCurrentMarkingVector(); int[] currentMarking = new int[markings.length]; for(int i = 0; i < markings.length; i++) { currentMarking[i] = markings[i].getFirst().getCurrentMarking(); } // TODO: reachability graph and coverability graph are the same // when the net is bounded so we could just generate the // coverability graph if(generateCoverability) { myTree tree = new myTree(sourcePetriNetView, currentMarking, reachabilityGraph); graph = "Coverability graph"; } gfinished = new Date().getTime(); System.gc(); //这里生成包含可达图的窗体 generateGraph(reachabilityGraph,fullreachabilityGraph, sourcePetriNetView, generateCoverability); allfinished = new Date().getTime(); graphtime = (gfinished - start) / 1000.0; constructiontime = (allfinished - gfinished) / 1000.0; totaltime = (allfinished - start) / 1000.0; DecimalFormat f = new DecimalFormat(); f.setMaximumFractionDigits(5); s += "<br>Generating " + graph + " took " + f.format(graphtime) + "s"; s += "<br>Constructing it took " + f.format(constructiontime) + "s"; s += "<br>Total time was " + f.format(totaltime) + "s"; results.setEnabled(true); } catch(OutOfMemoryError e) { System.gc(); results.setText(""); s = "Memory error: " + e.getMessage(); s += "<br>Not enough memory. Please use a larger heap size." + "<br>" + "<br>Note:" + "<br>The Java heap size can be specified with the -Xmx option." + "<br>E.g., to use 512MB as heap size, the command line looks like this:" + "<br>java -Xmx512m -classpath ...\n"; results.setText(s); return; } catch(StackOverflowError e) { s += "StackOverflow Error"; results.setText(s); return; } catch(ImmediateAbortException e) { s += "<br>Error: " + e.getMessage(); results.setText(s); return; } catch(TimelessTrapException e) { s += "<br>" + e.getMessage(); results.setText(s); return; } catch(IOException e) { s += "<br>" + e.getMessage(); results.setText(s); return; } catch(TreeTooBigException e) { s += "<br>" + e.getMessage(); results.setText(s); return; } catch (MarkingNotIntegerException e) { JOptionPane.showMessageDialog(null, "Weighting cannot be less than 0. Please re-enter"); sourcePetriNetView.restorePlaceViewsMarking(); return; } catch(Exception e) { e.printStackTrace(); s += "<br>Error" + e.getMessage(); results.setText(s); return; } finally { if(reachabilityGraph.exists()) { reachabilityGraph.delete(); } if(fullreachabilityGraph.exists()) { fullreachabilityGraph.delete(); } } } results.setText(s); } }; private final ActionListener AddHazardous =new ActionListener() { public void actionPerformed(ActionEvent e) { //PetriNetView sourcePetriNetView = ApplicationSettings.getApplicationView().getCurrentPetriNetView(); PetriNetView sourcePetriNetView=pn; frame.constructGraphHazardousFrame(sourcePetriNetView); } }; public String getName() { return MODULE_NAME; } //生成包含可达图的窗体,这里将可达图拓展 private void generateGraph(File rgFile,File tempFile, PetriNetView dataLayer, boolean coverabilityGraph) throws Exception { //包含可达图点与边的变量 DefaultGraph graph = createGraph(rgFile, dataLayer, coverabilityGraph); DefaultGraph fullgraph = createGraph(tempFile, dataLayer, coverabilityGraph); ExtensiveReachabilityGraph exgraph=new ExtensiveReachabilityGraph(dataLayer,fullgraph,graph); DefaultGraph ex=exgraph.ConstructExtensiveReachabilityGraph(); //验证可达图是否正确 // List<Node> nodes=ex.getAllNodes(); // HashMap<String,String> a=new HashMap<String, String>(); // for(int i=0;i<nodes.size();i++) // { // String temp=((PIPENode)nodes.get(i)).getMarking(); // String[] tempmarking=temp.replaceAll("[{}]","").trim().split("[,]"); // for(int j=2;j<tempmarking.length-1;j++) // { // String s=tempmarking[j]; // tempmarking[j]=tempmarking[j+1]; // tempmarking[j+1]=s; // } // String resmarking="("; // for(int j=0;j<tempmarking.length;j++) // { // resmarking+=(tempmarking[j]+","); // } // resmarking=resmarking.substring(0,resmarking.length()-1)+")"; // a.put(resmarking.replace(" ",""),((PIPENode)nodes.get(i)).getLabel()); // } // HashMap<String,String> b=new HashMap<String, String>(); // FileInputStream fis=new FileInputStream("test.txt"); // InputStreamReader isr=new InputStreamReader(fis); // BufferedReader br=new BufferedReader(isr); // String linetext=null; // while ((linetext=br.readLine())!=null) // { // String[] temp=linetext.replace(";","").split(":"); // b.put(temp[1],temp[0]); // } // // ArrayList<String[]> c=new ArrayList<String[]>(); // Iterator iter=a.entrySet().iterator(); // while (iter.hasNext()) // { // String[] temp=new String[2]; // HashMap.Entry entry = (HashMap.Entry) iter.next(); // temp[0]=(String) entry.getValue(); // temp[1]=b.get((String) entry.getKey()); // c.add(temp); // } PlaceView[] placeView = dataLayer.places(); String legend = ""; if(placeView.length > 0) { legend = "{" + placeView[0].getName(); } for(int i = 1; i < placeView.length; i++) { legend += ", " + placeView[i].getName(); } legend += "}"; //所有的节点与边被包含在了graph中,普通节点类型为PIPEVanishingState gframe.constructGraphFrame(ex, legend); HCAFrame hcaFrame=new HCAFrame(ex); hcaFrame.constructHCAtable(); //计算路径 Calculate_HCA cal=new Calculate_HCA(ex,hcaFrame.getHCAsses(),dataLayer); cal.getHcaRoad(); //ArrayList<ArrayList<Edge>> respath=cal.getRes_path(); //这里进行模拟 Simulation_HCA sim=new Simulation_HCA(ex,dataLayer,hcaFrame.getHCAsses()); sim.Simulation(); gframe.toFront(); gframe.setIconImage(( new ImageIcon(Thread.currentThread().getContextClassLoader(). getResource(ApplicationSettings.getImagePath() + "icon.png")).getImage())); gframe.setTitle(dataLayerName); } private static ArrayList<String> DetectHazardous(String mark) { ArrayList<String> Hazards=new ArrayList<String>(); for(int i=0;i<HazardousState.size();i++) { boolean flag=true; String markmode=HazardousState.elementAt(i).elementAt(2); if(mark.length()==markmode.length()) { for(int j =0;j<mark.length();j++) { if(mark.charAt(j)!=markmode.charAt(j)&&markmode.charAt(j)!='*') { flag=false; break; } } } if(flag) Hazards.add(HazardousState.elementAt(i).elementAt(0)); } return Hazards; } private static DefaultGraph createGraph(File rgFile, PetriNetView dataLayer, boolean coverabilityGraph) throws IOException { //包含可达图点与边的变量,在这里加入Harazardous state DefaultGraph graph = new DefaultGraph(); // //label转为paper上的以便debug // //b为Marking->Label // HashMap<String,String> b=new HashMap<String, String>(); // FileInputStream fis=new FileInputStream("test.txt"); // InputStreamReader isr=new InputStreamReader(fis); // BufferedReader br=new BufferedReader(isr); // String linetext=null; // while ((linetext=br.readLine())!=null) // { // String[] temp=linetext.replace(";","").split(":"); // b.put(temp[1],temp[0]); // } ReachabilityGraphFileHeader header = new ReachabilityGraphFileHeader(); RandomAccessFile reachabilityFile; try { reachabilityFile = new RandomAccessFile(rgFile, "r"); header.read(reachabilityFile); } catch(IncorrectFileFormatException e1) { System.err.println("createGraph: " + "incorrect file format on state space file"); return graph; } catch(IOException e1) { System.err.println("createGraph: unable to read header file"); return graph; } if((header.getNumStates() + header.getNumTransitions()) > 4000) { throw new IOException("There are " + header.getNumStates() + " states with " + header.getNumTransitions() + " arcs. The graph is too big to be displayed properly."); } //由于编译时报错:某些输入文件使用了未经检查或不安全的操作。将ArrayList nodes之类改为ArrayList<E> node ArrayList<Node> nodes = new ArrayList<Node>(); ArrayList<Edge> edges = new ArrayList<Edge>(); ArrayList<Node> loopEdges = new ArrayList<Node>(); ArrayList<String> loopEdgesTransitions = new ArrayList<String>(); String label; String marking; HazardousState=frame.getData(); int stateArraySize = header.getStateArraySize(); StateRecord record = new StateRecord(); record.read1(stateArraySize, reachabilityFile); label = "M0"; marking = record.getMarkingString(); //label=b.get(marking); if(record.getTangible()) { if(checkBox1.getState()) { nodes.add(coverabilityGraph ? new PIPEInitialState(label, marking) : new PIPEInitialTangibleState(label, marking)); } else { nodes.add(coverabilityGraph ? new PIPEState(label, marking) : new PIPETangibleState(label, marking)); } } else { if(checkBox1.getState()) { nodes.add(coverabilityGraph ? new PIPEInitialState(label, marking) : new PIPEInitialVanishingState(label, marking)); } else { nodes.add(coverabilityGraph ? new PIPEState(label, marking) : new PIPEVanishingState(label, marking)); } } //这里node添加时加入新的类,弄个方形的 for(int count = 1; count < header.getNumStates(); count++) { record.read1(stateArraySize, reachabilityFile); label = "M" + count; marking = record.getMarkingString(); //label=b.get(marking); //若该节点的标价满足某个Hazard条件,则添加为HazardousState ArrayList<String> hazards=DetectHazardous(marking); if(hazards.size()!=0) { nodes.add(new PIPEHazardousState(label,marking,hazards)); } else { if (record.getTangible()) { nodes.add(coverabilityGraph ? new PIPEState(label, marking) : new PIPETangibleState(label, marking)); } else { nodes.add(coverabilityGraph ? new PIPEState(label, marking) : new PIPEVanishingState(label, marking)); } } } reachabilityFile.seek(header.getOffsetToTransitions()); int numberTransitions = header.getNumTransitions(); for(int transitionCounter = 0; transitionCounter < numberTransitions; transitionCounter++) { TransitionRecord transitions = new TransitionRecord(); transitions.read1(reachabilityFile); int from = transitions.getFromState(); int to = transitions.getToState(); if(from != to) { if(dataLayer.getTransition(transitions.getTransitionNo()) instanceof LogicalTransitionView) edges.add(new PIPECATextEdge( (DefaultNode) (nodes.get(from)), (DefaultNode) (nodes.get(to)), dataLayer.getTransitionName(transitions.getTransitionNo()),((LogicalTransitionView) dataLayer.getTransition(transitions.getTransitionNo())).getAction_name())); else edges.add(new TextEdge( (DefaultNode) (nodes.get(from)), (DefaultNode) (nodes.get(to)), dataLayer.getTransitionName(transitions.getTransitionNo()))); } else { if(loopEdges.contains(nodes.get(from))) { int i = loopEdges.indexOf(nodes.get(from)); loopEdgesTransitions.set(i, loopEdgesTransitions.get(i) + ", " + dataLayer.getTransitionName(transitions.getTransitionNo())); } else { loopEdges.add(nodes.get(from)); loopEdgesTransitions.add( dataLayer.getTransitionName(transitions.getTransitionNo())); } } } for(int i = 0; i < loopEdges.size(); i++) { edges.add(new PIPELoopWithTextEdge((DefaultNode) (loopEdges.get(i)), (String) (loopEdgesTransitions.get(i)))); } graph.addElements(nodes, edges); reachabilityFile.close(); return graph; } private static DefaultGraph createExtensiveGraph(File rgFile, PetriNetView dataLayer, boolean coverabilityGraph) throws IOException { //包含可达图点与边的变量,在这里加入Harazardous state DefaultGraph graph = new DefaultGraph(); // //label转为paper上的以便debug // //b为Marking->Label // HashMap<String,String> b=new HashMap<String, String>(); // FileInputStream fis=new FileInputStream("test.txt"); // InputStreamReader isr=new InputStreamReader(fis); // BufferedReader br=new BufferedReader(isr); // String linetext=null; // while ((linetext=br.readLine())!=null) // { // String[] temp=linetext.replace(";","").split(":"); // b.put(temp[1],temp[0]); // } ReachabilityGraphFileHeader header = new ReachabilityGraphFileHeader(); RandomAccessFile reachabilityFile; try { reachabilityFile = new RandomAccessFile(rgFile, "r"); header.read(reachabilityFile); } catch(IncorrectFileFormatException e1) { System.err.println("createGraph: " + "incorrect file format on state space file"); return graph; } catch(IOException e1) { System.err.println("createGraph: unable to read header file"); return graph; } if((header.getNumStates() + header.getNumTransitions()) > 400) { throw new IOException("There are " + header.getNumStates() + " states with " + header.getNumTransitions() + " arcs. The graph is too big to be displayed properly."); } //由于编译时报错:某些输入文件使用了未经检查或不安全的操作。将ArrayList nodes之类改为ArrayList<E> node ArrayList<Node> nodes = new ArrayList<Node>(); ArrayList<Edge> edges = new ArrayList<Edge>(); ArrayList<Node> loopEdges = new ArrayList<Node>(); ArrayList<String> loopEdgesTransitions = new ArrayList<String>(); String label; String marking; HazardousState=frame.getData(); int stateArraySize = header.getStateArraySize(); StateRecord record = new StateRecord(); record.read1(stateArraySize, reachabilityFile); label = "M0"; marking = record.getMarkingString(); //label=b.get(marking); if(record.getTangible()) { if(checkBox1.getState()) { nodes.add(coverabilityGraph ? new PIPEInitialState(label, marking) : new PIPEInitialTangibleState(label, marking)); } else { nodes.add(coverabilityGraph ? new PIPEState(label, marking) : new PIPETangibleState(label, marking)); } } else { if(checkBox1.getState()) { nodes.add(coverabilityGraph ? new PIPEInitialState(label, marking) : new PIPEInitialVanishingState(label, marking)); } else { nodes.add(coverabilityGraph ? new PIPEState(label, marking) : new PIPEVanishingState(label, marking)); } } //这里node添加时加入新的类,弄个方形的 for(int count = 1; count < header.getNumStates(); count++) { record.read1(stateArraySize, reachabilityFile); label = "M" + count; marking = record.getMarkingString(); //label=b.get(marking); //若该节点的标价满足某个Hazard条件,则添加为HazardousState ArrayList<String> hazards=DetectHazardous(marking); if(hazards.size()!=0) { nodes.add(new PIPEHazardousState(label,marking,hazards)); } else { if (record.getTangible()) { nodes.add(coverabilityGraph ? new PIPEState(label, marking) : new PIPETangibleState(label, marking)); } else { nodes.add(coverabilityGraph ? new PIPEState(label, marking) : new PIPEVanishingState(label, marking)); } } } reachabilityFile.seek(header.getOffsetToTransitions()); int numberTransitions = header.getNumTransitions(); for(int transitionCounter = 0; transitionCounter < numberTransitions; transitionCounter++) { TransitionRecord transitions = new TransitionRecord(); transitions.read1(reachabilityFile); int from = transitions.getFromState(); int to = transitions.getToState(); if(from != to) { edges.add(new TextEdge( (DefaultNode) (nodes.get(from)), (DefaultNode) (nodes.get(to)), dataLayer.getTransitionName(transitions.getTransitionNo()))); } else { if(loopEdges.contains(nodes.get(from))) { int i = loopEdges.indexOf(nodes.get(from)); loopEdgesTransitions.set(i, loopEdgesTransitions.get(i) + ", " + dataLayer.getTransitionName(transitions.getTransitionNo())); } else { loopEdges.add(nodes.get(from)); loopEdgesTransitions.add( dataLayer.getTransitionName(transitions.getTransitionNo())); } } } for(int i = 0; i < loopEdges.size(); i++) { edges.add(new PIPELoopWithTextEdge((DefaultNode) (loopEdges.get(i)), (String) (loopEdgesTransitions.get(i)))); } graph.addElements(nodes, edges); return graph; } }
true
fce5afe5682a6c38640f9e839cbc3a2ac945e5ae
Java
qq9630232/Management
/app/src/main/java/com/example/freightmanagement/presenter/TrainingPresenter.java
UTF-8
1,575
2
2
[]
no_license
package com.example.freightmanagement.presenter; import com.example.freightmanagement.Base.BaseApiConstants; import com.example.freightmanagement.Base.BasePresenter; import com.example.freightmanagement.Utils.Network.OnRequestResultForCommon; import com.example.freightmanagement.Utils.Network.RestApi; import com.example.freightmanagement.presenter.constract.TrainingConstact; /** * Created by songdechuan on 2020/8/6. */ public class TrainingPresenter extends BasePresenter<TrainingConstact.View> implements TrainingConstact { @Override public void getTrainingList() { RestApi.getInstance().get(BaseApiConstants.API_TRAINING, new OnRequestResultForCommon() { @Override public void onSuccess(String json) { mView.trainingList(json); } @Override public void onFail() { super.onFail(); } @Override public void netUnlink() { super.netUnlink(); } }); } @Override public void getTestList(int id) { RestApi.getInstance().get("/cccc/examination/getExaminationDriverDatas/"+id, new OnRequestResultForCommon() { @Override public void onSuccess(String json) { mView.testResult(json); } @Override public void onFail() { super.onFail(); } @Override public void netUnlink() { super.netUnlink(); } }); } }
true
742a8fd1296ebd9d075541647a745d7364fa9cb7
Java
yusufjiruwala/channelPOS13
/src/com/forms/panels/frmDelivery.java
UTF-8
76,938
1.640625
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * frmDelivery.java * * Created on Apr 16, 2014, 3:42:01 PM */ package com.forms.panels; import com.forms.MainFrame; import com.forms.lovDialog; import com.generic.model.Row; import com.generic.model.localTableModel; import com.generic.model.qryColumn; import com.generic.utils.NumberEditor; import com.generic.utils.QueryExe; import com.generic.utils.utils; import com.keyboard.KeyBoardFrame; import com.keyboard.KeyBoardSelectionListner; import com.keyboard.keyboardViewer; import com.lov.selectListView; import java.awt.Color; import java.awt.KeyboardFocusManager; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.InputVerifier; import javax.swing.JComponent; import javax.swing.JFormattedTextField; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTabbedPane; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.event.CellEditorListener; import javax.swing.event.ChangeEvent; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.text.JTextComponent; /** * * @author Yusuf */ public class frmDelivery extends javax.swing.JDialog { private double keyfld = -1; private localTableModel payRows = new localTableModel(5); public double sumPaidAmt = 0; public double sumNetAmt = 0; public double sumCashAmt = 0; /** Creates new form frmDelivery */ public frmDelivery(double kf, java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); setLocationRelativeTo(null); this.keyfld = kf; setParentJf((MainFrame) parent); utils.setupFormTextBoxes(getRootPane().getContentPane()); } /** 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(); pnlBasic = new javax.swing.JPanel(); jLabel14 = new javax.swing.JLabel(); adrDeliveryDate = new javax.swing.JTextField(); adrHour = new javax.swing.JSpinner(); adrMin = new javax.swing.JSpinner(); jLabel1 = new javax.swing.JLabel(); adrCustomerName = new javax.swing.JTextField(); jLabel12 = new javax.swing.JLabel(); chkPickup = new javax.swing.JCheckBox(); jPanel5 = new javax.swing.JPanel(); jLabel13 = new javax.swing.JLabel(); adrArea = new javax.swing.JComboBox(); jLabel2 = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); adrPhone = new javax.swing.JTextField(); jButton3 = new javax.swing.JButton(); jLabel19 = new javax.swing.JLabel(); adrBlock = new javax.swing.JTextField(); jLabel15 = new javax.swing.JLabel(); adrOtherTel = new javax.swing.JTextField(); jLabel20 = new javax.swing.JLabel(); adrStreet = new javax.swing.JTextField(); jLabel21 = new javax.swing.JLabel(); adrJedda = new javax.swing.JTextField(); jLabel22 = new javax.swing.JLabel(); adrBldg = new javax.swing.JTextField(); jLabel23 = new javax.swing.JLabel(); adrFloorNo = new javax.swing.JTextField(); jLabel16 = new javax.swing.JLabel(); adrWorkAddress = new javax.swing.JTextField(); jLabel17 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); adrNotes = new javax.swing.JTextArea(); adrEmail = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); pnlRecipt = new javax.swing.JPanel(); jPanel6 = new javax.swing.JPanel(); jLabel18 = new javax.swing.JLabel(); adrRArea = new javax.swing.JComboBox(); jLabel3 = new javax.swing.JLabel(); adrRPhone = new javax.swing.JTextField(); jLabel24 = new javax.swing.JLabel(); adrRBlock1 = new javax.swing.JTextField(); jLabel25 = new javax.swing.JLabel(); adrROtherTel = new javax.swing.JTextField(); jLabel26 = new javax.swing.JLabel(); adrRStreet = new javax.swing.JTextField(); jLabel27 = new javax.swing.JLabel(); adrRJedda = new javax.swing.JTextField(); jLabel28 = new javax.swing.JLabel(); adrRBldg = new javax.swing.JTextField(); jLabel29 = new javax.swing.JLabel(); adrRFloorNo = new javax.swing.JTextField(); jLabel30 = new javax.swing.JLabel(); adrRWorkAddress = new javax.swing.JTextField(); chkRCopyClient = new javax.swing.JCheckBox(); pnlAdvPayment = new javax.swing.JPanel(); pnlMultiplePay = new javax.swing.JPanel(); sumTxtPaidAmt = new javax.swing.JTextField(); jScrollPane4 = new javax.swing.JScrollPane(); payTable = new javax.swing.JTable(); msg = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); pnlKb = new javax.swing.JPanel(); jButton5 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setBackground(new java.awt.Color(-16711936,true)); addWindowListener(new java.awt.event.WindowAdapter() { public void windowOpened(java.awt.event.WindowEvent evt) { frmDelivery.this.windowOpened(evt); } }); jTabbedPane1.setBackground(new java.awt.Color(-1,true)); jTabbedPane1.setFont(new java.awt.Font("Dialog", 0, 18)); jTabbedPane1.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { jTabbedPane1StateChanged(evt); } }); pnlBasic.setBackground(new java.awt.Color(-1,true)); pnlBasic.setToolTipText(""); jLabel14.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel14.setText("Delivery Date Time"); adrDeliveryDate.setMaximumSize(null); adrDeliveryDate.setMinimumSize(null); adrDeliveryDate.setPreferredSize(new java.awt.Dimension(50, 50)); adrDeliveryDate.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { adrDeliveryDateActionPerformed(evt); } }); adrDeliveryDate.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { frmDelivery.this.focusGained(evt); } }); adrHour.setModel(new javax.swing.SpinnerNumberModel(0, 0, 23, 1)); adrHour.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); adrHour.setName(""); // NOI18N adrMin.setModel(new javax.swing.SpinnerNumberModel(0, 0, 59, 1)); jLabel1.setText("Hour / Minutes"); adrCustomerName.setMaximumSize(null); adrCustomerName.setMinimumSize(null); adrCustomerName.setPreferredSize(null); adrCustomerName.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { adrCustomerNameActionPerformed(evt); } }); jLabel12.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel12.setText("Customer Name"); chkPickup.setFont(new java.awt.Font("Dialog", 0, 14)); chkPickup.setText("Pick up by client"); chkPickup.setOpaque(false); jPanel5.setBackground(new java.awt.Color(-1,true)); jPanel5.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(-16777216,true))); jPanel5.setLayout(new java.awt.GridLayout(3, 6, 5, 5)); jLabel13.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel13.setText("AREA"); jPanel5.add(jLabel13); adrArea.setEditable(true); adrArea.setMaximumSize(null); adrArea.setMinimumSize(null); adrArea.setPreferredSize(null); adrArea.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { adrAreaActionPerformed(evt); } }); jPanel5.add(adrArea); jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel2.setText("Phone/ID"); jPanel5.add(jLabel2); adrPhone.setMaximumSize(null); adrPhone.setMinimumSize(null); adrPhone.setPreferredSize(null); adrPhone.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { adrPhoneActionPerformed(evt); } }); adrPhone.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { adrPhoneFocusLost(evt); } }); jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/forms/panels/images/find.png"))); // NOI18N jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(adrPhone, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(adrPhone, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE) ); jPanel5.add(jPanel1); jLabel19.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel19.setText("Block"); jPanel5.add(jLabel19); adrBlock.setMaximumSize(null); adrBlock.setMinimumSize(null); adrBlock.setPreferredSize(null); jPanel5.add(adrBlock); jLabel15.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel15.setText("Other Tel"); jPanel5.add(jLabel15); adrOtherTel.setMaximumSize(null); adrOtherTel.setMinimumSize(null); adrOtherTel.setPreferredSize(null); adrOtherTel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { adrOtherTelActionPerformed(evt); } }); jPanel5.add(adrOtherTel); jLabel20.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel20.setText("Street"); jPanel5.add(jLabel20); adrStreet.setMaximumSize(null); adrStreet.setMinimumSize(null); adrStreet.setPreferredSize(null); jPanel5.add(adrStreet); jLabel21.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel21.setText("Jedda"); jPanel5.add(jLabel21); adrJedda.setMaximumSize(null); adrJedda.setMinimumSize(null); adrJedda.setPreferredSize(null); jPanel5.add(adrJedda); jLabel22.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel22.setText("Building"); jPanel5.add(jLabel22); adrBldg.setMaximumSize(null); adrBldg.setMinimumSize(null); adrBldg.setPreferredSize(null); jPanel5.add(adrBldg); jLabel23.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel23.setText("Floor No"); jPanel5.add(jLabel23); adrFloorNo.setMaximumSize(null); adrFloorNo.setMinimumSize(null); adrFloorNo.setPreferredSize(null); adrFloorNo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { adrFloorNoActionPerformed(evt); } }); jPanel5.add(adrFloorNo); jLabel16.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel16.setText("Flat No/Unit No"); jPanel5.add(jLabel16); adrWorkAddress.setMaximumSize(null); adrWorkAddress.setMinimumSize(null); adrWorkAddress.setPreferredSize(null); jPanel5.add(adrWorkAddress); jLabel17.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel17.setText("Order Notes"); adrNotes.setColumns(20); adrNotes.setRows(5); jScrollPane1.setViewportView(adrNotes); jLabel4.setText("Email "); javax.swing.GroupLayout pnlBasicLayout = new javax.swing.GroupLayout(pnlBasic); pnlBasic.setLayout(pnlBasicLayout); pnlBasicLayout.setHorizontalGroup( pnlBasicLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlBasicLayout.createSequentialGroup() .addContainerGap() .addGroup(pnlBasicLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlBasicLayout.createSequentialGroup() .addGroup(pnlBasicLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel14, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(pnlBasicLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlBasicLayout.createSequentialGroup() .addComponent(adrDeliveryDate, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(adrHour, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(adrMin, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 61, Short.MAX_VALUE) .addComponent(chkPickup, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(adrCustomerName, javax.swing.GroupLayout.DEFAULT_SIZE, 565, Short.MAX_VALUE))) .addGroup(pnlBasicLayout.createSequentialGroup() .addGap(6, 6, 6) .addGroup(pnlBasicLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel17, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(pnlBasicLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(pnlBasicLayout.createSequentialGroup() .addComponent(adrEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 248, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 348, Short.MAX_VALUE)) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 596, Short.MAX_VALUE))) .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, 708, Short.MAX_VALUE)) .addContainerGap()) ); pnlBasicLayout.setVerticalGroup( pnlBasicLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlBasicLayout.createSequentialGroup() .addContainerGap() .addGroup(pnlBasicLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel14, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(pnlBasicLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(adrDeliveryDate, javax.swing.GroupLayout.DEFAULT_SIZE, 31, Short.MAX_VALUE) .addComponent(jLabel1) .addComponent(adrHour, javax.swing.GroupLayout.DEFAULT_SIZE, 31, Short.MAX_VALUE) .addComponent(adrMin, javax.swing.GroupLayout.DEFAULT_SIZE, 31, Short.MAX_VALUE) .addComponent(chkPickup))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(pnlBasicLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(adrCustomerName, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(pnlBasicLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlBasicLayout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(pnlBasicLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(adrEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4))) .addComponent(jLabel17, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(25, 25, 25)) ); jTabbedPane1.addTab("Basic", new javax.swing.ImageIcon(getClass().getResource("/com/forms/panels/images/board.png")), pnlBasic, ""); // NOI18N pnlRecipt.setBackground(new java.awt.Color(-1,true)); jPanel6.setBackground(new java.awt.Color(-1,true)); jPanel6.setBorder(new javax.swing.border.SoftBevelBorder(0)); jPanel6.setLayout(new java.awt.GridLayout(3, 6, 5, 5)); jLabel18.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel18.setText("AREA"); jPanel6.add(jLabel18); adrRArea.setEditable(true); adrRArea.setMaximumSize(null); adrRArea.setMinimumSize(null); adrRArea.setPreferredSize(null); adrRArea.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { adrRAreaActionPerformed(evt); } }); jPanel6.add(adrRArea); jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel3.setText("Phone"); jPanel6.add(jLabel3); adrRPhone.setMaximumSize(null); adrRPhone.setMinimumSize(null); adrRPhone.setPreferredSize(null); adrRPhone.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { adrRPhoneActionPerformed(evt); } }); adrRPhone.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { adrRPhoneFocusLost(evt); } }); jPanel6.add(adrRPhone); jLabel24.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel24.setText("Block"); jPanel6.add(jLabel24); adrRBlock1.setMaximumSize(null); adrRBlock1.setMinimumSize(null); adrRBlock1.setPreferredSize(null); jPanel6.add(adrRBlock1); jLabel25.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel25.setText("Other Tel"); jPanel6.add(jLabel25); adrROtherTel.setMaximumSize(null); adrROtherTel.setMinimumSize(null); adrROtherTel.setPreferredSize(null); adrROtherTel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { adrROtherTelActionPerformed(evt); } }); jPanel6.add(adrROtherTel); jLabel26.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel26.setText("Street"); jPanel6.add(jLabel26); adrRStreet.setMaximumSize(null); adrRStreet.setMinimumSize(null); adrRStreet.setPreferredSize(null); jPanel6.add(adrRStreet); jLabel27.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel27.setText("Jedda"); jPanel6.add(jLabel27); adrRJedda.setMaximumSize(null); adrRJedda.setMinimumSize(null); adrRJedda.setPreferredSize(null); jPanel6.add(adrRJedda); jLabel28.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel28.setText("Building"); jPanel6.add(jLabel28); adrRBldg.setMaximumSize(null); adrRBldg.setMinimumSize(null); adrRBldg.setPreferredSize(null); jPanel6.add(adrRBldg); jLabel29.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel29.setText("Floor No"); jPanel6.add(jLabel29); adrRFloorNo.setMaximumSize(null); adrRFloorNo.setMinimumSize(null); adrRFloorNo.setPreferredSize(null); adrRFloorNo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { adrRFloorNoActionPerformed(evt); } }); jPanel6.add(adrRFloorNo); jLabel30.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel30.setText("Flat No/Unit No"); jPanel6.add(jLabel30); adrRWorkAddress.setMaximumSize(null); adrRWorkAddress.setMinimumSize(null); adrRWorkAddress.setPreferredSize(null); jPanel6.add(adrRWorkAddress); chkRCopyClient.setBackground(new java.awt.Color(-20561,true)); chkRCopyClient.setText("Copy Client Address"); chkRCopyClient.setOpaque(false); chkRCopyClient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { chkRCopyClientActionPerformed(evt); } }); javax.swing.GroupLayout pnlReciptLayout = new javax.swing.GroupLayout(pnlRecipt); pnlRecipt.setLayout(pnlReciptLayout); pnlReciptLayout.setHorizontalGroup( pnlReciptLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlReciptLayout.createSequentialGroup() .addContainerGap() .addGroup(pnlReciptLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(chkRCopyClient, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, 658, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(50, Short.MAX_VALUE)) ); pnlReciptLayout.setVerticalGroup( pnlReciptLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlReciptLayout.createSequentialGroup() .addComponent(chkRCopyClient) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(189, Short.MAX_VALUE)) ); jTabbedPane1.addTab("Recipient", new javax.swing.ImageIcon(getClass().getResource("/com/forms/panels/images/finish_all.png")), pnlRecipt); // NOI18N pnlAdvPayment.setBackground(new java.awt.Color(-1,true)); pnlMultiplePay.setBackground(new java.awt.Color(-1,true)); sumTxtPaidAmt.setEditable(false); sumTxtPaidAmt.setFont(new java.awt.Font("Tahoma", 1, 18)); sumTxtPaidAmt.setHorizontalAlignment(javax.swing.JTextField.RIGHT); sumTxtPaidAmt.setText("0"); sumTxtPaidAmt.setName("sumTxtCashAmt"); // NOI18N sumTxtPaidAmt.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { sumTxtPaidAmtActionPerformed(evt); } }); sumTxtPaidAmt.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { sumTxtPaidAmtsumTxtDiscAmtFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { sumTxtPaidAmtsumTxtDiscAmtFocusLost(evt); } }); jScrollPane4.setBackground(new java.awt.Color(-20561,true)); payTable.setFont(new java.awt.Font("Times New Roman", 1, 24)); payTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4", "Title 5" } )); payTable.setRowHeight(30); payTable.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { paytablemouseClicked(evt); } }); jScrollPane4.setViewportView(payTable); msg.setFont(new java.awt.Font("Dialog", 0, 14)); msg.setForeground(new java.awt.Color(-16776961,true)); msg.setText("msg"); javax.swing.GroupLayout pnlMultiplePayLayout = new javax.swing.GroupLayout(pnlMultiplePay); pnlMultiplePay.setLayout(pnlMultiplePayLayout); pnlMultiplePayLayout.setHorizontalGroup( pnlMultiplePayLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlMultiplePayLayout.createSequentialGroup() .addContainerGap() .addGroup(pnlMultiplePayLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 294, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(sumTxtPaidAmt, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(msg, javax.swing.GroupLayout.PREFERRED_SIZE, 363, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(47, Short.MAX_VALUE)) ); pnlMultiplePayLayout.setVerticalGroup( pnlMultiplePayLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlMultiplePayLayout.createSequentialGroup() .addGroup(pnlMultiplePayLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlMultiplePayLayout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(sumTxtPaidAmt, javax.swing.GroupLayout.DEFAULT_SIZE, 46, Short.MAX_VALUE)) .addComponent(msg, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); javax.swing.GroupLayout pnlAdvPaymentLayout = new javax.swing.GroupLayout(pnlAdvPayment); pnlAdvPayment.setLayout(pnlAdvPaymentLayout); pnlAdvPaymentLayout.setHorizontalGroup( pnlAdvPaymentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(pnlMultiplePay, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pnlAdvPaymentLayout.setVerticalGroup( pnlAdvPaymentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlAdvPaymentLayout.createSequentialGroup() .addComponent(pnlMultiplePay, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); jTabbedPane1.addTab("Advance Payments", new javax.swing.ImageIcon(getClass().getResource("/com/forms/panels/images/start_all.png")), pnlAdvPayment); // NOI18N jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/forms/panels/images/ok.png"))); // NOI18N jButton1.setText("OK"); jButton1.setOpaque(false); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/forms/panels/images/cancel.png"))); // NOI18N jButton2.setText("Cancel"); jButton2.setOpaque(false); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/forms/panels/images/details.png"))); // NOI18N jButton4.setText("Previous Orders"); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); javax.swing.GroupLayout pnlKbLayout = new javax.swing.GroupLayout(pnlKb); pnlKb.setLayout(pnlKbLayout); pnlKbLayout.setHorizontalGroup( pnlKbLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 723, Short.MAX_VALUE) ); pnlKbLayout.setVerticalGroup( pnlKbLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 175, Short.MAX_VALUE) ); jButton5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/forms/panels/images/keyboard.png"))); // NOI18N jButton5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton5ActionPerformed(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() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jButton4) .addGap(287, 287, 287) .addComponent(jButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 723, Short.MAX_VALUE) .addComponent(pnlKb, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 30, Short.MAX_VALUE) .addComponent(jButton1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(11, 11, 11) .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(pnlKb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed try { if (sumPaidAmt > 0 && !is_delivery_payment_posted(parentJf, parentJf.getSp().dataInv_date, -1)) { throw new Exception("Can not enter advance amount in closed date !"); } do_ok(); } catch (Exception ex) { Logger.getLogger(frmDelivery.class.getName()).log(Level.SEVERE, null, ex); try { dbConnection.rollback(); } catch (SQLException ex1) { } JOptionPane.showMessageDialog(this, ex.getMessage()); } }//GEN-LAST:event_jButton1ActionPerformed public void do_ok() throws Exception { if (adrDeliveryDate.getText() == null || adrDeliveryDate.getText().isEmpty()) { throw new SQLException("Must specifiy delivery date !"); } if (adrPhone.getText() == null || adrPhone.getText().isEmpty()) { throw new SQLException("Must specifiy phone !"); } if (adrCustomerName.getText() == null || adrCustomerName.getText().length() == 0) { throw new Exception("Must enter name of customer "); } Date dt = dateformat.parse(adrDeliveryDate.getText()); Timestamp dt2 = new Timestamp(dateformat2.parse(adrDeliveryDate.getText() + " " + adrHour.getModel().getValue() + ":" + adrMin.getModel().getValue()).getTime()); Date tdt = new Date(System.currentTimeMillis()); if (keyfld <= -1) { if (dt2.compareTo(tdt) < 0) { throw new Exception("Date must select greater than today date & Time ! # " + tdt.toString()); } PreparedStatement psk = dbConnection.prepareStatement("select nvl(max(keyfld),0)+1 keyfld ,nvl(max(b_no),0)+1 b_no from pos_onpur1", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rsk = psk.executeQuery(); if (rsk != null && rsk.first()) { keyfld = rsk.getDouble("keyfld"); dataBkInvoiceNo = rsk.getDouble("b_no"); rsk.close(); } } else { dataBkInvoiceNo = Double.valueOf(utils.getSqlValue("select b_no from pos_onpur1 where keyfld='" + keyfld + "'", dbConnection)); } QueryExe qe = new QueryExe(" begin " + "delete from pos_onpur1 where keyfld= :KEYFLD ; " + "" + " insert into pos_onpur1(KEYFLD, LOCATION_CODE, B_KIND, B_NO, B_DATE, B_DATETIME," + " DELIVERY_DATETIME, CUST_REFERENCE, TABLE_CODE," + " FLAG, CLOSING_TIME, INV_AMT, DISC_AMT, SLSMN, CUST_COUNTS," + " AREA, TEL, HOME_ADDRESS, WORK_ADDRESS, EMAIL, BDETAIL, " + " BCUST, TERMOFPAY, REMARK, REFERENCE, SPEC_COMMENTS, COMPLAINS, " + " LAST_DRIVER, ADDR_AREA, ADDR_BLOCK, ADDR_JEDDA, ADDR_STREET, ADDR_BLDG, ADDR_TEL , ADDR_FLOOR ," + " ADDR_R_AREA, ADDR_R_BLOCK, ADDR_R_JEDDA, ADDR_R_STREET, ADDR_R_BLDG, ADDR_R_TEL , " + " ADDR_R_FLOOR, CUST_NAME, PICK_UP,RECIPIENT_ADDRESS " + ") VALUES " + "(:KEYFLD, :LOCATION_CODE, :B_KIND, :B_NO, :B_DATE, :B_DATETIME," + ":DELIVERY_DATETIME, :CUST_REFERENCE, :TABLE_CODE," + " :FLAG, :CLOSING_TIME, (SELECT NVL(SUM((PRICE/PACK)*ALLQTY),0) FROM POS_ONPUR2 WHERE KEYFLD= :KEYFLD ) , " + " :DISC_AMT, :SLSMN, :CUST_COUNTS," + " :AREA, :TEL, :HOME_ADDRESS, :WORK_ADDRESS, :EMAIL, :BDETAIL," + " :BCUST, :TERMOFPAY, :REMARK, :REFERENCE, :SPEC_COMMENTS, :COMPLAINS," + " :LAST_DRIVER, :ADDR_AREA, :ADDR_BLOCK, :ADDR_JEDDA, :ADDR_STREET, :ADDR_BLDG, :ADDR_TEL, :ADDR_FLOOR," + " :ADDR_R_AREA, :ADDR_R_BLOCK, :ADDR_R_JEDDA, :ADDR_R_STREET, :ADDR_R_BLDG, :ADDR_R_TEL, :ADDR_R_FLOOR , :CUST_NAME, :PICK_UP ,:RECIPIENT_ADDRESS " + "); " + " DELETE FROM POSCUSTOMER WHERE CODE= :CUST_REFERENCE ; " + " INSERT INTO POSCUSTOMER (" + " CODE, NAME, NAMEA," + " AREA, TEL, HOME_ADDRESS," + " WORK_ADDRESS, FLAG, EMAIL," + " SPEC_COMMENTS," + " COMPLAINS, LAST_DRIVER,addr_jedda,addr_block,addr_street,addr_bldg, reference" + " ) values ( " + " :CUST_REFERENCE, :CUST_NAME, ''," + " :AREA, :TEL, :HOME_ADDRESS," + " :WORK_ADDRESS, 1, :EMAIL," + " :SPEC_COMMENTS," + " :COMPLAINS, :LAST_DRIVER, :addr_jedda, :addr_block, :addr_street, :addr_bldg, :reference" + " );" + "end;", dbConnection); qe.setParaValue("KEYFLD", keyfld); qe.setParaValue("LOCATION_CODE", parentJf.getSp().dataLocationCode); qe.setParaValue("B_KIND", "DELIVERY"); qe.setParaValue("B_NO", dataBkInvoiceNo); qe.setParaValue("B_DATE", dt); qe.setParaValue("B_DATETIME", dt); qe.setParaValue("DELIVERY_DATETIME", dt2); qe.setParaValue("CUST_REFERENCE", adrPhone.getText()); qe.setParaValue("TABLE_CODE", ""); qe.setParaValue("FLAG", 1); qe.setParaValue("CLOSING_TIME", null); //qe.setParaValue("INV_AMT", parentJf.getSp().sumGrossAmt); qe.setParaValue("DISC_AMT", 0); qe.setParaValue("SLSMN", ((parentJf.getSp().dataDlvSales < 0 ? parentJf.getSp().txtCashier.getSelectedItem() : parentJf.getSp().dataDlvSales))); qe.setParaValue("CUST_COUNTS", 1); qe.setParaValue("AREA", adrArea.getSelectedItem()); qe.setParaValue("TEL", adrPhone.getText()); qe.setParaValue("HOME_ADDRESS", ""); qe.setParaValue("WORK_ADDRESS", adrWorkAddress); qe.setParaValue("EMAIL", adrEmail); qe.setParaValue("BDETAIL", ""); qe.setParaValue("BCUST", ""); qe.setParaValue("TERMOFPAY", ""); qe.setParaValue("REMARK", ""); qe.setParaValue("REFERENCE", ""); qe.setParaValue("SPEC_COMMENTS", adrNotes.getText()); qe.setParaValue("COMPLAINS", ""); qe.setParaValue("LAST_DRIVER", ""); qe.setParaValue("ADDR_AREA", adrArea.getSelectedItem()); qe.setParaValue("ADDR_BLOCK", adrBlock); qe.setParaValue("ADDR_JEDDA", adrJedda); qe.setParaValue("ADDR_STREET", adrStreet); qe.setParaValue("ADDR_BLDG", adrBldg); qe.setParaValue("ADDR_TEL", adrOtherTel); qe.setParaValue("ADDR_FLOOR", adrFloorNo); qe.setParaValue("CUST_NAME", adrCustomerName); qe.setParaValue("PICK_UP", chkPickup.isSelected()); qe.setParaValue("ADDR_R_AREA", adrRArea.getSelectedItem()); qe.setParaValue("ADDR_R_BLOCK", adrRBlock1); qe.setParaValue("ADDR_R_JEDDA", adrRJedda); qe.setParaValue("ADDR_R_STREET", adrRStreet); qe.setParaValue("ADDR_R_BLDG", adrRBldg); qe.setParaValue("ADDR_R_TEL", adrROtherTel); qe.setParaValue("ADDR_R_FLOOR", adrRFloorNo); qe.setParaValue("RECIPIENT_ADDRESS", chkRCopyClient.isSelected()); qe.execute(); qe.close(); /* parentJf.getSp().adrArea.setSelectedItem(((String) adrArea.getSelectedItem())); parentJf.getSp().adrBldg.setText(parentJf.getSp().adrBldg.getText()); parentJf.getSp().adrBlock.setText(parentJf.getSp().adrBlock.getText()); parentJf.getSp().adrCustomerName.setText(parentJf.getSp().adrCustomerName.getText()); parentJf.getSp().adrDeliveryDate.setText(parentJf.getSp().adrDeliveryDate.getText()); parentJf.getSp().adrHour.setText(adrHour.getModel().getValue().toString()); parentJf.getSp().adrMin.setText(adrMin.getModel().getValue().toString()); parentJf.getSp().adrFloorNo.setText(adrFloorNo.getText()); parentJf.getSp().adrJedda.setText(adrJedda.getText()); parentJf.getSp().adrOtherTel.setText(adrOtherTel.getText()); parentJf.getSp().adrPhone.setText(adrPhone.getText()); parentJf.getSp().adrStreet.setText(adrStreet.getText()); parentJf.getSp().adrWorkAddress.setText(adrWorkAddress.getText()); */ save_advance_payment(); dbConnection.commit(); parentJf.getSp().onChangeCashier(false); setVisible(false); } private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed setVisible(false); }//GEN-LAST:event_jButton2ActionPerformed private void adrFloorNoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_adrFloorNoActionPerformed }//GEN-LAST:event_adrFloorNoActionPerformed private void adrOtherTelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_adrOtherTelActionPerformed }//GEN-LAST:event_adrOtherTelActionPerformed private void adrPhoneFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_adrPhoneFocusLost if (adrPhone.getText() == null || adrPhone.getText().length() == 0) { return; } int d = Integer.valueOf(parentJf.getMapVars().get("PHONE_MAX_DIGITS")); if (adrPhone.getText() != null && !adrPhone.getText().isEmpty() && adrPhone.getText().length() != d) { JOptionPane.showMessageDialog(this, "Must have typed " + d + " characters !"); adrPhone.requestFocus(); } PreparedStatement ps2 = null; try { ps2 = dbConnection.prepareStatement("select *from POSCUSTOMER where CODE=?", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ps2.setString(1, adrPhone.getText()); ResultSet rs2 = ps2.executeQuery(); if (rs2.first()) { adrCustomerName.setText(rs2.getString("NAME")); adrArea.setSelectedItem(rs2.getString("AREA")); adrBldg.setText(rs2.getString("ADDR_BLDG")); adrFloorNo.setText(rs2.getString("REFERENCE")); adrJedda.setText(rs2.getString("ADDR_JEDDA")); adrOtherTel.setText(rs2.getString("TEL")); adrStreet.setText(rs2.getString("ADDR_STREET")); adrWorkAddress.setText(rs2.getString("WORK_ADDRESS")); adrBlock.setText(rs2.getString("addr_block")); adrNotes.setText(rs2.getString("SPEC_COMMENTS")); } ps2.close(); } catch (SQLException ex) { try { Logger.getLogger(salesPanel.class.getName()).log(Level.SEVERE, null, ex); if (ps2 != null && ps2.isClosed() == false) { ps2.close(); } } catch (SQLException ex1) { Logger.getLogger(salesPanel.class.getName()).log(Level.SEVERE, null, ex1); } } }//GEN-LAST:event_adrPhoneFocusLost private void adrPhoneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_adrPhoneActionPerformed adrPhoneFocusLost(null); }//GEN-LAST:event_adrPhoneActionPerformed private void adrAreaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_adrAreaActionPerformed }//GEN-LAST:event_adrAreaActionPerformed private void focusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_focusGained kv.getAlphasPanel().removeAll(); kv.showCalendar(kv.getAlphasPanel()); Date dt = (new Date()); dt.setTime(System.currentTimeMillis()); kv.jd.setMinSelectableDate(dt); kv.getParentPanel().updateUI(); }//GEN-LAST:event_focusGained private void adrDeliveryDateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_adrDeliveryDateActionPerformed }//GEN-LAST:event_adrDeliveryDateActionPerformed private void adrCustomerNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_adrCustomerNameActionPerformed // TODO add your handling code here: }//GEN-LAST:event_adrCustomerNameActionPerformed private void windowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_windowOpened adrDeliveryDate.requestFocus(); kv.setCurrentMode(keyboardViewer.MODE_CALENDAR); }//GEN-LAST:event_windowOpened private void adrRAreaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_adrRAreaActionPerformed // TODO add your handling code here: }//GEN-LAST:event_adrRAreaActionPerformed private void adrRPhoneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_adrRPhoneActionPerformed // TODO add your handling code here: }//GEN-LAST:event_adrRPhoneActionPerformed private void adrRPhoneFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_adrRPhoneFocusLost // TODO add your handling code here: }//GEN-LAST:event_adrRPhoneFocusLost private void adrROtherTelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_adrROtherTelActionPerformed // TODO add your handling code here: }//GEN-LAST:event_adrROtherTelActionPerformed private void adrRFloorNoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_adrRFloorNoActionPerformed // TODO add your handling code here: }//GEN-LAST:event_adrRFloorNoActionPerformed private void chkRCopyClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkRCopyClientActionPerformed copy_rec_addr(); }//GEN-LAST:event_chkRCopyClientActionPerformed private void sumTxtPaidAmtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sumTxtPaidAmtActionPerformed // TODO add your handling code here: }//GEN-LAST:event_sumTxtPaidAmtActionPerformed private void sumTxtPaidAmtsumTxtDiscAmtFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_sumTxtPaidAmtsumTxtDiscAmtFocusGained }//GEN-LAST:event_sumTxtPaidAmtsumTxtDiscAmtFocusGained private void sumTxtPaidAmtsumTxtDiscAmtFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_sumTxtPaidAmtsumTxtDiscAmtFocusLost // TODO add your handling code here: }//GEN-LAST:event_sumTxtPaidAmtsumTxtDiscAmtFocusLost private void paytablemouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_paytablemouseClicked payTable.editCellAt(payTable.getSelectedRow(), 2); if (payTable.getEditorComponent() != null && payTable.getEditorComponent() instanceof JFormattedTextField) { ((JFormattedTextField) payTable.getEditorComponent()).selectAll(); } SwingUtilities.invokeLater(new Runnable() { public void run() { ((JFormattedTextField) payTable.getEditorComponent()).selectAll(); } }); }//GEN-LAST:event_paytablemouseClicked private void jTabbedPane1StateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jTabbedPane1StateChanged JTabbedPane st = (JTabbedPane) evt.getSource(); if (st.getSelectedComponent() == pnlRecipt) { copy_rec_addr(); } }//GEN-LAST:event_jTabbedPane1StateChanged private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed show_customers(); }//GEN-LAST:event_jButton3ActionPerformed private void show_customers() { try { lovDialog ld=lovDialog.getInstance(this,"select code,name from poscustomer order by name ", true,false); if (ld.getSelectedNo() >= 0) { adrPhone.setText(ld.getSlov().getLctb().getFieldValue(ld.getSelectedNo(), "CODE") + ""); adrPhoneActionPerformed(null); } } catch (SQLException ex) { Logger.getLogger(frmDelivery.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(this, ex.getMessage()); } } private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed try { lovDialog ld = lovDialog.getInstance(this, "select p2.refer,i.descr,p2.invoice_no," + " to_char(p2.dat,'dd/mm/rrrr') Inv_Date,p2.price,p2.allqty/p2.pack Quantity " + " from pospur1 p1,pospur2 p2,items i where p2.keyfld=p1.keyfld " + " and i.reference=p2.refer and p1.inv_ref='" + adrPhone.getText() + "' order by p2.dat desc", 650, 400,true,true); } catch (SQLException ex) { Logger.getLogger(frmDelivery.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(this, ex.getMessage()); } }//GEN-LAST:event_jButton4ActionPerformed private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed toggleKb(); }//GEN-LAST:event_jButton5ActionPerformed private void toggleKb() { if (pnlKb.isVisible()) { setSize(getWidth(), getHeight()-200); pnlKb.setVisible(false); } else { setSize(getWidth(), getHeight()+200); pnlKb.setVisible(true); pnlKb.setSize(getWidth(), 175); kv.setParentPanel(pnlKb); kv.createView(); kv.setShowPanels(keyboardViewer.MODE_NUMBERS); kv.getParentPanel().updateUI();; pnlKb.updateUI(); } } public void copy_rec_addr() { adrRArea.getModel().setSelectedItem(null); adrRBldg.setText(""); adrRBlock1.setText(""); adrRFloorNo.setText(""); adrRJedda.setText(""); adrROtherTel.setText(""); adrRPhone.setText(""); adrRStreet.setText(""); adrRWorkAddress.setText(""); adrRArea.setEditable(true); adrRBldg.setEditable(true); adrRBlock1.setEditable(true); adrRFloorNo.setEditable(true); adrRJedda.setEditable(true); adrROtherTel.setEditable(true); adrRPhone.setEditable(true); adrWorkAddress.setEditable(true); adrRStreet.setEditable(false); if (chkRCopyClient.isSelected()) { adrRArea.setSelectedIndex(adrArea.getSelectedIndex()); adrRBldg.setText(adrBldg.getText()); adrRBlock1.setText(adrBlock.getText()); adrRFloorNo.setText(adrFloorNo.getText()); adrRJedda.setText(adrJedda.getText()); adrROtherTel.setText(adrOtherTel.getText()); adrRPhone.setText(adrPhone.getText()); adrRStreet.setText(adrStreet.getText()); adrRWorkAddress.setText(adrWorkAddress.getText()); adrRArea.setEditable(false); adrRBldg.setEditable(false); adrRBlock1.setEditable(false); adrRFloorNo.setEditable(false); adrRJedda.setEditable(false); adrROtherTel.setEditable(false); adrRPhone.setEditable(false); adrWorkAddress.setEditable(false); adrRStreet.setEditable(false); } } /** * @param args the command line arguments */ // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JComboBox adrArea; private javax.swing.JTextField adrBldg; private javax.swing.JTextField adrBlock; private javax.swing.JTextField adrCustomerName; private javax.swing.JTextField adrDeliveryDate; private javax.swing.JTextField adrEmail; private javax.swing.JTextField adrFloorNo; private javax.swing.JSpinner adrHour; private javax.swing.JTextField adrJedda; private javax.swing.JSpinner adrMin; private javax.swing.JTextArea adrNotes; private javax.swing.JTextField adrOtherTel; private javax.swing.JTextField adrPhone; private javax.swing.JComboBox adrRArea; private javax.swing.JTextField adrRBldg; private javax.swing.JTextField adrRBlock1; private javax.swing.JTextField adrRFloorNo; private javax.swing.JTextField adrRJedda; private javax.swing.JTextField adrROtherTel; private javax.swing.JTextField adrRPhone; private javax.swing.JTextField adrRStreet; private javax.swing.JTextField adrRWorkAddress; private javax.swing.JTextField adrStreet; private javax.swing.JTextField adrWorkAddress; private javax.swing.JCheckBox chkPickup; private javax.swing.JCheckBox chkRCopyClient; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JButton jButton5; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel17; private javax.swing.JLabel jLabel18; private javax.swing.JLabel jLabel19; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel20; private javax.swing.JLabel jLabel21; private javax.swing.JLabel jLabel22; private javax.swing.JLabel jLabel23; private javax.swing.JLabel jLabel24; private javax.swing.JLabel jLabel25; private javax.swing.JLabel jLabel26; private javax.swing.JLabel jLabel27; private javax.swing.JLabel jLabel28; private javax.swing.JLabel jLabel29; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel30; private javax.swing.JLabel jLabel4; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JTabbedPane jTabbedPane1; private javax.swing.JLabel msg; private javax.swing.JTable payTable; private javax.swing.JPanel pnlAdvPayment; private javax.swing.JPanel pnlBasic; private javax.swing.JPanel pnlKb; private javax.swing.JPanel pnlMultiplePay; private javax.swing.JPanel pnlRecipt; private javax.swing.JTextField sumTxtPaidAmt; // End of variables declaration//GEN-END:variables private MainFrame parentJf = null; private Connection dbConnection = null; private keyboardViewer kv = null; private DecimalFormat decimalformat = null; private SimpleDateFormat dateformat = null; private SimpleDateFormat dateformat2 = null; private double dataBkInvoiceNo = -1; private KeyBoardFrame kf = new KeyBoardFrame(); private InputVerifier number_iv = new InputVerifier() { @Override public boolean verify(JComponent input) { JTextField txt = (JTextField) input; if (txt.getText().length() == 0) { return true; } boolean ret = false; try { //decimalformat.parse(txt.getText()); if (txt.getName().equals("sumTxtPaidAmt")) { sumPaidAmt = ((Number) decimalformat.parse(txt.getText())).doubleValue(); //txt.setText(decimalformat.format(sumPaidAmt)); } if (txt.getName().equals("sumTxtCashAmt")) { sumCashAmt = ((Number) decimalformat.parse(txt.getText())).doubleValue(); } update_sums(); ret = true; } catch (ParseException ex) { Logger.getLogger(salesPanel.class.getName()).log(Level.SEVERE, null, ex); ret = false; } return ret; } }; public void update_sums() { sumPaidAmt = payRows.getSummaryOf("AMOUNT", localTableModel.SUMMARY_SUM); sumTxtPaidAmt.setText(decimalformat.format(sumPaidAmt)); } public void fetchPayments() { this.parentJf = parentJf; sumTxtPaidAmt.setInputVerifier(number_iv); sumNetAmt = parentJf.getSp().sumNetAmt; if (kv == null) { kv = new keyboardViewer(pnlKb); kv.setShowPanels(keyboardViewer.MODE_NUMBERS); } decimalformat = new DecimalFormat(parentJf.getMapVars().get("money_number")); dateformat = new SimpleDateFormat(parentJf.getMapVars().get("short_date_format")); sumCashAmt = 0; sumPaidAmt = 0; sumCashAmt = sumNetAmt; payRows.clearALl(); payRows.getQrycols().add(new qryColumn(0, "NO")); payRows.getQrycols().add(new qryColumn(1, "DESCR")); payRows.getQrycols().add(new qryColumn(2, "AMOUNT")); payRows.getQrycols().add(new qryColumn(3, "ACCNO")); payRows.getQrycols().add(new qryColumn(4, "NAME")); payRows.getVisbleQrycols().addAll(payRows.getQrycols()); payRows.getColByName("NO").setCanEdit(false); payRows.getColByName("DESCR").setCanEdit(false); payRows.getColByName("ACCNO").setCanEdit(false); payRows.getColByName("NAME").setCanEdit(false); payRows.getColByName("AMOUNT").setAlignmnet(JLabel.TRAILING); payRows.getColByName("AMOUNT").setNumberFormat(decimalformat.toPattern()); payRows.getColByName("AMOUNT").setDatatype(19); payRows.getColByName("AMOUNT").setColor(Color.YELLOW); payRows.getColByName("ACCNO").setVisible(false); payRows.getColByName("NAME").setVisible(false); payRows.getVisbleQrycols().remove(payRows.getColByName("ACCNO")); payRows.getVisbleQrycols().remove(payRows.getColByName("NAME")); payTable.setModel(payRows); payTable.getColumnModel().getColumn(0).setCellRenderer(new ColorRenderer(true)); payTable.getColumnModel().getColumn(1).setCellRenderer(new ColorRenderer(true)); payTable.getColumnModel().getColumn(2).setCellRenderer(new ColorRenderer(true)); ((ColorRenderer) payTable.getColumnModel().getColumn(2).getCellRenderer()).setFont(payTable.getFont()); payTable.getColumnModel().getColumn(2).setCellEditor(new NumberEditor(decimalformat)); payTable.getColumnModel().getColumn(2).getCellEditor().addCellEditorListener(new CellEditorListener() { public void editingStopped(ChangeEvent e) { sumPaidAmt = payRows.getSummaryOf("AMOUNT", localTableModel.SUMMARY_SUM); sumTxtPaidAmt.setText(decimalformat.format(sumPaidAmt)); update_sums(); } public void editingCanceled(ChangeEvent e) { sumPaidAmt = payRows.getSummaryOf("AMOUNT", localTableModel.SUMMARY_SUM); sumTxtPaidAmt.setText(decimalformat.format(sumPaidAmt)); update_sums(); } }); payTable.getModel().addTableModelListener(new TableModelListener() { public void tableChanged(TableModelEvent e) { } }); try { double dataKeyfld = Double.valueOf(utils.getSqlValue("select nvl(max(keyfld),-1.000123131313123999 ) " + " from pospur1 where invoice_code=10 and orderno=" + keyfld, dbConnection)); String sq = "select INVOICETYPE.*,C_YCUST.NAME ACNAME,nvl(p.amount,0) AMOUNT " + " from invoicetype,C_YCUST ,pospayments p " + " where C_YCUST.CODE(+)=INVOICETYPE.ACCNO AND location_code=?" + " AND VOU_KEYFLD(+)=" + dataKeyfld + " and type_no(+)=invoicetype.no " + " and invoicetype.accno is not null " + " order by no "; PreparedStatement ps = parentJf.getSp().dbConnection.prepareStatement(sq, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ps.setString(1, parentJf.getSp().dataLocationCode); ResultSet rsx = ps.executeQuery(); rsx.beforeFirst(); while (rsx.next()) { Row rw = new Row(5); rw.lst.get(0).setValue(rsx.getString("NO"), Double.valueOf(rsx.getDouble("NO"))); rw.lst.get(1).setValue(rsx.getString("DESCR"), rsx.getString("DESCR")); rw.lst.get(2).setValue(rsx.getDouble("AMOUNT"), rsx.getDouble("AMOUNT")); rw.lst.get(3).setValue(rsx.getString("ACCNO"), rsx.getString("ACCNO")); rw.lst.get(4).setValue(rsx.getString("ACNAME"), rsx.getString("ACNAME")); payRows.getRows().add(rw); } ps.close(); update_sums(); if (!is_delivery_payment_posted(parentJf, parentJf.getSp().dataDlvAdvanceDate, keyfld)) { msg.setVisible(true); msg.setText("Can not update advance due to closed on # " + parentJf.getMapVars().get("POS_CLOSE_DATE_" + parentJf.getMapVars().get("DEFAULT_LOCATION"))); payTable.setEnabled(false); } } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(this, ex.getMessage()); } } private void setParentJf(MainFrame parent) { msg.setVisible(false); payTable.setEnabled(true); this.parentJf = parent; dbConnection = parentJf.getDbConneciton(); if (kv == null) { kv = new keyboardViewer(pnlKb); } decimalformat = new DecimalFormat(parentJf.getMapVars().get("money_number")); dateformat = new SimpleDateFormat(parentJf.getMapVars().get("short_date_format")); dateformat2 = new SimpleDateFormat(parentJf.getMapVars().get("short_date_format") + " H:m"); kv.createView(); kv.kb_listner = new KeyBoardSelectionListner() { public void OnKeyPress(String str, String mode, Object data, boolean isKeyCommand) { JTextComponent tb = null; if (KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner() != null && KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner() instanceof JTextComponent) { tb = (JTextComponent) KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); } if (isKeyCommand && mode.equals(keyboardViewer.MODE_CALENDAR) && (tb == null || !(tb instanceof JTextField))) { adrDeliveryDate.requestFocus(); adrDeliveryDate.setText(str); } } }; chkRCopyClient.setSelected(true); if (keyfld > -1) { adrArea.setSelectedItem(((String) parentJf.getSp().adrArea.getSelectedItem())); adrBldg.setText(parentJf.getSp().adrBldg.getText()); adrBlock.setText(parentJf.getSp().adrBlock.getText()); adrCustomerName.setText(parentJf.getSp().adrCustomerName.getText()); adrDeliveryDate.setText(parentJf.getSp().adrDeliveryDate.getText()); adrHour.getModel().setValue(0); adrMin.getModel().setValue(0); if (!(parentJf.getSp().adrHour.getText().isEmpty())) { adrHour.getModel().setValue(Integer.valueOf(parentJf.getSp().adrHour.getText())); } if (!(parentJf.getSp().adrMin.getText().isEmpty())) { adrMin.getModel().setValue(Integer.valueOf(parentJf.getSp().adrMin.getText())); } adrFloorNo.setText(parentJf.getSp().adrFloorNo.getText()); adrJedda.setText(parentJf.getSp().adrJedda.getText()); adrOtherTel.setText(parentJf.getSp().adrOtherTel.getText()); adrPhone.setText(parentJf.getSp().adrPhone.getText()); adrStreet.setText(parentJf.getSp().adrStreet.getText()); adrWorkAddress.setText(parentJf.getSp().adrWorkAddress.getText()); adrNotes.setText(parentJf.getSp().adrNotes.getText()); adrEmail.setText(parentJf.getSp().adrEmail.getText()); chkPickup.setSelected(parentJf.getSp().chkPickup.isSelected()); chkRCopyClient.setSelected(parentJf.getSp().chkRCopyClient.isSelected()); if (!chkRCopyClient.isSelected()) { adrRArea.setSelectedItem(parentJf.getSp().adrRArea.getSelectedItem()); adrRBldg.setText(parentJf.getSp().adrRBldg.getText()); adrRBlock1.setText(parentJf.getSp().adrRBlock1.getText()); adrRFloorNo.setText(parentJf.getSp().adrRFloorNo.getText()); adrRJedda.setText(parentJf.getSp().adrRJedda.getText()); adrROtherTel.setText(parentJf.getSp().adrROtherTel.getText()); adrRPhone.setText(parentJf.getSp().adrRPhone.getText()); adrRWorkAddress.setText(parentJf.getSp().adrRWorkAddress.getText()); adrRStreet.setText(parentJf.getSp().adrRStreet.getText()); } else { chkRCopyClientActionPerformed(null); } } fetchPayments(); toggleKb(); } public void save_advance_payment() throws Exception { double dataKeyfld = -1; double dataInvoiceNo = -1; try { PreparedStatement ps_up = null; if (keyfld < 0) { dataKeyfld = Double.valueOf(utils.getSqlValue("select nvl(max(KEYFLD),0)+1 from pospur1 " + " ", dbConnection)); } else { dataKeyfld = Double.valueOf(utils.getSqlValue("select nvl(max(keyfld),-1 ) " + "from pospur1 where invoice_code=10 and orderno=" + keyfld, dbConnection)); dataInvoiceNo = Double.valueOf(utils.getSqlValue("select nvl(max(invoice_no),-1 ) " + "from pospur1 where invoice_code=10 and orderno=" + keyfld + " and location_code='" + parentJf.getSp().dataLocationCode + "'", dbConnection)); if (dataKeyfld < 0) { dataKeyfld = Double.valueOf(utils.getSqlValue("select nvl(max(KEYFLD),0)+1 from pospur1 " + " ", dbConnection)); dataInvoiceNo = Double.valueOf(utils.getSqlValue("select nvl(max(invoice_no),0 )+1 " + "from pospur1 where invoice_code=10 and " + " location_code='" + parentJf.getSp().dataLocationCode + "'", dbConnection)); } } ps_up = dbConnection.prepareStatement("BEGIN " + "delete from pospur1 where invoice_code=10 and KEYFLD=" + dataKeyfld + ";" + "delete from pospayments where vou_keyfld=" + dataKeyfld + ";" + "update pos_onpur1 set advance_date=SYSDATE,advance_paid=0 where keyfld='"+keyfld+"' ; end; "); ps_up.executeUpdate(); ps_up.close(); if (sumPaidAmt <= 0) { return; } String sql = " begin insert into pospur1(" + "PERIODCODE, LOCATION_CODE, INVOICE_NO, " + "INVOICE_CODE, TYPE, INVOICE_DATE," + "STRA, USERNAME, INV_AMT, " + "DISC_AMT, CREATDT, KEYFLD,YEAR,SLSMN, " + "INV_REF,INV_REFNM,ADDR_AREA," + "ADDR_TEL ,HOME_ADDRESS,WORK_ADDRESS,SPEC_COMMENTS," + "COMPLAINS,addr_jedda,addr_block,addr_street," + "addr_bldg,reference_information,paidamt2,totqty,add_charge,MEMO,CTG,ORDERNO" + ")values ( " + ":PERIODCODE, :LOCATION_CODE, :INVOICE_NO, " + ":INVOICE_CODE, :TYPE, :INVOICE_DATE," + ":STRA, :USERNAME, :INV_AMT, " + ":DISC_AMT, sysdate, :KEYFLD,'2003',:SLSMN, " + ":INV_REF,:INV_REFNM,:ADDR_AREA," + ":ADDR_TEL ,:HOME_ADDRESS,:WORK_ADDRESS,:SPEC_COMMENTS," + ":COMPLAINS,:addr_jedda,:addr_block,:addr_street," + ":addr_bldg,:reference_information,:paidamt2,:totqty,:add_charge,:MEMO,:CTG,:ORDERNO" + "); update pos_onpur1 " + "set ADVANCE_KEYFLD= :KEYFLD , advance_paid= :INV_AMT , ADVANCE_DATE = :INVOICE_DATE where KEYFLD= :ORDERNO ;" + "end;"; QueryExe qe = new QueryExe(sql, dbConnection); qe.setParaValue("PERIODCODE", parentJf.getMapVars().get("CURRENT_PERIOD")); qe.setParaValue("LOCATION_CODE", parentJf.getSp().dataLocationCode); qe.setParaValue("INVOICE_NO", dataInvoiceNo); qe.setParaValue("INVOICE_CODE", 10); qe.setParaValue("TYPE", 1); qe.setParaValue("INVOICE_DATE", new java.sql.Date(parentJf.getSp().dataInv_date.getTime())); qe.setParaValue("STRA", parentJf.getSp().dataStore); qe.setParaValue("USERNAME", parentJf.getLp().getLogon_user()); qe.setParaValue("INV_AMT", sumPaidAmt); qe.setParaValue("DISC_AMT", 0); qe.setParaValue("KEYFLD", dataKeyfld); qe.setParaValue("SLSMN", parentJf.getSp().txtCashier.getSelectedItem()); qe.setParaValue("INV_REF", adrPhone.getText()); qe.setParaValue("INV_REFNM", adrCustomerName.getText()); qe.setParaValue("ADDR_AREA", ((String) adrArea.getSelectedItem())); qe.setParaValue("ADDR_TEL", adrOtherTel.getText()); qe.setParaValue("HOME_ADDRESS", ""); qe.setParaValue("WORK_ADDRESS", adrWorkAddress.getText()); qe.setParaValue("SPEC_COMMENTS", ""); qe.setParaValue("COMPLAINS", ""); qe.setParaValue("ADDR_JEDDA", adrJedda.getText()); qe.setParaValue("ADDR_BLOCK", adrBlock.getText()); qe.setParaValue("ADDR_STREET", adrStreet.getText()); qe.setParaValue("ADDR_BLDG", adrBldg.getText()); qe.setParaValue("REFERENCE_INFORMATION", adrFloorNo.getText()); qe.setParaValue("PAIDAMT2", sumPaidAmt); qe.setParaValue("TOTQTY", 0); qe.setParaValue("ADD_CHARGE", 0); qe.setParaValue("MEMO", "Advance payment "); qe.setParaValue("CTG", ""); qe.setParaValue("ORDERNO", keyfld); qe.execute(); qe.close(); qe = new QueryExe( "BEGIN insert into POSPAYMENTS(VOU_KEYFLD, TYPE_NO," + " AMOUNT, ACCNO, ACCNAME) values (:VOU_KEYFLD, :TYPE_NO," + " :AMOUNT, :ACCNO, :ACCNAME );" + " end;", dbConnection); payTable.removeEditor(); qe.parse(); for (int i = 0; i < payRows.getRows().size(); i++) { Row row = payRows.getRows().get(i); Double f = Double.valueOf(row.lst.get(2).getValue().toString()); if (f > 0) { if (row.lst.get(3).getValue() == null || row.lst.get(4).getValue() == null) { throw new Exception("Call Administrator for account payment for KWD : " + row.lst.get(2).getValue().toString() + " for " + row.lst.get(1).getValue()); } qe.setParaValue("VOU_KEYFLD", dataKeyfld); qe.setParaValue("TYPE_NO", ((Double) row.lst.get(0).getValue())); qe.setParaValue("AMOUNT", ((Double) row.lst.get(2).getValue())); qe.setParaValue("ACCNO", row.lst.get(3).getValue().toString()); qe.setParaValue("ACCNAME", row.lst.get(4).getValue().toString()); qe.execute(false); } } qe.close(); } catch (SQLException ex) { ex.printStackTrace(); dbConnection.rollback(); throw ex; } } public static boolean is_delivery_payment_posted(MainFrame parentJf, Date dt2, double dlv) throws Exception { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); if (parentJf.getMapVars().get("POS_CLOSE_DATE_" + parentJf.getMapVars().get("DEFAULT_LOCATION")) != null) { Date dt = sdf.parse(parentJf.getMapVars().get("POS_CLOSE_DATE_" + parentJf.getMapVars().get("DEFAULT_LOCATION"))); if (dt2.compareTo(dt) <= 0) { return false; } } if (dlv >= 0) { double flg = Double.valueOf(utils.getSqlValue("select flag from pospur1 where invoice_code=10 and orderno='" + dlv + "'", parentJf.getDbConneciton())); if (flg > 1) { return false; } } return true; } }
true
6a74200f0773ebf6c347b4169714e9e5b6af355b
Java
adamjshook/nimbus
/Nimbus/src/main/java/nimbus/client/CacheletNotConnectedException.java
UTF-8
750
2.625
3
[]
no_license
package nimbus.client; import java.io.IOException; public class CacheletNotConnectedException extends IOException { private static final long serialVersionUID = -4964573321449493981L; private Exception parent = null; private String id; public CacheletNotConnectedException(String host) { this(host, null); } public CacheletNotConnectedException(String host, Exception e) { this.id = host; parent = e; } public CacheletNotConnectedException(int id) { this(id, null); } public CacheletNotConnectedException(int id, Exception e) { this.id = Integer.toString(id); parent = e; } @Override public String getMessage() { return "Cachelet " + id + " is not connected" + (parent != null ? parent.getMessage() : ""); } }
true
014eb38b4d2b3edec3904f30d3a23535fb982bcd
Java
napile/napile.classpath
/jmx/src/main/java/javax/management/Attribute.java
UTF-8
1,959
2.5
2
[ "LicenseRef-scancode-mx4j", "BSD-2-Clause" ]
permissive
/* * Copyright (C) The MX4J Contributors. * All rights reserved. * * This software is distributed under the terms of the MX4J License version 1.0. * See the terms of the MX4J License in the documentation provided with this software. */ package javax.management; import java.io.Serializable; /** * @version $Revision: 1.8 $ */ public class Attribute implements Serializable { private static final long serialVersionUID = 2484220110589082382L; /** * @serial The attribute's name */ private final String name; /** * @serial The attribute's value */ private final Object value; private transient int hash; public Attribute(String name, Object value) { if (name == null) throw new RuntimeOperationsException(new IllegalArgumentException("The name of an attribute cannot be null")); this.name = name; this.value = value; } public boolean equals(Object obj) { if (obj == null) return false; if (obj == this) return true; try { Attribute other = (Attribute)obj; boolean namesEqual = name.equals(other.name); boolean valuesEqual = false; if (value == null) valuesEqual = other.value == null; else valuesEqual = value.equals(other.value); return namesEqual && valuesEqual; } catch (ClassCastException ignored) { } return false; } public int hashCode() { if (hash == 0) hash = computeHash(); return hash; } public String getName() { return name; } public Object getValue() { return value; } public String toString() { return new StringBuffer("Attribute's name: ").append(getName()).append(", value: ").append(getValue()).toString(); } private int computeHash() { int hash = name.hashCode(); if (value != null) hash ^= value.hashCode(); return hash; } }
true
f664c0b94d0fb9b97258b17a289f6995349a6ef1
Java
k957304/kong-wallet
/src/main/java/game/external/GiftServiceFallback.java
UTF-8
295
2.203125
2
[]
no_license
package game.external; import org.springframework.stereotype.Component; @Component public class GiftServiceFallback implements GiftService { @Override public void exchange(Gift gift) { System.out.println("Circuit breaker has been opened. Fallback returned instead."); } }
true
2d39095ab114c1c2914aa981f704451ad7fb730f
Java
kentsong/java
/designPattern/src/note/pattern/structural/Decorator/sample/drink/product/IceCreamRedTeaDrink.java
BIG5
705
2.875
3
[]
no_license
package note.pattern.structural.Decorator.sample.drink.product; import java.util.ArrayList; import note.pattern.structural.Decorator.sample.drink.AbstractDrink; import note.pattern.structural.Decorator.sample.material.IMaterial; import note.pattern.structural.Decorator.sample.material.IceCream; import note.pattern.structural.Decorator.sample.material.RedTea; public class IceCreamRedTeaDrink extends AbstractDrink { public IceCreamRedTeaDrink(){ //ӫ~W this.prodName = "BNO"; //J this.materials = new ArrayList<IMaterial>(); materials.add(new RedTea()); materials.add(new IceCream()); //˹ this.decorate(materials); } }
true
8fc7791e9182f4f05526f8240fdcbb88b5c32942
Java
alexeicoreiba/B07GoochiBankApp
/GoochiBankApp/app/src/main/java/com/bank/Interest.java
UTF-8
3,363
2.421875
2
[]
no_license
package com.bank; import android.content.Context; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.bank.account.Account; import com.bank.exceptions.NoAccessToAccountException; import com.bank.terminals.TellerTerminal; import com.example.vidur.bankapp.R; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; public class Interest extends AppCompatActivity { Context context; String accountName; String amount; TellerTerminal teller = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_interest); context = this.getApplication(); teller = (TellerTerminal) getIntent().getSerializableExtra("terminal"); Button button = (Button) findViewById(R.id.userTransferSubmit); button.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { if (useridauthen1(context)) { Intent i = new Intent(Interest.this, TellerOptions.class); i.putExtra("teller", teller); startActivity(i); } } }); Button exit = (Button) findViewById(R.id.Exit); exit.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent i = new Intent(Interest.this, TellerOptions.class); i.putExtra("teller", teller); startActivity(i); } }); } private boolean useridauthen1(Context context) { EditText etName = (EditText) findViewById(R.id.nameOfAccount2); accountName = etName.getText().toString(); boolean useridauthen = true; boolean passwordauthen = true; if (TextUtils.isEmpty(accountName)) { etName.setError("No Account Name"); useridauthen = false; } boolean passed = false; if (useridauthen) { passed = runDeposit(context); } return (passed); } private boolean runDeposit(Context context) { int accId = 0; EditText etName = (EditText) findViewById(R.id.nameOfAccount2); accountName = etName.getText().toString(); boolean success = false; //EnumMapAccountTypes accountsMap = new EnumMapAccountTypes(context); try { List<Account> listAcc = new ArrayList<>(); listAcc = teller.listAccounts(context); // Get the id of the inputed account name and make deposit // of given amount for (int i = 0; i < listAcc.size(); i++) { if (accountName.equals(listAcc.get(i).getName())) { accId = listAcc.get(i).getId(); } } teller.giveInterest(accId, context); Toast.makeText(getApplicationContext(), "Interest was given.", Toast.LENGTH_LONG).show(); success = true; } catch (NoAccessToAccountException e) { etName.setError("You do not have access to this account"); } if (!success) { Toast.makeText(getApplicationContext(), "Interest given was unsuccessful.(POSSIBLE: Wrong " + "accountName)", Toast.LENGTH_LONG).show(); } return success; } }
true
710ed334104395e7cf0f2b255cdcd8ac9193403b
Java
MariaDrenovichka/AmazonTask
/src/core/Browser.java
UTF-8
689
2.234375
2
[]
no_license
package core; import java.util.concurrent.TimeUnit; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; public class Browser { public static WebDriver driver; public static void start() { System.setProperty("webdriver.chrome.driver", "/usr/bin/chromedriver/chromedriver"); ChromeOptions options = new ChromeOptions(); options.addArguments("--start-maximized"); driver = new ChromeDriver(options); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); } public static void quit() { driver.quit(); } public static void goTo() { driver.get("https://www.amazon.com"); } }
true
143299556fe4a02a0f0b883250030f4a4383a049
Java
XiShanYongYe/CZsProjects
/Effa/src/PnmlPanel.java
UTF-8
1,089
2.484375
2
[]
no_license
import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class PnmlPanel extends JPanel { private static final long serialVersionUID = 1L; private JTextField textField; /** * Create the panel. */ public PnmlPanel() { setSize(400, 30); setLayout(new GridLayout(0, 3, 0, 0)); JLabel lblNewLabel = new JLabel("petri net"); add(lblNewLabel); textField = new JTextField(); add(textField); textField.setColumns(10); JButton btnNewButton = new JButton("Open"); // DPNMLManage dpm = new DPNMLManage(); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser chooser = new JFileChooser(); int value = chooser.showOpenDialog(PnmlPanel.this); if (value == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); } } }); add(btnNewButton); } }
true
7ec7fe423479c758fd7d7866e4fff723ac680458
Java
user654name/1010MyCode
/src/com/core/io/stream/io/stream/CopyCompare.java
UTF-8
3,348
3.5625
4
[]
no_license
package com.core.io.stream.io.stream; import java.io.*; /* 把d:\\**.mp4复制到当前项目目录下的copy.mp4中 四种方式比较复制效率 1. 普通一次读写一个字节 2. 普通流一次读写一个字节数组 3. 缓冲流一次读写一个字节 4. 缓冲流一次读写一个字节数组 copyFileByte duration: 117936 copyBuffedByte duration: 556 copyFileBytes duration: 284 copyBufferedBytes duration: 145 */ public class CopyCompare { public static void main(String[] args) throws IOException { copyFileByte(); copyBuffedByte(); copyFileBytes(); copyBufferedBytes(); } //普通一次读写一个字节 public static void copyFileByte() throws IOException { FileInputStream fis = new FileInputStream("e:myshoe.mp4"); FileOutputStream fos = new FileOutputStream("copy01.mp4"); int read = -1; long start = System.currentTimeMillis(); while((read = fis.read()) != -1) { fos.write(read); } long duration = System.currentTimeMillis() - start; System.out.println("copyFileByte duration: " + duration); fis.close(); fos.close(); } // 缓冲流一次读写一个字节 public static void copyBuffedByte() throws IOException { FileInputStream fis = new FileInputStream("e:\\myshoe.mp4"); BufferedInputStream bis = new BufferedInputStream(fis); FileOutputStream fos = new FileOutputStream("copy02.mp4"); BufferedOutputStream bos = new BufferedOutputStream(fos); int read = -1; long start = System.currentTimeMillis(); while((read = bis.read()) != -1) { bos.write(read); } long duration = System.currentTimeMillis() - start; System.out.println("copyBuffedByte duration: " + duration); bis.close(); bos.close(); } //普通流一次读写一个字节数组 public static void copyFileBytes() throws IOException { FileInputStream fis = new FileInputStream("e:\\myshoe.mp4"); FileOutputStream fos = new FileOutputStream("copy03.mp4"); int len = -1; byte[] buffer = new byte[1024]; long start = System.currentTimeMillis(); while((len = fis.read(buffer)) != -1) { fos.write(buffer, 0, len); } long duration = System.currentTimeMillis() - start; System.out.println("copyFileBytes duration: " + duration); fis.close(); fos.close(); } //缓冲流一次读写一个字节数组 public static void copyBufferedBytes() throws IOException { FileInputStream fis = new FileInputStream("e:\\myshoe.mp4"); BufferedInputStream bis = new BufferedInputStream(fis); FileOutputStream fos = new FileOutputStream("copy04.mp4"); BufferedOutputStream bos = new BufferedOutputStream(fos); int len = -1; byte[] buffer = new byte[1024]; long start = System.currentTimeMillis(); while((len = bis.read(buffer)) != -1) { bos.write(buffer, 0, len); } long duration = System.currentTimeMillis() - start; System.out.println("copyBufferedBytes duration: " + duration); bis.close(); bos.close(); } }
true