blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
sequencelengths
1
1
author_id
stringlengths
0
313
b9eda67abd1ef364d35b1e4902f6fa1298235190
4e46861f6f4fc91e90e815ca53a800cd1ef13ab4
/workspace/Zcode/src/arrays/MergeInterval.java
e5f38724cd04b6934a938d3050974e960acaf7fe
[]
no_license
websterzhao/LeetCode
38efa7f04f2faaa28fdebc674549eb3f32f1c01e
13e14ec031b0a7fd8c093e0dcf05c3e1f4796f14
refs/heads/master
2021-01-10T20:39:16.270422
2014-12-15T20:35:11
2014-12-15T20:35:11
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,352
java
package arrays; import java.util.ArrayList; import anode.Interval; public class MergeInterval { public ArrayList<Interval> merge(ArrayList<Interval> intervals) { if (intervals.size() <= 1) return intervals; ArrayList<Interval> ret = new ArrayList<Interval>(); mergeSort(intervals,0,intervals.size()-1); Interval prev = intervals.get(0); for (int i = 1; i < intervals.size(); i++) { Interval cur = intervals.get(i); if (prev.end < cur.start) { ret.add(prev); prev = cur; } else prev.end = cur.end>prev.end?cur.end:prev.end; } ret.add(prev); return ret; } private void mergeSort(ArrayList<Interval> intervals, int i, int j) { if(i>=j) return; int mid = i+(j-i)/2; mergeSort(intervals,i,mid); mergeSort(intervals,mid+1,j); ArrayList<Interval> arry = new ArrayList<Interval>(); int m = i; int n= mid+1; while(m<=mid&&n<=j){ Interval left = intervals.get(m); Interval right = intervals.get(n); if(left.start<right.start||(left.start==right.start&&left.end<right.end)){ arry.add(left); m++; } else { arry.add(right); n++; } } while(m<=mid){ Interval left = intervals.get(m); arry.add(left); m++; } for(int k =0;k<arry.size();k++){ // arry is new, should start from 0 intervals.set(i+k, arry.get(k)); // start from i } } }
429c91338c415761debe81c1c8a4018c4a101797
1dad4760232e128b0be51f0b0c780c974697a4a2
/app/src/main/java/com/wonokoyo/muserp/util/SharedPrefManager.java
e6c6f0b91a35441f07f8c422c794c07fef6042cf
[]
no_license
dennisprasetia/MUSERP
e9462d7e3ee6fdad657c67c3142e4901c7db3b76
b2f03f12d212c6713b8800c3da0aa58a2857366c
refs/heads/master
2021-07-15T18:23:05.304283
2021-06-05T05:06:07
2021-06-05T05:06:07
198,747,784
0
0
null
null
null
null
UTF-8
Java
false
false
1,243
java
package com.wonokoyo.muserp.util; import android.content.Context; import android.content.SharedPreferences; public class SharedPrefManager { public static final String SP_RPA_APP = "spRpaApp"; public static final String SP_ID_USER = "spIdUser"; public static final String SP_NAMA_USER = "spNamaUser"; public static final String SP_LOGIN = "spLogin"; SharedPreferences sp; SharedPreferences.Editor spEditor; public SharedPrefManager(Context context) { sp = context.getSharedPreferences(SP_RPA_APP, Context.MODE_PRIVATE); spEditor = sp.edit(); } public void saveSPString(String key, String value) { spEditor.putString(key, value); spEditor.commit(); } public void saveSPBoolean(String key, Boolean value) { spEditor.putBoolean(key, value); spEditor.commit(); } public String getSpIdUser() { return sp.getString(SP_ID_USER, ""); } public String getSpNamaUser() { return sp.getString(SP_NAMA_USER, ""); } public Boolean getSpLogin() { return sp.getBoolean(SP_LOGIN, false); } public void clearLogin() { saveSPString(SP_ID_USER, ""); saveSPBoolean(SP_LOGIN, false); } }
c0385c977e6a2def4cb37833bf578e3cebc57778
8024be47f6643ba998a2596353d42e3bca0be720
/uncertain-graph-java/src/hist/DegreeIntSet.java
1cacaa2c1a2b8235d622b2a583466ac2661ae38a
[]
no_license
hiepbkhn/itce2011
a8aaec08e426454671570e28f1dd4828d83d12ca
d8985d1484699bdbb7bbece572058a420a960eac
refs/heads/master
2021-04-22T12:49:38.516261
2019-02-11T15:45:42
2019-02-11T15:45:42
37,022,768
9
6
null
null
null
null
UTF-8
Java
false
false
10,536
java
/* * Apr 2 * - converted from Python * Apr 3 * - use GraphIntSet for edge switches */ package hist; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Random; import com.carrotsearch.hppc.cursors.IntCursor; import dp.mcmc.Dendrogram; import dp.mcmc.Int4; import grph.Grph; import grph.Grph.DIRECTION; import grph.VertexPair; import grph.in_memory.InMemoryGrph; import grph.io.EdgeListReader; import grph.io.EdgeListWriter; import grph.io.GraphBuildException; import grph.io.ParseException; import toools.io.file.RegularFile; import toools.set.IntSet; public class DegreeIntSet { //// // edit distance score (half) static int editScore(Grph G, Grph G0){ int score = 0; for (VertexPair p : G.getEdgePairs()){ int u = p.first; int v = p.second; IntSet s = G0.getNeighbours(u); if (!s.contains(v)) score += 1; } // return score; } //// static int[] readNodeDeg(int n_nodes, String filename_deg) throws Exception{ BufferedReader br = new BufferedReader(new FileReader(filename_deg)); int[] deg_seq = new int[n_nodes]; while (true){ String str = br.readLine(); if (str == null) break; String[] items = str.split(" "); int u_id = Integer.parseInt(items[0]); int u_deg = Integer.parseInt(items[1]); deg_seq[u_id] = u_deg; } br.close(); // return deg_seq; } //// // reorder node ids in outfile_1k to match original degrees in filename_deg static Grph reorderNodes(int n_nodes, String outfile_1k, String filename_deg) throws Exception{ Grph aG = new InMemoryGrph(); EdgeListReader reader = new EdgeListReader(); RegularFile f = new RegularFile(outfile_1k); aG = reader.readGraph(f); // .gen file // for (int u = 0; u < n_nodes; u++) // if (!aG.containsVertex(u)) // aG.addVertex(u); System.out.println("aG read from " + outfile_1k); System.out.println("#nodes = " + aG.getNumberOfVertices()); System.out.println("#edges = " + aG.getNumberOfEdges()); // original degrees (.deg file) int[] deg_list = readNodeDeg(n_nodes, filename_deg); List<Int2> org_pairs = new ArrayList<Int2>(); for (int u = 0; u < n_nodes; u++) org_pairs.add(new Int2(u, deg_list[u])); Collections.sort(org_pairs); // sort by degree (see Int2.java) // degrees in .gen file // List<Int2> gen_pairs = new ArrayList<Int2>(); // for (IntCursor c : aG.getVertices()) // gen_pairs.add(new Int2(c.value, aG.getVertexDegree(c.value))); // // Collections.sort(gen_pairs); // sort by degree (see Int2.java) // map HashMap<Integer, Integer> node_map = new HashMap<Integer, Integer>(); for (int u = 0; u < n_nodes; u++) node_map.put(u, org_pairs.get(u).val0); // Grph G0 = new InMemoryGrph("G0", true, DIRECTION.in_out); //InMemoryGrph.storeEdges = false for (VertexPair p : aG.getEdgePairs()){ int u = p.first; int v = p.second; G0.addSimpleEdge(node_map.get(u), node_map.get(v), false); } for (int u = 0; u < n_nodes; u++) if (!G0.containsVertex(u)) G0.addVertex(u); return G0; } //// (u,w),(v,t) --> (u,t),(v,w) static void edgeSwitchSimple(GraphIntSet I0, int u, int v, int w, int t){ I0.addEdge(u, t); I0.addEdge(v, w); I0.removeEdge(u, w); I0.removeEdge(v, t); } //// static int edgeSwitch(GraphIntSet I0, GraphIntSet I, int cur_score, int u, int v, int w, int t){ edgeSwitchSimple(I0, u,v,w,t); // update score int score = cur_score; if (I.e_list[u].contains(t)) score -= 1; if (I.e_list[v].contains(w)) score -= 1; if (I.e_list[u].contains(w)) score += 1; if (I.e_list[v].contains(t)) score += 1; // return score; } //// max_switch: static List<Int4> randomSwitch(GraphIntSet I0, GraphIntSet I, int n_nodes, int[] node_list, int max_switch, Int2 score){ Random random = new Random(); // find a random pair int count = 0; List<Int4> switch_list = new ArrayList<Int4>(); // list of (u,v,w,t) int n_switch = 1 + random.nextInt(max_switch); while (count < n_switch){ int u = node_list[random.nextInt(n_nodes)]; int v = node_list[random.nextInt(n_nodes)]; if (u != v && I0.e_list[u].size() > 0 && I0.e_list[v].size() > 0){ int[] u_neighbors = I0.e_list[u].toIntArray(); int[] v_neighbors = I0.e_list[v].toIntArray(); int u_num_nbrs = u_neighbors.length; int v_num_nbrs = v_neighbors.length; // select w,t int w = u_neighbors[random.nextInt(u_num_nbrs)]; int t = v_neighbors[random.nextInt(v_num_nbrs)]; if (w != v && t != u && w != t && !I0.e_list[u].contains(t) && !I0.e_list[v].contains(w)){ // fast // print u,v,w,t score.val0 = edgeSwitch(I0, I, score.val0, u,v,w,t); switch_list.add( new Int4(u,v,w,t)); count += 1; } } } // // return score, u,v,w,t // return score, switch_list; return switch_list; } //// G0: static void mcmcSampling(Grph G, Grph G0, double eps2, int n_steps, int n_samples, int sample_freq, int max_switch){ int n_nodes = G0.getNumberOfVertices(); int[] node_list = G0.getVertices().toIntArray(); // convert to GraphIntSet GraphIntSet I = new GraphIntSet(G); GraphIntSet I0 = new GraphIntSet(G0); // dU = n_nodes*(n_nodes-1) // O(n^2) // dU = math.log(n_nodes*(n_nodes-1)) double dU = 4.0; int out_freq = (n_steps + n_samples*sample_freq)/10; int cur_score = editScore(G, G0); List<Int4> switch_list; Random random = new Random(); // MCMC long start = System.currentTimeMillis(); int n_accept = 0; int n_equal = 0; for (int i = 0; i < n_steps + n_samples*sample_freq; i++){ if (i % out_freq == 0) System.out.println("i = " + i + " cur_score = " + cur_score + " n_accept = " + n_accept + " time : " + (System.currentTimeMillis() - start)); Int2 score = new Int2(cur_score, 0); // init by cur_score switch_list = randomSwitch(I0, I, n_nodes, node_list, max_switch, score); // debug if (cur_score == score.val0) n_equal += 1; double prob = Math.exp(eps2/(2*dU)*(cur_score-score.val0)); if (prob > 1.0) prob = 1.0; double prob_val = random.nextDouble(); if (prob_val < prob){ // accept cur_score = score.val0; n_accept += 1; }else{ // reverse ListIterator<Int4> it = switch_list.listIterator(switch_list.size()); // point to last while(it.hasPrevious()) { Int4 tuple = it.previous(); int u = tuple.val0; int v = tuple.val1; int w = tuple.val2; int t = tuple.val3; edgeSwitchSimple(I0, u,v,t,w); // t,w } } } // System.out.println("n_accept = " + n_accept); System.out.println("n_equal = " + n_equal); System.out.println("final score = " + cur_score); } //////////////////////////// public static void main(String[] args) throws Exception{ ClassLoader.getSystemClassLoader().setDefaultAssertionStatus(true); System.out.println("DegreeIntSet"); // load graph // String dataname = "polbooks"; // (105, 441) 105k steps, max_switch = 105 (6.6s) // String dataname = "polblogs"; // (1224,16715) String dataname = "as20graph"; // (6474,12572) 65k steps, max_switch = 6474 (191s) // String dataname = "wiki-Vote"; // (7115,100762) // String dataname = "ca-HepPh"; // (12006,118489) // String dataname = "ca-AstroPh"; // (18771,198050) // COMMAND-LINE String prefix = ""; int n_samples = 5; int sample_freq = 100; int burn_factor = 100; double eps1 = 1.0; double eps2 = 4.0; // for NON-PRIVATE int max_switch = 6474; if(args.length >= 7){ prefix = args[0]; dataname = args[1]; n_samples = Integer.parseInt(args[2]); sample_freq = Integer.parseInt(args[3]); burn_factor = Integer.parseInt(args[4]); eps1 = Double.parseDouble(args[5]); eps2 = Double.parseDouble(args[6]); } System.out.println("dataname = " + dataname); System.out.println("eps2 = " + eps2 + " max_switch = " + max_switch); System.out.println("burn_factor = " + burn_factor + " sample_freq = " + sample_freq + " n_samples = " + n_samples); // String filename = prefix + "_data/" + dataname + ".gr"; String filename_1k = prefix + "_dk/" + dataname + "_noisy.1k"; String filename_deg = filename_1k.substring(0,filename_1k.length()-3) + ".deg"; String outfile_1k = filename_1k.substring(0,filename_1k.length()-3) + ".gen"; // EdgeListReader reader = new EdgeListReader(); EdgeListWriter writer = new EdgeListWriter(); Grph G; RegularFile f = new RegularFile(filename); G = reader.readGraph(f); System.out.println("#nodes = " + G.getNumberOfVertices()); System.out.println("#edges = " + G.getNumberOfEdges()); // TEST reorderNodes(), editScore() int n_nodes = G.getNumberOfVertices(); Grph G0 = reorderNodes(n_nodes, outfile_1k, filename_deg); int cur_score = editScore(G, G0); System.out.println("score = " + cur_score); // TEST mcmcSampling() long start = System.currentTimeMillis(); mcmcSampling(G, G0, eps2, burn_factor*G.getNumberOfVertices(), n_samples, sample_freq, max_switch); System.out.println("mcmcSampling - DONE, elapsed " + (System.currentTimeMillis() - start)); } }
901976ace1943a4a9f046b0568ef57f63416f864
089583dcf109129ba304e927d2d6d88bf9a7b909
/Share.java
d5b5344f41b32be7258e44ec6b1a2a6e740074e1
[]
no_license
zabela/Chat
7ed934cecefd33f1f7f270ab5479a9d2c44c3726
93e0555bf7147691ab2d4c3b473f1b2b8a4bcb57
refs/heads/master
2016-09-07T11:39:56.854381
2013-07-05T12:14:53
2013-07-05T12:14:53
11,198,935
1
1
null
null
null
null
UTF-8
Java
false
false
601
java
package dchat; import java.net.InetAddress; public class Share extends PMsg { private String filename; private String type; /* SHARE <filename>\n * TYPE <type>\n * PEER <nick>\n * SEQUENCE <number>\0 */ public Share(String peer, InetAddress address, int sequence, String filename, String type) { super(peer, address, sequence); // TODO Auto-generated constructor stub this.filename = filename; this.type = type; } public String getInfo() { return "SHARE " + filename + "\nTYPE " + type + "\nPEER " + super.getPeer() + "\nSEQUENCE " + super.getSequence() + '\0'; } }
7bf21db9934c8755f0ffebcc2544a8143ca86b54
86af5192cfb33b0aad7b37cee95b4e571f8a9ca1
/src/com/mebigfatguy/junitflood/classpath/ClassLookup.java
9565dab2e06bba8d610dd4a1967f1df82fe0519f
[]
no_license
VijayEluri/junitflood
c78867f98467005e3c7fd95067167f5d1c3f60ef
3b976e000eeb03b9499072c50611b90aa3b7326a
refs/heads/master
2020-05-20T11:13:49.149441
2019-02-05T04:10:44
2019-02-05T04:10:44
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,191
java
/* * junitflood - An automatic junit test generator * Copyright 2011-2019 MeBigFatGuy.com * Copyright 2011-2019 Dave Brosius * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations * under the License. */ package com.mebigfatguy.junitflood.classpath; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import com.mebigfatguy.junitflood.Configuration; public class ClassLookup { private final ClassLoader classLoader; private final Map<String, ClassDetails> classDetails = new HashMap<String, ClassDetails>(); private final URL[] urls; public ClassLookup(Configuration config) throws MalformedURLException { Set<File> roots = new HashSet<File>(); roots.addAll(config.getScanClassPath()); roots.addAll(config.getAuxClassPath()); urls = new URL[roots.size()]; int i = 0; for (File root : roots) { urls[i++] = new URL("file://" + root.getAbsolutePath()); } classLoader = createClassLoader(); } public final ClassLoader createClassLoader() { return AccessController.<URLClassLoader>doPrivileged(new PrivilegedAction<URLClassLoader>() { @Override public URLClassLoader run() { return new URLClassLoader(urls); } }); } public Set<String> getConstructors(String clsName, String fromClass) { ClassDetails classInfo = classDetails.get(clsName); if (classInfo == null) { classInfo = new ClassDetails(classLoader, clsName); classDetails.put(clsName, classInfo); } return classInfo.getConstructors(fromClass); } }
167ef75a35753adc8cfd9b2d18ae1f2b73d89842
a11184300a06d16b4397a53731812a449a373671
/app/src/main/java/com/example/a3_lab/count.java
47f8c2e3c15f876f6e0f9cbc40d58412eb8ca38f
[]
no_license
Juke2Nuke/3_lab
13315bc30ad01dfe9d23571bb167a75385a026f4
5cabe4411ad05d3b5efa7d98f2adcb92533c86ad
refs/heads/master
2023-01-13T09:51:34.609791
2020-11-17T21:49:45
2020-11-17T21:49:45
313,718,725
0
0
null
null
null
null
UTF-8
Java
false
false
130
java
package com.example.a3_lab; public class count { int arithmetic(int input,char action) { return input; } }
0067abbfae47b9c86b6f8a42bff7a870590453fe
3dc7be30a4fe5a377adc7aab7a04c784ed81b715
/WebContent/WEB-INF/src/phm/ezcounting/PaySystem2.java
e9a52ae9cdc580f2dd423e08f7d2c1eed8767082
[]
no_license
phm1qazxsw2/mca_beta2
b6ba15fcc4ba653a8fc2287d7d1bca2b97d498f7
63af91469f86474a5edd15ab886363839e9fa9af
refs/heads/master
2021-01-18T13:02:54.771704
2015-03-04T03:32:01
2015-03-04T03:32:01
30,103,400
0
0
null
null
null
null
UTF-8
Java
false
false
14,759
java
package phm.ezcounting; import java.util.*; import java.sql.*; import java.util.Date; public class PaySystem2 { private int id; private Date created; private Date modified; private String paySystemCompanyName; private String paySystemCompanyAddress; private String paySystemCompanyPhone; private int paySystemLimitDate; private String paySystemCompanyUniteId; private String paySystemBankName; private String paySystemBankId; private String paySystemFirst5; private String paySystemBankStoreNickName; private String paySystemCompanyStoreNickName; private int paySystemBeforeLimitDate; private int paySystemLimitMoney; private int paySystemBankAccountId; private int paySystemMessageActive; private int paySystemMessageTo; private String paySystemMessageURL; private String paySystemMessageUser; private String paySystemMessagePass; private String paySystemMessageText; private int paySystemATMActive; private int paySystemStoreActive; private String paySystemReplaceWord; private int paySystemBirthActive; private String paySystemBirthWord; private int paySystemATMAccountId; private int paySystemEmailActive; private int paySystemEmailTo; private String paySystemEmailText; private int paySystemNoticeEmailTo; private int paySystemNoticeEmailType; private String paySystemNoticeEmailTitle; private String paySystemNoticeEmailText; private int paySystemNoticeMessageTo; private String paySystemNoticeMessageTest; private String paySystemEmailServer; private String paySystemEmailSender; private String paySystemEmailSenderAddress; private String paySystemEmailCode; private String paySystemFixATMAccount; private int paySystemFixATMNum; private int paySystemExtendNotpay; private String topLogoHtml; private String billLogoPath; private String billWaterMarkPath; private int useChecksum; private int version; private int customerType; private String website; private int banktype; private int pagetype; private int workflow; private int cardread; private String cardmachine; private int eventAuto; private int membrService; private String extraBankInfo; public PaySystem2() {} public int getId () { return id; } public Date getCreated () { return created; } public Date getModified () { return modified; } public String getPaySystemCompanyName () { return paySystemCompanyName; } public String getPaySystemCompanyAddress () { return paySystemCompanyAddress; } public String getPaySystemCompanyPhone () { return paySystemCompanyPhone; } public int getPaySystemLimitDate () { return paySystemLimitDate; } public String getPaySystemCompanyUniteId () { return paySystemCompanyUniteId; } public String getPaySystemBankName () { return paySystemBankName; } public String getPaySystemBankId () { return paySystemBankId; } public String getPaySystemFirst5 () { return paySystemFirst5; } public String getPaySystemBankStoreNickName () { return paySystemBankStoreNickName; } public String getPaySystemCompanyStoreNickName () { return paySystemCompanyStoreNickName; } public int getPaySystemBeforeLimitDate () { return paySystemBeforeLimitDate; } public int getPaySystemLimitMoney () { return paySystemLimitMoney; } public int getPaySystemBankAccountId () { return paySystemBankAccountId; } public int getPaySystemMessageActive () { return paySystemMessageActive; } public int getPaySystemMessageTo () { return paySystemMessageTo; } public String getPaySystemMessageURL () { return paySystemMessageURL; } public String getPaySystemMessageUser () { return paySystemMessageUser; } public String getPaySystemMessagePass () { return paySystemMessagePass; } public String getPaySystemMessageText () { return paySystemMessageText; } public int getPaySystemATMActive () { return paySystemATMActive; } public int getPaySystemStoreActive () { return paySystemStoreActive; } public String getPaySystemReplaceWord () { return paySystemReplaceWord; } public int getPaySystemBirthActive () { return paySystemBirthActive; } public String getPaySystemBirthWord () { return paySystemBirthWord; } public int getPaySystemATMAccountId () { return paySystemATMAccountId; } public int getPaySystemEmailActive () { return paySystemEmailActive; } public int getPaySystemEmailTo () { return paySystemEmailTo; } public String getPaySystemEmailText () { return paySystemEmailText; } public int getPaySystemNoticeEmailTo () { return paySystemNoticeEmailTo; } public int getPaySystemNoticeEmailType () { return paySystemNoticeEmailType; } public String getPaySystemNoticeEmailTitle () { return paySystemNoticeEmailTitle; } public String getPaySystemNoticeEmailText () { return paySystemNoticeEmailText; } public int getPaySystemNoticeMessageTo () { return paySystemNoticeMessageTo; } public String getPaySystemNoticeMessageTest () { return paySystemNoticeMessageTest; } public String getPaySystemEmailServer () { return paySystemEmailServer; } public String getPaySystemEmailSender () { return paySystemEmailSender; } public String getPaySystemEmailSenderAddress () { return paySystemEmailSenderAddress; } public String getPaySystemEmailCode () { return paySystemEmailCode; } public String getPaySystemFixATMAccount () { return paySystemFixATMAccount; } public int getPaySystemFixATMNum () { return paySystemFixATMNum; } public int getPaySystemExtendNotpay () { return paySystemExtendNotpay; } public String getTopLogoHtml () { return topLogoHtml; } public String getBillLogoPath () { return billLogoPath; } public String getBillWaterMarkPath () { return billWaterMarkPath; } public int getUseChecksum () { return useChecksum; } public int getVersion () { return version; } public int getCustomerType () { return customerType; } public String getWebsite () { return website; } public int getBanktype () { return banktype; } public int getPagetype () { return pagetype; } public int getWorkflow () { return workflow; } public int getCardread () { return cardread; } public String getCardmachine () { return cardmachine; } public int getEventAuto () { return eventAuto; } public int getMembrService () { return membrService; } public String getExtraBankInfo () { return extraBankInfo; } public void setId (int id) { this.id = id; } public void setCreated (Date created) { this.created = created; } public void setModified (Date modified) { this.modified = modified; } public void setPaySystemCompanyName (String paySystemCompanyName) { this.paySystemCompanyName = paySystemCompanyName; } public void setPaySystemCompanyAddress (String paySystemCompanyAddress) { this.paySystemCompanyAddress = paySystemCompanyAddress; } public void setPaySystemCompanyPhone (String paySystemCompanyPhone) { this.paySystemCompanyPhone = paySystemCompanyPhone; } public void setPaySystemLimitDate (int paySystemLimitDate) { this.paySystemLimitDate = paySystemLimitDate; } public void setPaySystemCompanyUniteId (String paySystemCompanyUniteId) { this.paySystemCompanyUniteId = paySystemCompanyUniteId; } public void setPaySystemBankName (String paySystemBankName) { this.paySystemBankName = paySystemBankName; } public void setPaySystemBankId (String paySystemBankId) { this.paySystemBankId = paySystemBankId; } public void setPaySystemFirst5 (String paySystemFirst5) { this.paySystemFirst5 = paySystemFirst5; } public void setPaySystemBankStoreNickName (String paySystemBankStoreNickName) { this.paySystemBankStoreNickName = paySystemBankStoreNickName; } public void setPaySystemCompanyStoreNickName (String paySystemCompanyStoreNickName) { this.paySystemCompanyStoreNickName = paySystemCompanyStoreNickName; } public void setPaySystemBeforeLimitDate (int paySystemBeforeLimitDate) { this.paySystemBeforeLimitDate = paySystemBeforeLimitDate; } public void setPaySystemLimitMoney (int paySystemLimitMoney) { this.paySystemLimitMoney = paySystemLimitMoney; } public void setPaySystemBankAccountId (int paySystemBankAccountId) { this.paySystemBankAccountId = paySystemBankAccountId; } public void setPaySystemMessageActive (int paySystemMessageActive) { this.paySystemMessageActive = paySystemMessageActive; } public void setPaySystemMessageTo (int paySystemMessageTo) { this.paySystemMessageTo = paySystemMessageTo; } public void setPaySystemMessageURL (String paySystemMessageURL) { this.paySystemMessageURL = paySystemMessageURL; } public void setPaySystemMessageUser (String paySystemMessageUser) { this.paySystemMessageUser = paySystemMessageUser; } public void setPaySystemMessagePass (String paySystemMessagePass) { this.paySystemMessagePass = paySystemMessagePass; } public void setPaySystemMessageText (String paySystemMessageText) { this.paySystemMessageText = paySystemMessageText; } public void setPaySystemATMActive (int paySystemATMActive) { this.paySystemATMActive = paySystemATMActive; } public void setPaySystemStoreActive (int paySystemStoreActive) { this.paySystemStoreActive = paySystemStoreActive; } public void setPaySystemReplaceWord (String paySystemReplaceWord) { this.paySystemReplaceWord = paySystemReplaceWord; } public void setPaySystemBirthActive (int paySystemBirthActive) { this.paySystemBirthActive = paySystemBirthActive; } public void setPaySystemBirthWord (String paySystemBirthWord) { this.paySystemBirthWord = paySystemBirthWord; } public void setPaySystemATMAccountId (int paySystemATMAccountId) { this.paySystemATMAccountId = paySystemATMAccountId; } public void setPaySystemEmailActive (int paySystemEmailActive) { this.paySystemEmailActive = paySystemEmailActive; } public void setPaySystemEmailTo (int paySystemEmailTo) { this.paySystemEmailTo = paySystemEmailTo; } public void setPaySystemEmailText (String paySystemEmailText) { this.paySystemEmailText = paySystemEmailText; } public void setPaySystemNoticeEmailTo (int paySystemNoticeEmailTo) { this.paySystemNoticeEmailTo = paySystemNoticeEmailTo; } public void setPaySystemNoticeEmailType (int paySystemNoticeEmailType) { this.paySystemNoticeEmailType = paySystemNoticeEmailType; } public void setPaySystemNoticeEmailTitle (String paySystemNoticeEmailTitle) { this.paySystemNoticeEmailTitle = paySystemNoticeEmailTitle; } public void setPaySystemNoticeEmailText (String paySystemNoticeEmailText) { this.paySystemNoticeEmailText = paySystemNoticeEmailText; } public void setPaySystemNoticeMessageTo (int paySystemNoticeMessageTo) { this.paySystemNoticeMessageTo = paySystemNoticeMessageTo; } public void setPaySystemNoticeMessageTest (String paySystemNoticeMessageTest) { this.paySystemNoticeMessageTest = paySystemNoticeMessageTest; } public void setPaySystemEmailServer (String paySystemEmailServer) { this.paySystemEmailServer = paySystemEmailServer; } public void setPaySystemEmailSender (String paySystemEmailSender) { this.paySystemEmailSender = paySystemEmailSender; } public void setPaySystemEmailSenderAddress (String paySystemEmailSenderAddress) { this.paySystemEmailSenderAddress = paySystemEmailSenderAddress; } public void setPaySystemEmailCode (String paySystemEmailCode) { this.paySystemEmailCode = paySystemEmailCode; } public void setPaySystemFixATMAccount (String paySystemFixATMAccount) { this.paySystemFixATMAccount = paySystemFixATMAccount; } public void setPaySystemFixATMNum (int paySystemFixATMNum) { this.paySystemFixATMNum = paySystemFixATMNum; } public void setPaySystemExtendNotpay (int paySystemExtendNotpay) { this.paySystemExtendNotpay = paySystemExtendNotpay; } public void setTopLogoHtml (String topLogoHtml) { this.topLogoHtml = topLogoHtml; } public void setBillLogoPath (String billLogoPath) { this.billLogoPath = billLogoPath; } public void setBillWaterMarkPath (String billWaterMarkPath) { this.billWaterMarkPath = billWaterMarkPath; } public void setUseChecksum (int useChecksum) { this.useChecksum = useChecksum; } public void setVersion (int version) { this.version = version; } public void setCustomerType (int customerType) { this.customerType = customerType; } public void setWebsite (String website) { this.website = website; } public void setBanktype (int banktype) { this.banktype = banktype; } public void setPagetype (int pagetype) { this.pagetype = pagetype; } public void setWorkflow (int workflow) { this.workflow = workflow; } public void setCardread (int cardread) { this.cardread = cardread; } public void setCardmachine (String cardmachine) { this.cardmachine = cardmachine; } public void setEventAuto (int eventAuto) { this.eventAuto = eventAuto; } public void setMembrService (int membrService) { this.membrService = membrService; } public void setExtraBankInfo (String extraBankInfo) { this.extraBankInfo = extraBankInfo; } public static final int SMS_TARGET_DEFAULT = 0; public static final int SMS_TARGET_BOTH = 1; public static final int VERSION_STANDARD = 0; public static final int VERSION_PROFESSIONAL = 1; public static final int CUSTOMER_TYPE_SCHOOL = 0; public static final int CUSTOMER_TYPE_COMPANY = 1; public static final int WORKFLOW_NONE = 0; public static final int WORKFLOW_KJF = 1; public static final int WORKFLOW_NEIL = 2; public boolean storePayEnabled() { if(getPaySystemStoreActive()==0 || getPaySystemStoreActive()==9) return false; return true; } }
c50553e3fdbfad1354f5c32088e37cef3075a7b8
f5defba2beabf0de5a0d36233d42071db916315b
/src/br/com/comanda/persistence/CategoriaDAO.java
f108318c4a0aa60f07e4fbb9683674e776a0ccde
[]
no_license
cesarquadros/comandaWEB
ed29d300e23b36206f60ce5dc0ab76f79905c075
7260a3f2ef8383d82d329b03ae8e1ab6b48940f3
refs/heads/master
2020-01-23T21:48:05.363748
2017-01-10T17:19:55
2017-01-10T17:19:55
74,675,182
0
0
null
null
null
null
UTF-8
Java
false
false
1,723
java
package br.com.comanda.persistence; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import br.com.comanda.entities.Categoria; public class CategoriaDAO extends Conexao { public List<Categoria> listAll() { List<Categoria> listCategoria = new ArrayList<Categoria>(); Categoria categoria = null; try { con = abreConexao(); String sql = "SELECT * FROM CATEGORIAS"; stmt = con.prepareStatement(sql); rs = stmt.executeQuery(); while (rs.next()) { categoria = new Categoria(); categoria.setCodCategoria(rs.getInt("cod_categoria")); categoria.setCategoria(rs.getString("categoria")); listCategoria.add(categoria); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { try { stmt.close(); con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return listCategoria; } public Categoria findById(Integer idCategoria){ Categoria categoria = null; String sql = "select * from categorias where cod_categoria=?"; try { con = abreConexao(); stmt = con.prepareStatement(sql); stmt.setInt(1, idCategoria); rs = stmt.executeQuery(); while(rs.next()){ categoria = new Categoria(); categoria.setCodCategoria(rs.getInt("cod_categoria")); categoria.setCategoria(rs.getString("categoria")); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { try { stmt.close(); con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return categoria; } }
caf3dbf371dd09ecf1e817874ca98b0d2b9c74e8
e6d2f8cfaa6b9723fe6cb93a81d8c5f4340f4cd3
/TEMA_04/Ejercicio11_4.java
f9085e1f4e09cdd45526656837bf4075d8633c50
[]
no_license
nax1999/mi-aprende-java-con-ejercicios
ba998949f6a72c943d7605316db5a039f28e57e3
6dc7a7d51fa7574012b6220c41f1b157602676aa
refs/heads/master
2020-09-09T13:12:47.706309
2019-11-13T13:29:13
2019-11-13T13:29:13
221,455,778
0
0
null
2019-11-13T12:36:07
2019-11-13T12:36:06
null
UTF-8
Java
false
false
1,135
java
/** * Ejercicio 11 | Tema 4 * Dada una hora, dice los segundos que faltan para la medianoche. * @author Lucia Blanco */ public class Ejercicio11_4 { // Clase principal public static void main(String[] args) { /* Lee la hora */ System.out.print("Por favor, introduce la hora (formato 24h): "); int hora = Integer.parseInt(System.console().readLine()); if ((0 < hora) && (hora > 23)) { System.out.println("El dato no es correcto"); } else { System.out.print("Por favor, introduce los minutos: "); int min = Integer.parseInt(System.console().readLine()); if ((0 < min) && (min > 59)) { System.out.println("El dato no es correcto"); } else { /* En caso de que ya sea media noche */ if ((hora == 0) && (min == 0)){ System.out.println("Ya es medianoche"); /* Demás casos */ } else { int horaSec = (23 - hora)* 3600; int minSec = (60 - min)* 60; int medianoche = horaSec + minSec; System.out.println("Faltan " + medianoche + " segundos para medianoche."); } } } } }
fbfde97bfaa80e46450f1d6b239bc997554b9275
d6e99ba2f6ee1d92b9b9972ba59e38a24920d991
/src/main/java/com/interviewbit/string/search/ImplementStrStr.java
95de1d4fe7afd66a4a89d715e9f7c2695ea3a726
[]
no_license
Mrinal-Bhattacharya/Data_Structure
3a7ddb637164eb38523292a433bfa64f477d7696
654422117874765f05524b13141f4d509b28f852
refs/heads/master
2021-01-18T12:24:12.720661
2020-02-05T06:12:32
2020-02-05T06:12:32
42,710,167
0
0
null
null
null
null
UTF-8
Java
false
false
562
java
package com.interviewbit.string.search; public class ImplementStrStr { public int strStr(final String A, final String B) { if ((A == null) || (B == null)) { return -1; } for (int i = 0; i < ((A.length() - B.length()) + 1); i++) { int j; for (j = 0; j < B.length(); j++) { if (A.charAt(i + j) != B.charAt(j)) { break; } } if (j == B.length()) { return i; } } return -1; } }
9eef77dc5f73cda6c82ddb50367e72eef8409292
29c78372eae9194e1bb2bd06a037503d43446325
/Tema7/Ejercicio7B_4.java
320061b771d2f5f8b6b7fc71627eb98508f9ffa7
[]
no_license
samuelvalverde28/ejercicios-java
3f67107eac1bb1b6ca6130ee5029a2c947555ca6
f396c497759987be19f75dceb95a508f0a847bc6
refs/heads/master
2020-03-30T12:11:07.941494
2019-01-08T08:11:18
2019-01-08T08:11:18
151,212,455
1
0
null
null
null
null
UTF-8
Java
false
false
946
java
public class Ejercicio7B_4{ public static void main(String[] arg) throws InterruptedException{ System.out.println("Introduce 20 numeros enteros"); int[][] num = new int[4][5]; //4 filas 5 columnas int[][] aux = new int [5][6]; for (int i= 0;i<4;i++){ for (int x = 0;x<5;x++){ num[i][x] = (int)(((Math.random()*900)+100)); aux[i][x] = num[i][x]; } } //relleno el arraid num y aux for (int i=0;i<4;i++){ for (int x=0;x<5;x++){ aux[i][5] += num[i][x]; } } //se calcula la suma de las filas en la columna 6 for (int i=0;i<6;i++){ for (int x=0;x<4;x++){ aux[4][i] += aux[x][i]; } } //se calcula la suma de las columnas en la fila 5 for (int i=0;i<5;i++){ System.out.println(); for (int x=0;x<6;x++){ System.out.print(aux[i][x]+" "); Thread.sleep(1000); } } //se muestra } }
137a937a7c2c2f6a7a122ac683b0713761e779dd
2a76f8d5b366ec0997fdf4373ea849f15aad4860
/ch03/src/main/java/com/sanqing/action/SubjectAddAction.java
d8c49f8618f0fb1b42e714cc76f9d4cd78440b88
[]
no_license
py85252876/JavaWeb
008d69f274c69780eccc2eb70c58f4f5bb3b9714
ffde4d7b210b29b1b0bdccf7cae2b04167c1ea72
refs/heads/master
2021-06-19T14:31:16.830488
2017-06-02T22:45:11
2017-06-02T22:45:11
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,627
java
package com.sanqing.action; import com.opensymphony.xwork2.ActionSupport; import com.sanqing.po.Subject; import com.sanqing.service.SubjectService; import com.sanqing.service.SubjectServiceImpl; //该Action用来接收试题参数,并调用业务逻辑组件SubjectService来完成试题添加 public class SubjectAddAction extends ActionSupport { private String subjectTitle; private String subjectOptionA; private String subjectOptionB; private String subjectOptionC; private String subjectOptionD; private String subjectAnswer; private String subjectParse; private SubjectService subjectService = new SubjectServiceImpl(); public String getSubjectTitle() { return subjectTitle; } public void setSubjectTitle(String subjectTitle) { this.subjectTitle = subjectTitle; } public String getSubjectOptionA() { return subjectOptionA; } public void setSubjectOptionA(String subjectOptionA) { this.subjectOptionA = subjectOptionA; } public String getSubjectOptionB() { return subjectOptionB; } public void setSubjectOptionB(String subjectOptionB) { this.subjectOptionB = subjectOptionB; } public String getSubjectOptionC() { return subjectOptionC; } public void setSubjectOptionC(String subjectOptionC) { this.subjectOptionC = subjectOptionC; } public String getSubjectOptionD() { return subjectOptionD; } public void setSubjectOptionD(String subjectOptionD) { this.subjectOptionD = subjectOptionD; } public String getSubjectAnswer() { return subjectAnswer; } public void setSubjectAnswer(String subjectAnswer) { this.subjectAnswer = subjectAnswer; } public String getSubjectParse() { return subjectParse; } public void setSubjectParse(String subjectParse) { this.subjectParse = subjectParse; } public String execute() throws Exception { Subject subject = new Subject(); subject.setSubjectTitle(subjectTitle); subject.setSubjectOptionA(subjectOptionA); subject.setSubjectOptionB(subjectOptionB); subject.setSubjectOptionC(subjectOptionC); subject.setSubjectOptionD(subjectOptionD); subject.setSubjectAnswer(subjectAnswer); subject.setSubjectParse(subjectParse); if (subjectService.saveSubject(subject)) { return SUCCESS; } else { this.addActionError("该试题已经添加过了,请不要重复添加!"); return INPUT; } } }
1523c546bffc64423c8d18422520fad22245f18c
50dc9073024ccc537f846673af124b55275c257a
/app/src/main/java/com/olebas/photogallery/SingleFragmentActivity.java
dc8e9301f196f31f59acab33396979f2e5c85dd5
[]
no_license
olebas13/PhotoGallery
47b3529bb0b90aacd3df075c1b209aa375218e21
ff636ad75302aef31e10f8f4b135d70c72fffc68
refs/heads/master
2020-04-03T12:08:36.833563
2018-11-15T14:33:43
2018-11-15T14:33:43
140,697,931
0
0
null
null
null
null
UTF-8
Java
false
false
840
java
package com.olebas.photogallery; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v7.app.AppCompatActivity; public abstract class SingleFragmentActivity extends AppCompatActivity { protected abstract Fragment createFragment(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fragment); FragmentManager fm = getSupportFragmentManager(); Fragment fragment = fm.findFragmentById(R.id.fragment_container); if (fragment == null) { fragment = createFragment(); fm.beginTransaction() .add(R.id.fragment_container, fragment) .commit(); } } }
9af23c5e67b392f6e6c16c05d51e8a801e7c4702
f26ddff8c5da940b37fdb547ee9643864a035f1f
/src/main/java/bmlfms/util/TreeBuilderMenu.java
2676c1c99ad4ca4d24aec6528d992752d6fd0b88
[]
no_license
TennoClash/-Building-Material-Leasing-Financial-Management-System
0a072852135b161841331a509eff3658017bdd71
8bd270b8e5b826b560c062de54672877203b6467
refs/heads/master
2020-04-10T06:42:27.409623
2018-12-18T05:54:44
2018-12-18T05:54:44
160,862,228
0
0
null
null
null
null
UTF-8
Java
false
false
2,446
java
package bmlfms.util; import java.util.ArrayList; import java.util.List; import javax.print.DocFlavor.STRING; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.serializer.SerializerFeature; import bmlfms.entity.Menu; public class TreeBuilderMenu { List<Menu> nodes = new ArrayList<>(); public String buildTree(List<Menu> nodes) { TreeBuilderMenu treeBuilder = new TreeBuilderMenu(nodes); return treeBuilder.buildJSONTree(); } public TreeBuilderMenu() { } public TreeBuilderMenu(List<Menu> nodes) { super(); this.nodes = nodes; } // 构建JSON树形结构 public String buildJSONTree() { List<Menu> nodeTree = buildTree(); JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; return JSON.toJSONString(nodeTree, SerializerFeature.WriteDateUseDateFormat); } // 构建树形结构 public List<Menu> buildTree() { List<Menu> treeNodes = new ArrayList<>(); List<Menu> rootNodes = getRootNodes(); for (Menu rootNode : rootNodes) { buildChildNodes(rootNode); treeNodes.add(rootNode); } return treeNodes; } // 递归子节点 public void buildChildNodes(Menu node) { List<Menu> children = getChildNodes(node); if (!children.isEmpty()) { for (Menu child : children) { buildChildNodes(child); } node.setChildren(children); } } // 获取父节点下所有的子节点 public List<Menu> getChildNodes(Menu pnode) { List<Menu> childNodes = new ArrayList<>(); for (Menu n : nodes) { if (pnode.getMenuId()==n.getPid()) { childNodes.add(n); } } return childNodes; } // 判断是否为根节点 public boolean rootNode(Menu node) { boolean isRootNode = true; for (Menu n : nodes) { if (node.getPid()==n.getMenuId()) { isRootNode = false; break; } } return isRootNode; } // 获取集合中所有的根节点 public List<Menu> getRootNodes() { List<Menu> rootNodes = new ArrayList<>(); for (Menu n : nodes) { if (rootNode(n)) { rootNodes.add(n); } } return rootNodes; } }
a68cc08d6c2fbb4642039ba477b8ce786fb5de2d
ff745fde8d956400f9de7ee017a18eb5fcadcaae
/Metadata.java
fdb167a4d79ef4545c47116551ad1c72caecc4f6
[]
no_license
Akhila08/JavaImage
f7c19393ceb107058031dc1d8a213e5df836d28c
da51a4857d64a0562890d2488e08b068a48cc49d
refs/heads/master
2016-09-05T17:24:12.567971
2015-09-11T12:39:27
2015-09-11T12:39:27
39,903,706
0
1
null
2015-09-15T07:55:53
2015-07-29T16:19:39
Java
UTF-8
Java
false
false
3,129
java
@@ -0,0 +1,104 @@ import org.w3c.dom.*; import java.io.*; import static java.lang.System.out; import java.util.*; import javax.imageio.*; import javax.imageio.stream.*; import javax.imageio.metadata.*; public class Metadata { public static void main(String[] args) { Metadata meta = new Metadata(); String filename = "C:\\Users\\Sai\\Desktop\\hihi.jpg"; if (new File(filename).exists()) { meta.readAndDisplayMetadata(filename); } else { System.out.println("cannot find file: " + filename); } } void readAndDisplayMetadata( String fileName ) { try { File file = new File(fileName); ImageInputStream iis = ImageIO.createImageInputStream(file); Iterator<ImageReader> readers = ImageIO.getImageReaders(iis); if (readers.hasNext()) { // pick the first available ImageReader ImageReader reader = readers.next(); // attach source to the reader reader.setInput(iis, true); // read metadata of first image IIOMetadata metadata = reader.getImageMetadata(0); String[] names = metadata.getMetadataFormatNames(); int length = names.length; for (int i = 0; i < length; i++) { System.out.println( "Format name: " + names[ i ] ); displayMetadata(metadata.getAsTree(names[i])); } File file1 = new File("out.txt"); //Your file FileOutputStream fos = new FileOutputStream(file1); PrintStream ps = new PrintStream(fos); System.setOut(ps); } } catch (Exception e) { e.printStackTrace(); } } void displayMetadata(Node root) { displayMetadata(root, 0); } void indent(int level) { for (int i = 0; i < level; i++) System.out.print(" "); } void displayMetadata(Node node, int level) { // print open tag of element indent(level); System.out.print("<" + node.getNodeName()); NamedNodeMap map = node.getAttributes(); if (map != null) { // print attribute values int length = map.getLength(); for (int i = 0; i < length; i++) { Node attr = map.item(i); System.out.print(" " + attr.getNodeName() + "=\"" + attr.getNodeValue() + "\""); } } Node child = node.getFirstChild(); if (child == null) { // no children, so close element and return System.out.println("/>"); return; } // children, so close current tag System.out.println(">"); while (child != null) { // print children recursively displayMetadata(child, level + 1); child = child.getNextSibling(); } // print close tag of element indent(level); System.out.println("</" + node.getNodeName() + ">"); } } \ No newline at end of file
3107f52b73f9745db4fe89f79d4f3508ee073882
01b67b2ba9b1d251b8158279c18e7ea69c888fd5
/backend/meduo-tools/meduo-tools-core/src/main/java/org/quick/meduo/tools/core/collection/BoundedPriorityQueue.java
94e2518434ef6605c8ae320046a341d4fcb7be4e
[ "LicenseRef-scancode-unknown-license-reference", "MulanPSL-2.0", "LicenseRef-scancode-mulanpsl-2.0-en" ]
permissive
suwinner1987/meduo
7489e24a4623c95ed4794d3262839478f65566d5
34c8d707a423dfbcf1b0f103a527eb1f3735c188
refs/heads/master
2023-06-10T11:02:53.867308
2020-11-23T07:43:48
2020-11-23T07:43:48
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,159
java
package org.quick.meduo.tools.core.collection; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Iterator; import java.util.PriorityQueue; /** * 有界优先队列<br> * 按照给定的排序规则,排序元素,当队列满时,按照给定的排序规则淘汰末尾元素(去除末尾元素) * @author xiaoleilu * * @param <E> 成员类型 */ public class BoundedPriorityQueue<E> extends PriorityQueue<E>{ private static final long serialVersionUID = 3794348988671694820L; //容量 private final int capacity; private final Comparator<? super E> comparator; public BoundedPriorityQueue(int capacity) { this(capacity, null); } /** * 构造 * @param capacity 容量 * @param comparator 比较器 */ public BoundedPriorityQueue(int capacity, final Comparator<? super E> comparator) { super(capacity, (o1, o2) -> { int cResult; if(comparator != null) { cResult = comparator.compare(o1, o2); }else { @SuppressWarnings("unchecked") Comparable<E> o1c = (Comparable<E>)o1; cResult = o1c.compareTo(o2); } return - cResult; }); this.capacity = capacity; this.comparator = comparator; } /** * 加入元素,当队列满时,淘汰末尾元素 * @param e 元素 * @return 加入成功与否 */ @Override public boolean offer(E e) { if(size() >= capacity) { E head = peek(); if (this.comparator().compare(e, head) <= 0){ return true; } //当队列满时,就要淘汰顶端队列 poll(); } return super.offer(e); } /** * 添加多个元素<br> * 参数为集合的情况请使用{@link PriorityQueue#addAll} * @param c 元素数组 * @return 是否发生改变 */ public boolean addAll(E[] c) { return this.addAll(Arrays.asList(c)); } /** * @return 返回排序后的列表 */ public ArrayList<E> toList() { final ArrayList<E> list = new ArrayList<>(this); list.sort(comparator); return list; } @Override public Iterator<E> iterator() { return toList().iterator(); } }
24f6de567e7a20c9b470d9b5a6192ac797493080
045699573f75c253513115887e04f29f1e23e432
/src/main/java/com/geetion/puputuan/engine/handlernew/impl/SameTypeMatcher.java
ab4574c1be4d269a6249d19569fd2ccec288e620
[]
no_license
zhuobinchan/popoteam_server_v1.0
61b46d716d3257f3110ab79ec7da04c7c6d4d8e3
f4dd97f76e8d5192a54a3eafc06cd79c280155a9
refs/heads/master
2021-01-21T23:04:51.632776
2017-06-23T05:48:15
2017-06-23T05:48:15
95,187,326
1
1
null
null
null
null
UTF-8
Java
false
false
2,968
java
package com.geetion.puputuan.engine.handlernew.impl; import com.geetion.puputuan.common.constant.GroupTypeAndStatus; import com.geetion.puputuan.engine.handlernew.RedisMatcher; import com.geetion.puputuan.model.Group; import com.geetion.puputuan.model.Recommend; import com.geetion.puputuan.model.UserRecommend; import org.apache.log4j.Logger; import java.util.*; /** * 同类型 */ public class SameTypeMatcher extends RedisMatcher { private final Logger logger = Logger.getLogger(SameTypeMatcher.class); @Override public boolean matchGroup(Long groupId, Long userId, Date time) { logger.info("==========SameTypeMatcher,Thread name: " + Thread.currentThread().getName() +", groupId: " + groupId); Group mainGroup = groupService.getGroupById(groupId); // 当队伍已经解散直接返回false if(mainGroup.getStatus().equals(GroupTypeAndStatus.GROUP_DISSOLUTION)){ logger.info("==========SameTypeMatcher, " + groupId + " is dissolution ================="); // 当队伍解散时,会触发清理对应redis的缓存数据 // 但可能存在解散之前,刚好队伍中的缓存被取出,由于bean的缓存是由id + modifyTime组成 // 当bean有多条数据时,需要在线程执行中,将对应的bean进行删除。 runMatchUtil.cleanRedis(groupId); return false; } if(!mainGroup.getBarId().equals(60003L)){ return this.nextMatchGroup(groupId, userId, time); } Map<String, Object> params = new HashMap<>(); params.put("barId", mainGroup.getBarId()); params.put("status", GroupTypeAndStatus.GROUP_MATCHING); params.put("groupId", groupId); List<Group> matchGroup = groupService.selectMatchGroupByParam(params); // 匹配不到队伍,执行下一个匹配算法 if(matchGroup.size() == 0 ){ return this.nextMatchGroup(groupId, userId, time); } List<Group> voteGroup = this.selectVoteGroup(groupId); List<Group> mergeGroup = this.mergeGroup(matchGroup, voteGroup); this.excludeSuperLikeGroup(mainGroup, mergeGroup); this.excludeDislikeGroup(userId, mainGroup, mergeGroup); this.pollLikeGroupToFirst(userId, mainGroup, mergeGroup); List<Recommend> recommends = new ArrayList<>(); List<UserRecommend> userRecommends = new ArrayList<>(); this.addRecommend(mainGroup, mergeGroup, recommends); // 如果过滤之后,没有生成新的推荐信息,执行下一个算法 if(recommends.size() == 0 ){ return this.nextMatchGroup(groupId, userId, time); } if (this.ifNewestGroup(mainGroup, time)) { this.addUserRecommend(mainGroup, recommends, userRecommends); this.sendRecommendMsgHuanxin(mainGroup, userId, time, false); return true; } return false; } }
69f04bcaa73b14ef295dcae9a0da40236d80b84d
879668e82be73ebd4d7800281acbc1a607f64c29
/Domicilio/src/main/java/edu/unimagdalena/Domicilio/controller/MensajerosController.java
fda7d86b85731a1f7cff636a7e68e2e4176aa652
[]
no_license
CristianCrespo/backendSM
92bb8e2cca902c34805ffd95dd45e0c1e8fbc142
c32e2034f499eadc2c012b9c8445f93b0fdb5f2f
refs/heads/main
2023-07-16T20:50:55.654118
2021-08-21T00:13:53
2021-08-21T00:13:53
398,428,555
0
0
null
null
null
null
UTF-8
Java
false
false
2,455
java
package edu.unimagdalena.Domicilio.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; 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.RestController; import edu.unimagdalena.Domicilio.model.Mensajeros; import edu.unimagdalena.Domicilio.services.InterMensajero; @RestController @RequestMapping("/api") @CrossOrigin(origins = {"http://localhost:8080","http://localhost:3000"}) //@CrossOrigin(origins = "*") public class MensajerosController { @Autowired private InterMensajero mService; @PostMapping("/Mensajeros/crear") public Mensajeros crear(@RequestBody Mensajeros pro) { return mService.crearM(pro); } //aqui ustedes esperan localhot:8080/Mensajeros/actualizar/5 //y estan enviando localhost:8080/Mensajeros/actualizar5 //ven la diferenencia?Request URL: http://localhost:8080/api/Mensajeros/actualizar/5 @PutMapping("/Mensajeros/actualizar/{id}") public Mensajeros update(@RequestBody Mensajeros ms, @PathVariable("id") Long id) { Mensajeros oldM = mService.buscarM_Id(id); String nombreM = ms.getNombreM(); oldM.setNombreM(nombreM); String cedulaM = ms.getCedulaM(); oldM.setCedulaM(cedulaM); String celularM = ms.getCelularM(); oldM.setCelularM(celularM); String placa = ms.getPlaca(); oldM.setPlaca(placa); String direccionM = ms.getDireccionM(); oldM.setDireccionM(direccionM); return mService.actualizarM(oldM); } @GetMapping("/Mensajeros/{id}") public void buscarM_Id(@PathVariable("id")Long id) { Mensajeros m = mService.buscarM_Id(id); mService.buscarM_Id(id); } @DeleteMapping("/Mensajeros/borrar/{id}") public void borrar(@PathVariable("id") Long id) { Mensajeros m = mService.buscarM_Id(id); mService.eliminarM(m); } @DeleteMapping("/Mensajeros/borrarTodo") public void borrarTodo() { mService.EliminarTodos(); } @GetMapping("/Mensajeros/listar") public List<Mensajeros> listar(){ return mService.buscar_Ms(); } }
5fce2bd555e48a38d2654cfca4fd581220d38855
5f9bf68f33ebce721ace18f0338f44afab15cc3e
/src/main/java/org/gitlab4j/api/webhook/EventChanges.java
67d0f3f5c9b67a9c298d5c0de99d83e9e733adbf
[ "MIT" ]
permissive
tiagoapimenta/gitlab4j-api
17350e0cb48bcdaeff7679cb15a3f3725562fa10
043521ac4a8c9353a25aa384bc5d8ae4c9d6e98c
refs/heads/master
2020-05-14T09:33:18.808886
2019-04-12T18:24:30
2019-04-12T18:24:30
181,742,183
0
0
MIT
2019-04-16T18:09:50
2019-04-16T18:09:49
null
UTF-8
Java
false
false
2,559
java
package org.gitlab4j.api.webhook; import java.util.Date; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import org.gitlab4j.api.models.Assignee; import org.gitlab4j.api.utils.JacksonJson; @XmlAccessorType(XmlAccessType.FIELD) public class EventChanges { private ChangeContainer<Date> updatedAt; private ChangeContainer<Integer> updatedById; private ChangeContainer<Date> dueDate; private ChangeContainer<Integer> milestoneId; private ChangeContainer<List<EventLabel>> labels; private ChangeContainer<List<Assignee>> assignees; private ChangeContainer<Integer> totalTimeSpent; private ChangeContainer<Boolean> confidential; public ChangeContainer<Date> getUpdatedAt() { return updatedAt; } public void setUpdatedAt(ChangeContainer<Date> updatedAt) { this.updatedAt = updatedAt; } public ChangeContainer<Integer> getUpdatedById() { return updatedById; } public void setUpdatedById(ChangeContainer<Integer> updatedById) { this.updatedById = updatedById; } public ChangeContainer<Date> getDueDate() { return dueDate; } public void setDueDate(ChangeContainer<Date> dueDate) { this.dueDate = dueDate; } public ChangeContainer<Integer> getMilestoneId() { return milestoneId; } public void setMilestoneId(ChangeContainer<Integer> milestoneId) { this.milestoneId = milestoneId; } public ChangeContainer<List<EventLabel>> getLabels() { return labels; } public void setLabels(ChangeContainer<List<EventLabel>> labels) { this.labels = labels; } public ChangeContainer<List<Assignee>> getAssignees() { return assignees; } public void setAssignees(ChangeContainer<List<Assignee>> assignees) { this.assignees = assignees; } public ChangeContainer<Integer> getTotalTimeSpent() { return totalTimeSpent; } public void setTotalTimeSpent(ChangeContainer<Integer> totalTimeSpent) { this.totalTimeSpent = totalTimeSpent; } public ChangeContainer<Boolean> getConfidential() { return confidential; } public void setConfidential(ChangeContainer<Boolean> confidential) { this.confidential = confidential; } @Override public String toString() { return (JacksonJson.toJsonString(this)); } }
2f245f3280f92267ddb429823bebcb889cd2d3b9
3653ada64d12727b7bcc11d78f9516d4ca67fca1
/src/main/java/com/tagtrade/service/bean/Content.java
fcd54f295e97fe1ab1c0264fc6bffb6ca213f65f
[]
no_license
tyswell/untiypickersever
eb5c3b9387414155cde7bd1568259b6f56586d99
3a0c689370c9310f8c5fa19d6949be4fdc58ce79
refs/heads/master
2020-05-29T08:54:01.029073
2017-01-30T07:57:42
2017-01-30T07:57:42
69,435,058
0
0
null
null
null
null
UTF-8
Java
false
false
1,609
java
package com.tagtrade.service.bean; import java.util.Date; public class Content { private Integer contentId; private Integer urlCode; private Integer facebookGropCode; private String title; private String description; private String contentWebId; private String urlContentLink; private Date dateContentCreate; public Integer getContentId() { return contentId; } public void setContentId(Integer contentId) { this.contentId = contentId; } public Integer getUrlCode() { return urlCode; } public void setUrlCode(Integer urlCode) { this.urlCode = urlCode; } public Integer getFacebookGropCode() { return facebookGropCode; } public void setFacebookGropCode(Integer facebookGropCode) { this.facebookGropCode = facebookGropCode; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getContentWebId() { return contentWebId; } public void setContentWebId(String contentWebId) { this.contentWebId = contentWebId; } public String getUrlContentLink() { return urlContentLink; } public void setUrlContentLink(String urlContentLink) { this.urlContentLink = urlContentLink; } public Date getDateContentCreate() { return dateContentCreate; } public void setDateContentCreate(Date dateContentCreate) { this.dateContentCreate = dateContentCreate; } }
1ce712d847fd4165fdfaab8d161071735e8dbfe8
66df378fac707b20df268f6df02e83b6cd599615
/screenchange/src/main/java/com/netease/mint/screenchange/MainActivity.java
10f5f62318e405cfe8e1d4e803ad325184dfdf34
[]
no_license
maoqis/AndroidTest
2f8ecb3aed3e7dc296c2dca93a05119639abfc32
22b845fb646c607f93a48a12c3d497fe5b450565
refs/heads/master
2020-12-02T06:34:56.908339
2017-07-11T10:20:59
2017-07-11T10:20:59
96,859,004
0
0
null
null
null
null
UTF-8
Java
false
false
5,501
java
package com.netease.mint.screenchange; import android.content.Context; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.ImageView; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; import pw.qlm.inputmethodholder.InputMethodHolder; import pw.qlm.inputmethodholder.OnInputMethodListener; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private static final String TAG = "MainActivity"; private ImageView imageView; private TextView tv_change_screen_orientation; private EditText editText; private ScrollView scv_input; private OnInputMethodListener onInputMethodListener; private boolean isInputShow; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } private void initView() { imageView = (ImageView) findViewById(R.id.imageView); tv_change_screen_orientation = (TextView) findViewById(R.id.tv_change_screen_orientation); tv_change_screen_orientation.setOnClickListener(this); editText = (EditText) findViewById(R.id.editText); editText.setOnClickListener(this); scv_input = (ScrollView) findViewById(R.id.scv_input); scv_input.setOnClickListener(this); onInputMethodListener = new OnInputMethodListener() { @Override public void onShow(boolean result) { Toast.makeText(MainActivity.this, "Show input method! " + result, Toast.LENGTH_SHORT).show(); isInputShow = true; } @Override public void onHide(boolean result) { Toast.makeText(MainActivity.this, "Hide input method! " + result, Toast.LENGTH_SHORT).show(); } }; InputMethodHolder.registerListener(onInputMethodListener); } public static void hideSoftKey(View view) { InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0);//强制隐藏键盘 } public static void showSoftKey(View view) { InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(view, InputMethodManager.SHOW_FORCED); //强制显示键盘 } @Override public void onClick(View v) { switch (v.getId()) { case R.id.tv_change_screen_orientation: changeScreen(); break; } } @Override public void onConfigurationChanged(Configuration newConfig) { Log.d(TAG, "onConfigurationChanged() called with: newConfig = [" + newConfig + "]"); super.onConfigurationChanged(newConfig); if (newConfig.orientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) { //切换到竖屏 //修改布局文件 // setContentView(R.layout.activity_main); //findViewById .... //TODO something onChangeLandScape(); Log.d(TAG, " -- onConfigurationChanged 可以在竖屏方向 to do something"); } else { //切换到横屏 //修改布局文件 // setContentView(R.layout.activity_main); //findViewById .... //TODO something onChangePortrait(); Log.d(TAG, " -- onConfigurationChanged 可以在横屏方向 to do something"); } } public void changeScreen() { if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) { //切换竖屏 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } else { //切换横屏 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } } protected void onChangePortrait() { } protected void onChangeLandScape() { } @Override protected void onStart() { Log.d(TAG, "onStart() called"); super.onStart(); } @Override protected void onRestart() { Log.d(TAG, "onRestart() called"); super.onRestart(); } @Override protected void onResume() { Log.d(TAG, "onResume() called"); super.onResume(); } @Override protected void onPause() { Log.d(TAG, "onPause() called"); super.onPause(); } @Override protected void onStop() { Log.d(TAG, "onStop() called"); super.onStop(); } @Override protected void onDestroy() { Log.d(TAG, "onDestroy() called"); InputMethodHolder.unregisterListener(onInputMethodListener); super.onDestroy(); } private void submit() { // validate String editTextString = editText.getText().toString().trim(); if (TextUtils.isEmpty(editTextString)) { Toast.makeText(this, "editTextString不能为空", Toast.LENGTH_SHORT).show(); return; } // TODO validate success, do something } }
3919b2cf5b6a600f235529081cde69be588b492c
47d9e725dd6a16b96b4f9ba79d8c54ebea72fef6
/src/main/java/com/example/odyssey/models/ChatMessage.java
8e5bc9b75d17b068739d1d48660f844fc04f6c84
[]
no_license
sp-2/Odyssey
67e2683a56079a5bb6efe8132f22f1111df555b4
3ca23d3ca2fe9ceaf5f361da2693862a22ebfcb2
refs/heads/main
2021-06-19T14:06:55.591641
2021-02-02T04:51:18
2021-02-02T04:51:18
172,402,765
0
0
null
null
null
null
UTF-8
Java
false
false
660
java
package com.example.odyssey.models; public class ChatMessage { private MessageType type; private String content; private String sender; public enum MessageType { CHAT, JOIN, LEAVE } public MessageType getType() { return type; } public void setType(MessageType type) { this.type = type; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getSender() { return sender; } public void setSender(String sender) { this.sender = sender; } }
2ca9deec6478160c9f1a00bf5b121b60e5150506
a49b092199d0dfb6b44f1893aca266140e4284ba
/src/java/bean/Paiement.java
42ffa5d05132bbd8736282272ab1720ffccf64da
[]
no_license
benchebanianas/commande
ad85be0fb818aa0e244348fe29c002a544730cff
f8c1c135cc0b589defe8fdff8db34145f6df1d8c
refs/heads/master
2016-08-11T21:43:17.828786
2016-03-05T08:44:44
2016-03-05T08:44:44
53,191,959
0
0
null
null
null
null
UTF-8
Java
false
false
3,886
java
/* * 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 bean; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.ManyToOne; import javax.persistence.Temporal; /** * * @author Younes */ @Entity @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS) public class Paiement implements Serializable { protected static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) protected Long id; protected BigDecimal montant; protected int mode; // 1=espece,2=cheque,3=letttre de change protected String description; protected String numeroEffet; protected String photoEffet; @Temporal(javax.persistence.TemporalType.DATE) protected Date dateEcheance; @Temporal(javax.persistence.TemporalType.DATE) protected Date datePaiement; protected boolean encaisser; @Temporal(javax.persistence.TemporalType.DATE) protected Date dateEncaissement; public Date getDateEncaissement() { return dateEncaissement; } public String getPhotoEffet() { return photoEffet; } public void setPhotoEffet(String photoEffet) { this.photoEffet = photoEffet; } public void setDateEncaissement(Date dateEncaissement) { this.dateEncaissement = dateEncaissement; } public boolean getEncaisser() { return encaisser; } public void setEncaisser(boolean encaisser) { this.encaisser = encaisser; } public BigDecimal getMontant() { if (montant == null) { montant = new BigDecimal(0); } return montant; } public void setMontant(BigDecimal montant) { this.montant = montant; } public int getMode() { return mode; } public void setMode(int mode) { this.mode = mode; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Date getDateEcheance() { return dateEcheance; } public void setDateEcheance(Date dateEcheance) { this.dateEcheance = dateEcheance; } public Date getDatePaiement() { return datePaiement; } public void setDatePaiement(Date datePaiement) { this.datePaiement = datePaiement; } public String getNumeroEffet() { return numeroEffet; } public void setNumeroEffet(String numeroEffet) { this.numeroEffet = numeroEffet; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Paiement)) { return false; } Paiement other = (Paiement) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "bean.Paiement[ id=" + id + " ]"; } }
[ "HawkEye@HawkEye" ]
HawkEye@HawkEye
ca02f7e74818ddbb252ed991a13a366a487a60a6
cacec52e5653ab773d35d7f1b4f4f660580d7826
/web-admin/src/main/java/com/alipay/api/domain/McardNotifyMessage.java
fd8d23cef6565275734778b232f27aa74a3993dc
[]
no_license
liuyuhua1984/GameAdminWeb
6d830e7ad1551ac1803abd12e9359c6bfd5965ec
c590fd88d768c8231e2160bf7415996b0027ac98
refs/heads/master
2021-08-28T13:40:50.540862
2017-12-12T10:20:06
2017-12-12T10:20:06
106,268,614
0
2
null
null
null
null
UTF-8
Java
false
false
1,432
java
package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 通知消息 * * @author auto create * @since 1.0, 2017-06-06 17:13:14 */ public class McardNotifyMessage extends AlipayObject { private static final long serialVersionUID = 2786624282196353367L; /** * 用户提醒信息,按如下格式拼装,需要ISV提供change_reason。 积分变动模板:{change_reason},您的积分有变动 余额变动模板:{change_reason},您的余额有变动 等级变更无需提供原因。 */ @ApiField("change_reason") private String changeReason; /** * JSON格式扩展信息,主要是发送消息中的变量 */ @ApiField("ext_info") private String extInfo; /** * 消息类型,每种消息都定义了固定消息模板, POINT_UPDATE:积分变更消息 BALANCE_UPDATE:余额变更消息 LEVEL_UPDATE:等级变更消息 */ @ApiField("message_type") private String messageType; public String getChangeReason() { return this.changeReason; } public void setChangeReason(String changeReason) { this.changeReason = changeReason; } public String getExtInfo() { return this.extInfo; } public void setExtInfo(String extInfo) { this.extInfo = extInfo; } public String getMessageType() { return this.messageType; } public void setMessageType(String messageType) { this.messageType = messageType; } }
461ab020684c0872875f1933dd625ae92933c058
0b1b63e4a59b04391107bba7f7dd17b53dbd1ad9
/app/src/free/java/com/udacity/gradle/builditbigger/MainActivityFragment.java
99f8089387afa140646f4c6acdbef0c7c65c90ad
[]
no_license
bccant/Chandu_TellMeAJoke
a79e1768875404b4c6edfd8cedd8d8acbe1fd0a7
1ada622a65e8352a6efc024792ead1ee77ec84ca
refs/heads/master
2020-07-22T09:36:09.272399
2019-09-08T18:26:04
2019-09-08T18:26:04
207,152,890
0
0
null
null
null
null
UTF-8
Java
false
false
1,220
java
package com.udacity.gradle.builditbigger; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.udacity.gradle.builditbigger.R; /** * A placeholder fragment containing a simple view. */ public class MainActivityFragment extends Fragment { public MainActivityFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_main, container, false); AdView mAdView = (AdView) root.findViewById(R.id.adView); // Create an ad request. Check logcat output for the hashed device ID to // get test ads on a physical device. e.g. // "Use AdRequest.Builder.addTestDevice("ABCDEF012345") to get test ads on this device." AdRequest adRequest = new AdRequest.Builder() .addTestDevice(AdRequest.DEVICE_ID_EMULATOR) .build(); mAdView.loadAd(adRequest); return root; } }
0c30b3fedefa86bf9d0b4a36cfab6ec252fd8783
d4ba636068fc2ffbb45f313012103afb9080c4e3
/Other/N2F/Src/J2ME/N2F AAF/tags/v0.1/src/com/genetibase/askafriend/common/network/stub/SubmitQuestion.java
7b1aab84af3ba11b5b2dffe85b2f43dde70d7744
[]
no_license
SHAREVIEW/GenXSource
785ae187531e757860748a2e49d9b6a175c97402
5e5fe1d5816560ac41a117210fd40a314536f7a4
refs/heads/master
2020-07-20T22:05:24.794801
2019-09-06T05:00:39
2019-09-06T05:00:39
206,716,265
0
0
null
2019-09-06T05:00:12
2019-09-06T05:00:12
null
UTF-8
Java
false
false
2,968
java
// This class was generated by the JAXRPC SI, do not edit. // Contents subject to change without notice. // JSR-172 Reference Implementation wscompile 1.0, using: JAX-RPC Standard Implementation (1.1, build R59) package com.genetibase.askafriend.common.network.stub; public class SubmitQuestion { protected java.lang.String webMemberID; protected java.lang.String webPassword; protected java.lang.String question; protected int numberOfPhotos; protected int responseType; protected com.genetibase.askafriend.common.network.stub.ArrayOfString customResponses; protected int duration; protected boolean isPrivate; public SubmitQuestion() { } public SubmitQuestion(java.lang.String webMemberID, java.lang.String webPassword, java.lang.String question, int numberOfPhotos, int responseType, com.genetibase.askafriend.common.network.stub.ArrayOfString customResponses, int duration, boolean isPrivate) { this.webMemberID = webMemberID; this.webPassword = webPassword; this.question = question; this.numberOfPhotos = numberOfPhotos; this.responseType = responseType; this.customResponses = customResponses; this.duration = duration; this.isPrivate = isPrivate; } public java.lang.String getWebMemberID() { return webMemberID; } public void setWebMemberID(java.lang.String webMemberID) { this.webMemberID = webMemberID; } public java.lang.String getWebPassword() { return webPassword; } public void setWebPassword(java.lang.String webPassword) { this.webPassword = webPassword; } public java.lang.String getQuestion() { return question; } public void setQuestion(java.lang.String question) { this.question = question; } public int getNumberOfPhotos() { return numberOfPhotos; } public void setNumberOfPhotos(int numberOfPhotos) { this.numberOfPhotos = numberOfPhotos; } public int getResponseType() { return responseType; } public void setResponseType(int responseType) { this.responseType = responseType; } public com.genetibase.askafriend.common.network.stub.ArrayOfString getCustomResponses() { return customResponses; } public void setCustomResponses(com.genetibase.askafriend.common.network.stub.ArrayOfString customResponses) { this.customResponses = customResponses; } public int getDuration() { return duration; } public void setDuration(int duration) { this.duration = duration; } public boolean isIsPrivate() { return isPrivate; } public void setIsPrivate(boolean isPrivate) { this.isPrivate = isPrivate; } }
0031461ef0d8d7baa3f436a282460400f6453753
9b8c4fe1a67f610148a65bde665ad0c1ef8751a6
/app/src/main/java/xyz/elfanrodhian/movieand/koneksi/Controller.java
f3c29222d4325f876e517d4d20eb745156280e1e
[]
no_license
ElfanRodh/MovieAnd
123257297a2aa144707484d929f005e0ab326d15
f605cad04fda50b9d6cb89048866b75c2a5fa019
refs/heads/master
2020-04-11T07:36:27.547105
2018-12-17T11:54:40
2018-12-17T11:54:40
161,616,380
0
0
null
null
null
null
UTF-8
Java
false
false
1,716
java
package xyz.elfanrodhian.movieand.koneksi; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.IOException; import okhttp3.HttpUrl; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import static xyz.elfanrodhian.movieand.BuildConfig.THE_MOVIE_DB_API_KEY; /** * Created by elfar on 15/12/18. */ public class Controller { static final String BASE_URL = "http://api.themoviedb.org/3/"; public Retrofit getRetrofit() { Gson gson = new GsonBuilder() .setLenient() .create(); OkHttpClient okHttpClient = new OkHttpClient().newBuilder().addInterceptor(new Interceptor() { @Override public okhttp3.Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); HttpUrl originalHttpUrl = originalRequest.url(); HttpUrl url = originalHttpUrl.newBuilder() .addQueryParameter("api_key", THE_MOVIE_DB_API_KEY) .build(); // Request customization: add request headers Request.Builder requestBuilder = originalRequest.newBuilder().url(url); Request request = requestBuilder.build(); return chain.proceed(request); } }).build(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create(gson)) .build(); return retrofit; } }
c5d5cf7c5bb1fde88e1358ae93d1ba9f9cb1fcb6
6253283b67c01a0d7395e38aeeea65e06f62504b
/decompile/app/Settings/src/main/java/com/android/settings/wifi/HwCustAdvancedWifiSettings.java
e154f5cc11822b95963c56a6444007480b13f98b
[]
no_license
sufadi/decompile-hw
2e0457a0a7ade103908a6a41757923a791248215
4c3efd95f3e997b44dd4ceec506de6164192eca3
refs/heads/master
2023-03-15T15:56:03.968086
2017-11-08T03:29:10
2017-11-08T03:29:10
null
0
0
null
null
null
null
UTF-8
Java
false
false
864
java
package com.android.settings.wifi; import android.content.Context; import android.support.v7.preference.ListPreference; import android.support.v7.preference.PreferenceGroup; public class HwCustAdvancedWifiSettings { protected static final String TAG = "HwCustAdvancedWifiSettings"; public Context mContext; public HwCustAdvancedWifiSettings(Context context) { this.mContext = context; } public boolean getIsShowsleepPolicyPref() { return false; } public void removeSleepPolicyPref(PreferenceGroup mWifiSettingsCategory, ListPreference sleepPolicyPref) { } public void initCustPreference(AdvancedWifiSettings advancedWifiSettings) { } public void resumeCustPreference(AdvancedWifiSettings advancedWifiSettings) { } public void onCustPreferenceChange(String key, Object newValue) { } }
dd6acf33600adc967a1286919009df16df0f370f
fb493965ee4290b62da586221ac6912f8c78ac98
/src/main/java/nl/futureedge/sonar/plugin/issueresolver/helper/SearchHelper.java
5991f25d553273cad449fe81e17db247b4ad1080
[ "Apache-2.0" ]
permissive
willemsrb/sonar-issueresolver-plugin
2a9bd052b12b9edb209591c4fdabea5264e9d0c3
7998296c8fe597f6917f155fa8ecc40c3f856d71
refs/heads/master
2021-01-22T21:54:28.816088
2017-05-08T09:18:37
2017-05-08T09:18:37
85,491,032
13
4
null
null
null
null
UTF-8
Java
false
false
1,323
java
package nl.futureedge.sonar.plugin.issueresolver.helper; import java.util.Arrays; import java.util.Collections; import org.sonarqube.ws.client.issue.SearchWsRequest; /** * Search functionality. */ public final class SearchHelper { private SearchHelper() { } /** * Create search request for resolved issues. * * @param projectKey * project key * @return search request */ public static SearchWsRequest findIssuesForExport(final String projectKey) { final SearchWsRequest searchIssuesRequest = new SearchWsRequest(); searchIssuesRequest.setProjectKeys(Collections.singletonList(projectKey)); searchIssuesRequest.setAdditionalFields(Collections.singletonList("comments")); searchIssuesRequest.setStatuses(Arrays.asList("CONFIRMED", "REOPENED", "RESOLVED")); searchIssuesRequest.setPage(1); searchIssuesRequest.setPageSize(100); return searchIssuesRequest; } public static SearchWsRequest findIssuesForImport(final String projectKey) { final SearchWsRequest searchIssuesRequest = new SearchWsRequest(); searchIssuesRequest.setProjectKeys(Collections.singletonList(projectKey)); searchIssuesRequest.setAdditionalFields(Collections.singletonList("comments")); searchIssuesRequest.setPage(1); searchIssuesRequest.setPageSize(100); return searchIssuesRequest; } }
bf95e676fa1151224eac2384e1f7428177a3981b
647ec12ce50f06e7380fdbfb5b71e9e2d1ac03b4
/com.tencent.mm/classes.jar/com/tencent/mm/plugin/appbrand/page/b/a$a.java
9c171ce909aa7ef786f18bb9d14172b410a4850a
[]
no_license
tsuzcx/qq_apk
0d5e792c3c7351ab781957bac465c55c505caf61
afe46ef5640d0ba6850cdefd3c11badbd725a3f6
refs/heads/main
2022-07-02T10:32:11.651957
2022-02-01T12:41:38
2022-02-01T12:41:38
453,860,108
36
9
null
2022-01-31T09:46:26
2022-01-31T02:43:22
Java
UTF-8
Java
false
false
615
java
package com.tencent.mm.plugin.appbrand.page.b; import kotlin.Metadata; @Metadata(d1={""}, d2={"Lcom/tencent/mm/plugin/appbrand/page/navigation/AppBrandPageConfirmNavigateBackInterceptorWC$Companion;", "", "()V", "REPORT_EVENT_CLICK_LEAVE_BUTTON", "", "REPORT_EVENT_CLICK_STAY_BUTTON", "REPORT_EVENT_SHOW_DIALOG", "TAG", "", "plugin-appbrand-integration_release"}, k=1, mv={1, 5, 1}, xi=48) public final class a$a {} /* Location: L:\local\mybackup\temp\qq_apk\com.tencent.mm\classes2.jar * Qualified Name: com.tencent.mm.plugin.appbrand.page.b.a.a * JD-Core Version: 0.7.0.1 */
ae7fbc74c05efc833111ac7ca7f66f0c1ce67f68
97f34059353000a7358e3e8c9d4d7d4ccea614d7
/Spring-Hibernate-SQLite/src/main/java/be/jeffreyvanmulem/dao/UserDAO.java
0b91bdac96035463b57ef920d2f98a6dc9f9466c
[]
no_license
phamtuanchip/first-class
3e27b3c5daf397ddba3015a52dfe6347967c2dcd
82cb9dc0b1111bace94fa091f743808c48f740e6
refs/heads/master
2020-03-28T05:26:36.121015
2017-02-09T07:38:12
2017-02-09T07:38:12
7,457,892
0
1
null
null
null
null
UTF-8
Java
false
false
230
java
package be.jeffreyvanmulem.dao; /** * Created by IntelliJ IDEA. * User: Jeffrey * Date: 06/01/12 * Time: 10:09 * To change this template use File | Settings | File Templates. */ public class UserDAO extends AbstractDAO{ }
5208c9bb450b3b0439f25609f375d9d30012d12e
2c0d9a20366f32cf7e90b36c8d8c6b365e22ac3d
/gui_demo/src/main/java/com/demo/project/gui/QueryUI.java
45321083ca01cb1d4c91bd32b775d0851d2e295d
[]
no_license
xuchao6969/GUI_demo
d62573cbc80c0c8ac47efd8d2e102dc764225f32
4c45607f70db7b945af60490a22e0acbd20af31f
refs/heads/master
2023-05-06T17:42:57.042134
2021-05-31T05:52:43
2021-05-31T05:52:43
372,394,005
3
0
null
null
null
null
UTF-8
Java
false
false
5,608
java
package com.demo.project.gui; import com.demo.project.service.LoginService; import com.demo.project.service.QueryService; import javax.swing.*; import javax.swing.event.TableColumnModelEvent; import javax.swing.table.DefaultTableModel; import javax.swing.table.JTableHeader; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Random; /** * 多条件查询界面 * @author xc * @date 2021-05-28 */ public class QueryUI extends JFrame { private static final long serialVersionUID = -6788045638380819221L; private JTextField studentNo;//学号 private JRadioButton boy;//性别 男 private JRadioButton girl;//性别 女 //小容器 private JLabel j1; private JLabel j2; private JLabel j3; private JLabel j4; private JLabel j5; private JLabel jboy; private JLabel jgirl; //小按钮 private JButton b2; private JButton b3; private ButtonGroup bg; private DefaultTableModel model; private JTable table; private JScrollPane scrollPane; /** * 查询UI的构造 * */ public QueryUI() { //设置登录窗口标题 this.setTitle(""); //去掉窗口的装饰(边框) // this.setUndecorated(true); //采用指定的窗口装饰风格 this.getRootPane().setWindowDecorationStyle(JRootPane.NONE); //窗体组件初始化 init(); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //设置布局为绝对定位 this.setLayout(null); this.setBounds(0, 0, 900, 300); //设置窗体的图标 Image img0 = new ImageIcon("").getImage(); this.setIconImage(img0); //窗体大小不能改变 this.setResizable(false); //居中显示 this.setLocationRelativeTo(null); //窗体显示 this.setVisible(true); } /** * 窗体组件初始化 * */ public void init() { //创建一个容器,其中的图片大小和setBounds第三、四个参数要基本一致(需要自己计算裁剪) Container container = this.getContentPane(); j1 = new JLabel(); //设置背景色 Image img1 = new ImageIcon("").getImage(); j1.setIcon(new ImageIcon(img1)); j1.setBounds(0, 0, 900, 300); j2 = new JLabel(); Image img2 = new ImageIcon("").getImage(); j2.setIcon(new ImageIcon(img2)); j2.setBounds(40, 95, 50, 53); //学号输入标签 j3 = new JLabel("请输入学生的学号进行查询:"); j3.setBounds(20, 20, 200, 20); //学号输入框 studentNo = new JTextField(); studentNo.setBounds(200, 20, 150, 20); boy = new JRadioButton("男", true);//性别 男 boy.setBounds(20, 50, 20, 20); jboy = new JLabel("男");//性别标签 jboy.setBounds(40, 50, 250, 20); girl = new JRadioButton("女");//性别 女 girl.setBounds(60, 50, 20, 20); jgirl = new JLabel("女");//性别标签 jgirl.setBounds(80, 50, 250, 20); bg = new ButtonGroup(); bg.add(boy); bg.add(girl); //查询按钮 b2 = new JButton("查询"); b2.setBounds(800, 20, 60, 60); b2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); //遍历清除表格当前行 for (int i=0; i<table.getRowCount(); i++){ model.removeRow(i); i--; } if("查询".equals(cmd)) { String studentNoStr = studentNo.getText(); String gender = ""; Enumeration<AbstractButton> btns = bg.getElements(); while(btns.hasMoreElements()){ AbstractButton btn = btns.nextElement(); if (btn.isSelected()){ gender = btn.getText().equals("男")?"1":btn.getText().equals("女")?"2":"3"; break; } } //查询行数 List<String[]> rows = QueryService.getStudentByStudentNoAndGender(studentNoStr, gender); //遍历渲染新的查询行数 for (String[] row: rows){ model.addRow(row); } } } }); String[][] datas = {}; String[] titles = { "姓名", "年龄", "性别", "学号", "用户名", "密码", "E-mail", "电话", "qq", "班级", "生日", "地址", "邮编" }; model = new DefaultTableModel(datas, titles); table = new JTable(model); scrollPane = new JScrollPane(table); scrollPane.setBounds(20,90, 850,150); scrollPane.setBackground(Color.green); table.setVisible(true); getContentPane().add(scrollPane,BorderLayout.CENTER); //所有组件用容器装载 j1.add(j2); j1.add(j3); j1.add(boy); j1.add(girl); j1.add(jboy); j1.add(jgirl); j1.add(b2); container.add(j1); container.add(scrollPane); container.add(studentNo); } public static void main(String[] args) { new QueryUI(); } }
e70c809246907c469fd36c906b795dba8095c8b3
fca57e1ba147d5e61ad43acff79882477fef645c
/app/build/generated/source/aidl/debug/com/system/ui/service/DoubleServiceSystem.java
a549d2a95a304e7195a78a1929b55a4e1a918044
[]
no_license
zhaolei9527/com_system_ui
62d08728ebadb23f7208eea4e3eff79a59708e1b
b42376eb0a65382e5e50dba4588313bbabcd5105
refs/heads/master
2021-01-18T12:53:31.366243
2017-08-16T10:51:43
2017-08-16T10:51:46
100,367,261
0
0
null
null
null
null
UTF-8
Java
false
false
2,723
java
/* * This file is auto-generated. DO NOT MODIFY. * Original file: C:\\Users\\Administrator\\Downloads\\com_system_ui1\\app\\src\\main\\aidl\\com\\system\\ui\\service\\DoubleServiceSystem.aidl */ package com.system.ui.service; /** * 双服务系统 */ public interface DoubleServiceSystem extends android.os.IInterface { /** Local-side IPC implementation stub class. */ public static abstract class Stub extends android.os.Binder implements com.system.ui.service.DoubleServiceSystem { private static final java.lang.String DESCRIPTOR = "com.system.ui.service.DoubleServiceSystem"; /** Construct the stub at attach it to the interface. */ public Stub() { this.attachInterface(this, DESCRIPTOR); } /** * Cast an IBinder object into an com.system.ui.service.DoubleServiceSystem interface, * generating a proxy if needed. */ public static com.system.ui.service.DoubleServiceSystem asInterface(android.os.IBinder obj) { if ((obj==null)) { return null; } android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR); if (((iin!=null)&&(iin instanceof com.system.ui.service.DoubleServiceSystem))) { return ((com.system.ui.service.DoubleServiceSystem)iin); } return new com.system.ui.service.DoubleServiceSystem.Stub.Proxy(obj); } @Override public android.os.IBinder asBinder() { return this; } @Override public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException { switch (code) { case INTERFACE_TRANSACTION: { reply.writeString(DESCRIPTOR); return true; } case TRANSACTION_getServiceName: { data.enforceInterface(DESCRIPTOR); java.lang.String _result = this.getServiceName(); reply.writeNoException(); reply.writeString(_result); return true; } } return super.onTransact(code, data, reply, flags); } private static class Proxy implements com.system.ui.service.DoubleServiceSystem { private android.os.IBinder mRemote; Proxy(android.os.IBinder remote) { mRemote = remote; } @Override public android.os.IBinder asBinder() { return mRemote; } public java.lang.String getInterfaceDescriptor() { return DESCRIPTOR; } @Override public java.lang.String getServiceName() throws android.os.RemoteException { android.os.Parcel _data = android.os.Parcel.obtain(); android.os.Parcel _reply = android.os.Parcel.obtain(); java.lang.String _result; try { _data.writeInterfaceToken(DESCRIPTOR); mRemote.transact(Stub.TRANSACTION_getServiceName, _data, _reply, 0); _reply.readException(); _result = _reply.readString(); } finally { _reply.recycle(); _data.recycle(); } return _result; } } static final int TRANSACTION_getServiceName = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0); } public java.lang.String getServiceName() throws android.os.RemoteException; }
d5cc2af4d155835e0b843cddf278282dda2441d3
dc5845012037b7685785788bd90e54ab4a47c1db
/program_za_avtomatsko_pisanje_poročila/Folders.java
654d18a5f9cd7d35655fc1307ac05034c7356837
[]
no_license
lrakar/lav-03
b56b71aecdef211651d2d9ad06d205dc658cc0f5
3fd360ffd88fd1ce2983bcca81f20b4a2e6b50d7
refs/heads/master
2023-05-26T07:54:19.568518
2021-06-02T17:15:50
2021-06-02T17:15:50
364,054,782
0
0
null
null
null
null
UTF-8
Java
false
false
1,302
java
import java.io.*; import java.util.*; public class Folders { public static int sumAllFolders; //stevilo vseh map public static String[] listFolders; //imena vseh map public static String folderName; //samo ime trenutne mape public static String folderPath; //samo pot do trenutne mape public File porocilo; public File masterdir; public void getPathsMaster(){ porocilo = new File("C:\\java\\Porocilo_RSO\\porocilo.md"); // class File s potjo do poročila masterdir = new File("C:\\java\\vaje_04"); // class File s potjo do master direktorija } public void set(){ PorociloGenerator main = new PorociloGenerator(); listFolders = masterdir.list(); //vsa imena map se shranijo v arraye sumAllFolders = masterdir.list().length; //povemo stevilo vseh map folderName = listFolders[PorociloGenerator.i];//povemo ime trenutne mape(pri i-ju) folderPath = file.getAbsolutePath(masterdir.toString() + "\\" +folderName);// povemo pot trenutne mape } public void writeName(){ set(); //pisemo v porocilo ime mape main.pw.println(" "); //enter main.pw.printf("# %s", folderName.substring(2));//substring brez cifer za urejanje (01,02,03) main.pw.println(" "); //enter } }
9938e46d520138e4ff5fc67bc6d8eedfd269270f
1002431b6ef4e18c25a673c7bf3dea698ce0e92c
/src/main/java/ua/softjourn/eib/config/LoggingConfiguration.java
6e96018b02494486bc8f645c93d5624e6f41cee9
[]
no_license
suhotskiy/EIBHackathon
2f4668f2f3ca6d7bf6f5f0c4424924c675f07907
07ef2e6168ffb4a2255b4d5a1e26bb4b5c809191
refs/heads/master
2020-03-20T06:39:45.048128
2018-06-13T18:34:10
2018-06-13T18:34:10
137,255,908
0
0
null
null
null
null
UTF-8
Java
false
false
6,576
java
package ua.softjourn.eib.config; import java.net.InetSocketAddress; import java.util.Iterator; import io.github.jhipster.config.JHipsterProperties; import ch.qos.logback.classic.AsyncAppender; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.boolex.OnMarkerEvaluator; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.classic.spi.LoggerContextListener; import ch.qos.logback.core.Appender; import ch.qos.logback.core.filter.EvaluatorFilter; import ch.qos.logback.core.spi.ContextAwareBase; import ch.qos.logback.core.spi.FilterReply; import net.logstash.logback.appender.LogstashTcpSocketAppender; import net.logstash.logback.encoder.LogstashEncoder; import net.logstash.logback.stacktrace.ShortenedThrowableConverter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; @Configuration public class LoggingConfiguration { private static final String LOGSTASH_APPENDER_NAME = "LOGSTASH"; private static final String ASYNC_LOGSTASH_APPENDER_NAME = "ASYNC_LOGSTASH"; private final Logger log = LoggerFactory.getLogger(LoggingConfiguration.class); private LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); private final String appName; private final String serverPort; private final JHipsterProperties jHipsterProperties; public LoggingConfiguration(@Value("${spring.application.name}") String appName, @Value("${server.port}") String serverPort, JHipsterProperties jHipsterProperties) { this.appName = appName; this.serverPort = serverPort; this.jHipsterProperties = jHipsterProperties; if (jHipsterProperties.getLogging().getLogstash().isEnabled()) { addLogstashAppender(context); addContextListener(context); } if (jHipsterProperties.getMetrics().getLogs().isEnabled()) { setMetricsMarkerLogbackFilter(context); } } private void addContextListener(LoggerContext context) { LogbackLoggerContextListener loggerContextListener = new LogbackLoggerContextListener(); loggerContextListener.setContext(context); context.addListener(loggerContextListener); } private void addLogstashAppender(LoggerContext context) { log.info("Initializing Logstash logging"); LogstashTcpSocketAppender logstashAppender = new LogstashTcpSocketAppender(); logstashAppender.setName(LOGSTASH_APPENDER_NAME); logstashAppender.setContext(context); String customFields = "{\"app_name\":\"" + appName + "\",\"app_port\":\"" + serverPort + "\"}"; // More documentation is available at: https://github.com/logstash/logstash-logback-encoder LogstashEncoder logstashEncoder=new LogstashEncoder(); // Set the Logstash appender config from JHipster properties logstashEncoder.setCustomFields(customFields); // Set the Logstash appender config from JHipster properties logstashAppender.addDestinations(new InetSocketAddress(jHipsterProperties.getLogging().getLogstash().getHost(),jHipsterProperties.getLogging().getLogstash().getPort())); ShortenedThrowableConverter throwableConverter = new ShortenedThrowableConverter(); throwableConverter.setRootCauseFirst(true); logstashEncoder.setThrowableConverter(throwableConverter); logstashEncoder.setCustomFields(customFields); logstashAppender.setEncoder(logstashEncoder); logstashAppender.start(); // Wrap the appender in an Async appender for performance AsyncAppender asyncLogstashAppender = new AsyncAppender(); asyncLogstashAppender.setContext(context); asyncLogstashAppender.setName(ASYNC_LOGSTASH_APPENDER_NAME); asyncLogstashAppender.setQueueSize(jHipsterProperties.getLogging().getLogstash().getQueueSize()); asyncLogstashAppender.addAppender(logstashAppender); asyncLogstashAppender.start(); context.getLogger("ROOT").addAppender(asyncLogstashAppender); } // Configure a log filter to remove "metrics" logs from all appenders except the "LOGSTASH" appender private void setMetricsMarkerLogbackFilter(LoggerContext context) { log.info("Filtering metrics logs from all appenders except the {} appender", LOGSTASH_APPENDER_NAME); OnMarkerEvaluator onMarkerMetricsEvaluator = new OnMarkerEvaluator(); onMarkerMetricsEvaluator.setContext(context); onMarkerMetricsEvaluator.addMarker("metrics"); onMarkerMetricsEvaluator.start(); EvaluatorFilter<ILoggingEvent> metricsFilter = new EvaluatorFilter<>(); metricsFilter.setContext(context); metricsFilter.setEvaluator(onMarkerMetricsEvaluator); metricsFilter.setOnMatch(FilterReply.DENY); metricsFilter.start(); for (ch.qos.logback.classic.Logger logger : context.getLoggerList()) { for (Iterator<Appender<ILoggingEvent>> it = logger.iteratorForAppenders(); it.hasNext();) { Appender<ILoggingEvent> appender = it.next(); if (!appender.getName().equals(ASYNC_LOGSTASH_APPENDER_NAME)) { log.debug("Filter metrics logs from the {} appender", appender.getName()); appender.setContext(context); appender.addFilter(metricsFilter); appender.start(); } } } } /** * Logback configuration is achieved by configuration file and API. * When configuration file change is detected, the configuration is reset. * This listener ensures that the programmatic configuration is also re-applied after reset. */ class LogbackLoggerContextListener extends ContextAwareBase implements LoggerContextListener { @Override public boolean isResetResistant() { return true; } @Override public void onStart(LoggerContext context) { addLogstashAppender(context); } @Override public void onReset(LoggerContext context) { addLogstashAppender(context); } @Override public void onStop(LoggerContext context) { // Nothing to do. } @Override public void onLevelChange(ch.qos.logback.classic.Logger logger, Level level) { // Nothing to do. } } }
15c366b4950cebb1c95a7956acd6af2e5cd073eb
79c679d71435c6a3c856188500a8c5cd9004b8a5
/consumer-feign/src/main/java/com/example/consumerfeign/controller/HiController.java
cbc06c7c6cd527e3883f9bd853204a2e0b94771f
[]
no_license
zhankun/eureka-demo
5a421b5f2a9fbd8911c201f5b39649630fd14e1d
f32d5c7bbaef013de4fd7c90b9c6234467bffd67
refs/heads/master
2020-03-16T05:44:45.315590
2018-05-08T07:01:52
2018-05-08T07:01:52
132,539,383
1
0
null
null
null
null
UTF-8
Java
false
false
805
java
package com.example.consumerfeign.controller; import com.example.consumerfeign.service.SchedualServiceHi; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** * @author zhankun * @Date 2018/5/8 10:37 */ @RestController @RequestMapping(value = "feign") public class HiController { @Autowired SchedualServiceHi schedualServiceHi; @RequestMapping(value = "sayHi",method = RequestMethod.GET) public String sayHi(@RequestParam(value = "name") String name) { return schedualServiceHi.sayHiFromProvider(name); } }
7f42a60aad2b7d5963d5db2f8a71bf73e04b888b
df0a0c05ab87d1ebdcf7bb115a637aef3a695f89
/src/Chapter3/Question4.java
cba17e347ffa004454fcdb1b04840ec83738a231
[]
no_license
AmrMahfouz/cracking-the-code-interview
6034e4f5c36157220d24256df261599d023ede5c
823e8ce1817fb90416f5bf40d8d586a34ffa1211
refs/heads/master
2020-03-19T04:44:19.559396
2018-06-15T14:09:25
2018-06-15T14:09:25
135,860,712
0
0
null
null
null
null
UTF-8
Java
false
false
1,506
java
package Chapter3; import java.util.Stack; /** * Queue via Stacks: Implement a MyQueue class which implements a queue using two stacks. */ class Question4 { private static class MyQueue { private Stack<Integer> enqueueStack; private Stack<Integer> dequeueStack; public MyQueue() { enqueueStack = new Stack<>(); dequeueStack = new Stack<>(); } public void enqueue(int value) { while (!dequeueStack.isEmpty()) { enqueueStack.push(dequeueStack.pop()); } enqueueStack.push(value); } public int dequeue() { while (!enqueueStack.isEmpty()) { dequeueStack.push(enqueueStack.pop()); } return dequeueStack.pop(); } public int size() { if (!enqueueStack.isEmpty()) { return enqueueStack.size(); } return dequeueStack.size(); } public int peek() { while (!enqueueStack.isEmpty()) { dequeueStack.push(enqueueStack.pop()); } return dequeueStack.peek(); } } public static void main(String[] args) { MyQueue myQueue = new MyQueue(); myQueue.enqueue(1); myQueue.enqueue(2); myQueue.enqueue(3); System.out.println(myQueue.dequeue()); System.out.println(myQueue.peek()); System.out.println(myQueue.size()); } }
f2368b4a229ef5663472835f40425a7c16207606
2c766e6a4394fd8f56a54f79a3d8b188591ce2b5
/src/main/java/com/mart/ffmagic/item/ItemFireflyJar.java
464aca8a502309bd9162f26fb3be3fe242f99bbe
[]
no_license
Martacus/FireflyMagic
e55806ed7a61a48ea9d8d15ab95c20d77137a5c2
b1a8d883093a05d09674556c791ce0597a5c8f5f
refs/heads/master
2020-05-16T11:50:49.118480
2019-05-19T17:50:31
2019-05-19T17:50:31
183,028,592
0
1
null
null
null
null
UTF-8
Java
false
false
1,411
java
package com.mart.ffmagic.item; import com.hrznstudio.titanium.item.ItemBase; import com.mart.ffmagic.FireflyMagic; import com.mart.ffmagic.entity.EntityFirefly; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.ActionResult; import net.minecraft.util.EnumHand; import net.minecraft.world.World; public class ItemFireflyJar extends ItemBase { private final EntityFirefly.FireflyType type; public ItemFireflyJar(String name, EntityFirefly.FireflyType type) { super(name, new Item.Properties().maxStackSize(1).group(FireflyMagic.GROUP)); this.type = type; } @Override public ActionResult<ItemStack> onItemRightClick(World worldIn, EntityPlayer player, EnumHand hand) { if(!worldIn.isRemote && player.isSneaking()){ Entity firefly = FireflyMagic.FIREFLY.spawn(worldIn, ItemStack.EMPTY, player, player.getPosition(), false, false); firefly.getDataManager().set(EntityFirefly.TYPE, type.name()); if(!player.abilities.isCreativeMode){ player.getHeldItem(hand).shrink(1); player.addItemStackToInventory(new ItemStack(ModItems.firefly_jar)); } } return super.onItemRightClick(worldIn, player, hand); } }
c97891f774256ff3dd14cf8cd3bce77274a5f068
85bc9c0e490ea4ce485e61218c9c30cacfcbdead
/app/src/androidTest/java/com/udacity/luisev96/baking/ExampleInstrumentedTest.java
053e06b9e7d0a455b6486c5588acdf1f614f4a36
[]
no_license
LuisVargasVic/Baking
c1b854ffeb3fe17376ce69f0e281da8374b99008
d7c0281067402832a25707e73b2de827015de0bc
refs/heads/master
2020-09-26T04:30:24.929797
2019-11-15T15:29:37
2019-11-15T15:29:37
226,165,249
0
0
null
null
null
null
UTF-8
Java
false
false
770
java
package com.udacity.luisev96.baking; import android.content.Context; import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); assertEquals("com.udacity.luisev96.baking", appContext.getPackageName()); } }
5228781622084d8dd634f32c7fea8e6b2c50b78e
47938a8ae6ced5d40ca558a449346e753ffa39a7
/app/src/main/java/com/tq/fragment/fragment2/VideoFragment.java
7a028d6af0790c38fad0bef2969d999c7cb06eab
[]
no_license
Dreamer206602/TabLayoutSamples
0caa0a22fc6cc2326b84e87a3bc7d5a15ad7b41c
7d0ff7228f10e837d8ee6176550b205252fd28b3
refs/heads/master
2021-01-10T18:06:47.694003
2016-03-30T08:11:44
2016-03-30T08:11:44
54,956,223
1
0
null
null
null
null
UTF-8
Java
false
false
966
java
package com.tq.fragment.fragment2; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.tq.R; import com.tq.fragment.BaseFragment; /** * A simple {@link Fragment} subclass. */ public class VideoFragment extends BaseFragment { private volatile static VideoFragment instance; public static VideoFragment getInstance(){ if(instance==null){ synchronized (VideoFragment.class){ if(instance==null){ instance=new VideoFragment(); } } } return instance; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_video, container, false); } }
9bc13d8d6fb6bc4d802b0e612fb2681b3b3abf02
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/22/22_d9080176bfcba1f1eb83f1cbf9f0c6845afc530c/Camera/22_d9080176bfcba1f1eb83f1cbf9f0c6845afc530c_Camera_s.java
7356e27d05ada062f817c6bb27c428ee529730f6
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
72,878
java
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.camera; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.hardware.Camera.Parameters; import android.hardware.Camera.PictureCallback; import android.hardware.Camera.Size; import android.location.Location; import android.location.LocationManager; import android.location.LocationProvider; import android.media.AudioManager; import android.media.ToneGenerator; import android.net.Uri; import android.os.Bundle; import android.os.Debug; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import android.preference.PreferenceManager; import android.preference.PreferenceScreen; import android.provider.MediaStore; import android.text.format.DateFormat; import android.util.AttributeSet; import android.util.Log; import android.view.GestureDetector; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.OrientationEventListener; import android.view.SurfaceHolder; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.view.MenuItem.OnMenuItemClickListener; import android.widget.ImageView; import android.widget.ZoomButtonsController; import com.android.camera.gallery.IImage; import com.android.camera.gallery.IImageList; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Activity of the Camera which used to see preview and take pictures. */ public class Camera extends Activity implements View.OnClickListener, ShutterButton.OnShutterButtonListener, SurfaceHolder.Callback, Switcher.OnSwitchListener, FlashButton.ModeChangeListener, OnSharedPreferenceChangeListener { private static final String TAG = "camera"; private static final int CROP_MSG = 1; private static final int FIRST_TIME_INIT = 2; private static final int RESTART_PREVIEW = 3; private static final int CLEAR_SCREEN_DELAY = 4; private static final int SCREEN_DELAY = 2 * 60 * 1000; private static final int FOCUS_BEEP_VOLUME = 100; private double mZoomValue; // The current zoom value. private boolean mZooming = false; private double mZoomStep; private double mZoomMax; public static final double ZOOM_STEP_MIN = 0.25; public static final String ZOOM_STOP = "stop"; public static final String ZOOM_IMMEDIATE = "zoom-immediate"; public static final String ZOOM_CONTINUOUS = "zoom-continuous"; public static final double ZOOM_MIN = 1.0; public static final String ZOOM_SPEED = "99"; private Parameters mParameters; // The parameter strings to communicate with camera driver. public static final String PARM_ZOOM_STATE = "zoom-state"; public static final String PARM_ZOOM_STEP = "zoom-step"; public static final String PARM_ZOOM_TO_LEVEL = "zoom-to-level"; public static final String PARM_ZOOM_SPEED = "zoom-speed"; public static final String PARM_ZOOM_MAX = "max-picture-continuous-zoom"; private OrientationEventListener mOrientationListener; private int mLastOrientation = OrientationEventListener.ORIENTATION_UNKNOWN; private SharedPreferences mPreferences; private static final int IDLE = 1; private static final int SNAPSHOT_IN_PROGRESS = 2; private static final boolean SWITCH_CAMERA = true; private static final boolean SWITCH_VIDEO = false; private int mStatus = IDLE; private static final String sTempCropFilename = "crop-temp"; private android.hardware.Camera mCameraDevice; private VideoPreview mSurfaceView; private SurfaceHolder mSurfaceHolder = null; private ShutterButton mShutterButton; private FocusRectangle mFocusRectangle; private FlashButton mFlashButton; private ImageView mGpsIndicator; private ToneGenerator mFocusToneGenerator; private ZoomButtonsController mZoomButtons; private GestureDetector mGestureDetector; private Switcher mSwitcher; private boolean mStartPreviewFail = false; // mPostCaptureAlert, mLastPictureButton, mThumbController // are non-null only if isImageCaptureIntent() is true. private ImageView mLastPictureButton; private ThumbnailController mThumbController; private int mViewFinderWidth, mViewFinderHeight; private ImageCapture mImageCapture = null; private boolean mPreviewing; private boolean mPausing; private boolean mFirstTimeInitialized; private boolean mIsImageCaptureIntent; private boolean mRecordLocation; private static final int FOCUS_NOT_STARTED = 0; private static final int FOCUSING = 1; private static final int FOCUSING_SNAP_ON_FINISH = 2; private static final int FOCUS_SUCCESS = 3; private static final int FOCUS_FAIL = 4; private int mFocusState = FOCUS_NOT_STARTED; private ContentResolver mContentResolver; private boolean mDidRegister = false; private final ArrayList<MenuItem> mGalleryItems = new ArrayList<MenuItem>(); private LocationManager mLocationManager = null; // Use OneShotPreviewCallback to measure the time between // JpegPictureCallback and preview. private final OneShotPreviewCallback mOneShotPreviewCallback = new OneShotPreviewCallback(); private final ShutterCallback mShutterCallback = new ShutterCallback(); private final RawPictureCallback mRawPictureCallback = new RawPictureCallback(); private final AutoFocusCallback mAutoFocusCallback = new AutoFocusCallback(); private final ZoomCallback mZoomCallback = new ZoomCallback(); // Use the ErrorCallback to capture the crash count // on the mediaserver private final ErrorCallback mErrorCallback = new ErrorCallback(); private long mFocusStartTime; private long mFocusCallbackTime; private long mCaptureStartTime; private long mShutterCallbackTime; private long mRawPictureCallbackTime; private long mJpegPictureCallbackTime; private int mPicturesRemaining; // These latency time are for the CameraLatency test. public long mAutoFocusTime; public long mShutterLag; public long mShutterAndRawPictureCallbackTime; public long mJpegPictureCallbackTimeLag; public long mRawPictureAndJpegPictureCallbackTime; // Add the media server tag public static boolean mMediaServerDied = false; // Focus mode. Options are pref_camera_focusmode_entryvalues. private String mFocusMode; private final Handler mHandler = new MainHandler(); private OnScreenSettings mSettings; /** * This Handler is used to post message back onto the main thread of the * application */ private class MainHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case RESTART_PREVIEW: { restartPreview(); break; } case CLEAR_SCREEN_DELAY: { getWindow().clearFlags( WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); break; } case FIRST_TIME_INIT: { initializeFirstTime(); break; } } } } // Snapshots can only be taken after this is called. It should be called // once only. We could have done these things in onCreate() but we want to // make preview screen appear as soon as possible. private void initializeFirstTime() { if (mFirstTimeInitialized) return; // Create orientation listenter. This should be done first because it // takes some time to get first orientation. mOrientationListener = new OrientationEventListener(Camera.this) { @Override public void onOrientationChanged(int orientation) { // We keep the last known orientation. So if the user // first orient the camera then point the camera to // floor/sky, we still have the correct orientation. if (orientation != ORIENTATION_UNKNOWN) { mLastOrientation = orientation; } } }; mOrientationListener.enable(); // Initialize location sevice. mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); readPreference(); if (mRecordLocation) startReceivingLocationUpdates(); checkStorage(); // Initialize last picture button. mContentResolver = getContentResolver(); if (!mIsImageCaptureIntent) { findViewById(R.id.camera_switch).setOnClickListener(this); mLastPictureButton = (ImageView) findViewById(R.id.review_thumbnail); mLastPictureButton.setOnClickListener(this); mThumbController = new ThumbnailController( getResources(), mLastPictureButton, mContentResolver); mThumbController.loadData(ImageManager.getLastImageThumbPath()); // Update last image thumbnail. updateThumbnailButton(); } // Initialize shutter button. mShutterButton = (ShutterButton) findViewById(R.id.shutter_button); mShutterButton.setOnShutterButtonListener(this); mShutterButton.setVisibility(View.VISIBLE); mFocusRectangle = (FocusRectangle) findViewById(R.id.focus_rectangle); updateFocusIndicator(); // Initialize flash button if (mParameters.getSupportedFlashModes() != null) { mFlashButton = (FlashButton) findViewById(R.id.flash_button); String flashMode = mPreferences.getString( CameraSettings.KEY_FLASH_MODE, "auto"); mFlashButton.setMode(flashMode); mFlashButton.setVisibility(View.VISIBLE); mFlashButton.setListener(this); } // Initialize GPS indicator. mGpsIndicator = (ImageView) findViewById(R.id.gps_indicator); mGpsIndicator.setImageResource(R.drawable.ic_camera_sym_gps); ImageManager.ensureOSXCompatibleFolder(); installIntentFilter(); initializeFocusTone(); initializeZoom(); mFirstTimeInitialized = true; } private void updateThumbnailButton() { // Update last image if URI is invalid and the storage is ready. if (!mThumbController.isUriValid() && mPicturesRemaining >= 0) { updateLastImage(); } mThumbController.updateDisplayIfNeeded(); } // If the activity is paused and resumed, this method will be called in // onResume. private void initializeSecondTime() { // Start orientation listener as soon as possible because it takes // some time to get first orientation. mOrientationListener.enable(); // Start location update if needed. readPreference(); if (mRecordLocation) startReceivingLocationUpdates(); installIntentFilter(); initializeFocusTone(); checkStorage(); if (!mIsImageCaptureIntent) { updateThumbnailButton(); } } private void initializeZoom() { // Check if the phone has zoom capability. String zoomState = mParameters.get(PARM_ZOOM_STATE); if (zoomState == null) return; mZoomValue = Double.parseDouble(mParameters.get(PARM_ZOOM_TO_LEVEL)); mZoomMax = Double.parseDouble(mParameters.get(PARM_ZOOM_MAX)); mZoomStep = Double.parseDouble(mParameters.get(PARM_ZOOM_STEP)); mParameters.set(PARM_ZOOM_SPEED, ZOOM_SPEED); mCameraDevice.setParameters(mParameters); mGestureDetector = new GestureDetector(this, new ZoomGestureListener()); mCameraDevice.setZoomCallback(mZoomCallback); mZoomButtons = new ZoomButtonsController(mSurfaceView); mZoomButtons.setAutoDismissed(true); mZoomButtons.setZoomSpeed(100); mZoomButtons.setOnZoomListener( new ZoomButtonsController.OnZoomListener() { public void onVisibilityChanged(boolean visible) { if (visible) { updateZoomButtonsEnabled(); } } public void onZoom(boolean zoomIn) { if (mZooming) return; if (zoomIn) { if (mZoomValue < mZoomMax) { mZoomValue += mZoomStep; zoomToLevel(ZOOM_CONTINUOUS); } } else { if (mZoomValue > ZOOM_MIN) { mZoomValue -= mZoomStep; zoomToLevel(ZOOM_CONTINUOUS); } } updateZoomButtonsEnabled(); } }); } private void zoomToLevel(String type) { if (type == null) { Log.e(TAG, "Zoom type is null."); return; } if (mZoomValue > mZoomMax) mZoomValue = mZoomMax; if (mZoomValue < ZOOM_MIN) mZoomValue = ZOOM_MIN; // If the application sets a unchanged zoom value, the driver will stuck // at the zoom state. This is a work-around to ensure the state is at // "stop". mParameters.set(PARM_ZOOM_STATE, ZOOM_STOP); mCameraDevice.setParameters(mParameters); mParameters.set(PARM_ZOOM_TO_LEVEL, Double.toString(mZoomValue)); mParameters.set(PARM_ZOOM_STATE, type); mCameraDevice.setParameters(mParameters); if (ZOOM_CONTINUOUS.equals(type)) mZooming = true; } private void updateZoomButtonsEnabled() { mZoomButtons.setZoomInEnabled(mZoomValue < mZoomMax); mZoomButtons.setZoomOutEnabled(mZoomValue > ZOOM_MIN); } private class ZoomGestureListener extends GestureDetector.SimpleOnGestureListener { @Override public boolean onDown(MotionEvent e) { // Show zoom buttons only when preview is started and snapshot // is not in progress. mZoomButtons may be null if it is not // initialized. if (!mPausing && isCameraIdle() && mPreviewing && mZoomButtons != null) { mZoomButtons.setVisible(true); } return true; } @Override public boolean onDoubleTap(MotionEvent e) { // Perform zoom only when preview is started and snapshot is not in // progress. if (mPausing || !isCameraIdle() || !mPreviewing || mZoomButtons == null || mZooming) { return false; } if (mZoomValue < mZoomMax) { // Zoom in to the maximum. while (mZoomValue < mZoomMax) { mZoomValue += ZOOM_STEP_MIN; zoomToLevel(ZOOM_IMMEDIATE); // Wait for a while so we are not changing zoom too fast. try { Thread.currentThread().sleep(5); } catch (InterruptedException ex) { } } } else { // Zoom out to the minimum. while (mZoomValue > ZOOM_MIN) { mZoomValue -= ZOOM_STEP_MIN; zoomToLevel(ZOOM_IMMEDIATE); // Wait for a while so we are not changing zoom too fast. try { Thread.currentThread().sleep(5); } catch (InterruptedException ex) { } } } updateZoomButtonsEnabled(); return true; } } @Override public boolean dispatchTouchEvent(MotionEvent m) { if (!super.dispatchTouchEvent(m) && mGestureDetector != null) { return mGestureDetector.onTouchEvent(m); } return true; } LocationListener [] mLocationListeners = new LocationListener[] { new LocationListener(LocationManager.GPS_PROVIDER), new LocationListener(LocationManager.NETWORK_PROVIDER) }; private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_MEDIA_MOUNTED) || action.equals(Intent.ACTION_MEDIA_UNMOUNTED) || action.equals(Intent.ACTION_MEDIA_CHECKING) || action.equals(Intent.ACTION_MEDIA_SCANNER_STARTED)) { checkStorage(); } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) { checkStorage(); if (!mIsImageCaptureIntent) { updateThumbnailButton(); } } } }; private class LocationListener implements android.location.LocationListener { Location mLastLocation; boolean mValid = false; String mProvider; public LocationListener(String provider) { mProvider = provider; mLastLocation = new Location(mProvider); } public void onLocationChanged(Location newLocation) { if (newLocation.getLatitude() == 0.0 && newLocation.getLongitude() == 0.0) { // Hack to filter out 0.0,0.0 locations return; } // If GPS is available before start camera, we won't get status // update so update GPS indicator when we receive data. if (mRecordLocation && LocationManager.GPS_PROVIDER.equals(mProvider)) { mGpsIndicator.setVisibility(View.VISIBLE); } mLastLocation.set(newLocation); mValid = true; } public void onProviderEnabled(String provider) { } public void onProviderDisabled(String provider) { mValid = false; } public void onStatusChanged( String provider, int status, Bundle extras) { switch(status) { case LocationProvider.OUT_OF_SERVICE: case LocationProvider.TEMPORARILY_UNAVAILABLE: { mValid = false; if (mRecordLocation && LocationManager.GPS_PROVIDER.equals(provider)) { mGpsIndicator.setVisibility(View.INVISIBLE); } break; } } } public Location current() { return mValid ? mLastLocation : null; } } private final class OneShotPreviewCallback implements android.hardware.Camera.PreviewCallback { public void onPreviewFrame(byte[] data, android.hardware.Camera camera) { long now = System.currentTimeMillis(); if (mJpegPictureCallbackTime != 0) { mJpegPictureCallbackTimeLag = now - mJpegPictureCallbackTime; Log.v(TAG, "mJpegPictureCallbackTimeLag = " + mJpegPictureCallbackTimeLag + "ms"); mJpegPictureCallbackTime = 0; } else { Log.v(TAG, "Got first frame"); } } } private final class ShutterCallback implements android.hardware.Camera.ShutterCallback { public void onShutter() { mShutterCallbackTime = System.currentTimeMillis(); mShutterLag = mShutterCallbackTime - mCaptureStartTime; Log.v(TAG, "mShutterLag = " + mShutterLag + "ms"); clearFocusState(); } } private final class RawPictureCallback implements PictureCallback { public void onPictureTaken( byte [] rawData, android.hardware.Camera camera) { mRawPictureCallbackTime = System.currentTimeMillis(); mShutterAndRawPictureCallbackTime = mRawPictureCallbackTime - mShutterCallbackTime; Log.v(TAG, "mShutterAndRawPictureCallbackTime = " + mShutterAndRawPictureCallbackTime + "ms"); } } private final class JpegPictureCallback implements PictureCallback { Location mLocation; public JpegPictureCallback(Location loc) { mLocation = loc; } public void onPictureTaken( final byte [] jpegData, final android.hardware.Camera camera) { if (mPausing) { return; } mJpegPictureCallbackTime = System.currentTimeMillis(); mRawPictureAndJpegPictureCallbackTime = mJpegPictureCallbackTime - mRawPictureCallbackTime; Log.v(TAG, "mRawPictureAndJpegPictureCallbackTime = " + mRawPictureAndJpegPictureCallbackTime + "ms"); mImageCapture.storeImage(jpegData, camera, mLocation); if (!mIsImageCaptureIntent) { long delay = 1200 - ( System.currentTimeMillis() - mRawPictureCallbackTime); mHandler.sendEmptyMessageDelayed( RESTART_PREVIEW, Math.max(delay, 0)); } } } private final class AutoFocusCallback implements android.hardware.Camera.AutoFocusCallback { public void onAutoFocus( boolean focused, android.hardware.Camera camera) { mFocusCallbackTime = System.currentTimeMillis(); mAutoFocusTime = mFocusCallbackTime - mFocusStartTime; Log.v(TAG, "mAutoFocusTime = " + mAutoFocusTime + "ms"); if (mFocusState == FOCUSING_SNAP_ON_FINISH) { // Take the picture no matter focus succeeds or fails. No need // to play the AF sound if we're about to play the shutter // sound. if (focused) { mFocusState = FOCUS_SUCCESS; } else { mFocusState = FOCUS_FAIL; } mImageCapture.onSnap(); } else if (mFocusState == FOCUSING) { // User is half-pressing the focus key. Play the focus tone. // Do not take the picture now. ToneGenerator tg = mFocusToneGenerator; if (tg != null) { tg.startTone(ToneGenerator.TONE_PROP_BEEP2); } if (focused) { mFocusState = FOCUS_SUCCESS; } else { mFocusState = FOCUS_FAIL; } } else if (mFocusState == FOCUS_NOT_STARTED) { // User has released the focus key before focus completes. // Do nothing. } updateFocusIndicator(); } } private final class ErrorCallback implements android.hardware.Camera.ErrorCallback { public void onError(int error, android.hardware.Camera camera) { if (error == android.hardware.Camera.CAMERA_ERROR_SERVER_DIED) { mMediaServerDied = true; Log.v(TAG, "media server died"); } } } private final class ZoomCallback implements android.hardware.Camera.ZoomCallback { public void onZoomUpdate(int zoomLevel, android.hardware.Camera camera) { mZoomValue = (double) zoomLevel / 1000; mZooming = false; } } private class ImageCapture { private boolean mCancel = false; private Uri mLastContentUri; Bitmap mCaptureOnlyBitmap; private void storeImage(byte[] data, Location loc) { try { long dateTaken = System.currentTimeMillis(); String name = createName(dateTaken) + ".jpg"; mLastContentUri = ImageManager.addImage( mContentResolver, name, dateTaken, loc, // location for the database goes here 0, // the dsp will use the right orientation so // don't "double set it" ImageManager.CAMERA_IMAGE_BUCKET_NAME, name); if (mLastContentUri == null) { // this means we got an error mCancel = true; } if (!mCancel) { ImageManager.storeImage( mLastContentUri, mContentResolver, 0, null, data); ImageManager.setImageSize(mContentResolver, mLastContentUri, new File(ImageManager.CAMERA_IMAGE_BUCKET_NAME, name).length()); } } catch (Exception ex) { Log.e(TAG, "Exception while compressing image.", ex); } } public void storeImage(final byte[] data, android.hardware.Camera camera, Location loc) { if (!mIsImageCaptureIntent) { storeImage(data, loc); sendBroadcast(new Intent( "com.android.camera.NEW_PICTURE", mLastContentUri)); setLastPictureThumb(data, mImageCapture.getLastCaptureUri()); mThumbController.updateDisplayIfNeeded(); } else { BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 4; mCaptureOnlyBitmap = BitmapFactory.decodeByteArray( data, 0, data.length, options); showPostCaptureAlert(); } } /** * Initiate the capture of an image. */ public void initiate() { if (mCameraDevice == null) { return; } mCancel = false; capture(); } public Uri getLastCaptureUri() { return mLastContentUri; } public Bitmap getLastBitmap() { return mCaptureOnlyBitmap; } private void capture() { mCaptureOnlyBitmap = null; // Set rotation. int orientation = mLastOrientation; if (orientation != OrientationEventListener.ORIENTATION_UNKNOWN) { orientation += 90; } orientation = ImageManager.roundOrientation(orientation); Log.v(TAG, "mLastOrientation = " + mLastOrientation + ", orientation = " + orientation); mParameters.setRotation(orientation); // Clear previous GPS location from the parameters. mParameters.removeGpsData(); // Set GPS location. Location loc = mRecordLocation ? getCurrentLocation() : null; if (loc != null) { double lat = loc.getLatitude(); double lon = loc.getLongitude(); boolean hasLatLon = (lat != 0.0d) || (lon != 0.0d); if (hasLatLon) { mParameters.setGpsLatitude(lat); mParameters.setGpsLongitude(lon); if (loc.hasAltitude()) { mParameters.setGpsAltitude(loc.getAltitude()); } else { // for NETWORK_PROVIDER location provider, we may have // no altitude information, but the driver needs it, so // we fake one. mParameters.setGpsAltitude(0); } if (loc.getTime() != 0) { // Location.getTime() is UTC in milliseconds. // gps-timestamp is UTC in seconds. long utcTimeSeconds = loc.getTime() / 1000; mParameters.setGpsTimestamp(utcTimeSeconds); } } else { loc = null; } } mCameraDevice.setParameters(mParameters); mCameraDevice.takePicture(mShutterCallback, mRawPictureCallback, new JpegPictureCallback(loc)); mPreviewing = false; } public void onSnap() { // If we are already in the middle of taking a snapshot then ignore. if (mPausing || mStatus == SNAPSHOT_IN_PROGRESS) { return; } mCaptureStartTime = System.currentTimeMillis(); // Don't check the filesystem here, we can't afford the latency. // Instead, check the cached value which was calculated when the // preview was restarted. if (mPicturesRemaining < 1) { updateStorageHint(mPicturesRemaining); return; } mStatus = SNAPSHOT_IN_PROGRESS; mImageCapture.initiate(); } private void clearLastBitmap() { if (mCaptureOnlyBitmap != null) { mCaptureOnlyBitmap.recycle(); mCaptureOnlyBitmap = null; } } } private void setLastPictureThumb(byte[] data, Uri uri) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 16; Bitmap lastPictureThumb = BitmapFactory.decodeByteArray(data, 0, data.length, options); mThumbController.setData(uri, lastPictureThumb); } private static String createName(long dateTaken) { return DateFormat.format("yyyy-MM-dd kk.mm.ss", dateTaken).toString(); } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); Window win = getWindow(); win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); setContentView(R.layout.camera); mSurfaceView = (VideoPreview) findViewById(R.id.camera_preview); mViewFinderWidth = mSurfaceView.getLayoutParams().width; mViewFinderHeight = mSurfaceView.getLayoutParams().height; mPreferences = PreferenceManager.getDefaultSharedPreferences(this); mPreferences.registerOnSharedPreferenceChangeListener(this); /* * To reduce startup time, we start the preview in another thread. * We make sure the preview is started at the end of onCreate. */ Thread startPreviewThread = new Thread(new Runnable() { public void run() { try { mStartPreviewFail = false; startPreview(); } catch (CameraHardwareException e) { mStartPreviewFail = true; } } }); startPreviewThread.start(); // don't set mSurfaceHolder here. We have it set ONLY within // surfaceChanged / surfaceDestroyed, other parts of the code // assume that when it is set, the surface is also set. SurfaceHolder holder = mSurfaceView.getHolder(); holder.addCallback(this); holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); mIsImageCaptureIntent = isImageCaptureIntent(); LayoutInflater inflater = getLayoutInflater(); ViewGroup rootView = (ViewGroup) findViewById(R.id.camera); if (mIsImageCaptureIntent) { View controlBar = inflater.inflate( R.layout.attach_camera_control, rootView); controlBar.findViewById(R.id.btn_cancel).setOnClickListener(this); controlBar.findViewById(R.id.btn_retake).setOnClickListener(this); controlBar.findViewById(R.id.btn_done).setOnClickListener(this); } else { inflater.inflate(R.layout.camera_control, rootView); mSwitcher = ((Switcher) findViewById(R.id.camera_switch)); mSwitcher.setOnSwitchListener(this); mSwitcher.addTouchView(findViewById(R.id.camera_switch_set)); } // Make sure preview is started. try { startPreviewThread.join(); if (mStartPreviewFail) showCameraErrorAndFinish(); } catch (InterruptedException ex) { // ignore } // Resize mVideoPreview to the right aspect ratio. resizeForPreviewAspectRatio(mSurfaceView); } @Override public void onStart() { super.onStart(); if (!mIsImageCaptureIntent) { mSwitcher.setSwitch(SWITCH_CAMERA); } } private void checkStorage() { if (ImageManager.isMediaScannerScanning(getContentResolver())) { mPicturesRemaining = MenuHelper.NO_STORAGE_ERROR; } else { calculatePicturesRemaining(); } updateStorageHint(mPicturesRemaining); } public void onClick(View v) { switch (v.getId()) { case R.id.btn_retake: hidePostCaptureAlert(); restartPreview(); break; case R.id.review_thumbnail: if (isCameraIdle()) { viewLastImage(); } break; case R.id.btn_done: doAttach(); break; case R.id.btn_cancel: doCancel(); } } private void doAttach() { if (mPausing) { return; } Bitmap bitmap = mImageCapture.getLastBitmap(); String cropValue = null; Uri saveUri = null; Bundle myExtras = getIntent().getExtras(); if (myExtras != null) { saveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT); cropValue = myExtras.getString("crop"); } if (cropValue == null) { // First handle the no crop case -- just return the value. If the // caller specifies a "save uri" then write the data to it's // stream. Otherwise, pass back a scaled down version of the bitmap // directly in the extras. if (saveUri != null) { OutputStream outputStream = null; try { outputStream = mContentResolver.openOutputStream(saveUri); bitmap.compress(Bitmap.CompressFormat.JPEG, 75, outputStream); outputStream.close(); setResult(RESULT_OK); finish(); } catch (IOException ex) { // ignore exception } finally { if (outputStream != null) { try { outputStream.close(); } catch (IOException ex) { // ignore exception } } } } else { float scale = .5F; Matrix m = new Matrix(); m.setScale(scale, scale); bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true); setResult(RESULT_OK, new Intent("inline-data").putExtra("data", bitmap)); finish(); } } else { // Save the image to a temp file and invoke the cropper Uri tempUri = null; FileOutputStream tempStream = null; try { File path = getFileStreamPath(sTempCropFilename); path.delete(); tempStream = openFileOutput(sTempCropFilename, 0); bitmap.compress(Bitmap.CompressFormat.JPEG, 75, tempStream); tempStream.close(); tempUri = Uri.fromFile(path); } catch (FileNotFoundException ex) { setResult(Activity.RESULT_CANCELED); finish(); return; } catch (IOException ex) { setResult(Activity.RESULT_CANCELED); finish(); return; } finally { if (tempStream != null) { try { tempStream.close(); } catch (IOException ex) { // ignore exception } } } Bundle newExtras = new Bundle(); if (cropValue.equals("circle")) { newExtras.putString("circleCrop", "true"); } if (saveUri != null) { newExtras.putParcelable(MediaStore.EXTRA_OUTPUT, saveUri); } else { newExtras.putBoolean("return-data", true); } Intent cropIntent = new Intent(); cropIntent.setClass(Camera.this, CropImage.class); cropIntent.setData(tempUri); cropIntent.putExtras(newExtras); startActivityForResult(cropIntent, CROP_MSG); } } private void doCancel() { setResult(RESULT_CANCELED, new Intent()); finish(); } public void onShutterButtonFocus(ShutterButton button, boolean pressed) { if (mPausing) { return; } switch (button.getId()) { case R.id.shutter_button: doFocus(pressed); break; } } public void onShutterButtonClick(ShutterButton button) { if (mPausing) { return; } switch (button.getId()) { case R.id.shutter_button: doSnap(); break; } } private OnScreenHint mStorageHint; private void updateStorageHint(int remaining) { String noStorageText = null; if (remaining == MenuHelper.NO_STORAGE_ERROR) { String state = Environment.getExternalStorageState(); if (state == Environment.MEDIA_CHECKING || ImageManager.isMediaScannerScanning(getContentResolver())) { noStorageText = getString(R.string.preparing_sd); } else { noStorageText = getString(R.string.no_storage); } } else if (remaining < 1) { noStorageText = getString(R.string.not_enough_space); } if (noStorageText != null) { if (mStorageHint == null) { mStorageHint = OnScreenHint.makeText(this, noStorageText); } else { mStorageHint.setText(noStorageText); } mStorageHint.show(); } else if (mStorageHint != null) { mStorageHint.cancel(); mStorageHint = null; } } private void installIntentFilter() { // install an intent filter to receive SD card related events. IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED); intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED); intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING); intentFilter.addDataScheme("file"); registerReceiver(mReceiver, intentFilter); mDidRegister = true; } private void initializeFocusTone() { // Initialize focus tone generator. try { mFocusToneGenerator = new ToneGenerator( AudioManager.STREAM_SYSTEM, FOCUS_BEEP_VOLUME); } catch (Throwable ex) { Log.w(TAG, "Exception caught while creating tone generator: ", ex); mFocusToneGenerator = null; } } private void readPreference() { mRecordLocation = mPreferences.getBoolean( "pref_camera_recordlocation_key", false); mFocusMode = mPreferences.getString( CameraSettings.KEY_FOCUS_MODE, getString(R.string.pref_camera_focusmode_default)); } @Override public void onResume() { super.onResume(); mPausing = false; mJpegPictureCallbackTime = 0; mImageCapture = new ImageCapture(); // Start the preview if it is not started. if (!mPreviewing && !mStartPreviewFail) { try { startPreview(); } catch (CameraHardwareException e) { showCameraErrorAndFinish(); return; } } if (mSurfaceHolder != null) { // If first time initialization is not finished, put it in the // message queue. if (!mFirstTimeInitialized) { mHandler.sendEmptyMessage(FIRST_TIME_INIT); } else { initializeSecondTime(); } } mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY); } private static ImageManager.DataLocation dataLocation() { return ImageManager.DataLocation.EXTERNAL; } @Override protected void onPause() { mPausing = true; stopPreview(); // Close the camera now because other activities may need to use it. closeCamera(); if (mSettings != null && mSettings.isVisible()) { mSettings.setVisible(false); } if (mFirstTimeInitialized) { mOrientationListener.disable(); mGpsIndicator.setVisibility(View.INVISIBLE); if (!mIsImageCaptureIntent) { mThumbController.storeData( ImageManager.getLastImageThumbPath()); } hidePostCaptureAlert(); } if (mDidRegister) { unregisterReceiver(mReceiver); mDidRegister = false; } stopReceivingLocationUpdates(); if (mFocusToneGenerator != null) { mFocusToneGenerator.release(); mFocusToneGenerator = null; } if (mStorageHint != null) { mStorageHint.cancel(); mStorageHint = null; } // If we are in an image capture intent and has taken // a picture, we just clear it in onPause. mImageCapture.clearLastBitmap(); mImageCapture = null; // This is necessary to make the ZoomButtonsController unregister // its configuration change receiver. if (mZoomButtons != null) { mZoomButtons.setVisible(false); } // Remove the messages in the event queue. mHandler.removeMessages(CLEAR_SCREEN_DELAY); mHandler.removeMessages(RESTART_PREVIEW); mHandler.removeMessages(FIRST_TIME_INIT); super.onPause(); } @Override protected void onActivityResult( int requestCode, int resultCode, Intent data) { switch (requestCode) { case CROP_MSG: { Intent intent = new Intent(); if (data != null) { Bundle extras = data.getExtras(); if (extras != null) { intent.putExtras(extras); } } setResult(resultCode, intent); finish(); File path = getFileStreamPath(sTempCropFilename); path.delete(); break; } } } private boolean canTakePicture() { return isCameraIdle() && mPreviewing && (mPicturesRemaining > 0); } private void autoFocus() { // Initiate autofocus only when preview is started and snapshot is not // in progress. if (canTakePicture()) { Log.v(TAG, "Start autofocus."); if (mZoomButtons != null) mZoomButtons.setVisible(false); mFocusStartTime = System.currentTimeMillis(); mFocusState = FOCUSING; updateFocusIndicator(); mCameraDevice.autoFocus(mAutoFocusCallback); } } private void clearFocusState() { mFocusState = FOCUS_NOT_STARTED; updateFocusIndicator(); } private void updateFocusIndicator() { if (mFocusRectangle == null) return; if (mFocusState == FOCUSING || mFocusState == FOCUSING_SNAP_ON_FINISH) { mFocusRectangle.showStart(); } else if (mFocusState == FOCUS_SUCCESS) { mFocusRectangle.showSuccess(); } else if (mFocusState == FOCUS_FAIL) { mFocusRectangle.showFail(); } else { mFocusRectangle.clear(); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (!isCameraIdle()) { // ignore backs while we're taking a picture return true; } break; case KeyEvent.KEYCODE_FOCUS: if (mFirstTimeInitialized && event.getRepeatCount() == 0) { doFocus(true); } return true; case KeyEvent.KEYCODE_CAMERA: if (mFirstTimeInitialized && event.getRepeatCount() == 0) { doSnap(); } return true; case KeyEvent.KEYCODE_DPAD_CENTER: // If we get a dpad center event without any focused view, move // the focus to the shutter button and press it. if (mFirstTimeInitialized && event.getRepeatCount() == 0) { // Start auto-focus immediately to reduce shutter lag. After // the shutter button gets the focus, doFocus() will be // called again but it is fine. doFocus(true); if (mShutterButton.isInTouchMode()) { mShutterButton.requestFocusFromTouch(); } else { mShutterButton.requestFocus(); } mShutterButton.setPressed(true); } return true; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_FOCUS: if (mFirstTimeInitialized) { doFocus(false); } return true; } return super.onKeyUp(keyCode, event); } private void doSnap() { // If the user has half-pressed the shutter and focus is completed, we // can take the photo right away. If the focus mode is infinity, we can // also take the photo. if (mFocusMode.equals(getString( R.string.pref_camera_focusmode_value_infinity)) || (mFocusState == FOCUS_SUCCESS || mFocusState == FOCUS_FAIL)) { if (mZoomButtons != null) mZoomButtons.setVisible(false); mImageCapture.onSnap(); } else if (mFocusState == FOCUSING) { // Half pressing the shutter (i.e. the focus button event) will // already have requested AF for us, so just request capture on // focus here. mFocusState = FOCUSING_SNAP_ON_FINISH; } else if (mFocusState == FOCUS_NOT_STARTED) { // Focus key down event is dropped for some reasons. Just ignore. } } private void doFocus(boolean pressed) { // Do the focus if the mode is auto. No focus needed in infinity mode. if (mFocusMode.equals(getString( R.string.pref_camera_focusmode_value_auto))) { if (pressed) { // Focus key down. autoFocus(); } else { // Focus key up. if (mFocusState != FOCUSING_SNAP_ON_FINISH) { // User releases half-pressed focus key. clearFocusState(); } } } } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // Make sure we have a surface in the holder before proceeding. if (holder.getSurface() == null) { Log.d(TAG, "holder.getSurface() == null"); return; } // The mCameraDevice will be null if it fails to connect to the camera // hardware. In this case we will show a dialog and then finish the // activity, so it's OK to ignore it. if (mCameraDevice == null) return; mSurfaceHolder = holder; mViewFinderWidth = w; mViewFinderHeight = h; // Sometimes surfaceChanged is called after onPause. Ignore it. if (mPausing || isFinishing()) return; // Set preview display if the surface is being created. Preview was // already started. if (holder.isCreating()) { setPreviewDisplay(holder); } // If first time initialization is not finished, send a message to do // it later. We want to finish surfaceChanged as soon as possible to let // user see preview first. if (!mFirstTimeInitialized) { mHandler.sendEmptyMessage(FIRST_TIME_INIT); } else { initializeSecondTime(); } } public void surfaceCreated(SurfaceHolder holder) { } public void surfaceDestroyed(SurfaceHolder holder) { stopPreview(); mSurfaceHolder = null; } private void closeCamera() { if (mCameraDevice != null) { CameraHolder.instance().release(); mCameraDevice = null; mPreviewing = false; } } private void ensureCameraDevice() throws CameraHardwareException { if (mCameraDevice == null) { mCameraDevice = CameraHolder.instance().open(); } } private void updateLastImage() { IImageList list = ImageManager.makeImageList( mContentResolver, dataLocation(), ImageManager.INCLUDE_IMAGES, ImageManager.SORT_ASCENDING, ImageManager.CAMERA_IMAGE_BUCKET_ID); int count = list.getCount(); if (count > 0) { IImage image = list.getImageAt(count - 1); Uri uri = image.fullSizeImageUri(); mThumbController.setData(uri, image.miniThumbBitmap()); } else { mThumbController.setData(null, null); } list.close(); } private void showCameraErrorAndFinish() { Resources ress = getResources(); Util.showFatalErrorAndFinish(Camera.this, ress.getString(R.string.camera_error_title), ress.getString(R.string.cannot_connect_camera)); } private void restartPreview() { // make sure the surfaceview fills the whole screen when previewing mSurfaceView.setAspectRatio(VideoPreview.DONT_CARE); try { startPreview(); } catch (CameraHardwareException e) { showCameraErrorAndFinish(); return; } // Calculate this in advance of each shot so we don't add to shutter // latency. It's true that someone else could write to the SD card in // the mean time and fill it, but that could have happened between the // shutter press and saving the JPEG too. calculatePicturesRemaining(); } private void setPreviewDisplay(SurfaceHolder holder) { try { mCameraDevice.setPreviewDisplay(holder); } catch (Throwable ex) { closeCamera(); throw new RuntimeException("setPreviewDisplay failed", ex); } } private void startPreview() throws CameraHardwareException { if (mPausing || isFinishing()) return; ensureCameraDevice(); // If we're previewing already, stop the preview first (this will blank // the screen). if (mPreviewing) stopPreview(); setPreviewDisplay(mSurfaceHolder); setCameraParameter(); final long wallTimeStart = SystemClock.elapsedRealtime(); final long threadTimeStart = Debug.threadCpuTimeNanos(); // Set one shot preview callback for latency measurement. mCameraDevice.setOneShotPreviewCallback(mOneShotPreviewCallback); mCameraDevice.setErrorCallback(mErrorCallback); try { Log.v(TAG, "startPreview"); mCameraDevice.startPreview(); } catch (Throwable ex) { closeCamera(); throw new RuntimeException("startPreview failed", ex); } mPreviewing = true; mStatus = IDLE; long threadTimeEnd = Debug.threadCpuTimeNanos(); long wallTimeEnd = SystemClock.elapsedRealtime(); if ((wallTimeEnd - wallTimeStart) > 3000) { Log.w(TAG, "startPreview() to " + (wallTimeEnd - wallTimeStart) + " ms. Thread time was" + (threadTimeEnd - threadTimeStart) / 1000000 + " ms."); } } private void stopPreview() { if (mCameraDevice != null && mPreviewing) { Log.v(TAG, "stopPreview"); mCameraDevice.stopPreview(); } mPreviewing = false; // If auto focus was in progress, it would have been canceled. clearFocusState(); } private void resizeForPreviewAspectRatio(View v) { ViewGroup.LayoutParams params; params = v.getLayoutParams(); Size size = mParameters.getPreviewSize(); params.width = (int) (params.height * size.width / size.height); Log.v(TAG, "resize to " + params.width + "x" + params.height); v.setLayoutParams(params); } private Size getOptimalPreviewSize(List<Size> sizes) { Size optimalSize = null; if (sizes != null) { optimalSize = sizes.get(0); for (int i = 1; i < sizes.size(); i++) { if (Math.abs(sizes.get(i).height - mViewFinderHeight) < Math.abs(optimalSize.height - mViewFinderHeight)) { optimalSize = sizes.get(i); } } Log.v(TAG, "Optimal preview size is " + optimalSize.width + "x" + optimalSize.height); } return optimalSize; } private void setCameraParameter() { mParameters = mCameraDevice.getParameters(); // Reset preview frame rate to the maximum because it may be lowered by // video camera application. List<Integer> frameRates = mParameters.getSupportedPreviewFrameRates(); if (frameRates != null) { Integer max = Collections.max(frameRates); mParameters.setPreviewFrameRate(max); } // Set a preview size that is closest to the viewfinder height. List<Size> sizes = mParameters.getSupportedPreviewSizes(); Size optimalSize = getOptimalPreviewSize(sizes); if (optimalSize != null) { mParameters.setPreviewSize(optimalSize.width, optimalSize.height); } // Set picture size. String pictureSize = mPreferences.getString( CameraSettings.KEY_PICTURE_SIZE, getString(R.string.pref_camera_picturesize_default)); setCameraPictureSizeIfSupported(pictureSize); // Set JPEG quality. String jpegQuality = mPreferences.getString( CameraSettings.KEY_JPEG_QUALITY, getString(R.string.pref_camera_jpegquality_default)); mParameters.setJpegQuality(Integer.parseInt(jpegQuality)); // Set flash mode. if (mParameters.getSupportedFlashModes() != null) { String flashMode = mPreferences.getString( CameraSettings.KEY_FLASH_MODE, "auto"); mParameters.setFlashMode(flashMode); } // Set white balance parameter. if (mParameters.getSupportedWhiteBalance() != null) { String whiteBalance = mPreferences.getString( CameraSettings.KEY_WHITE_BALANCE, getString(R.string.pref_camera_whitebalance_default)); mParameters.setWhiteBalance(whiteBalance); } // Set color effect parameter. if (mParameters.getSupportedColorEffects() != null) { String colorEffect = mPreferences.getString( CameraSettings.KEY_COLOR_EFFECT, getString(R.string.pref_camera_coloreffect_default)); mParameters.setColorEffect(colorEffect); } mCameraDevice.setParameters(mParameters); } private void gotoGallery() { MenuHelper.gotoCameraImageGallery(this); } private void viewLastImage() { if (mThumbController.isUriValid()) { Uri targetUri = mThumbController.getUri(); targetUri = targetUri.buildUpon().appendQueryParameter( "bucketId", ImageManager.CAMERA_IMAGE_BUCKET_ID).build(); Intent intent = new Intent(this, ReviewImage.class); intent.setData(targetUri); intent.putExtra(MediaStore.EXTRA_FULL_SCREEN, true); intent.putExtra(MediaStore.EXTRA_SHOW_ACTION_ICONS, true); intent.putExtra("com.android.camera.ReviewMode", true); try { startActivity(intent); } catch (ActivityNotFoundException ex) { Log.e(TAG, "review image fail", ex); } } else { Log.e(TAG, "Can't view last image."); } } private void startReceivingLocationUpdates() { if (mLocationManager != null) { try { mLocationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 1000, 0F, mLocationListeners[1]); } catch (java.lang.SecurityException ex) { Log.i(TAG, "fail to request location update, ignore", ex); } catch (IllegalArgumentException ex) { Log.d(TAG, "provider does not exist " + ex.getMessage()); } try { mLocationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 1000, 0F, mLocationListeners[0]); } catch (java.lang.SecurityException ex) { Log.i(TAG, "fail to request location update, ignore", ex); } catch (IllegalArgumentException ex) { Log.d(TAG, "provider does not exist " + ex.getMessage()); } } } private void stopReceivingLocationUpdates() { if (mLocationManager != null) { for (int i = 0; i < mLocationListeners.length; i++) { try { mLocationManager.removeUpdates(mLocationListeners[i]); } catch (Exception ex) { Log.i(TAG, "fail to remove location listners, ignore", ex); } } } } private Location getCurrentLocation() { // go in best to worst order for (int i = 0; i < mLocationListeners.length; i++) { Location l = mLocationListeners[i].current(); if (l != null) return l; } return null; } private boolean isCameraIdle() { return mStatus == IDLE && mFocusState == FOCUS_NOT_STARTED; } private boolean isImageCaptureIntent() { String action = getIntent().getAction(); return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action)); } private void showPostCaptureAlert() { if (mIsImageCaptureIntent) { findViewById(R.id.shutter_button).setVisibility(View.INVISIBLE); int[] pickIds = {R.id.btn_retake, R.id.btn_done}; for (int id : pickIds) { View button = findViewById(id); ((View) button.getParent()).setVisibility(View.VISIBLE); } } } private void hidePostCaptureAlert() { if (mIsImageCaptureIntent) { findViewById(R.id.shutter_button).setVisibility(View.VISIBLE); int[] pickIds = {R.id.btn_retake, R.id.btn_done}; for (int id : pickIds) { View button = findViewById(id); ((View) button.getParent()).setVisibility(View.GONE); } } } private int calculatePicturesRemaining() { mPicturesRemaining = MenuHelper.calculatePicturesRemaining(); return mPicturesRemaining; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); // Only show the menu when camera is idle. for (int i = 0; i < menu.size(); i++) { menu.getItem(i).setVisible(isCameraIdle()); } return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); if (mIsImageCaptureIntent) { // No options menu for attach mode. return false; } else { addBaseMenuItems(menu); } return true; } private void addBaseMenuItems(Menu menu) { MenuItem gallery = menu.add(Menu.NONE, Menu.NONE, MenuHelper.POSITION_GOTO_GALLERY, R.string.camera_gallery_photos_text) .setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { gotoGallery(); return true; } }); gallery.setIcon(android.R.drawable.ic_menu_gallery); mGalleryItems.add(gallery); MenuItem item = menu.add(Menu.NONE, Menu.NONE, MenuHelper.POSITION_CAMERA_SETTING, R.string.settings) .setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { if (mSettings == null) { mSettings = new OnScreenSettings( findViewById(R.id.camera_preview)); CameraSettings helper = new CameraSettings(Camera.this, mParameters); mSettings.setPreferenceScreen(helper .getPreferenceScreen(R.xml.camera_preferences)); } mSettings.setVisible(true); return true; } }); item.setIcon(android.R.drawable.ic_menu_preferences); } public boolean onSwitchChanged(Switcher source, boolean onOff) { if (onOff == SWITCH_VIDEO) { if (!isCameraIdle()) return false; MenuHelper.gotoVideoMode(this); finish(); } return true; } public boolean onFlashModeChanged(String modeString) { if (mPausing) return false; mParameters.setFlashMode(modeString); mCameraDevice.setParameters(mParameters); SharedPreferences.Editor editor = mPreferences.edit(); editor.putString(CameraSettings.KEY_FLASH_MODE, modeString); editor.commit(); return true; } private void setCameraPictureSizeIfSupported(String sizeString) { List<Size> pictureSizes = mParameters.getSupportedPictureSizes(); if (pictureSizes != null) { int index = sizeString.indexOf('x'); int width = Integer.parseInt(sizeString.substring(0, index)); int height = Integer.parseInt(sizeString.substring(index + 1)); for (Size size: pictureSizes) { if (size.width == width && size.height == height) { mParameters.setPictureSize(width, height); break; } } } } public void onSharedPreferenceChanged( SharedPreferences preferences, String key) { // ignore the events after "onPause()" if (mPausing) return; if (CameraSettings.KEY_FLASH_MODE.equals(key)) { mParameters.setFlashMode(preferences.getString(key, "auto")); mCameraDevice.setParameters(mParameters); } else if (CameraSettings.KEY_FOCUS_MODE.equals(key)) { mFocusMode = preferences.getString(key, getString(R.string.pref_camera_focusmode_default)); } else if (CameraSettings.KEY_PICTURE_SIZE.equals(key)) { String pictureSize = preferences.getString(key, getString(R.string.pref_camera_picturesize_default)); setCameraPictureSizeIfSupported(pictureSize); mCameraDevice.setParameters(mParameters); } else if (CameraSettings.KEY_JPEG_QUALITY.equals(key)) { String jpegQuality = preferences.getString(key, getString(R.string.pref_camera_jpegquality_default)); mParameters.setJpegQuality(Integer.parseInt(jpegQuality)); mCameraDevice.setParameters(mParameters); } else if (CameraSettings.KEY_RECORD_LOCATION.equals(key)) { mRecordLocation = preferences.getBoolean(key, false); if (mRecordLocation) { startReceivingLocationUpdates(); } else { stopReceivingLocationUpdates(); } } else if (CameraSettings.KEY_COLOR_EFFECT.equals(key)) { String colorEffect = preferences.getString(key, getString(R.string.pref_camera_coloreffect_default)); mParameters.setColorEffect(colorEffect); mCameraDevice.setParameters(mParameters); } else if (CameraSettings.KEY_WHITE_BALANCE.equals(key)) { String whiteBalance = preferences.getString(key, getString(R.string.pref_camera_whitebalance_default)); mParameters.setWhiteBalance(whiteBalance); mCameraDevice.setParameters(mParameters); } else if (CameraSettings.KEY_SCENE_MODE.equals(key)) { String sceneMode = preferences.getString(key, getString(R.string.pref_camera_scenemode_default)); mParameters.setSceneMode(sceneMode); mCameraDevice.setParameters(mParameters); } } } class FocusRectangle extends View { @SuppressWarnings("unused") private static final String TAG = "FocusRectangle"; public FocusRectangle(Context context, AttributeSet attrs) { super(context, attrs); } private void setDrawable(int resid) { setBackgroundDrawable(getResources().getDrawable(resid)); } public void showStart() { setDrawable(R.drawable.focus_focusing); } public void showSuccess() { setDrawable(R.drawable.focus_focused); } public void showFail() { setDrawable(R.drawable.focus_focus_failed); } public void clear() { setBackgroundDrawable(null); } } // FlashButton changes state every time it is clicked. // The ModeChangeListener notifies that event. class FlashButton extends ImageView implements View.OnClickListener { private static final String TAG = "FlashButton"; private static final int MODE_OFF = 0; private static final int MODE_ON = 1; private static final int MODE_AUTO = 2; private static final String[] MODE_STRINGS = new String[] { "off", "on", "auto" }; private static final int[] FLASH_IMAGES = new int[] { R.drawable.flash_off, R.drawable.flash_on, R.drawable.flash_auto }; private int mCurrentMode; private ModeChangeListener mListener; public interface ModeChangeListener { // Returns true if the listener agrees to change mode. public boolean onFlashModeChanged(String modeString); } public FlashButton(Context context, AttributeSet attrs) { super(context, attrs); updateMode(MODE_AUTO); setOnClickListener(this); } public void setMode(String modeString) { for (int i = 0; i < MODE_STRINGS.length; i++) { if (MODE_STRINGS[i].equals(modeString)) { updateModeIfNecessary(i); return; } } Log.w(TAG, "Unknown mode: " + modeString); } public void setListener(ModeChangeListener listener) { mListener = listener; } public void onClick(View v) { int nextMode = (mCurrentMode + 1) % FLASH_IMAGES.length; updateMode(nextMode); } private void updateModeIfNecessary(int mode) { if (mode == mCurrentMode) return; if (mode < 0 || mode >= FLASH_IMAGES.length) { return; } updateMode(mode); } private void updateMode(int mode) { if (mListener == null) return; if (!mListener.onFlashModeChanged(MODE_STRINGS[mode])) return; mCurrentMode = mode; setImageResource(FLASH_IMAGES[mode]); } }
9a39e4fd915fe1121676fe7413251150da3be857
8a4b80f34c02279d615e06c9d7e4a827d2c7d491
/src/main/java/SeleniumSessions/GoogleSearch.java
151074e6a8f6fab5233f6f86bb19de13c2958d89
[]
no_license
sigoel10/Jan2021SeleniumSessions
abb0372deb60ef3fa76b50562bba0a0f4f682b49
9d5f9d1a2a6b0f9e7ff453b35eeb0a726bb6d073
refs/heads/master
2023-04-09T10:44:50.627967
2021-04-21T13:52:38
2021-04-21T13:52:38
360,187,773
0
0
null
null
null
null
UTF-8
Java
false
false
1,023
java
package SeleniumSessions; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import io.github.bonigarcia.wdm.WebDriverManager; public class GoogleSearch { static WebDriver driver; public static void main(String[] args) throws InterruptedException { //pass the keyword and it will gave multiple suggestions //select a particular suggestion and google searchn should display that page WebDriverManager.chromedriver().setup(); driver = new ChromeDriver(); driver.get("https://www.google.com"); driver.findElement(By.name("q")).sendKeys("testing"); Thread.sleep(2000); List<WebElement> suggList = driver.findElements(By.xpath("//ul[@role='listbox']//div[@class='sbl1']//span")); for (WebElement e: suggList) { String text = e.getText(); System.out.println(text); if(text.equals("testing life cycle")) { e.click(); break; } } } }
77f8c7807a612d84b06c3ecccce0bb0fe013c569
5db11b0c9098351480c57de617336ab7dff483e1
/tools/PacketSamuraiAE/src/packetsamurai/parser/datatree/DataForBlock.java
95612540bdd1e1e2bf5feefd9e120a825e8e1bc9
[]
no_license
VictorManKBO/aion_gserver_4_0
d7c6383a005f1a716fcee5e4bd0c33df30a0e0c5
ed24bf40c9fcff34cd0c64243b10ab44e60bb258
refs/heads/master
2022-11-15T19:52:47.654179
2020-07-13T10:16:04
2020-07-13T10:16:04
277,644,635
0
0
null
null
null
null
UTF-8
Java
false
false
757
java
package packetsamurai.parser.datatree; import packetsamurai.parser.formattree.PartContainer; /** * * @author Gilles Duboscq * */ public class DataForBlock extends DataTreeNodeContainer { private int _iteration; private int _size; // avoids construction of root ForBlock @SuppressWarnings("unused") private DataForBlock() { super(); // TODO Auto-generated constructor stub } public DataForBlock(DataTreeNodeContainer container, PartContainer part, int iteration, int size) { super(container, part); _iteration = iteration; _size = size; } @Override public String treeString() { return "Iteration "+(_iteration+1)+"/"+_size; } }
b164285cbf2b1346a0b106475665401eb293a995
98d313cf373073d65f14b4870032e16e7d5466f0
/gradle-open-labs/example/src/main/java/se/molybden/Class23813.java
09b4df7a0e4f7cefc8cbef991fc68d8b7d421876
[]
no_license
Molybden/gradle-in-practice
30ac1477cc248a90c50949791028bc1cb7104b28
d7dcdecbb6d13d5b8f0ff4488740b64c3bbed5f3
refs/heads/master
2021-06-26T16:45:54.018388
2016-03-06T20:19:43
2016-03-06T20:19:43
24,554,562
0
0
null
null
null
null
UTF-8
Java
false
false
110
java
public class Class23813{ public void callMe(){ System.out.println("called"); } }
8641d1c7a8aa88f91ecfa74ff66b8df4e687bf16
334bca3a94a61eec18ea60bb03c552928337c7b7
/ForecastFragment.java
44de59915589428f4554f443de560454ea762a34
[]
no_license
atul-17/Sunshine-Version-2
77d032d3a0f2d25b31f157d23fbe8d56901fde0b
4244cc65e9fa7ba2ebb9cb8631f9ac31725e5806
refs/heads/master
2021-01-22T16:44:45.473798
2016-09-21T12:55:57
2016-09-21T12:55:57
68,816,752
0
0
null
null
null
null
UTF-8
Java
false
false
5,632
java
package com.example.android.sunshine.app; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.format.Time; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import Util.Constants; import model.WeatherData; import Util.WeatherService; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; /** * Created by atul on 19/9/16. */ public class ForecastFragment extends Fragment { public ListView foreCastList; public List<String> weatherData= new ArrayList<String>(); public ForecastFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //to tell that fragment has options menu to be infalted setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); weatherData.add("Today - Sunny - 88/63 "); weatherData.add("Tommorrow - Foggy - 70/26"); weatherData.add("weds - cloudy - 72/63"); weatherData.add("Thurs - Rainy - 64/51"); weatherData.add("Fri - Foggy - 70/46"); weatherData.add("Sat - Sunny - 76/68"); foreCastList = (ListView)rootView.findViewById(R.id.listview_forecast); ArrayAdapter<String> weatherAdapter = new ArrayAdapter<String>(getActivity(),R.layout.list_item_forecast,R.id.list_item_forecast_textview,weatherData); foreCastList.setAdapter(weatherAdapter); return rootView; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.action_refresh: WeatherTask("bangalore"); Log.d("atul","onOptinons item selected"); return true; } return super.onOptionsItemSelected(item); } public void WeatherTask(String city){ Retrofit retrofit = new Retrofit.Builder() // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .baseUrl(Constants.BASEURL) .build(); WeatherService weatherService = retrofit.create(WeatherService.class); Call<WeatherData> call = weatherService.getWheatherReport(city,"metrics",7,Constants.APIKEY); call.enqueue(new Callback<WeatherData>() { @Override public void onResponse(Call<WeatherData> call, Response<WeatherData> response) { Time dayTime = new Time(); dayTime.setToNow(); String[] weatherString = new String[7]; int julianStartDay = Time.getJulianDay(System.currentTimeMillis(),dayTime.gmtoff); dayTime = new Time(); for (int i = 0;i<response.body().getList().size();i++){ for (int j =0;j<response.body().getList().get(i).getWeather().size();j++){ // Log.d("atul",response.body().getList().get(i).getWeather().get(j).getDescription()); String day; String highLow; String description; long dateTime; dateTime = dayTime.setJulianDay(julianStartDay + i); day = getReadableString(dateTime); double high = response.body().getList().get(i).getTemp().getMax(); double low = response.body().getList().get(i).getTemp().getMin(); highLow = formatHighLows(high,low); description = response.body().getList().get(i).getWeather().get(j).getDescription(); weatherString[i]=day +" - "+description+ " - "+highLow; } } weatherData.clear(); ArrayAdapter<String> weatherAdapter = new ArrayAdapter<String>(getActivity(),R.layout.list_item_forecast,R.id.list_item_forecast_textview,weatherString); foreCastList.setAdapter(weatherAdapter); } @Override public void onFailure(Call<WeatherData> call, Throwable t) { Log.d("atul","failure"+t); } }); } private String getReadableString(long time){ //the api return a unix timestamp which must //converted to date SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE MMM dd"); return simpleDateFormat.format(time); } /* prepare the weather of high/lows for presentation */ private String formatHighLows(double high,double low){ long roundedHigh = Math.round(high); long roundedLOw = Math.round(low); String highLowStr = roundedHigh +"/ "+roundedLOw; return highLowStr; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { getActivity().getMenuInflater().inflate(R.menu.forecastfragment,menu); } }
96f919f4ad64f1b7d9a6ac90282dd9f1d06a03f1
acf41d6650d43440cc580b67da361a231a64e191
/app/src/main/java/artisanng/hycode/artisanng/FragmentChatRecyclerAdapter.java
35eedde860ad4f6d0b99a7b28b81087455b50a11
[]
no_license
charles0007/ArtisanNG
28bbb5073e905c9bdd64ce158074c1e34b3941f0
7ce7dd53a57741d8911a8dd4582c3f1a4352e88a
refs/heads/master
2020-08-10T10:42:09.251615
2019-10-14T11:20:47
2019-10-14T11:20:47
214,327,038
0
0
null
null
null
null
UTF-8
Java
false
false
2,490
java
package artisanng.hycode.artisanng; import android.app.Activity; import android.graphics.Typeface; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.HashMap; import de.hdodenhof.circleimageview.CircleImageView; public class FragmentChatRecyclerAdapter extends RecyclerView.Adapter<FragmentChatRecyclerAdapter.MyViewHolder> { // private ArrayList<DataModel> dataSet; private Activity activity; private ArrayList<HashMap<String, String>> data; private static LayoutInflater inflater = null; public FragmentChatRecyclerAdapter(Activity a, ArrayList<HashMap<String, String>> d) { activity = a; data = d; } public static class MyViewHolder extends RecyclerView.ViewHolder { TextView right; public MyViewHolder(View itemView) { super(itemView); View vi=itemView; right = (TextView) vi.findViewById(R.id.rightTextPending); // title vi.findViewById(R.id.rightTextSent).setVisibility(View.GONE); vi.findViewById(R.id.leftText).setVisibility(View.INVISIBLE); } } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.msglist, parent, false); // // view.setOnClickListener(ArtisanList.myOnClickListener); // MyViewHolder myViewHolder = new MyViewHolder(view); return myViewHolder; } @Override public void onBindViewHolder(final MyViewHolder holder, final int listPosition) { TextView right=holder.right; Typeface typeface = Typeface.createFromAsset(activity.getAssets(), "fonts/ERASMD.TTF"); right.setTypeface(typeface); HashMap<String, String> listDriver = new HashMap<String, String>(); listDriver = data.get(listPosition); final String right_chat = listDriver.get("msgText"); final String UniqueId = listDriver.get("UniqueId"); right.setText(right_chat); } @Override public int getItemCount() { return data.size(); } }
49343c7f1fd8bc2678b4bddd6a71c269a77e683c
065c1f648e8dd061a20147ff9c0dbb6b5bc8b9be
/ant_cluster/17188/src_1.java
26c0baa4f1f9af877aef4ba03cbcfed7402fa284
[]
no_license
martinezmatias/GenPat-data-C3
63cfe27efee2946831139747e6c20cf952f1d6f6
b360265a6aa3bb21bd1d64f1fc43c3b37d0da2a4
refs/heads/master
2022-04-25T17:59:03.905613
2020-04-15T14:41:34
2020-04-15T14:41:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
22,694
java
/* * Copyright 2000-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.tools.ant; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.io.IOException; import org.apache.tools.ant.taskdefs.PreSetDef; /** * Wrapper class that holds all the information necessary to create a task * or data type that did not exist when Ant started, or one which * has had its definition updated to use a different implementation class. * */ public class UnknownElement extends Task { /** * Holds the name of the task/type or nested child element of a * task/type that hasn't been defined at parser time or has * been redefined since original creation. */ private String elementName; /** * Holds the namespace of the element. */ private String namespace; /** * Holds the namespace qname of the element. */ private String qname; /** * The real object after it has been loaded. */ private Object realThing; /** * List of child elements (UnknownElements). */ private List/*<UnknownElement>*/ children = null; /** Specifies if a predefined definition has been done */ private boolean presetDefed = false; /** * Creates an UnknownElement for the given element name. * * @param elementName The name of the unknown element. * Must not be <code>null</code>. */ public UnknownElement (String elementName) { this.elementName = elementName; } /** * @return the list of nested UnknownElements for this UnknownElement. */ public List getChildren() { return children; } /** * Returns the name of the XML element which generated this unknown * element. * * @return the name of the XML element which generated this unknown * element. */ public String getTag() { return elementName; } /** Return the namespace of the XML element associated with this component. * * @return Namespace URI used in the xmlns declaration. */ public String getNamespace() { return namespace; } /** * Set the namespace of the XML element associated with this component. * This method is typically called by the XML processor. * If the namespace is "ant:current", the component helper * is used to get the current antlib uri. * * @param namespace URI used in the xmlns declaration. */ public void setNamespace(String namespace) { if (namespace.equals(ProjectHelper.ANT_CURRENT_URI)) { ComponentHelper helper = ComponentHelper.getComponentHelper( getProject()); namespace = helper.getCurrentAntlibUri(); } this.namespace = namespace; } /** Return the qname of the XML element associated with this component. * * @return namespace Qname used in the element declaration. */ public String getQName() { return qname; } /** Set the namespace qname of the XML element. * This method is typically called by the XML processor. * * @param qname the qualified name of the element */ public void setQName(String qname) { this.qname = qname; } /** * Get the RuntimeConfigurable instance for this UnknownElement, containing * the configuration information. * * @return the configuration info. */ public RuntimeConfigurable getWrapper() { return super.getWrapper(); } /** * Creates the real object instance and child elements, then configures * the attributes and text of the real object. This unknown element * is then replaced with the real object in the containing target's list * of children. * * @exception BuildException if the configuration fails */ public void maybeConfigure() throws BuildException { //ProjectComponentHelper helper=ProjectComponentHelper.getProjectComponentHelper(); //realThing = helper.createProjectComponent( this, getProject(), null, // this.getTag()); configure(makeObject(this, getWrapper())); } /** * Configure the given object from this UnknownElement * * @param realObject the real object this UnknownElement is representing. * */ public void configure(Object realObject) { realThing = realObject; getWrapper().setProxy(realThing); Task task = null; if (realThing instanceof Task) { task = (Task) realThing; task.setRuntimeConfigurableWrapper(getWrapper()); // For Script to work. Ugly // The reference is replaced by RuntimeConfigurable this.getOwningTarget().replaceChild(this, (Task) realThing); } handleChildren(realThing, getWrapper()); // configure attributes of the object and it's children. If it is // a task container, defer the configuration till the task container // attempts to use the task if (task != null) { task.maybeConfigure(); } else { getWrapper().maybeConfigure(getProject()); } } /** * Handles output sent to System.out by this task or its real task. * * @param output The output to log. Should not be <code>null</code>. */ protected void handleOutput(String output) { if (realThing instanceof Task) { ((Task) realThing).handleOutput(output); } else { super.handleOutput(output); } } /** * @see Task#handleInput(byte[], int, int) * * @since Ant 1.6 */ protected int handleInput(byte[] buffer, int offset, int length) throws IOException { if (realThing instanceof Task) { return ((Task) realThing).handleInput(buffer, offset, length); } else { return super.handleInput(buffer, offset, length); } } /** * Handles output sent to System.out by this task or its real task. * * @param output The output to log. Should not be <code>null</code>. */ protected void handleFlush(String output) { if (realThing instanceof Task) { ((Task) realThing).handleFlush(output); } else { super.handleFlush(output); } } /** * Handles error output sent to System.err by this task or its real task. * * @param output The error output to log. Should not be <code>null</code>. */ protected void handleErrorOutput(String output) { if (realThing instanceof Task) { ((Task) realThing).handleErrorOutput(output); } else { super.handleErrorOutput(output); } } /** * Handles error output sent to System.err by this task or its real task. * * @param output The error output to log. Should not be <code>null</code>. */ protected void handleErrorFlush(String output) { if (realThing instanceof Task) { ((Task) realThing).handleErrorOutput(output); } else { super.handleErrorOutput(output); } } /** * Executes the real object if it's a task. If it's not a task * (e.g. a data type) then this method does nothing. */ public void execute() { if (realThing == null) { // plain impossible to get here, maybeConfigure should // have thrown an exception. throw new BuildException("Could not create task of type: " + elementName, getLocation()); } if (realThing instanceof Task) { ((Task) realThing).execute(); } // the task will not be reused ( a new init() will be called ) // Let GC do its job realThing = null; // FIXME: the following should be done as well, but is // commented out for the moment as the unit tests fail // if it is done //getWrapper().setProxy(null); } /** * Adds a child element to this element. * * @param child The child element to add. Must not be <code>null</code>. */ public void addChild(UnknownElement child) { if (children == null) { children = new ArrayList(); } children.add(child); } /** * Creates child elements, creates children of the children * (recursively), and sets attributes of the child elements. * * @param parent The configured object for the parent. * Must not be <code>null</code>. * * @param parentWrapper The wrapper containing child wrappers * to be configured. Must not be <code>null</code> * if there are any children. * * @exception BuildException if the children cannot be configured. */ protected void handleChildren( Object parent, RuntimeConfigurable parentWrapper) throws BuildException { if (parent instanceof TypeAdapter) { parent = ((TypeAdapter) parent).getProxy(); } String parentUri = getNamespace(); Class parentClass = parent.getClass(); IntrospectionHelper ih = IntrospectionHelper.getHelper(parentClass); if (children != null) { Iterator it = children.iterator(); for (int i = 0; it.hasNext(); i++) { RuntimeConfigurable childWrapper = parentWrapper.getChild(i); UnknownElement child = (UnknownElement) it.next(); try { if (!handleChild( parentUri, ih, parent, child, childWrapper)) { if (!(parent instanceof TaskContainer)) { ih.throwNotSupported(getProject(), parent, child.getTag()); } else { // a task container - anything could happen - just add the // child to the container TaskContainer container = (TaskContainer) parent; container.addTask(child); } } } catch (UnsupportedElementException ex) { ex.setMessage( parentWrapper.getElementTag() + " doesn't support the nested \"" + ex.getElement() + "\" element."); throw ex; } } } } /** * @return the component name - uses ProjectHelper#genComponentName() */ protected String getComponentName() { return ProjectHelper.genComponentName(getNamespace(), getTag()); } /** * This is used then the realobject of the UE is a PreSetDefinition. * This is also used when a presetdef is used on a presetdef * The attributes, elements and text are applied to this * UE. * * @param u an UnknownElement containing the attributes, elements and text */ public void applyPreSet(UnknownElement u) { if (presetDefed) { return; } // Do the runtime getWrapper().applyPreSet(u.getWrapper()); if (u.children != null) { List newChildren = new ArrayList(); newChildren.addAll(u.children); if (children != null) { newChildren.addAll(children); } children = newChildren; } presetDefed = true; } /** * Creates a named task or data type. If the real object is a task, * it is configured up to the init() stage. * * @param ue The unknown element to create the real object for. * Must not be <code>null</code>. * @param w Ignored in this implementation. * * @return the task or data type represented by the given unknown element. */ protected Object makeObject(UnknownElement ue, RuntimeConfigurable w) { ComponentHelper helper = ComponentHelper.getComponentHelper( getProject()); String name = ue.getComponentName(); Object o = helper.createComponent(ue, ue.getNamespace(), name); if (o == null) { throw getNotFoundException("task or type", name); } if (o instanceof PreSetDef.PreSetDefinition) { PreSetDef.PreSetDefinition def = (PreSetDef.PreSetDefinition) o; o = def.createObject(ue.getProject()); ue.applyPreSet(def.getPreSets()); if (o instanceof Task) { Task task = (Task) o; task.setTaskType(ue.getTaskType()); task.setTaskName(ue.getTaskName()); } } if (o instanceof Task) { Task task = (Task) o; task.setOwningTarget(getOwningTarget()); task.init(); } return o; } /** * Creates a named task and configures it up to the init() stage. * * @param ue The UnknownElement to create the real task for. * Must not be <code>null</code>. * @param w Ignored. * * @return the task specified by the given unknown element, or * <code>null</code> if the task name is not recognised. */ protected Task makeTask(UnknownElement ue, RuntimeConfigurable w) { Task task = getProject().createTask(ue.getTag()); if (task != null) { task.setLocation(getLocation()); // UnknownElement always has an associated target task.setOwningTarget(getOwningTarget()); task.init(); } return task; } /** * Returns a very verbose exception for when a task/data type cannot * be found. * * @param what The kind of thing being created. For example, when * a task name could not be found, this would be * <code>"task"</code>. Should not be <code>null</code>. * @param elementName The name of the element which could not be found. * Should not be <code>null</code>. * * @return a detailed description of what might have caused the problem. */ protected BuildException getNotFoundException(String what, String elementName) { String lSep = System.getProperty("line.separator"); String msg = "Could not create " + what + " of type: " + elementName + "." + lSep + lSep + "Ant could not find the task or a class this " + "task relies upon." + lSep + lSep + "This is common and has a number of causes; the usual " + lSep + "solutions are to read the manual pages then download and" + lSep + "install needed JAR files, or fix the build file: " + lSep + " - You have misspelt '" + elementName + "'." + lSep + " Fix: check your spelling." + lSep + " - The task needs an external JAR file to execute" + lSep + " and this is not found at the right place in the classpath." + lSep + " Fix: check the documentation for dependencies." + lSep + " Fix: declare the task." + lSep + " - The task is an Ant optional task and the JAR file and/or libraries" + lSep + " implementing the functionality were not found at the time you" + lSep + " yourself built your installation of Ant from the Ant sources." + lSep + " Fix: Look in the ANT_HOME/lib for the 'ant-' JAR corresponding to the" + lSep + " task and make sure it contains more than merely a META-INF/MANIFEST.MF." + lSep + " If all it contains is the manifest, then rebuild Ant with the needed" + lSep + " libraries present in ${ant.home}/lib/optional/ , or alternatively," + lSep + " download a pre-built release version from apache.org" + lSep + " - The build file was written for a later version of Ant" + lSep + " Fix: upgrade to at least the latest release version of Ant" + lSep + " - The task is not an Ant core or optional task " + lSep + " and needs to be declared using <taskdef>." + lSep + " - You are attempting to use a task defined using " + lSep + " <presetdef> or <macrodef> but have spelt wrong or not " + lSep + " defined it at the point of use" + lSep + lSep + "Remember that for JAR files to be visible to Ant tasks implemented" + lSep + "in ANT_HOME/lib, the files must be in the same directory or on the" + lSep + "classpath" + lSep + lSep + "Please neither file bug reports on this problem, nor email the" + lSep + "Ant mailing lists, until all of these causes have been explored," + lSep + "as this is not an Ant bug."; return new BuildException(msg, getLocation()); } /** * Returns the name to use in logging messages. * * @return the name to use in logging messages. */ public String getTaskName() { //return elementName; return realThing == null || !(realThing instanceof Task) ? super.getTaskName() : ((Task) realThing).getTaskName(); } /** * Returns the task instance after it has been created and if it is a task. * * @return a task instance or <code>null</code> if the real object is not * a task. */ public Task getTask() { if (realThing instanceof Task) { return (Task) realThing; } return null; } /** * Return the configured object * * @return the real thing whatever it is * * @since ant 1.6 */ public Object getRealThing() { return realThing; } /** * Set the configured object * @param realThing the configured object * @since ant 1.7 */ public void setRealThing(Object realThing) { this.realThing = realThing; } /** * Try to create a nested element of <code>parent</code> for the * given tag. * * @return whether the creation has been successful */ private boolean handleChild( String parentUri, IntrospectionHelper ih, Object parent, UnknownElement child, RuntimeConfigurable childWrapper) { String childName = ProjectHelper.genComponentName( child.getNamespace(), child.getTag()); if (ih.supportsNestedElement(parentUri, childName)) { IntrospectionHelper.Creator creator = ih.getElementCreator( getProject(), parentUri, parent, childName, child); creator.setPolyType(childWrapper.getPolyType()); Object realChild = creator.create(); if (realChild instanceof PreSetDef.PreSetDefinition) { PreSetDef.PreSetDefinition def = (PreSetDef.PreSetDefinition) realChild; realChild = creator.getRealObject(); child.applyPreSet(def.getPreSets()); } childWrapper.setCreator(creator); childWrapper.setProxy(realChild); if (realChild instanceof Task) { Task childTask = (Task) realChild; childTask.setRuntimeConfigurableWrapper(childWrapper); childTask.setTaskName(childName); childTask.setTaskType(childName); childTask.setLocation(child.getLocation()); } child.handleChildren(realChild, childWrapper); return true; } return false; } /** * like contents equals, but ignores project * @param obj the object to check against * @return true if this unknownelement has the same contents the other */ public boolean similar(Object obj) { if (obj == null) { return false; } if (!getClass().getName().equals(obj.getClass().getName())) { return false; } UnknownElement other = (UnknownElement) obj; // Are the names the same ? if (!equalsString(elementName, other.elementName)) { return false; } if (!namespace.equals(other.namespace)) { return false; } if (!qname.equals(other.qname)) { return false; } // Are attributes the same ? if (!getWrapper().getAttributeMap().equals( other.getWrapper().getAttributeMap())) { return false; } // Is the text the same? // Need to use equals on the string and not // on the stringbuffer as equals on the string buffer // does not compare the contents. if (!getWrapper().getText().toString().equals( other.getWrapper().getText().toString())) { return false; } // Are the sub elements the same ? if (children == null || children.size() == 0) { return other.children == null || other.children.size() == 0; } if (other.children == null) { return false; } if (children.size() != other.children.size()) { return false; } for (int i = 0; i < children.size(); ++i) { UnknownElement child = (UnknownElement) children.get(i); if (!child.similar(other.children.get(i))) { return false; } } return true; } private boolean equalsString(String a, String b) { if (a == null) { return b == null; } return a.equals(b); } }
d6fbc4bce156089ad8d8874e1b55586d37001df9
1bb0414112bdc74c5f56a0cab3f831924df55d15
/src/com/jarp/designpatterns/structural/adapter/PrinterWorkAdapter.java
ddfdd8ae83df4a05ef28a78f2f5c6d079f4b7eb3
[ "MIT" ]
permissive
imjarp/Patterns
d9e61a5f2f8449d8bdcfdd02a43e5ad92c3e34e3
6403c0b0b7f6e89eefa339c7ff8bd363a1a6a81f
refs/heads/master
2021-01-20T04:32:55.523046
2013-11-19T23:40:02
2013-11-19T23:40:02
null
0
0
null
null
null
null
UTF-8
Java
false
false
780
java
/** * */ package com.jarp.designpatterns.structural.adapter; /** * @author JARP * */ public class PrinterWorkAdapter implements PrinterWork { VirtualPrinter mVirtualPrinter; public PrinterWorkAdapter(String extension) { if(extension.equalsIgnoreCase("pdf")) { mVirtualPrinter = new PrintPDFWork(); } else { mVirtualPrinter = new PrintDocumentImageWork(); } } /* (non-Javadoc) * @see com.jarp.designpatterns.structural.adapter.PrinterWork#print(java.lang.String) */ @Override public void print(String pages, String extension,String fileName) { if(extension.equalsIgnoreCase("pdf")) { mVirtualPrinter.printPDF(fileName, extension, null); } else { mVirtualPrinter.printPDF(fileName, extension, null); } } }
21ab66f48c56fdddf68f5c7fe129ad344857d3d7
876724d654445d8bc8d21e95371d4b33e74559f8
/TModifiedTPlamsa/TPlasmaX10/plasmax10/syntaxtree/InclusiveOrExpression.java
b81ee1b5ffcf1d56db35085e7d7d6ba1557f7411
[]
no_license
Mah-D/Retargetable-Compiler
c119e48ec8d6efee095f8d4bf994016da54cbbc0
84b7b81bb35bf5fc24bf5e6799b83d42880c3ffa
refs/heads/master
2016-08-04T21:41:26.159827
2015-07-14T20:18:33
2015-07-14T20:18:33
39,096,022
0
0
null
null
null
null
UTF-8
Java
false
false
802
java
// // Generated by JTB 1.3.2 // package plasmax10.syntaxtree; /** * Grammar production: * f0 -> ExclusiveOrExpression() * f1 -> ( InclusiveOrExpressionRest() )* */ public class InclusiveOrExpression implements Node { public ExclusiveOrExpression f0; public NodeListOptional f1; public InclusiveOrExpression(ExclusiveOrExpression n0, NodeListOptional n1) { f0 = n0; f1 = n1; } public void accept(plasmax10.visitor.Visitor v) { v.visit(this); } public <R,A> R accept(plasmax10.visitor.GJVisitor<R,A> v, A argu) { return v.visit(this,argu); } public <R> R accept(plasmax10.visitor.GJNoArguVisitor<R> v) { return v.visit(this); } public <A> void accept(plasmax10.visitor.GJVoidVisitor<A> v, A argu) { v.visit(this,argu); } }
a41418cb88822c6006d6421b91f6065f19e6160c
dbcf97a3ed78f1da67c4867bf3bed6493c8bc4b4
/app/src/main/java/com/example/q/jde3/TwoFragment.java
59908b348d69ac104494858f375c367ec719c375
[]
no_license
uneap/lab01
b063dd7579a737478fb49cc91dabfdfccdde2fd9
c0b12aaca02e30a2585a8a9849e97c63893159b8
refs/heads/master
2021-09-18T08:57:25.011594
2018-06-30T11:49:41
2018-06-30T11:49:41
null
0
0
null
null
null
null
UTF-8
Java
false
false
803
java
package com.example.q.jde3; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.q.jde3.R; public class TwoFragment extends Fragment{ public TwoFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_two, container, false); } }
15bbf2015f47d6ada8a27a4f05c5aa84cac485a0
4f9c446de4766e2b1782f005fd795c7f74e38777
/SoccerScore/app/src/main/java/com/example/android/soccerscore/MainActivity.java
8ef316fcb907bfa54e32ceedfeef7df4b166ef67
[]
no_license
Bannanaboss/Android
e41806131860f74dbfde0cc4ad122f8958e5fcb3
1c1a84d34e28ecc6dc3585cad7977130efbc1dc9
refs/heads/master
2021-01-11T21:42:59.194100
2017-01-23T11:11:30
2017-01-23T11:11:30
78,771,536
0
0
null
null
null
null
UTF-8
Java
false
false
1,925
java
package com.example.android.soccerscore; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity { int scoreTeamA = 0; int scoreTeamB = 0; int foulTeamA = 0; int foulTeamB = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void increment(View view) { scoreTeamA += 1; displayForTeamA(scoreTeamA); } public void foul(View view) { foulTeamA += 1; displayFoulForTeamA(foulTeamA); } public void incrementB(View view) { scoreTeamB += 1; displayForTeamB(scoreTeamB); } public void foulB(View view) { foulTeamB += 1; displayFoulForTeamB(foulTeamB); } public void resetScore(View view) { scoreTeamA = 0; scoreTeamB = 0; foulTeamA = 0; foulTeamB = 0; displayForTeamA(scoreTeamA); displayForTeamB(scoreTeamB); displayFoulForTeamA(foulTeamA); displayFoulForTeamB(foulTeamB); } public void displayForTeamA(int score) { TextView scoreView = (TextView) findViewById(R.id.team_a_score); scoreView.setText(String.valueOf(score)); } public void displayFoulForTeamA(int score) { TextView scoreView = (TextView) findViewById(R.id.team_a_foul); scoreView.setText(String.valueOf(score)); } public void displayForTeamB(int score) { TextView scoreView = (TextView) findViewById(R.id.team_b_score); scoreView.setText(String.valueOf(score)); } public void displayFoulForTeamB(int score) { TextView scoreView = (TextView) findViewById(R.id.team_b_foul); scoreView.setText(String.valueOf(score)); } }
f2f6e839c39ef7c22bf97caa61c773b7033f5226
4750e1050a9d0560b7132c44dbc5631cca2bebc1
/memorygame-common/memorygame-common-exception/src/main/java/hu/icell/exception/UserAllreadyExistException.java
3b4420030c88a76e0af116e187029872fcd64347
[]
no_license
berenyilajos/memorygame-swarm
c997446482dfdfe86b9ef9e8d2aaa40d61b111f4
6c7fc2aab92627b86048289a16585d410cd9dac5
refs/heads/master
2022-12-03T08:57:21.484406
2020-11-17T13:07:33
2020-11-17T13:07:33
97,708,402
0
0
null
2022-11-24T07:40:30
2017-07-19T11:24:19
Java
UTF-8
Java
false
false
820
java
package hu.icell.exception; public class UserAllreadyExistException extends Exception { private static final long serialVersionUID = 1L; public static final String USER_ALLREADY_EXISTS = "Ez a felhasználónév már létezik!"; public UserAllreadyExistException() { super(USER_ALLREADY_EXISTS); } public UserAllreadyExistException(String message) { super(message); } public UserAllreadyExistException(Throwable cause) { super(cause); } public UserAllreadyExistException(String message, Throwable cause) { super(message, cause); } public UserAllreadyExistException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
1dd40cbf35e9625329a7b54eabe28853eeea4215
efd37e48624870cb219ee7e4b9ed7ea403853be4
/src/main/java/raymond/dataprovider/filter/OrTranslator.java
325cfe95fbc0dff922814e85fb08451f5f277533
[]
no_license
cheneych/UniversityClub
8c7ca18c059f1ce9c1ab26d5b5b7178ce7e0eb0e
7ab0284836913fe2780f7d0d1c8d63bb548f7956
refs/heads/master
2020-03-30T21:25:45.886214
2019-03-23T23:59:11
2019-03-23T23:59:11
151,628,230
1
0
null
null
null
null
UTF-8
Java
false
false
1,030
java
/* * Copyright 2000-2014 Vaadin Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package raymond.dataprovider.filter; public class OrTranslator implements FilterTranslator { @Override public boolean translatesFilter(Filter filter) { return filter instanceof Or; } @Override public String getWhereStringForFilter(Filter filter, StatementHelper sh) { return QueryBuilder.group(QueryBuilder .getJoinedFilterString(((Or) filter).getFilters(), "OR", sh)); } }
c4150ecc348c659431890a0410ff357414755dd2
1e2ad1e9dc5dedd089863233b9c76f8d98e9cd6f
/src/main/java/net/gillets/pivo/domain/pivo/id/PivoEntityTypeLinkId.java
5085c66374e8525940bc9ab4e0c8e9c412749467
[ "Unlicense" ]
permissive
telligcirdec/pivo-java
90ab3316190ed7a175533402ae63726d280c6d89
899b1b3f8dbad397692504dc71d53285e06432a9
refs/heads/main
2023-08-31T08:40:37.878960
2021-10-27T19:28:40
2021-10-27T19:28:40
356,972,484
0
0
null
null
null
null
UTF-8
Java
false
false
347
java
package net.gillets.pivo.domain.pivo.id; import java.io.Serializable; import lombok.Data; @Data public class PivoEntityTypeLinkId implements Serializable { private static final long serialVersionUID = -2023951071681018490L; private String entityATypeCode; private String entityBTypeCode; private String entityLinkTypeCode; }
4ba45ac59dcbd7cfac9e067c6cc1e9192ccc2b65
76023c10e17ad499c0c264c51b85ed803ebbe240
/src/main/java/com/gft/imobiliaria/Service/ImagemService.java
beb36cd954085ffd8860ebb6f3a9f9de93551938
[]
no_license
Cleyson-Garcia/Imobiliaria-Spring-Boot
9578c5244d540fcad8185d6ed4f514bec2b2a710
129450d6688ec01e5c310e2dc5bae8392e72192e
refs/heads/master
2023-04-18T08:38:15.768200
2021-05-06T19:01:12
2021-05-06T19:01:12
363,222,838
0
0
null
null
null
null
UTF-8
Java
false
false
399
java
package com.gft.imobiliaria.Service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.gft.imobiliaria.Entity.Imagem; import com.gft.imobiliaria.Repository.ImagemRepository; @Service public class ImagemService { @Autowired private ImagemRepository rep; public void saveImage(Imagem imagem) { rep.save(imagem); } }
4ff4f1e37cb0a5ac9529a844abf01f0905cea3d9
454c8245b81440b08018ab3c115e13725575fa71
/src/main/java/ru/mecotrade/kidtracker/security/UserDeviceFilter.java
d348b85d6a96099d74a35b911af0bfefd5b5ec81
[ "Apache-2.0" ]
permissive
AIR-FRAME/kidtracker
c27147a46167ef3208c72d5239abebc13ad476e7
f927eb53a0f923d536e87a084fb1dfb4563b1558
refs/heads/master
2023-06-10T15:11:57.718369
2021-07-10T07:46:09
2021-07-10T07:46:09
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,053
java
/* * Copyright 2020 Sergey Shadchin ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.mecotrade.kidtracker.security; import lombok.extern.slf4j.Slf4j; import org.springframework.security.authentication.InsufficientAuthenticationException; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; import org.springframework.web.filter.GenericFilterBean; import org.springframework.web.util.UriTemplate; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Map; @Slf4j public class UserDeviceFilter extends GenericFilterBean { private final static UriTemplate URI_TEMPLATE = new UriTemplate("/api/device/{deviceId}/{:.*}"); private final AuthenticationFailureHandler failureHandler = new SimpleUrlAuthenticationFailureHandler(); @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; String uri = httpServletRequest.getRequestURI(); Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null && authentication.getPrincipal() instanceof UserPrincipal) { UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal(); userPrincipal.getUserInfo().setPassword(null); Map<String, String> uriParams = URI_TEMPLATE.match(uri); String deviceId = uriParams.get("deviceId"); if (deviceId != null && userPrincipal.getUserInfo().getKids().stream().noneMatch(k -> k.getDevice().getId().equals(deviceId))) { log.warn("User {} attempts to access unauthorized device {} in request {}", userPrincipal.getUserInfo().getUsername(), deviceId, uri); throw new InsufficientAuthenticationException(deviceId); } } chain.doFilter(request, response); } }
be65e4b9a8f23b40cd53099e15051e8c6c95f246
558d6077f00e4bc000f0c15518d0ce1a8464ddef
/src/main/java/com/meriame/dto/VersementDTO.java
d32a3a101a49bd3e44027ec5ff2ebb98bf2a92a8
[]
no_license
mEzzahraoui/EBanking
20fbee00dd1fb563b7d0b0845321992d74d38bff
deeb26f29bb71e816876e4f108a8f82f7886f4fd
refs/heads/master
2020-04-15T18:00:51.026460
2019-01-16T17:22:31
2019-01-16T17:22:31
164,896,646
0
1
null
null
null
null
UTF-8
Java
false
false
1,659
java
package com.meriame.dto; import java.util.Date; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import com.fasterxml.jackson.annotation.JsonBackReference; import com.meriame.model.Compte; @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name="Versement") public class VersementDTO { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int id; @ManyToOne @JsonBackReference(value="compteVersementSour") private Long cmptSource; @ManyToOne @JsonBackReference(value="compteVersementDest") private Long cmptDestination; @Temporal(TemporalType.TIMESTAMP) private Date dateTransaction; private double montant; public int getId() { return id; } public void setId(int id) { this.id = id; } public Long getCmptSource() { return cmptSource; } public void setCmptSource(Long cmptSource) { this.cmptSource = cmptSource; } public Long getCmptDestination() { return cmptDestination; } public void setCmptDestination(Long cmptDestination) { this.cmptDestination = cmptDestination; } public Date getDateTransaction() { return dateTransaction; } public void setDateTransaction(Date dateTransaction) { this.dateTransaction = dateTransaction; } public double getMontant() { return montant; } public void setMontant(double montant) { this.montant = montant; } }
61a7316db221b72e29ad58fb5305d85945f4cef8
a65ac298c606c11bbb993fcce2114c9ba80a1d7e
/src/basicQuestions/Graph/BFS.java
7d486d87a4fa45ae696a3e81e13d4331fd73e022
[]
no_license
chptiger/Algorithm
81627bf02585473e59d1990a6124a5323caa8fec
4fa2e1f96de0504dadee5d6592a5c431522a4107
refs/heads/master
2021-07-13T06:39:59.742964
2019-01-16T08:02:44
2019-01-16T08:02:44
28,924,442
0
1
null
null
null
null
UTF-8
Java
false
false
2,098
java
package basicQuestions.Graph; import java.util.LinkedList; import java.util.Queue; public class BFS { /* * ------------------------------------------ Data structure used to represent a * graph ------------------------------------------ */ int[][] adjMatrix; int rootNode = 0; int NNodes; boolean[] visited; /* * ------------------------------- Construct a graph of N nodes * ------------------------------- */ BFS(int N) { NNodes = N; adjMatrix = new int[N][N]; visited = new boolean[N]; } BFS(int[][] mat) { int i, j; NNodes = mat.length; adjMatrix = new int[NNodes][NNodes]; visited = new boolean[NNodes]; for (i = 0; i < NNodes; i++) for (j = 0; j < NNodes; j++) adjMatrix[i][j] = mat[i][j]; } public void bfs() { // BFS uses Queue data structure Queue<Integer> q = new LinkedList<Integer>(); q.add(rootNode); visited[rootNode] = true; printNode(rootNode); while (!q.isEmpty()) { int n, child; n = (q.peek()).intValue(); child = getUnvisitedChildNode(n); if (child != -1) { visited[child] = true; printNode(child); q.add(child); } else { q.remove(); } } clearVisited(); // Clear visited property of nodes } int getUnvisitedChildNode(int n) { int j; for (j = 0; j < NNodes; j++) { if (adjMatrix[n][j] > 0) { if (!visited[j]) return (j); } } return (-1); } void clearVisited() { int i; for (i = 0; i < visited.length; i++) visited[i] = false; } void printNode(int n) { System.out.println(n); } public static void main(String[] args) { // 0 1 2 3 4 5 6 7 8 // =================================================== int[][] conn = { { 0, 1, 0, 1, 0, 0, 0, 0, 1 }, // 0 { 1, 0, 0, 0, 0, 0, 0, 1, 0 }, // 1 { 0, 0, 0, 1, 0, 1, 0, 1, 0 }, // 2 { 1, 0, 1, 0, 1, 0, 0, 0, 0 }, // 3 { 0, 0, 0, 1, 0, 0, 0, 0, 1 }, // 4 { 0, 0, 1, 0, 0, 0, 1, 0, 0 }, // 5 { 0, 0, 0, 0, 0, 1, 0, 0, 0 }, // 6 { 0, 1, 1, 0, 0, 0, 0, 0, 0 }, // 7 { 1, 0, 0, 0, 1, 0, 0, 0, 0 } };// 8 BFS G = new BFS(conn); G.bfs(); } }
2e4a8b41d2c9361dc8a4c2cee4a67c84e5f00aed
b46938bf2ffb073c319f54e01ad51458324a288d
/docker/src/main/java/org/jclouds/docker/binders/BindInputStreamToRequest.java
855a2e5d41709fde0026cb1ec48713328b7ae537
[ "Apache-2.0" ]
permissive
igreenfield/jclouds-labs
51f0e0b28cc06dff8131386993601390ea2414e5
f9d2be3feedda61f578a7c1c2a6cdb799003c88c
refs/heads/master
2021-01-15T10:58:42.862797
2014-11-11T07:59:44
2014-11-11T07:59:44
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,726
java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jclouds.docker.binders; import com.google.common.base.Throwables; import com.google.common.io.Files; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.docker.features.internal.Archives; import org.jclouds.http.HttpRequest; import org.jclouds.io.Payload; import org.jclouds.io.Payloads; import org.jclouds.logging.Logger; import org.jclouds.rest.Binder; import javax.annotation.Resource; import javax.inject.Named; import javax.inject.Singleton; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; @Singleton public class BindInputStreamToRequest implements Binder { @Resource @Named(ComputeServiceConstants.COMPUTE_LOGGER) protected Logger logger = Logger.NULL; @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof File, "this binder is only valid for File!"); checkNotNull(request, "request"); File dockerFile = (File) input; File tmpDir = Files.createTempDir(); final File targetFile = new File(tmpDir + File.separator + "Dockerfile"); try { Files.copy(dockerFile, targetFile); File archive = Archives.tar(tmpDir, File.createTempFile("archive", ".tar")); FileInputStream data = new FileInputStream(archive); Payload payload = Payloads.newInputStreamPayload(data); payload.getContentMetadata().setContentLength(data.getChannel().size()); payload.getContentMetadata().setContentType("application/tar"); request.setPayload(payload); } catch (IOException e) { logger.error(e, "Couldn't create a tarball for %s", targetFile); throw Throwables.propagate(e); } return request; } }
8cd927fda3b0a1cee816a1b548d0363f973d0672
2a91e6d59cc6037980df339903f8a27d1981b6fd
/src/main/java/gscript/factory/log/GroovyProgressLog.java
28552735648b3d04d52b617cef24ea8e38c05618
[]
no_license
springevil82/gscript
9d13bd38ec8d34113465d01c7ce86e1beb6fe9fb
8f84c12ad5eb4ee5ea449c9146ead42981439351
refs/heads/master
2021-01-23T10:29:06.801358
2017-07-25T12:45:17
2017-07-25T12:45:17
93,054,447
0
0
null
null
null
null
UTF-8
Java
false
false
492
java
package gscript.factory.log; public interface GroovyProgressLog extends AutoCloseable { void setProgressText(String text); void setProgressDetailText(String text); void setProgressMax(int maxValue); void moveProgress(); void setProgressInfinity(boolean infinityProgress); void addInfo(Object text); void addWarn(Object text); void addError(Object text); void throwException(Object text); boolean isCancelled(); void deleteLogFile(); }
f65dd96e2e3e4669de56c94c7422093377fb6501
8f220128ef71d7c39a60a1a04063c2a17cbd1985
/src/lyn/android/fragment/viewpager/FragmentViewPagerActivity.java
2abd528d60cd4da4b2feb035d88abe7ddb9304a1
[]
no_license
LynLin0/Lyn
c0d12b3a0f48aa26dd0a23a0fff8817281d58798
143593f695e536377245db77f721521c2f6a6a39
refs/heads/master
2016-08-12T18:12:43.427523
2015-11-16T12:42:24
2015-11-16T12:42:24
36,854,680
0
0
null
null
null
null
UTF-8
Java
false
false
1,550
java
package lyn.android.fragment.viewpager; import lyn.android.R; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.widget.RadioGroup; import android.widget.RadioGroup.OnCheckedChangeListener; public class FragmentViewPagerActivity extends FragmentActivity implements OnCheckedChangeListener{ public static final String ARGUMENT_INFO = "info"; private NonSwipeableViewPager viewpager; private RadioGroup radiogroup; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_act_viewpager); findView(); setupView(); } private void findView() { viewpager = (NonSwipeableViewPager)findViewById(R.id.fragment_viewpager_viewpager); radiogroup = (RadioGroup)findViewById(R.id.fragment_viewpager_first_radiogroup); } private void setupView() { viewpager.setOffscreenPageLimit(3); viewpager.setAdapter(new FragmentViewPagerAdapter(getSupportFragmentManager())); radiogroup.setOnCheckedChangeListener(this); } @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.fragment_viewpager_first_radiobutton: viewpager.setCurrentItem(0); break; case R.id.fragment_viewpager_second_radiobutton: viewpager.setCurrentItem(1); break; case R.id.fragment_viewpager_third_radiobutton: viewpager.setCurrentItem(2); break; case R.id.fragment_viewpager_fourth_radiobutton: viewpager.setCurrentItem(3); break; default: break; } } }
4f623493d9880aee44dc6d6637f9f7e726d8c7dd
47aee0241b4e5506254c868e2b270df6baa9dd79
/IdeaProjects/BigData/TrafficProject/src/main/java/com/mujie/spark/skynet/RandomExtractCars.java
c537f0b7d4770f73156f8995dc6d9b9534c68746
[]
no_license
Andy112646/TrafficProject
a8bbafc6fbf31b5f483760aaac821bbc86a2356c
366533ab2d7f22d477583889f749388270ed8047
refs/heads/master
2022-07-13T17:56:01.182391
2020-03-21T06:27:04
2020-03-21T06:27:04
218,442,526
1
0
null
2022-07-01T21:28:45
2019-10-30T04:21:23
Scala
UTF-8
Java
false
false
19,052
java
package com.mujie.spark.skynet; import java.text.SimpleDateFormat; import java.util.*; import java.util.Map.Entry; import com.mujie.spark.domain.CarTrack; import com.mujie.spark.domain.RandomExtractCar; import com.mujie.spark.domain.RandomExtractMonitorDetail; import com.mujie.spark.domain.Task; import com.spark.spark.test.MockData; import org.apache.commons.collections.IteratorUtils; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaPairRDD; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.api.java.function.PairFlatMapFunction; import org.apache.spark.api.java.function.PairFunction; import org.apache.spark.api.java.function.VoidFunction; import org.apache.spark.broadcast.Broadcast; import org.apache.spark.sql.Row; import com.alibaba.fastjson.JSONObject; import com.mujie.spark.conf.ConfigurationManager; import com.mujie.spark.constant.Constants; import com.mujie.spark.dao.ICarTrackDAO; import com.mujie.spark.dao.IRandomExtractDAO; import com.mujie.spark.dao.ITaskDAO; import com.mujie.spark.dao.factory.DAOFactory; import com.mujie.spark.util.DateUtils; import com.mujie.spark.util.ParamUtils; import com.mujie.spark.util.SparkUtils; import com.mujie.spark.util.StringUtils; import org.apache.spark.sql.SparkSession; import scala.Tuple2; /** * * 抽取N辆车的信息 * @author root * */ public class RandomExtractCars { public static void main(String[] args) { /** * 判断应用程序是否在本地执行 */ JavaSparkContext sc = null; SparkSession spark = null; Boolean onLocal = ConfigurationManager.getBoolean(Constants.SPARK_LOCAL); if(onLocal){ // 构建Spark运行时的环境参数 SparkConf conf = new SparkConf().setAppName(Constants.SPARK_APP_NAME); conf.setMaster("local"); sc = new JavaSparkContext(conf); spark = SparkSession.builder().getOrCreate(); MockData.mock(sc, spark); }else{ System.out.println("++++++++++++++++++++++++++++++++++++++开启hive的支持"); spark = SparkSession.builder().enableHiveSupport().getOrCreate(); spark.sql("use traffic"); } //从配置文件中查询出来指定的任务ID long taskId = ParamUtils.getTaskIdFromArgs(args, Constants.SPARK_LOCAL_TASKID_EXTRACT_CAR); /** * 通过taskId从数据库中查询相应的参数 * 1、通过DAOFactory工厂类创建出TaskDAO组件 * 2、查询task */ ITaskDAO taskDAO = DAOFactory.getTaskDAO(); Task task = taskDAO.findTaskById(taskId); if(task == null){ System.out.println("没有找打对应的taskID参数"); System.exit(1); } /** * task对象已经获取到,因为params是一个json,所以需要创建一个解析json的对象 */ JSONObject taskParamsJsonObject = JSONObject.parseObject(task.getTaskParams()); /** * 统计出这一段时间内,所有卡口的信息,所以需要根据param参数,去monitor_flow_action临时表中获取结果 */ JavaRDD<Row> cameraRDD = SparkUtils.getCameraRDDByDateRange(spark, taskParamsJsonObject); /** * 随机抽取N个车辆信息,比如一天有24个小时,其中08:00~09:00的车辆数量占当天总车流量的50%,在这天中我们需要随机抽取100个, * 那么08:00~09:00的,就得抽取100*50%=50,而且这50个需要随机抽取。 * 我 们需要使用Spark自己实现一个算法,按照时间段分段抽取车辆信息,然后这些车辆信息可以很权威的代表整个城市的车辆信息, * 我们可以基于这些抽样的数据进行数据分析,可以绘制出这些车辆每天的运行轨迹,对于道路的规划起到了很重要的作用, * 比如,我们抽样出来的数据80%的车辆在早高峰和晚高峰都是基本同样的行车轨迹,然而他们每天途径的路段都会堵车,这时候我们可以根据这些数据对道路进行规划 * 可以根据用户的画像进行多维度的数据分析 * * 下面方法中将抽取出来的车辆信息插入到random_extract_car表中,将抽取的car的详细数据放入了random_extract_car_detail_info 表中 * 返回了(car,Row) */ JavaPairRDD<String, Row> randomExtractCar2DetailRDD = randomExtractCarInfo(sc,taskId,taskParamsJsonObject,cameraRDD); /** * carTrackRDD<String,String> * k:car * v:date|carTracker * 相同的车辆会出现在不同的时间段中,那么我们可以追踪在这个日期段中车辆的行驶轨迹 */ JavaPairRDD<String, String> carTrackRDD = getCarTrack(taskId,randomExtractCar2DetailRDD); /** * 将每一辆车的轨迹信息写入到数据库表car_track中 */ saveCarTrack2DB(taskId,carTrackRDD); System.out.println("all finished..."); sc.close(); } private static void saveCarTrack2DB(final long taskId,JavaPairRDD<String, String> carTrackRDD) { //action执行 carTrackRDD.foreachPartition(new VoidFunction<Iterator<Tuple2<String,String>>>() { /** * */ private static final long serialVersionUID = 1L; @Override public void call(Iterator<Tuple2<String, String>> iterator) throws Exception { List<CarTrack> carTracks = new ArrayList<>(); while (iterator.hasNext()) { Tuple2<String, String> tuple = iterator.next(); String car = tuple._1; String dateAndCarTrack = tuple._2; String date = StringUtils.getFieldFromConcatString(dateAndCarTrack, "\\|", Constants.FIELD_DATE); String track = StringUtils.getFieldFromConcatString(dateAndCarTrack, "\\|",Constants.FIELD_CAR_TRACK); CarTrack carTrack = new CarTrack(taskId, date,car, track); carTracks.add(carTrack); } //将车辆的轨迹存入数据库表car_track中 ICarTrackDAO carTrackDAO = DAOFactory.getCarTrackDAO(); carTrackDAO.insertBatchCarTrack(carTracks); } }); } /** * 对抽取出来的car进行跟踪轨迹 * @param taskId * @param randomExtractCar2DetailRDD * @return (car,"dateHour=2019-07-01|carTrack=monitor_id,monitor_id,monitor_id...") */ private static JavaPairRDD<String, String> getCarTrack(long taskId, JavaPairRDD<String, Row> randomExtractCar2DetailRDD) { JavaPairRDD<String, Iterable<Row>> groupByCar = randomExtractCar2DetailRDD.groupByKey(); JavaPairRDD<String, String> carTrackRDD = groupByCar.mapToPair(new PairFunction<Tuple2<String,Iterable<Row>>, String,String>() { /** * */ private static final long serialVersionUID = 1L; @Override public Tuple2<String, String> call(Tuple2<String, Iterable<Row>> tuple) throws Exception { String car = tuple._1; Iterator<Row> carMetailsIterator = tuple._2.iterator(); List<Row> rows = IteratorUtils.toList(carMetailsIterator); //按照卡扣拍摄的时间 action_time 来排序 Collections.sort(rows, new Comparator<Row>() { @Override public int compare(Row r1, Row r2) { if(DateUtils.after(r1.getAs("action_time"), r2.getAs("action_time"))){ return 1; } return -1; } }); StringBuilder carTrack = new StringBuilder(); String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); for (Row row : rows) { carTrack.append(","+row.getAs("monitor_id")); } return new Tuple2<>(car, Constants.FIELD_DATE+"="+date+"|"+Constants.FIELD_CAR_TRACK+"="+carTrack.substring(1)); } }); return carTrackRDD; } /** * cameraRDD * 1、key:8-9 value:carCount mapTopair countByKey * 2、计算出来8-9的占全天总车流量的百分比 * 3、Map<date,Map<hour,List<Interger>>> * 4、进行抽取 * @param sc * @param taskId * @param params * @param cameraRDD * @return 抽取到的(car,row) * * * * ("dateHour"="2019-07-01_08","car"="京X91427") * * 1、date_hour key car */ private static JavaPairRDD<String, Row> randomExtractCarInfo( JavaSparkContext sc, final long taskId,JSONObject params, JavaRDD<Row> cameraRDD) { /** * key:时间段 value:car * dateHourCar2DetailRDD ---- ("dateHour"="2019-08-01_08","car"="京X91427") */ JavaPairRDD<String, String> dateHourCar2DetailRDD = cameraRDD.mapToPair(new PairFunction<Row, String,String>() { private static final long serialVersionUID = 1L; @Override public Tuple2<String, String> call(Row row) throws Exception { String actionTime = row.getAs("action_time");//2019-07-06 06:18:49 String dateHour = DateUtils.getDateHour(actionTime);//2019-07-06_06 String car = row.getAs("car"); /** * 为什么要使用组合Key? * 因为在某一个时间段内,这一两车很有可能经过多个卡扣 */ String key = Constants.FIELD_DATE_HOUR + "=" + dateHour; String value = Constants.FIELD_CAR + "=" + car; //(dateHour=2019-07-06_06 , car=鲁xxxxx) return new Tuple2<>(key, value); } }); /** * key-value <car,row> * car2DetailRDD ---- ("京X91427",Row) * */ JavaPairRDD<String, Row> car2DetailRDD = cameraRDD.mapToPair(new PairFunction<Row, String , Row>() { private static final long serialVersionUID = 1L; @Override public Tuple2<String, Row> call(Row row) throws Exception { String car = row.getAs("car"); return new Tuple2<>(car, row); } }); /** * 相同的时间段内出现的车辆我们去重 * key:时间段 value:car * dateHour2DetailRDD ---- ("dateHour"="2019-07-01_08","car"="京X91427") */ JavaPairRDD<String, String> dateHour2DetailRDD = dateHourCar2DetailRDD.distinct(); /** * String:dateHour * Object:去重后的这个小时段的总的车流量 */ Map<String, Long> countByKey = dateHour2DetailRDD.countByKey(); Map<String, Map<String,Long>> dateHourCountMap = new HashMap<>(); for (Entry<String, Long> entry : countByKey.entrySet()) { String dateHour = entry.getKey();//2019-03-25_20 String[] dateHourSplit = dateHour.split("_"); String date = dateHourSplit[0];//2019-03-25 String hour = dateHourSplit[1];//20 //本日期时段对应的车辆数 Long count = Long.parseLong(String.valueOf(entry.getValue())); Map<String, Long> hourCountMap = dateHourCountMap.get(date); if(hourCountMap == null){ hourCountMap = new HashMap<String,Long>(); dateHourCountMap.put(date, hourCountMap); } hourCountMap.put(hour, count); } /** * 要抽取的车辆数 * 假设要抽取100辆车 */ int extractNums = Integer.parseInt(ParamUtils.getParam(params, Constants.FIELD_EXTRACT_NUM)); /** * 一共抽取100辆车,平均每天应该抽取多少辆车呢? * extractNumPerDay = 100 , dateHourCountMap.size()为有多少不同的天数日期,就是多长 */ int extractNumPerDay = extractNums / dateHourCountMap.size(); /** * 记录每天每小时抽取索引的集合 * dateHourExtractMap ---- Map<"日期",Map<"小时段",List<Integer>(抽取数据索引)>> */ Map<String, Map<String,List<Integer>>> dateHourExtractMap = new HashMap<>(); Random random = new Random(); //dateHourCountMap ---- Map<date,Map<hour,carCount>> for (Entry<String, Map<String, Long>> entry : dateHourCountMap.entrySet()) { String date = entry.getKey(); /** * hourCountMap key:hour value:carCount * 当前日期下,每小时对应的车辆数 */ Map<String, Long> hourCountMap = entry.getValue(); //计算出这一天总的车流量 long dateCarCount = 0L; Collection<Long> values = hourCountMap.values(); for (long tmpHourCount : values) { dateCarCount += tmpHourCount; } /** * 小时段对应的应该抽取车辆的索引集合 * hourExtractMap ---- Map<小时,List<>> */ Map<String, List<Integer>> hourExtractMap = dateHourExtractMap.get(date); if(hourExtractMap == null){ hourExtractMap = new HashMap<String,List<Integer>>(); dateHourExtractMap.put(date, hourExtractMap); } /** * 遍历的是每个小时对应的车流量总数信息 * hourCountMap key:hour value:carCount */ for (Entry<String, Long> hourCountEntry : hourCountMap.entrySet()) { //当前小时段 String hour = hourCountEntry.getKey(); //当前小时段对应的真实的车辆数 long hourCarCount = hourCountEntry.getValue(); //计算出这个小时的车流量占总车流量的百分比,然后计算出在这个时间段内应该抽取出来的车辆信息的数量 int hourExtractNum = (int)(((double)hourCarCount / (double)dateCarCount) * extractNumPerDay); /** * 如果在这个时间段内抽取的车辆信息数量比这个时间段内的车流量还要多的话,只需要将count的值赋值给hourExtractNum就可以 * */ if(hourExtractNum >= hourCarCount){ hourExtractNum = (int)hourCarCount; } //获取当前小时 存储随机数的List集合 List<Integer> extractIndexs = hourExtractMap.get(hour); if(extractIndexs == null){ extractIndexs = new ArrayList<Integer>(); hourExtractMap.put(hour, extractIndexs); } /** * 生成抽取的car的index, 实际上就是生成一系列的随机数 随机数的范围就是0-count(这个时间段内的车流量) 将这些随机数放入一个list集合中 * 那么这里这个随机数的最大值没有超过实际上这个时间点对应的中的车流量总数,这里的list长度也就是要抽取数据个数的大小。 * 假设在一天中,7~8点这个时间段总车流量为100,假设我们之前刚刚算出应该在7~8点抽出的车辆数为20 * 那么 我们怎么样随机抽取呢? * 1.循环20次 * 2.每次循环搞一个0~100的随机数,放入一个list<Integer>中,那么这个list中的每一个元素就是我们这里说的car的index * 3.最后得到一个长度为20的car的indexList<Integer>集合,一会取值,取20个,那么取哪个值呢,就取这里List中的下标对应的car * */ for(int i = 0 ; i < hourExtractNum ; i++){ /** * 50 */ int index = random.nextInt((int)hourCarCount); while(extractIndexs.contains(index)){ index = random.nextInt((int)hourCarCount); } extractIndexs.add(index); } } } /******************************************************************/ // Map<String, Map<String, IntList>> fastutilDateHourExtractMap = new HashMap<String, Map<String, IntList>>(); // // for (Map.Entry<String, Map<String, List<Integer>>> dateHourExtractEntry : dateHourExtractMap.entrySet()) { // String date = dateHourExtractEntry.getKey(); // Map<String, List<Integer>> hourExtractMap = dateHourExtractEntry.getValue(); // // Map<String, IntList> fastutilHourExtractMap = new HashMap<String, IntList>(); // // for (Map.Entry<String, List<Integer>> hourExtractEntry : hourExtractMap.entrySet()) { // String hour = hourExtractEntry.getKey(); // List<Integer> extractList = hourExtractEntry.getValue(); // // IntList fastutilExtractList = new IntArrayList(); // // for (int i = 0; i < extractList.size(); i++) { // fastutilExtractList.add(extractList.get(i)); // } // // fastutilHourExtractMap.put(hour, fastutilExtractList); // } // // fastutilDateHourExtractMap.put(date, fastutilHourExtractMap); // } /******************************************************************/ Broadcast<Map<String, Map<String, List<Integer>>>> dateHourExtractBroadcast = sc.broadcast(dateHourExtractMap); /** * 在dateHour2DetailRDD中进行随机抽取车辆信息, * 首先第一步:按照date_hour进行分组,然后对组内的信息按照 dateHourExtractBroadcast参数抽取相应的车辆信息 * 抽取出来的结果直接放入到MySQL数据库中。 * * extractCarRDD ----抽取出来的所有车辆 */ JavaPairRDD<String, String> extractCarRDD = dateHour2DetailRDD.groupByKey().flatMapToPair( new PairFlatMapFunction<Tuple2<String,Iterable<String>>, String,String>() { /** * */ private static final long serialVersionUID = 1L; @Override public Iterator<Tuple2<String, String>> call(Tuple2<String, Iterable<String>> t) throws Exception { //将要返回的当前日期当前小时段下抽取出来的车辆集合 List<Tuple2<String,String>> list = new ArrayList<>(); //按index下标抽取的这个时间段对应的车辆集合 List<RandomExtractCar> carRandomExtracts = new ArrayList<>(); String dateHour = t._1;//2019-07-06_08 //Iterator<car>=>Iterator<car = "xxx"> Iterator<String> iterator = t._2.iterator(); String date = dateHour.split("_")[0]; String hour = dateHour.split("_")[1]; Map<String, Map<String, List<Integer>>> dateHourExtractMap = dateHourExtractBroadcast.value(); List<Integer> indexList = dateHourExtractMap.get(date).get(hour); int index = 0; while(iterator.hasNext()){ String car = iterator.next().split("=")[1]; if(indexList.contains(index)){ System.out.println("抽取到的车辆 ----"+car); RandomExtractCar carRandomExtract = new RandomExtractCar(taskId, car, date, dateHour); carRandomExtracts.add(carRandomExtract); list.add(new Tuple2<>(car, car)); } index++; } /** * 将抽取出来的车辆信息插入到random_extract_car表中 */ IRandomExtractDAO randomExtractDAO = DAOFactory.getRandomExtractDAO(); randomExtractDAO.insertBatchRandomExtractCar(carRandomExtracts); return list.iterator(); } }); /** * extractCarRDD K:car V:car * 抽取到的所有的car,这里去和开始得到的符合日期内的车辆详细信息car2DetailRDD ,得到抽取到的car的详细信息 * */ JavaPairRDD<String, Row> randomExtractCar2DetailRDD = extractCarRDD.distinct().join(car2DetailRDD).mapPartitionsToPair( new PairFlatMapFunction<Iterator<Tuple2<String,Tuple2<String,Row>>>, String,Row>() { private static final long serialVersionUID = 1L; @Override public Iterator<Tuple2<String, Row>> call(Iterator<Tuple2<String, Tuple2<String, Row>>> iterator) throws Exception { List<RandomExtractMonitorDetail> randomExtractMonitorDetails = new ArrayList<>(); List<Tuple2<String, Row>> list = new ArrayList<>(); while(iterator.hasNext()){ Tuple2<String, Tuple2<String, Row>> tuple = iterator.next(); Row row = tuple._2._2; String car = tuple._1; RandomExtractMonitorDetail m = new RandomExtractMonitorDetail(taskId, row.getString(0), row.getString(1), row.getString(2), row.getString(3), row.getString(4), row.getString(5), row.getString(6)); randomExtractMonitorDetails.add(m); list.add(new Tuple2<>(car, row)); } //将车辆详细信息插入random_extract_car_detail_info表中。 IRandomExtractDAO randomExtractDAO = DAOFactory.getRandomExtractDAO(); randomExtractDAO.insertBatchRandomExtractDetails(randomExtractMonitorDetails); return list.iterator(); } }); return randomExtractCar2DetailRDD; } }
a0482ecb80ef99ebc2b9f848a8a1112982069604
947288aedf9a7406585fcd03a0fd8c5219ebc4ed
/src/Leetcode/Q447_Number_of_Boomerangs.java
c6ae976a3b679f93e369c08c7f4a9b73947e09a8
[]
no_license
checkcheckzach/coding
ee2f5326726ae059ccefcc7fd6d865edef9c3a48
81e1bed6d1cedc15430c9e5d65449ffc1bcdfdce
refs/heads/master
2023-06-16T11:10:52.648869
2021-07-09T08:58:38
2021-07-09T08:58:38
null
0
0
null
null
null
null
UTF-8
Java
false
false
868
java
package Leetcode; import java.util.HashMap; import java.util.Map; /** * Created by rbhatnagar2 on 1/15/17. */ public class Q447_Number_of_Boomerangs { public int numberOfBoomerangs(int[][] points) { int res = 0; Map<Integer, Integer> map = new HashMap<>(); for(int i=0; i<points.length; i++) { for(int j=0; j<points.length; j++) { if(i == j) continue; int d = getDistance(points[i], points[j]); map.put(d, map.getOrDefault(d, 0) + 1); } for(int val : map.values()) { res += val * (val-1); } map.clear(); } return res; } private int getDistance(int[] a, int[] b) { int dx = a[0] - b[0]; int dy = a[1] - b[1]; return dx*dx + dy*dy; } }
d4db01f0b3dbbe51afe310d8b4ee2e158497b291
617ef0bf0ce671d2c940a2c3ac7177ed78e091d8
/CleverZoneLastVersion/CleverZone/src/cleverZone.java
4fb09644fd4439318894b4de303cb5a7c01f017b
[]
no_license
supernour09/CleverZone
54b14db9b5dac551ebd74722703801158c21e987
fe9e793a9e82fa6d241d7488671701821a600df2
refs/heads/master
2020-12-24T11:53:43.955404
2017-02-03T19:52:30
2017-02-03T19:52:30
73,008,992
0
2
null
null
null
null
UTF-8
Java
false
false
71,807
java
import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JOptionPane; import java.awt.Font; import java.awt.CardLayout; import javax.swing.JPanel; import javax.swing.border.TitledBorder; import javax.swing.UIManager; import java.awt.Color; import javax.swing.JRadioButton; import java.awt.event.ActionListener; import java.util.Enumeration; import java.util.Vector; import java.awt.event.ActionEvent; import javax.swing.AbstractButton; import javax.swing.ButtonGroup; import javax.swing.DefaultListModel; import javax.swing.JPasswordField; import javax.swing.JFormattedTextField; import javax.swing.ImageIcon; import javax.swing.JList; import javax.swing.JScrollPane; import javax.swing.JToolBar; public class cleverZone { private String gameTypeStr = ""; // needed in "get selected subjects & show games buttons in playGame Panel" private JFrame frm_CreategGame; private Control control = new Control(); private JTextField mcqTmpQuesTxtField; private JTextField mcqTmpCho1TxtField; private JTextField mcqTmpCho2TxtField; private JTextField mcqTmpCho3TxtField; private JTextField mcqTmpCho4TxtField; private JTextField mcqTmpAnsTxtField; private final ButtonGroup createGameGameTypebuttonGroup = new ButtonGroup(); private JTextField mtTmpLefttxtfield1; private JTextField mtTmpLefttxtfield2; private JTextField mtTmpLefttxtfield3; private JTextField mtTmpLefttxtfield4; private JTextField mtTmpLefttxtfieldA; private JTextField mtTmpLefttxtfieldB; private JTextField mtTmpLefttxtfieldC; private JTextField mtTmpLefttxtfieldD; private JTextField mtTmpAns1; private JTextField mtTmpAns2; private JTextField mtTmpAns3; private JTextField mtTmpAns4; private JTextField t_fTmpQuesTxtField; private JTextField t_fTmpAnsTxtField; private String Subject; private String Name; private McQ McQ_Game = new McQ(); private Match match_game = new Match(); private T_F tfGame = new T_F(); private int McQCnt=0;//index for the current mcq question private int T_FCnt=0;//index for the current t/f question private int MatchCnt=0;//index for the current match question Account theAccount = new Account(); private JTextField createGameGameNameTxtField; private JTextField createGameGameSubjectTxtField; private JPasswordField loginPasswordTxtField; private JTextField loginUsernameTxtField; private JTextField registerNameTxtField; private JTextField registerUserNameTxtField; private JTextField registerEmailTxtField; private JPasswordField registerPasswordTxtField; private JPasswordField registerConfirmPasswordTxtField; private final ButtonGroup registerTypeButtonGroup = new ButtonGroup(); private final ButtonGroup registerGenderButtonGroup = new ButtonGroup(); private JTextField mcqGameQuesTxtField; private final ButtonGroup mcqGameChoicesButtonGroup = new ButtonGroup(); private JTextField t_fGameQuesTxtField; private final ButtonGroup t_fGameButtonGroup = new ButtonGroup(); private JTextField mtGameLeft1TxtField; private JTextField mtGameLeft2TxtField; private JTextField mtGameLeft3TxtField; private JTextField mtGameLeft4TxtField; private JTextField mtGameRightATxtField; private JTextField mtGameRightBTxtField; private JTextField mtGameRightCTxtField; private JTextField mtGameRightDTxtField; private final ButtonGroup mtGameButtonGroup1 = new ButtonGroup(); private final ButtonGroup mtGameButtonGroup2 = new ButtonGroup(); private final ButtonGroup mtGameButtonGroup3 = new ButtonGroup(); private final ButtonGroup mtGameButtonGroup4 = new ButtonGroup(); private final ButtonGroup PlayGameGameTypeButtonGroup = new ButtonGroup(); /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { cleverZone window = new cleverZone(); window.frm_CreategGame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public cleverZone() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frm_CreategGame = new JFrame(); frm_CreategGame.setTitle("Clever Zone"); frm_CreategGame.setBounds(100, 100, 850, 500); frm_CreategGame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frm_CreategGame.getContentPane().setLayout(new CardLayout(0, 0)); JButton playGameBtnGetSubjects = new JButton("Get Selected Subjects"); playGameBtnGetSubjects.setFont(new Font("Chiller", Font.BOLD, 18)); JPanel homePanel = new JPanel(); frm_CreategGame.getContentPane().add(homePanel, "name_19208349551372"); homePanel.setLayout(null); homePanel.setVisible(true); JPanel registerPanel = new JPanel(); frm_CreategGame.getContentPane().add(registerPanel, "name_23837330151410"); registerPanel.setLayout(null); registerPanel.setVisible(false); JPanel loginPanel = new JPanel(); frm_CreategGame.getContentPane().add(loginPanel, "name_23376607050557"); loginPanel.setLayout(null); loginPanel.setVisible(false); JPanel createGamePanel = new JPanel(); frm_CreategGame.getContentPane().add(createGamePanel, "name_20877916505726"); createGamePanel.setLayout(null); createGamePanel.setVisible(false); JPanel sProfilePanel = new JPanel(); frm_CreategGame.getContentPane().add(sProfilePanel, "name_26370065916662"); sProfilePanel.setLayout(null); sProfilePanel.setVisible(false); JPanel tProfilePanel = new JPanel(); frm_CreategGame.getContentPane().add(tProfilePanel, "name_27465590731761"); tProfilePanel.setLayout(null); tProfilePanel.setVisible(false); JPanel playGamePanel = new JPanel(); frm_CreategGame.getContentPane().add(playGamePanel, "name_30648042944926"); playGamePanel.setLayout(null); playGamePanel.setVisible(false); JPanel mcqGamePanel = new JPanel(); frm_CreategGame.getContentPane().add(mcqGamePanel, "name_90324256806965"); mcqGamePanel.setLayout(null); mcqGamePanel.setVisible(false); JPanel t_fGamePanel = new JPanel(); frm_CreategGame.getContentPane().add(t_fGamePanel, "name_91870340021553"); t_fGamePanel.setLayout(null); t_fGamePanel.setVisible(false); JPanel mtGamePanel = new JPanel(); frm_CreategGame.getContentPane().add(mtGamePanel, "name_93563546412412"); mtGamePanel.setLayout(null); mtGamePanel.setVisible(false); JLabel label_35 = new JLabel("Matching Game"); label_35.setFont(new Font("Chiller", Font.BOLD, 40)); label_35.setBounds(271, 11, 203, 61); mtGamePanel.add(label_35); mtGamePanel.setVisible(false); JLabel lblNewLabel_10 = new JLabel("A"); lblNewLabel_10.setFont(new Font("Chiller", Font.BOLD, 20)); lblNewLabel_10.setBounds(10, 108, 20, 24); mtGamePanel.add(lblNewLabel_10); JPanel mtGameChoicesInternalPanel = new JPanel(); mtGameChoicesInternalPanel.setBorder(new TitledBorder(null, "Match", TitledBorder.LEADING, TitledBorder.TOP, null, null)); mtGameChoicesInternalPanel.setBounds(10, 187, 710, 199); mtGamePanel.add(mtGameChoicesInternalPanel); mtGameChoicesInternalPanel.setLayout(null); JLabel label_36 = new JLabel("1"); label_36.setFont(new Font("Chiller", Font.BOLD, 20)); label_36.setBounds(12, 40, 27, 20); mtGameChoicesInternalPanel.add(label_36); JLabel label_37 = new JLabel("2"); label_37.setFont(new Font("Chiller", Font.BOLD, 20)); label_37.setBounds(10, 80, 27, 20); mtGameChoicesInternalPanel.add(label_37); JLabel label_38 = new JLabel("3"); label_38.setFont(new Font("Chiller", Font.BOLD, 20)); label_38.setBounds(10, 120, 27, 20); mtGameChoicesInternalPanel.add(label_38); JLabel label_39 = new JLabel("4"); label_39.setFont(new Font("Chiller", Font.BOLD, 20)); label_39.setBounds(10, 160, 27, 20); mtGameChoicesInternalPanel.add(label_39); mtGameLeft1TxtField = new JTextField(); mtGameLeft1TxtField.setColumns(10); mtGameLeft1TxtField.setBounds(47, 40, 183, 20); mtGameChoicesInternalPanel.add(mtGameLeft1TxtField); mtGameLeft2TxtField = new JTextField(); mtGameLeft2TxtField.setColumns(10); mtGameLeft2TxtField.setBounds(47, 80, 183, 20); mtGameChoicesInternalPanel.add(mtGameLeft2TxtField); mtGameLeft3TxtField = new JTextField(); mtGameLeft3TxtField.setColumns(10); mtGameLeft3TxtField.setBounds(47, 120, 183, 20); mtGameChoicesInternalPanel.add(mtGameLeft3TxtField); mtGameLeft4TxtField = new JTextField(); mtGameLeft4TxtField.setColumns(10); mtGameLeft4TxtField.setBounds(47, 160, 183, 20); mtGameChoicesInternalPanel.add(mtGameLeft4TxtField); JRadioButton mtGameRdBtnA1 = new JRadioButton("A"); mtGameButtonGroup1.add(mtGameRdBtnA1); mtGameRdBtnA1.setFont(new Font("Chiller", Font.BOLD, 20)); mtGameRdBtnA1.setBounds(301, 40, 42, 23); mtGameChoicesInternalPanel.add(mtGameRdBtnA1); JRadioButton mtGameRdBtnB1 = new JRadioButton("B"); mtGameButtonGroup1.add(mtGameRdBtnB1); mtGameRdBtnB1.setFont(new Font("Chiller", Font.BOLD, 20)); mtGameRdBtnB1.setBounds(372, 40, 42, 23); mtGameChoicesInternalPanel.add(mtGameRdBtnB1); JRadioButton mtGameRdBtnC1 = new JRadioButton("C"); mtGameButtonGroup1.add(mtGameRdBtnC1); mtGameRdBtnC1.setFont(new Font("Chiller", Font.BOLD, 20)); mtGameRdBtnC1.setBounds(443, 40, 42, 23); mtGameChoicesInternalPanel.add(mtGameRdBtnC1); JRadioButton mtGameRdBtnD1 = new JRadioButton("D"); mtGameButtonGroup1.add(mtGameRdBtnD1); mtGameRdBtnD1.setFont(new Font("Chiller", Font.BOLD, 20)); mtGameRdBtnD1.setBounds(514, 40, 42, 23); mtGameChoicesInternalPanel.add(mtGameRdBtnD1); JRadioButton mtGameRdBtnA2 = new JRadioButton("A"); mtGameButtonGroup2.add(mtGameRdBtnA2); mtGameRdBtnA2.setFont(new Font("Chiller", Font.BOLD, 20)); mtGameRdBtnA2.setBounds(301, 80, 42, 23); mtGameChoicesInternalPanel.add(mtGameRdBtnA2); JRadioButton mtGameRdBtnB2 = new JRadioButton("B"); mtGameButtonGroup2.add(mtGameRdBtnB2); mtGameRdBtnB2.setFont(new Font("Chiller", Font.BOLD, 20)); mtGameRdBtnB2.setBounds(372, 80, 42, 23); mtGameChoicesInternalPanel.add(mtGameRdBtnB2); JRadioButton mtGameRdBtnC2 = new JRadioButton("C"); mtGameButtonGroup2.add(mtGameRdBtnC2); mtGameRdBtnC2.setFont(new Font("Chiller", Font.BOLD, 20)); mtGameRdBtnC2.setBounds(443, 80, 42, 23); mtGameChoicesInternalPanel.add(mtGameRdBtnC2); JRadioButton mtGameRdBtnD2 = new JRadioButton("D"); mtGameButtonGroup2.add(mtGameRdBtnD2); mtGameRdBtnD2.setFont(new Font("Chiller", Font.BOLD, 20)); mtGameRdBtnD2.setBounds(514, 80, 42, 23); mtGameChoicesInternalPanel.add(mtGameRdBtnD2); JRadioButton mtGameRdBtnA3 = new JRadioButton("A"); mtGameButtonGroup3.add(mtGameRdBtnA3); mtGameRdBtnA3.setFont(new Font("Chiller", Font.BOLD, 20)); mtGameRdBtnA3.setBounds(301, 120, 42, 23); mtGameChoicesInternalPanel.add(mtGameRdBtnA3); JRadioButton mtGameRdBtnB3 = new JRadioButton("B"); mtGameButtonGroup3.add(mtGameRdBtnB3); mtGameRdBtnB3.setFont(new Font("Chiller", Font.BOLD, 20)); mtGameRdBtnB3.setBounds(372, 120, 42, 23); mtGameChoicesInternalPanel.add(mtGameRdBtnB3); JRadioButton mtGameRdBtnC3 = new JRadioButton("C"); mtGameButtonGroup3.add(mtGameRdBtnC3); mtGameRdBtnC3.setFont(new Font("Chiller", Font.BOLD, 20)); mtGameRdBtnC3.setBounds(443, 120, 42, 23); mtGameChoicesInternalPanel.add(mtGameRdBtnC3); JRadioButton mtGameRdBtnD3 = new JRadioButton("D"); mtGameButtonGroup3.add(mtGameRdBtnD3); mtGameRdBtnD3.setFont(new Font("Chiller", Font.BOLD, 20)); mtGameRdBtnD3.setBounds(514, 120, 42, 23); mtGameChoicesInternalPanel.add(mtGameRdBtnD3); JRadioButton mtGameRdBtnA4 = new JRadioButton("A"); mtGameButtonGroup4.add(mtGameRdBtnA4); mtGameRdBtnA4.setFont(new Font("Chiller", Font.BOLD, 20)); mtGameRdBtnA4.setBounds(301, 160, 42, 23); mtGameChoicesInternalPanel.add(mtGameRdBtnA4); JRadioButton mtGameRdBtnB4 = new JRadioButton("B"); mtGameButtonGroup4.add(mtGameRdBtnB4); mtGameRdBtnB4.setFont(new Font("Chiller", Font.BOLD, 20)); mtGameRdBtnB4.setBounds(372, 160, 42, 23); mtGameChoicesInternalPanel.add(mtGameRdBtnB4); JRadioButton mtGameRdBtnC4 = new JRadioButton("C"); mtGameButtonGroup4.add(mtGameRdBtnC4); mtGameRdBtnC4.setFont(new Font("Chiller", Font.BOLD, 20)); mtGameRdBtnC4.setBounds(443, 160, 42, 23); mtGameChoicesInternalPanel.add(mtGameRdBtnC4); JRadioButton mtGameRdBtnD4 = new JRadioButton("D"); mtGameButtonGroup4.add(mtGameRdBtnD4); mtGameRdBtnD4.setFont(new Font("Chiller", Font.BOLD, 20)); mtGameRdBtnD4.setBounds(514, 160, 42, 23); mtGameChoicesInternalPanel.add(mtGameRdBtnD4); JButton mtGameBtnShowAns = new JButton("Show Answer"); mtGameBtnShowAns.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { JOptionPane.showMessageDialog(null, match_game.Questions.get(0).AnswerA.get(0)+" "+match_game.Questions.get(0).AnswerB.get(0)+"\n"+ match_game.Questions.get(0).AnswerA.get(1)+" "+match_game.Questions.get(0).AnswerB.get(1)+"\n"+ match_game.Questions.get(0).AnswerA.get(2)+" "+match_game.Questions.get(0).AnswerB.get(2)+"\n"+ match_game.Questions.get(0).AnswerA.get(3)+" "+match_game.Questions.get(0).AnswerB.get(3)+"\n"); MatchCnt++; if(MatchCnt==match_game.GetQuestions().size()) { JOptionPane.showMessageDialog(null, "ConGraTulationsssssSSsSSssSss"); mtGamePanel.setVisible(false); playGamePanel.setVisible(true); } else { mtGameRightATxtField.setText(match_game.Questions.get(MatchCnt).GetQuestionA().get(0)); mtGameRightBTxtField.setText(match_game.Questions.get(MatchCnt).GetQuestionA().get(1)); mtGameRightCTxtField.setText(match_game.Questions.get(MatchCnt).GetQuestionA().get(2)); mtGameRightDTxtField.setText(match_game.Questions.get(MatchCnt).GetQuestionA().get(3)); mtGameLeft1TxtField.setText(match_game.Questions.get(MatchCnt).QuestionB.get(0)); mtGameLeft2TxtField.setText(match_game.Questions.get(MatchCnt).QuestionB.get(1)); mtGameLeft3TxtField.setText(match_game.Questions.get(MatchCnt).QuestionB.get(2)); mtGameLeft4TxtField.setText(match_game.Questions.get(MatchCnt).QuestionB.get(3)); } } }); mtGameBtnShowAns.setEnabled(false); mtGameBtnShowAns.setFont(new Font("Chiller", Font.BOLD, 20)); mtGameBtnShowAns.setBounds(430, 394, 140, 38); mtGamePanel.add(mtGameBtnShowAns); JButton mtGameBtnNextQues = new JButton("Next Question"); mtGameBtnNextQues.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String a ="",b="",c="",d=""; Enumeration<AbstractButton> buto = mtGameButtonGroup1.getElements(); while(buto.hasMoreElements()) { JRadioButton jrd = (JRadioButton) buto.nextElement(); if(jrd.isSelected()){ a = jrd.getText(); } } Enumeration<AbstractButton> buto1 = mtGameButtonGroup2.getElements(); while(buto1.hasMoreElements()) { JRadioButton jrd = (JRadioButton) buto1.nextElement(); if(jrd.isSelected()){ b = jrd.getText(); } } Enumeration<AbstractButton> buto2 = mtGameButtonGroup3.getElements(); while(buto2.hasMoreElements()) { JRadioButton jrd = (JRadioButton) buto2.nextElement(); if(jrd.isSelected()){ c = jrd.getText(); } } Enumeration<AbstractButton> buto3 = mtGameButtonGroup4.getElements(); while(buto3.hasMoreElements()) { JRadioButton jrd = (JRadioButton) buto3.nextElement(); if(jrd.isSelected()){ d = jrd.getText(); } } int x=a.charAt(0)-65; String A=match_game.Questions.get(MatchCnt).QuestionB.get(x); x=b.charAt(0)-65; String B=match_game.Questions.get(MatchCnt).QuestionB.get(x); x=c.charAt(0)-65; String C=match_game.Questions.get(MatchCnt).QuestionB.get(x); x=d.charAt(0)-65; String D=match_game.Questions.get(MatchCnt).QuestionB.get(x); if((match_game.Questions.get(MatchCnt).AnswerA.get(0).equals(A))&&(match_game.Questions.get(MatchCnt).AnswerA.get(1).equals(B)) &&((match_game.Questions.get(MatchCnt).AnswerA.get(2).equals(C)))&&((match_game.Questions.get(MatchCnt).AnswerA.get(3).equals(D)))) { JOptionPane.showMessageDialog(null, "Correct Answer"); MatchCnt++; if(MatchCnt==match_game.GetQuestions().size()) { JOptionPane.showMessageDialog(null, "ConGraTulationsssssSSsSSssSss"); mtGamePanel.setVisible(false); playGamePanel.setVisible(true); } else { mtGameRightATxtField.setText(match_game.Questions.get(MatchCnt).GetQuestionA().get(0)); mtGameRightBTxtField.setText(match_game.Questions.get(MatchCnt).GetQuestionA().get(1)); mtGameRightCTxtField.setText(match_game.Questions.get(MatchCnt).GetQuestionA().get(2)); mtGameRightDTxtField.setText(match_game.Questions.get(MatchCnt).GetQuestionA().get(3)); mtGameLeft1TxtField.setText(match_game.Questions.get(MatchCnt).QuestionB.get(0)); mtGameLeft2TxtField.setText(match_game.Questions.get(MatchCnt).QuestionB.get(1)); mtGameLeft3TxtField.setText(match_game.Questions.get(MatchCnt).QuestionB.get(2)); mtGameLeft4TxtField.setText(match_game.Questions.get(MatchCnt).QuestionB.get(3)); } } else { JOptionPane.showMessageDialog(null, "Wrong Answer"); } } }); mtGameBtnNextQues.setEnabled(false); mtGameBtnNextQues.setFont(new Font("Chiller", Font.BOLD, 20)); mtGameBtnNextQues.setBounds(580, 394, 140, 38); mtGamePanel.add(mtGameBtnNextQues); mtGameRightATxtField = new JTextField(); mtGameRightATxtField.setColumns(10); mtGameRightATxtField.setBounds(45, 110, 260, 20); mtGamePanel.add(mtGameRightATxtField); JLabel lblB = new JLabel("B"); lblB.setFont(new Font("Chiller", Font.BOLD, 20)); lblB.setBounds(10, 152, 20, 24); mtGamePanel.add(lblB); mtGameRightBTxtField = new JTextField(); mtGameRightBTxtField.setColumns(10); mtGameRightBTxtField.setBounds(45, 155, 260, 20); mtGamePanel.add(mtGameRightBTxtField); JLabel lblC = new JLabel("C"); lblC.setFont(new Font("Chiller", Font.BOLD, 20)); lblC.setBounds(364, 107, 20, 24); mtGamePanel.add(lblC); JLabel lblD = new JLabel("D"); lblD.setFont(new Font("Chiller", Font.BOLD, 20)); lblD.setBounds(364, 152, 20, 24); mtGamePanel.add(lblD); mtGameRightCTxtField = new JTextField(); mtGameRightCTxtField.setColumns(10); mtGameRightCTxtField.setBounds(394, 110, 260, 20); mtGamePanel.add(mtGameRightCTxtField); mtGameRightDTxtField = new JTextField(); mtGameRightDTxtField.setColumns(10); mtGameRightDTxtField.setBounds(394, 156, 260, 20); mtGamePanel.add(mtGameRightDTxtField); JButton mtGameBtnStartGame = new JButton("Start Game"); mtGameBtnStartGame.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { MatchCnt=0; mtGameBtnStartGame.setEnabled(false); mtGameBtnNextQues.setEnabled(true); mtGameBtnShowAns.setEnabled(true); mtGameRightATxtField.setText(match_game.Questions.get(0).GetQuestionA().get(0)); mtGameRightBTxtField.setText(match_game.Questions.get(0).GetQuestionA().get(1)); mtGameRightCTxtField.setText(match_game.Questions.get(0).GetQuestionA().get(2)); mtGameRightDTxtField.setText(match_game.Questions.get(0).GetQuestionA().get(3)); mtGameLeft1TxtField.setText(match_game.Questions.get(0).QuestionB.get(0)); mtGameLeft2TxtField.setText(match_game.Questions.get(0).QuestionB.get(1)); mtGameLeft3TxtField.setText(match_game.Questions.get(0).QuestionB.get(2)); mtGameLeft4TxtField.setText(match_game.Questions.get(0).QuestionB.get(3)); } }); mtGameBtnStartGame.setFont(new Font("Chiller", Font.BOLD, 20)); mtGameBtnStartGame.setBounds(280, 394, 140, 38); mtGamePanel.add(mtGameBtnStartGame); JButton button_4 = new JButton("Profile"); button_4.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(theAccount.isType()) { mtGamePanel.setVisible(false); sProfilePanel.setVisible(true); } else { mtGamePanel.setVisible(false); tProfilePanel.setVisible(true); } } }); button_4.setFont(new Font("Chiller", Font.BOLD, 20)); button_4.setBounds(0, 0, 88, 45); mtGamePanel.add(button_4); JPanel mcqTmpPanel = new JPanel(); frm_CreategGame.getContentPane().add(mcqTmpPanel, "name_21338434580942"); mcqTmpPanel.setLayout(null); mcqTmpPanel.setVisible(false); JPanel t_fTmpPanel = new JPanel(); frm_CreategGame.getContentPane().add(t_fTmpPanel, "name_15292477849874"); t_fTmpPanel.setLayout(null); t_fTmpPanel.setVisible(false); JPanel mtTmpPanel = new JPanel(); frm_CreategGame.getContentPane().add(mtTmpPanel, "name_14470309516722"); mtTmpPanel.setLayout(null); mtTmpPanel.setVisible(false); registerNameTxtField = new JTextField(); registerNameTxtField.setColumns(10); registerNameTxtField.setBounds(20, 166, 226, 37); registerPanel.add(registerNameTxtField); registerUserNameTxtField = new JTextField(); registerUserNameTxtField.setColumns(10); registerUserNameTxtField.setBounds(20, 262, 226, 37); registerPanel.add(registerUserNameTxtField); JLabel label_21 = new JLabel("Name"); label_21.setFont(new Font("Chiller", Font.BOLD, 30)); label_21.setBounds(20, 97, 106, 58); registerPanel.add(label_21); JLabel label_22 = new JLabel("Username"); label_22.setFont(new Font("Chiller", Font.BOLD, 30)); label_22.setBounds(20, 214, 116, 37); registerPanel.add(label_22); JLabel label_23 = new JLabel("Age"); label_23.setFont(new Font("Chiller", Font.BOLD, 30)); label_23.setBounds(596, 104, 80, 51); registerPanel.add(label_23); JLabel label_24 = new JLabel("Password"); label_24.setFont(new Font("Chiller", Font.BOLD, 30)); label_24.setBounds(595, 207, 129, 51); registerPanel.add(label_24); JLabel label_25 = new JLabel("Email"); label_25.setFont(new Font("Chiller", Font.BOLD, 30)); label_25.setBounds(20, 309, 80, 51); registerPanel.add(label_25); JLabel label_26 = new JLabel("Register"); label_26.setFont(new Font("Chiller", Font.BOLD, 40)); label_26.setBounds(314, 11, 178, 73); registerPanel.add(label_26); JLabel label_27 = new JLabel("Confirm password"); label_27.setFont(new Font("Chiller", Font.BOLD, 30)); label_27.setBounds(596, 309, 226, 51); registerPanel.add(label_27); JFormattedTextField registerAgeformattedTxtField = new JFormattedTextField(); registerAgeformattedTxtField.setBounds(595, 166, 227, 37); registerPanel.add(registerAgeformattedTxtField); JPanel registerTypeInternalPanel = new JPanel(); registerTypeInternalPanel.setLayout(null); registerTypeInternalPanel.setBorder(new TitledBorder(null, "Type", TitledBorder.LEADING, TitledBorder.TOP, null, null)); registerTypeInternalPanel.setBounds(314, 166, 185, 100); registerPanel.add(registerTypeInternalPanel); JRadioButton registerRdBtnTeacher = new JRadioButton("Teacher"); registerTypeButtonGroup.add(registerRdBtnTeacher); registerRdBtnTeacher.setBounds(12, 22, 121, 23); registerTypeInternalPanel.add(registerRdBtnTeacher); JRadioButton registerRdBtnStudent = new JRadioButton("Student"); registerTypeButtonGroup.add(registerRdBtnStudent); registerRdBtnStudent.setSelected(true); registerRdBtnStudent.setBounds(12, 51, 121, 23); registerTypeInternalPanel.add(registerRdBtnStudent); JButton button = new JButton("Submit"); button.setFont(new Font("Chiller", Font.BOLD, 30)); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String type ="",gender=""; Enumeration<AbstractButton> buto = registerTypeButtonGroup.getElements(); while(buto.hasMoreElements()) { JRadioButton jrd = (JRadioButton) buto.nextElement(); if(jrd.isSelected()){ type = jrd.getText(); } } Enumeration<AbstractButton> buto2 = registerGenderButtonGroup.getElements(); while(buto2.hasMoreElements()) { JRadioButton jrd = (JRadioButton) buto2.nextElement(); if(jrd.isSelected()){ gender = jrd.getText(); } } //System.out.println(gender + " " + type); if(registerEmailTxtField.getText().isEmpty() || registerUserNameTxtField.getText().isEmpty()||registerAgeformattedTxtField.getText().isEmpty() ||registerPasswordTxtField.getText().isEmpty() || registerConfirmPasswordTxtField.getText().isEmpty()||registerNameTxtField.getText().isEmpty() ){ JOptionPane.showMessageDialog(null, "Please enter the data needed"); }else if(!registerPasswordTxtField.getText().equals(registerConfirmPasswordTxtField.getText())){ JOptionPane.showMessageDialog(null, "The password doesn't match"); } else{ if(type.equals("Teacher")){ theAccount = new Teacher(); theAccount.setType(false); }else{ theAccount = new Student(); theAccount.setType(true); } //tmp.setAga(); theAccount.setName(registerNameTxtField.getText()); theAccount.setPassword(registerPasswordTxtField.getText()); theAccount.setUsername(registerUserNameTxtField.getText()); theAccount.setEmail(registerEmailTxtField.getText()); theAccount.setGender(gender.charAt(0)); int t = Integer.parseInt(registerAgeformattedTxtField.getText()); theAccount.setAga(t); if(control.ValidateData(theAccount)){ if(type.equals("Student")) { registerNameTxtField.setText(""); registerPasswordTxtField.setText(""); registerUserNameTxtField.setText(""); registerEmailTxtField.setText(""); registerPanel.setVisible(false); sProfilePanel.setVisible(true); } else { registerNameTxtField.setText(""); registerPasswordTxtField.setText(""); registerUserNameTxtField.setText(""); registerEmailTxtField.setText(""); registerPanel.setVisible(false); tProfilePanel.setVisible(true); } }else{ JOptionPane.showMessageDialog(null, "Email is wrong OR Username exits"); } } } }); button.setBounds(348, 413, 129, 47); registerPanel.add(button); registerEmailTxtField = new JTextField(); registerEmailTxtField.setColumns(10); registerEmailTxtField.setBounds(20, 371, 226, 37); registerPanel.add(registerEmailTxtField); registerPasswordTxtField = new JPasswordField(); registerPasswordTxtField.setBounds(596, 270, 226, 37); registerPanel.add(registerPasswordTxtField); registerConfirmPasswordTxtField = new JPasswordField(); registerConfirmPasswordTxtField.setBounds(596, 371, 226, 37); registerPanel.add(registerConfirmPasswordTxtField); JPanel registerGenderInternalPanel = new JPanel(); registerGenderInternalPanel.setLayout(null); registerGenderInternalPanel.setBorder(new TitledBorder(null, "Gender", TitledBorder.LEADING, TitledBorder.TOP, null, null)); registerGenderInternalPanel.setBounds(314, 273, 185, 100); registerPanel.add(registerGenderInternalPanel); JRadioButton registerRdBtnMale = new JRadioButton("M"); registerGenderButtonGroup.add(registerRdBtnMale); registerRdBtnMale.setSelected(true); registerRdBtnMale.setBounds(6, 19, 109, 23); registerGenderInternalPanel.add(registerRdBtnMale); JRadioButton registerRdBtnFemale = new JRadioButton("F"); registerGenderButtonGroup.add(registerRdBtnFemale); registerRdBtnFemale.setBounds(6, 48, 109, 23); registerGenderInternalPanel.add(registerRdBtnFemale); JButton loginBtnLogin = new JButton("Login"); loginBtnLogin.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(control.VallidLogin(loginUsernameTxtField.getText(), loginPasswordTxtField.getText())){ if(control.CheckType(loginUsernameTxtField.getText())){ theAccount = control.getAccount(loginUsernameTxtField.getText()); loginPanel.setVisible(false); sProfilePanel.setVisible(true); }else{ theAccount = control.getAccount(loginUsernameTxtField.getText()); loginPanel.setVisible(false); tProfilePanel.setVisible(true); } }else{ JOptionPane.showMessageDialog(null, "Wrong Username or Password "); } } }); loginBtnLogin.setFont(new Font("Chiller", Font.BOLD, 40)); loginBtnLogin.setBounds(309, 317, 186, 69); loginPanel.add(loginBtnLogin); loginPasswordTxtField = new JPasswordField(); loginPasswordTxtField.setFont(new Font("Chiller", Font.PLAIN, 18)); loginPasswordTxtField.setBounds(189, 233, 201, 31); loginPanel.add(loginPasswordTxtField); JLabel label_19 = new JLabel("Password :"); label_19.setFont(new Font("Chiller", Font.BOLD, 30)); label_19.setBounds(31, 223, 148, 54); loginPanel.add(label_19); JLabel label_20 = new JLabel("Username :"); label_20.setFont(new Font("Chiller", Font.BOLD, 30)); label_20.setBounds(31, 112, 148, 44); loginPanel.add(label_20); loginUsernameTxtField = new JTextField(); loginUsernameTxtField.setFont(new Font("Chiller", Font.PLAIN, 18)); loginUsernameTxtField.setColumns(10); loginUsernameTxtField.setBounds(189, 112, 201, 31); loginPanel.add(loginUsernameTxtField); JButton btnHome = new JButton("Home"); btnHome.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { loginPanel.setVisible(false); homePanel.setVisible(true); } }); btnHome.setFont(new Font("Chiller", Font.BOLD, 20)); btnHome.setBounds(0, 0, 88, 45); loginPanel.add(btnHome); JLabel lblLogin = new JLabel("Login"); lblLogin.setFont(new Font("Chiller", Font.BOLD, 40)); lblLogin.setBounds(332, 0, 79, 77); loginPanel.add(lblLogin); JButton sProfileBtnPlayGame = new JButton("Play Game"); sProfileBtnPlayGame.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { sProfilePanel.setVisible(false); playGamePanel.setVisible(true); } }); sProfileBtnPlayGame.setFont(new Font("Chiller", Font.BOLD, 40)); sProfileBtnPlayGame.setBounds(224, 237, 305, 61); sProfilePanel.add(sProfileBtnPlayGame); JLabel label_28 = new JLabel("Student Profile"); label_28.setFont(new Font("Chiller", Font.BOLD, 40)); label_28.setBounds(272, 75, 215, 61); sProfilePanel.add(label_28); JButton sProfileBtnLogout = new JButton("Log Out"); sProfileBtnLogout.setFont(new Font("Chiller", Font.BOLD, 18)); sProfileBtnLogout.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { theAccount = new Account(); sProfilePanel.setVisible(false); homePanel.setVisible(true); } }); sProfileBtnLogout.setBounds(0, 0, 104, 34); sProfilePanel.add(sProfileBtnLogout); JButton tProfileBtnPlayGame = new JButton("Play Game"); tProfileBtnPlayGame.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { tProfilePanel.setVisible(false); playGamePanel.setVisible(true); } }); tProfileBtnPlayGame.setFont(new Font("Chiller", Font.BOLD, 40)); tProfileBtnPlayGame.setBounds(222, 311, 305, 61); tProfilePanel.add(tProfileBtnPlayGame); JButton tProfileBtnAddGame = new JButton("Add Game"); tProfileBtnAddGame.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { tProfilePanel.setVisible(false); createGamePanel.setVisible(true); } }); tProfileBtnAddGame.setFont(new Font("Chiller", Font.BOLD, 40)); tProfileBtnAddGame.setBounds(222, 190, 305, 61); tProfilePanel.add(tProfileBtnAddGame); JLabel label_29 = new JLabel("Teacher Profile"); label_29.setFont(new Font("Chiller", Font.BOLD, 40)); label_29.setBounds(270, 62, 215, 61); tProfilePanel.add(label_29); JButton tProfileBtnLogout = new JButton("Log Out"); tProfileBtnLogout.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { theAccount = new Account(); tProfilePanel.setVisible(false); homePanel.setVisible(true); } }); tProfileBtnLogout.setFont(new Font("Chiller", Font.BOLD, 18)); tProfileBtnLogout.setBounds(0, 0, 104, 34); tProfilePanel.add(tProfileBtnLogout); JLabel lblNewLabel_7 = new JLabel("Game Subject"); lblNewLabel_7.setBounds(10, 178, 142, 36); lblNewLabel_7.setFont(new Font("Chiller", Font.BOLD, 30)); createGamePanel.add(lblNewLabel_7); JPanel createGameGameTypeInternalPanel = new JPanel(); createGameGameTypeInternalPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Game Type", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0))); createGameGameTypeInternalPanel.setBounds(13, 234, 599, 117); createGamePanel.add(createGameGameTypeInternalPanel); createGameGameTypeInternalPanel.setLayout(null); JRadioButton createGameRdBtnMcq = new JRadioButton("MCQ"); createGameRdBtnMcq.setSelected(true); createGameGameTypebuttonGroup.add(createGameRdBtnMcq); createGameRdBtnMcq.setBounds(20, 36, 111, 25); createGameGameTypeInternalPanel.add(createGameRdBtnMcq); JRadioButton createGameRdBtnMatch = new JRadioButton("Match"); createGameGameTypebuttonGroup.add(createGameRdBtnMatch); createGameRdBtnMatch.setBounds(20, 64, 111, 25); createGameGameTypeInternalPanel.add(createGameRdBtnMatch); JRadioButton createGameRdBtnT_F = new JRadioButton("T/F"); createGameGameTypebuttonGroup.add(createGameRdBtnT_F); createGameRdBtnT_F.setBounds(20, 87, 111, 25); createGameGameTypeInternalPanel.add(createGameRdBtnT_F); JButton createGameBtnCreateGame = new JButton("Create Game"); createGameBtnCreateGame.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String type =""; Enumeration<AbstractButton> buto = createGameGameTypebuttonGroup.getElements(); while(buto.hasMoreElements()) { JRadioButton jrd = (JRadioButton) buto.nextElement(); if(jrd.isSelected()){ type = jrd.getText(); } } if( createGameGameSubjectTxtField.getText().isEmpty() || createGameGameNameTxtField.getText().isEmpty() ) { JOptionPane.showMessageDialog(null, "Please enter all the data"); return; } if(control.checkGameName(createGameGameNameTxtField.getText())){ JOptionPane.showMessageDialog(null, "Name already exits"); return; } Subject = createGameGameSubjectTxtField.getText(); Name = createGameGameNameTxtField.getText(); createGameGameSubjectTxtField.setText(""); createGameGameNameTxtField.setText(""); if(type.equals("MCQ")) { mcqTmpPanel.setVisible(true); createGamePanel.setVisible(false); } else if(type.equals("Match")) { mtTmpPanel.setVisible(true); createGamePanel.setVisible(false); } else if(type.equals("T/F")) { t_fTmpPanel.setVisible(true); createGamePanel.setVisible(false); } } }); createGameBtnCreateGame.setFont(new Font("Chiller", Font.BOLD, 30)); createGameBtnCreateGame.setBounds(617, 371, 170, 57); createGamePanel.add(createGameBtnCreateGame); JLabel lblNewLabel_8 = new JLabel("Create Game"); lblNewLabel_8.setFont(new Font("Chiller", Font.BOLD, 40)); lblNewLabel_8.setBounds(279, 11, 192, 77); createGamePanel.add(lblNewLabel_8); JLabel lblGameName = new JLabel("Game Name"); lblGameName.setFont(new Font("Chiller", Font.BOLD, 30)); lblGameName.setBounds(10, 110, 142, 36); createGamePanel.add(lblGameName); createGameGameNameTxtField = new JTextField(); createGameGameNameTxtField.setColumns(10); createGameGameNameTxtField.setBounds(183, 119, 424, 27); createGamePanel.add(createGameGameNameTxtField); createGameGameSubjectTxtField = new JTextField(); createGameGameSubjectTxtField.setColumns(10); createGameGameSubjectTxtField.setBounds(183, 187, 424, 27); createGamePanel.add(createGameGameSubjectTxtField); JButton btnProfile = new JButton("Profile"); btnProfile.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(theAccount.isType()) { createGamePanel.setVisible(false); sProfilePanel.setVisible(true); } else { createGamePanel.setVisible(false); tProfilePanel.setVisible(true); } } }); btnProfile.setFont(new Font("Chiller", Font.BOLD, 20)); btnProfile.setBounds(0, 0, 88, 45); createGamePanel.add(btnProfile); JLabel label_33 = new JLabel("T or F Game"); label_33.setFont(new Font("Chiller", Font.BOLD, 40)); label_33.setBounds(299, 11, 187, 61); t_fGamePanel.add(label_33); JLabel label_34 = new JLabel("Question"); label_34.setFont(new Font("Chiller", Font.BOLD, 40)); label_34.setBounds(10, 102, 131, 47); t_fGamePanel.add(label_34); t_fGameQuesTxtField = new JTextField(); t_fGameQuesTxtField.setFont(new Font("Arial", Font.PLAIN, 20)); t_fGameQuesTxtField.setColumns(10); t_fGameQuesTxtField.setBounds(169, 102, 586, 44); t_fGamePanel.add(t_fGameQuesTxtField); JPanel t_fGameChoicesInternalPanel = new JPanel(); t_fGameChoicesInternalPanel.setLayout(null); t_fGameChoicesInternalPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "True or False", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0))); t_fGameChoicesInternalPanel.setBounds(10, 180, 745, 118); t_fGamePanel.add(t_fGameChoicesInternalPanel); JRadioButton t_fGameRdBtnTrue = new JRadioButton("True"); t_fGameButtonGroup.add(t_fGameRdBtnTrue); t_fGameRdBtnTrue.setSelected(true); t_fGameRdBtnTrue.setBounds(6, 36, 227, 23); t_fGameChoicesInternalPanel.add(t_fGameRdBtnTrue); JRadioButton t_fGameRdBtnFalse = new JRadioButton("False"); t_fGameButtonGroup.add(t_fGameRdBtnFalse); t_fGameRdBtnFalse.setBounds(6, 72, 227, 23); t_fGameChoicesInternalPanel.add(t_fGameRdBtnFalse); JButton t_fGameBtnSubmitAns = new JButton("Submit Answer"); t_fGameBtnSubmitAns.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String type =""; Enumeration<AbstractButton> buto = t_fGameButtonGroup.getElements(); while(buto.hasMoreElements()) { JRadioButton jrd = (JRadioButton) buto.nextElement(); if(jrd.isSelected()){ type = jrd.getText(); } } String ans = tfGame.Questions.get(T_FCnt).GetAnswer(); if(type.equals(ans)){ JOptionPane.showMessageDialog(null, "Correct Answer"); } else { JOptionPane.showMessageDialog(null, "Wrong Answer"); } T_FCnt++; if(T_FCnt==tfGame.Questions.size()) { JOptionPane.showMessageDialog(null, "Congratulation"); t_fGamePanel.setVisible(false); playGamePanel.setVisible(true); } t_fGameQuesTxtField.setText(tfGame.Questions.get(T_FCnt).GetQuestion()); } }); t_fGameBtnSubmitAns.setEnabled(false); t_fGameBtnSubmitAns.setFont(new Font("Chiller", Font.BOLD, 20)); t_fGameBtnSubmitAns.setBounds(615, 309, 140, 38); t_fGamePanel.add(t_fGameBtnSubmitAns); JButton t_fGameBtnShowAns = new JButton("Show Answer"); t_fGameBtnShowAns.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, tfGame.Questions.get(T_FCnt).GetAnswer()); T_FCnt++; if(T_FCnt==tfGame.Questions.size()) { JOptionPane.showMessageDialog(null, "Congratulation"); t_fGamePanel.setVisible(false); playGamePanel.setVisible(true); } t_fGameQuesTxtField.setText(tfGame.Questions.get(T_FCnt).GetQuestion()); } }); t_fGameBtnShowAns.setEnabled(false); t_fGameBtnShowAns.setFont(new Font("Chiller", Font.BOLD, 20)); t_fGameBtnShowAns.setBounds(465, 309, 140, 38); t_fGamePanel.add(t_fGameBtnShowAns); JButton t_fGameBtnStartGame = new JButton("Start Game"); t_fGameBtnStartGame.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { T_FCnt=0; t_fGameBtnStartGame.setEnabled(false); t_fGameQuesTxtField.setText(tfGame.Questions.get(0).GetQuestion()); t_fGameBtnShowAns.setEnabled(true); t_fGameBtnSubmitAns.setEnabled(true); } }); t_fGameBtnStartGame.setFont(new Font("Chiller", Font.BOLD, 20)); t_fGameBtnStartGame.setBounds(315, 309, 140, 38); t_fGamePanel.add(t_fGameBtnStartGame); JButton button_3 = new JButton("Profile"); button_3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(theAccount.isType()) { t_fGamePanel.setVisible(false); sProfilePanel.setVisible(true); } else { t_fGamePanel.setVisible(false); tProfilePanel.setVisible(true); } } }); button_3.setFont(new Font("Chiller", Font.BOLD, 20)); button_3.setBounds(0, 0, 88, 45); t_fGamePanel.add(button_3); JLabel label_16 = new JLabel("T or F Questions Template"); label_16.setFont(new Font("Chiller", Font.BOLD, 40)); label_16.setBounds(222, 54, 369, 61); t_fTmpPanel.add(label_16); JLabel label_17 = new JLabel("Question"); label_17.setFont(new Font("Chiller", Font.BOLD, 40)); label_17.setBounds(50, 194, 131, 47); t_fTmpPanel.add(label_17); t_fTmpQuesTxtField = new JTextField(); t_fTmpQuesTxtField.setColumns(10); t_fTmpQuesTxtField.setBounds(273, 194, 459, 44); t_fTmpPanel.add(t_fTmpQuesTxtField); JLabel label_18 = new JLabel("Correct Answer"); label_18.setFont(new Font("Chiller", Font.BOLD, 40)); label_18.setBounds(48, 288, 213, 37); t_fTmpPanel.add(label_18); t_fTmpAnsTxtField = new JTextField(); t_fTmpAnsTxtField.setColumns(10); t_fTmpAnsTxtField.setBounds(273, 281, 459, 44); t_fTmpPanel.add(t_fTmpAnsTxtField); JButton t_fTmpBtnAddQ = new JButton("Add Question"); t_fTmpBtnAddQ.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(t_fTmpQuesTxtField.getText().isEmpty() || t_fTmpAnsTxtField.getText().isEmpty()){ JOptionPane.showMessageDialog(null, "Please enter all the data "); }else{ T_FQuestion t = new T_FQuestion(t_fTmpQuesTxtField.getText(), t_fTmpAnsTxtField.getText()); tfGame.AddQuestion(t); t_fTmpQuesTxtField.setText(""); t_fTmpAnsTxtField.setText(""); } } }); t_fTmpBtnAddQ.setFont(new Font("Chiller", Font.BOLD, 30)); t_fTmpBtnAddQ.setBounds(308, 395, 181, 38); t_fTmpPanel.add(t_fTmpBtnAddQ); JButton t_fTmpBtnAddQSubmit = new JButton("Submit Game"); t_fTmpBtnAddQSubmit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { tfGame.setName(Name); tfGame.setSubject(Subject); control.AddGame(tfGame); //Vector<Game> tmp = control.GetAllGame(0, Subject); t_fTmpPanel.setVisible(false); tProfilePanel.setVisible(true); } }); t_fTmpBtnAddQSubmit.setFont(new Font("Chiller", Font.BOLD, 30)); t_fTmpBtnAddQSubmit.setBounds(516, 395, 182, 38); t_fTmpPanel.add(t_fTmpBtnAddQSubmit); JButton button_6 = new JButton("Profile"); button_6.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(theAccount.isType()) { t_fTmpPanel.setVisible(false); sProfilePanel.setVisible(true); } else { t_fTmpPanel.setVisible(false); tProfilePanel.setVisible(true); } } }); button_6.setFont(new Font("Chiller", Font.BOLD, 20)); button_6.setBounds(0, 0, 88, 45); t_fTmpPanel.add(button_6); mcqTmpQuesTxtField = new JTextField(); mcqTmpQuesTxtField.setBounds(141, 114, 436, 32); mcqTmpPanel.add(mcqTmpQuesTxtField); mcqTmpQuesTxtField.setColumns(10); mcqTmpCho1TxtField = new JTextField(); mcqTmpCho1TxtField.setBounds(141, 191, 250, 20); mcqTmpPanel.add(mcqTmpCho1TxtField); mcqTmpCho1TxtField.setColumns(10); mcqTmpCho2TxtField = new JTextField(); mcqTmpCho2TxtField.setBounds(544, 191, 250, 20); mcqTmpPanel.add(mcqTmpCho2TxtField); mcqTmpCho2TxtField.setColumns(10); mcqTmpCho3TxtField = new JTextField(); mcqTmpCho3TxtField.setBounds(141, 256, 250, 20); mcqTmpPanel.add(mcqTmpCho3TxtField); mcqTmpCho3TxtField.setColumns(10); mcqTmpCho4TxtField = new JTextField(); mcqTmpCho4TxtField.setBounds(544, 256, 250, 20); mcqTmpPanel.add(mcqTmpCho4TxtField); mcqTmpCho4TxtField.setColumns(10); mcqTmpAnsTxtField = new JTextField(); mcqTmpAnsTxtField.setBounds(255, 337, 279, 38); mcqTmpPanel.add(mcqTmpAnsTxtField); mcqTmpAnsTxtField.setColumns(10); JLabel lblNewLabel = new JLabel("Question"); lblNewLabel.setBounds(10, 114, 109, 32); mcqTmpPanel.add(lblNewLabel); lblNewLabel.setFont(new Font("Chiller", Font.BOLD, 30)); JLabel lblNewLabel_1 = new JLabel("Choice 1"); lblNewLabel_1.setBounds(10, 177, 109, 42); mcqTmpPanel.add(lblNewLabel_1); lblNewLabel_1.setFont(new Font("Chiller", Font.BOLD, 25)); JLabel lblNewLabel_2 = new JLabel("Choice 2"); lblNewLabel_2.setBounds(425, 177, 109, 42); mcqTmpPanel.add(lblNewLabel_2); lblNewLabel_2.setFont(new Font("Chiller", Font.BOLD, 25)); JLabel lblNewLabel_3 = new JLabel("Choice 3"); lblNewLabel_3.setBounds(10, 247, 109, 32); mcqTmpPanel.add(lblNewLabel_3); lblNewLabel_3.setFont(new Font("Chiller", Font.BOLD, 25)); JLabel lblNewLabel_4 = new JLabel("Choice 4"); lblNewLabel_4.setBounds(425, 247, 109, 32); mcqTmpPanel.add(lblNewLabel_4); lblNewLabel_4.setFont(new Font("Chiller", Font.BOLD, 25)); JLabel lblNewLabel_5 = new JLabel("Correct Answer"); lblNewLabel_5.setBounds(10, 330, 279, 38); mcqTmpPanel.add(lblNewLabel_5); lblNewLabel_5.setFont(new Font("Chiller", Font.BOLD, 40)); JLabel lblNewLabel_6 = new JLabel("MCQ Questions Template"); lblNewLabel_6.setBounds(220, 7, 357, 80); mcqTmpPanel.add(lblNewLabel_6); lblNewLabel_6.setFont(new Font("Chiller", Font.BOLD, 40)); JButton mcqTmpBtnAddQ = new JButton("Add Question"); mcqTmpBtnAddQ.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String[] choc = new String[4]; String qq = mcqTmpQuesTxtField.getText(); choc[0] = mcqTmpCho1TxtField.getText(); choc[1] = mcqTmpCho2TxtField.getText(); choc[2] = mcqTmpCho3TxtField.getText(); choc[3] = mcqTmpCho4TxtField.getText(); String aa = mcqTmpAnsTxtField.getText(); MCQ_Question q = new MCQ_Question(qq, aa, choc); if(mcqTmpQuesTxtField.getText().isEmpty() || mcqTmpCho1TxtField.getText().isEmpty()|| mcqTmpCho2TxtField.getText().isEmpty()||mcqTmpCho3TxtField.getText().isEmpty()|| mcqTmpCho4TxtField.getText().isEmpty()||mcqTmpAnsTxtField.getText().isEmpty() ){ } McQ_Game.AddQuestion(q); mcqTmpQuesTxtField.setText(""); mcqTmpCho1TxtField.setText(""); mcqTmpCho2TxtField.setText(""); mcqTmpCho3TxtField.setText(""); mcqTmpCho4TxtField.setText(""); mcqTmpAnsTxtField.setText(""); } }); mcqTmpBtnAddQ.setFont(new Font("Chiller", Font.BOLD, 30)); mcqTmpBtnAddQ.setBounds(612, 337, 182, 38); mcqTmpPanel.add(mcqTmpBtnAddQ); JButton mcqTmpBtnSubmit = new JButton("Submit Game"); mcqTmpBtnSubmit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { McQ_Game.setSubject(Subject); McQ_Game.setName(Name); control.AddGame(McQ_Game); mcqTmpPanel.setVisible(false); tProfilePanel.setVisible(true); } }); mcqTmpBtnSubmit.setFont(new Font("Chiller", Font.BOLD, 30)); mcqTmpBtnSubmit.setBounds(612, 386, 182, 38); mcqTmpPanel.add(mcqTmpBtnSubmit); JButton button_5 = new JButton("Profile"); button_5.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(theAccount.isType()) { mcqTmpPanel.setVisible(false); sProfilePanel.setVisible(true); } else { mcqTmpPanel.setVisible(false); tProfilePanel.setVisible(true); } } }); button_5.setFont(new Font("Chiller", Font.BOLD, 20)); button_5.setBounds(0, 0, 88, 45); mcqTmpPanel.add(button_5); JLabel label = new JLabel("Matching Questions Template"); label.setFont(new Font("Chiller", Font.BOLD, 40)); label.setBounds(177, 11, 418, 61); mtTmpPanel.add(label); JLabel label_1 = new JLabel("left"); label_1.setFont(new Font("Chiller", Font.BOLD, 30)); label_1.setBounds(20, 83, 63, 36); mtTmpPanel.add(label_1); JLabel label_2 = new JLabel("1"); label_2.setFont(new Font("Chiller", Font.BOLD, 20)); label_2.setBounds(20, 129, 27, 20); mtTmpPanel.add(label_2); JLabel label_3 = new JLabel("2"); label_3.setFont(new Font("Chiller", Font.BOLD, 20)); label_3.setBounds(18, 164, 27, 20); mtTmpPanel.add(label_3); JLabel label_4 = new JLabel("3"); label_4.setFont(new Font("Chiller", Font.BOLD, 20)); label_4.setBounds(18, 195, 27, 20); mtTmpPanel.add(label_4); JLabel label_5 = new JLabel("4"); label_5.setFont(new Font("Chiller", Font.BOLD, 20)); label_5.setBounds(18, 226, 27, 20); mtTmpPanel.add(label_5); mtTmpLefttxtfield1 = new JTextField(); mtTmpLefttxtfield1.setColumns(10); mtTmpLefttxtfield1.setBounds(55, 130, 183, 20); mtTmpPanel.add(mtTmpLefttxtfield1); mtTmpLefttxtfield2 = new JTextField(); mtTmpLefttxtfield2.setColumns(10); mtTmpLefttxtfield2.setBounds(55, 161, 183, 20); mtTmpPanel.add(mtTmpLefttxtfield2); mtTmpLefttxtfield3 = new JTextField(); mtTmpLefttxtfield3.setColumns(10); mtTmpLefttxtfield3.setBounds(55, 192, 183, 20); mtTmpPanel.add(mtTmpLefttxtfield3); mtTmpLefttxtfield4 = new JTextField(); mtTmpLefttxtfield4.setColumns(10); mtTmpLefttxtfield4.setBounds(55, 223, 183, 20); mtTmpPanel.add(mtTmpLefttxtfield4); JLabel label_6 = new JLabel("Right"); label_6.setFont(new Font("Chiller", Font.BOLD, 30)); label_6.setBounds(309, 83, 63, 36); mtTmpPanel.add(label_6); JLabel label_12 = new JLabel("A"); label_12.setFont(new Font("Chiller", Font.BOLD, 20)); label_12.setBounds(309, 130, 27, 20); mtTmpPanel.add(label_12); JLabel label_13 = new JLabel("B"); label_13.setFont(new Font("Chiller", Font.BOLD, 20)); label_13.setBounds(309, 161, 27, 20); mtTmpPanel.add(label_13); JLabel label_14 = new JLabel("C"); label_14.setFont(new Font("Chiller", Font.BOLD, 20)); label_14.setBounds(309, 192, 27, 20); mtTmpPanel.add(label_14); JLabel label_15 = new JLabel("D"); label_15.setFont(new Font("Chiller", Font.BOLD, 20)); label_15.setBounds(309, 223, 27, 20); mtTmpPanel.add(label_15); mtTmpLefttxtfieldA = new JTextField(); mtTmpLefttxtfieldA.setColumns(10); mtTmpLefttxtfieldA.setBounds(346, 130, 183, 20); mtTmpPanel.add(mtTmpLefttxtfieldA); mtTmpLefttxtfieldB = new JTextField(); mtTmpLefttxtfieldB.setColumns(10); mtTmpLefttxtfieldB.setBounds(346, 161, 183, 20); mtTmpPanel.add(mtTmpLefttxtfieldB); mtTmpLefttxtfieldC = new JTextField(); mtTmpLefttxtfieldC.setColumns(10); mtTmpLefttxtfieldC.setBounds(346, 192, 183, 20); mtTmpPanel.add(mtTmpLefttxtfieldC); mtTmpLefttxtfieldD = new JTextField(); mtTmpLefttxtfieldD.setColumns(10); mtTmpLefttxtfieldD.setBounds(346, 223, 183, 20); mtTmpPanel.add(mtTmpLefttxtfieldD); JLabel label_7 = new JLabel("Answers"); label_7.setFont(new Font("Chiller", Font.BOLD, 30)); label_7.setBounds(10, 282, 83, 36); mtTmpPanel.add(label_7); JLabel label_8 = new JLabel("1"); label_8.setFont(new Font("Chiller", Font.BOLD, 20)); label_8.setBounds(10, 345, 27, 20); mtTmpPanel.add(label_8); mtTmpAns1 = new JTextField(); mtTmpAns1.setColumns(10); mtTmpAns1.setBounds(55, 346, 38, 21); mtTmpPanel.add(mtTmpAns1); JLabel label_9 = new JLabel("2"); label_9.setFont(new Font("Chiller", Font.BOLD, 20)); label_9.setBounds(140, 343, 27, 20); mtTmpPanel.add(label_9); mtTmpAns2 = new JTextField(); mtTmpAns2.setColumns(10); mtTmpAns2.setBounds(184, 346, 38, 21); mtTmpPanel.add(mtTmpAns2); JLabel label_10 = new JLabel("3"); label_10.setFont(new Font("Chiller", Font.BOLD, 20)); label_10.setBounds(268, 343, 27, 20); mtTmpPanel.add(label_10); mtTmpAns3 = new JTextField(); mtTmpAns3.setColumns(10); mtTmpAns3.setBounds(309, 344, 38, 21); mtTmpPanel.add(mtTmpAns3); JLabel label_11 = new JLabel("4"); label_11.setFont(new Font("Chiller", Font.BOLD, 20)); label_11.setBounds(398, 345, 27, 20); mtTmpPanel.add(label_11); mtTmpAns4 = new JTextField(); mtTmpAns4.setColumns(10); mtTmpAns4.setBounds(435, 346, 38, 21); mtTmpPanel.add(mtTmpAns4); JButton mtTmpBtnAddQuestion = new JButton("Add Question"); mtTmpBtnAddQuestion.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if( mtTmpLefttxtfield1.getText().isEmpty() || mtTmpLefttxtfield2.getText().isEmpty() || mtTmpLefttxtfield3.getText().isEmpty() || mtTmpLefttxtfield4.getText().isEmpty() || mtTmpLefttxtfieldA.getText().isEmpty() || mtTmpLefttxtfieldB.getText().isEmpty()|| mtTmpLefttxtfieldC.getText().isEmpty() || mtTmpLefttxtfieldD.getText().isEmpty() || mtTmpAns1.getText().isEmpty() || mtTmpAns2.getText().isEmpty()|| mtTmpAns3.getText().isEmpty() || mtTmpAns4.getText().isEmpty()) { JOptionPane.showMessageDialog(null, "Please enter all the data"); return; } else { MatchQuestion mtQu = new MatchQuestion(); mtQu.QuestionA.addElement(mtTmpLefttxtfield1.getText()); mtQu.QuestionA.addElement(mtTmpLefttxtfield2.getText()); mtQu.QuestionA.addElement(mtTmpLefttxtfield3.getText()); mtQu.QuestionA.addElement(mtTmpLefttxtfield4.getText()); mtQu.QuestionB.addElement(mtTmpLefttxtfieldA.getText()); mtQu.QuestionB.addElement(mtTmpLefttxtfieldB.getText()); mtQu.QuestionB.addElement(mtTmpLefttxtfieldC.getText()); mtQu.QuestionB.addElement(mtTmpLefttxtfieldD.getText()); mtQu.AnswerA.addElement(mtQu.getStr( mtTmpAns1.getText().charAt(0)) ); mtQu.AnswerA.addElement(mtQu.getStr( mtTmpAns2.getText().charAt(0)) ); mtQu.AnswerA.addElement(mtQu.getStr( mtTmpAns3.getText().charAt(0)) ); mtQu.AnswerA.addElement(mtQu.getStr( mtTmpAns4.getText().charAt(0)) ); match_game.AddQuestion(mtQu); mtTmpLefttxtfield1.setText(""); mtTmpLefttxtfield2.setText(""); mtTmpLefttxtfield3.setText(""); mtTmpLefttxtfield4.setText(""); mtTmpLefttxtfieldA.setText(""); mtTmpLefttxtfieldB.setText(""); mtTmpLefttxtfieldC.setText(""); mtTmpLefttxtfieldD.setText(""); mtTmpAns1.setText(""); mtTmpAns2.setText(""); mtTmpAns3.setText(""); mtTmpAns4.setText(""); } }}); mtTmpBtnAddQuestion.setFont(new Font("Chiller", Font.BOLD, 30)); mtTmpBtnAddQuestion.setBounds(559, 335, 182, 35); mtTmpPanel.add(mtTmpBtnAddQuestion); JButton mtTmpBtnSubmit = new JButton("Submit Game"); mtTmpBtnSubmit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { match_game.setName(Name); match_game.setSubject(Subject); control.AddGame(match_game); //System.out.println(match_game); mtTmpPanel.setVisible(false); tProfilePanel.setVisible(true); } }); mtTmpBtnSubmit.setFont(new Font("Chiller", Font.BOLD, 30)); mtTmpBtnSubmit.setBounds(559, 393, 182, 35); mtTmpPanel.add(mtTmpBtnSubmit); JButton button_7 = new JButton("Profile"); button_7.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(theAccount.isType()) { mtTmpPanel.setVisible(false); sProfilePanel.setVisible(true); } else { mtTmpPanel.setVisible(false); tProfilePanel.setVisible(true); } } }); button_7.setFont(new Font("Chiller", Font.BOLD, 20)); button_7.setBounds(0, 0, 88, 45); mtTmpPanel.add(button_7); JLabel label_30 = new JLabel("Clever Zone"); label_30.setForeground(Color.BLACK); label_30.setFont(new Font("Chiller", Font.BOLD, 76)); label_30.setBackground(Color.WHITE); label_30.setBounds(275, 162, 363, 149); homePanel.add(label_30); JButton homeBtnLogIn = new JButton("Login"); homeBtnLogIn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { homePanel.setVisible(false); loginPanel.setVisible(true); } }); homeBtnLogIn.setForeground(Color.BLACK); homeBtnLogIn.setFont(new Font("Chiller", Font.BOLD, 40)); homeBtnLogIn.setContentAreaFilled(false); homeBtnLogIn.setBorderPainted(false); homeBtnLogIn.setBackground(Color.WHITE); homeBtnLogIn.setBounds(680, 110, 150, 65); homePanel.add(homeBtnLogIn); JButton homeBtnStudentRegister = new JButton("Register"); homeBtnStudentRegister.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { homePanel.setVisible(false); registerPanel.setVisible(true); } }); homeBtnStudentRegister.setOpaque(false); homeBtnStudentRegister.setForeground(Color.BLACK); homeBtnStudentRegister.setFont(new Font("Chiller", Font.BOLD, 40)); homeBtnStudentRegister.setContentAreaFilled(false); homeBtnStudentRegister.setBorderPainted(false); homeBtnStudentRegister.setBackground(Color.WHITE); homeBtnStudentRegister.setBounds(680, 200, 150, 65); homePanel.add(homeBtnStudentRegister); JLabel label_31 = new JLabel("MCQ Game"); label_31.setFont(new Font("Chiller", Font.BOLD, 40)); label_31.setBounds(300, 11, 163, 61); mcqGamePanel.add(label_31); JLabel label_32 = new JLabel("Question"); label_32.setFont(new Font("Chiller", Font.BOLD, 30)); label_32.setBounds(10, 96, 99, 27); mcqGamePanel.add(label_32); mcqGameQuesTxtField = new JTextField(); mcqGameQuesTxtField.setFont(new Font("Arial", Font.PLAIN, 15)); mcqGameQuesTxtField.setColumns(10); mcqGameQuesTxtField.setBounds(119, 96, 632, 27); mcqGamePanel.add(mcqGameQuesTxtField); JPanel mcqGameChoicesInternalPanel = new JPanel(); mcqGameChoicesInternalPanel.setBorder(new TitledBorder(null, "Choices", TitledBorder.LEADING, TitledBorder.TOP, null, null)); mcqGameChoicesInternalPanel.setBounds(10, 154, 745, 188); mcqGamePanel.add(mcqGameChoicesInternalPanel); mcqGameChoicesInternalPanel.setLayout(null); JRadioButton mcqGameRdBtnChoice1 = new JRadioButton("Choice 1"); mcqGameRdBtnChoice1.setSelected(true); mcqGameChoicesButtonGroup.add(mcqGameRdBtnChoice1); mcqGameRdBtnChoice1.setBounds(6, 36, 227, 23); mcqGameChoicesInternalPanel.add(mcqGameRdBtnChoice1); JRadioButton mcqGameRdBtnChoice2 = new JRadioButton("Choice 2"); mcqGameChoicesButtonGroup.add(mcqGameRdBtnChoice2); mcqGameRdBtnChoice2.setBounds(6, 72, 227, 23); mcqGameChoicesInternalPanel.add(mcqGameRdBtnChoice2); JRadioButton mcqGameRdBtnChoice3 = new JRadioButton("Choice 3"); mcqGameChoicesButtonGroup.add(mcqGameRdBtnChoice3); mcqGameRdBtnChoice3.setBounds(6, 108, 227, 23); mcqGameChoicesInternalPanel.add(mcqGameRdBtnChoice3); JRadioButton mcqGameRdBtnChoice4 = new JRadioButton("Choice 4"); mcqGameChoicesButtonGroup.add(mcqGameRdBtnChoice4); mcqGameRdBtnChoice4.setBounds(6, 144, 227, 23); mcqGameChoicesInternalPanel.add(mcqGameRdBtnChoice4); JButton mcqGameBtnNextQues = new JButton("Next Question"); mcqGameBtnNextQues.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String type=""; Enumeration<AbstractButton> buto = mcqGameChoicesButtonGroup.getElements(); while(buto.hasMoreElements()) { JRadioButton jrd = (JRadioButton) buto.nextElement(); if(jrd.isSelected()){ type = jrd.getText(); } } if(McQ_Game.getQuestions().get(McQCnt).GetAnswer().equals(type)) { JOptionPane.showMessageDialog(null, "Correct Answer"); McQCnt++; if(McQCnt==McQ_Game.getQuestions().size()) { JOptionPane.showMessageDialog(null, "Congratss"); mcqGamePanel.setVisible(false); playGamePanel.setVisible(true); } else { mcqGameQuesTxtField.setText(McQ_Game.Questions.get(McQCnt).GetQuestion()); mcqGameRdBtnChoice1.setText(McQ_Game.Questions.get(McQCnt).choices[0]); mcqGameRdBtnChoice2.setText(McQ_Game.Questions.get(McQCnt).choices[1]); mcqGameRdBtnChoice3.setText(McQ_Game.Questions.get(McQCnt).choices[2]); mcqGameRdBtnChoice4.setText(McQ_Game.Questions.get(McQCnt).choices[3]); } } else { JOptionPane.showMessageDialog(null, "Wrong Answer"); } } }); mcqGameBtnNextQues.setEnabled(false); mcqGameBtnNextQues.setFont(new Font("Chiller", Font.BOLD, 20)); mcqGameBtnNextQues.setBounds(615, 353, 140, 38); mcqGamePanel.add(mcqGameBtnNextQues); JButton mcqGameBtnShowAns = new JButton("Show Answer"); mcqGameBtnShowAns.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null,"The Correct Answer is :"+ McQ_Game.getQuestions().get(McQCnt).GetAnswer()); McQCnt++; if(McQCnt==McQ_Game.getQuestions().size()) { JOptionPane.showMessageDialog(null, "Congratss"); mcqGamePanel.setVisible(false); playGamePanel.setVisible(true); } else { mcqGameQuesTxtField.setText(McQ_Game.Questions.get(McQCnt).GetQuestion()); mcqGameRdBtnChoice1.setText(McQ_Game.Questions.get(McQCnt).choices[0]); mcqGameRdBtnChoice2.setText(McQ_Game.Questions.get(McQCnt).choices[1]); mcqGameRdBtnChoice3.setText(McQ_Game.Questions.get(McQCnt).choices[2]); mcqGameRdBtnChoice4.setText(McQ_Game.Questions.get(McQCnt).choices[3]); } } }); mcqGameBtnShowAns.setEnabled(false); mcqGameBtnShowAns.setFont(new Font("Chiller", Font.BOLD, 20)); mcqGameBtnShowAns.setBounds(465, 353, 140, 38); mcqGamePanel.add(mcqGameBtnShowAns); JButton mcqGameBtnStartGame = new JButton("Start Game"); mcqGameBtnStartGame.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { McQCnt=0; mcqGameBtnStartGame.setEnabled(false); mcqGameBtnShowAns.setEnabled(true); mcqGameBtnNextQues.setEnabled(true); mcqGameQuesTxtField.setText(McQ_Game.Questions.get(0).GetQuestion()); mcqGameRdBtnChoice1.setText(McQ_Game.Questions.get(0).choices[0]); mcqGameRdBtnChoice2.setText(McQ_Game.Questions.get(0).choices[1]); mcqGameRdBtnChoice3.setText(McQ_Game.Questions.get(0).choices[2]); mcqGameRdBtnChoice4.setText(McQ_Game.Questions.get(0).choices[3]); } }); mcqGameBtnStartGame.setFont(new Font("Chiller", Font.BOLD, 20)); mcqGameBtnStartGame.setBounds(315, 353, 140, 38); mcqGamePanel.add(mcqGameBtnStartGame); JButton button_2 = new JButton("Profile"); button_2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(theAccount.isType()) { mcqGamePanel.setVisible(false); sProfilePanel.setVisible(true); } else { mcqGamePanel.setVisible(false); tProfilePanel.setVisible(true); } } }); button_2.setFont(new Font("Chiller", Font.BOLD, 20)); button_2.setBounds(0, 0, 88, 45); mcqGamePanel.add(button_2); JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(545, 143, 230, 229); playGamePanel.add(scrollPane); JList playGameSubjectList = new JList(); scrollPane.setViewportView(playGameSubjectList); JButton playGameBtnPlayGame = new JButton("Play Game"); playGameBtnPlayGame.setFont(new Font("Chiller", Font.BOLD, 18)); playGameBtnPlayGame.setEnabled(false); playGameBtnPlayGame.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { playGameSubjectList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); String selectedGame = (String) playGameSubjectList.getSelectedValue(); System.out.println("selected game :: " + selectedGame); if(selectedGame.isEmpty()) { JOptionPane.showMessageDialog(null, "Please Select the Subject"); }else{ Game thG= control.getGame(selectedGame); if(thG instanceof T_F){ tfGame = (T_F)thG; playGameBtnPlayGame.setEnabled(false); playGameBtnGetSubjects.setEnabled(true); t_fGamePanel.setVisible(true); playGamePanel.setVisible(false); }else if(thG instanceof McQ){ McQ_Game= (McQ) thG; playGameBtnPlayGame.setEnabled(false); playGameBtnGetSubjects.setEnabled(true); mcqGamePanel.setVisible(true); playGamePanel.setVisible(false); }else if(thG instanceof Match){ match_game = (Match) thG; playGameBtnPlayGame.setEnabled(false); playGameBtnGetSubjects.setEnabled(true); mtGamePanel.setVisible(true); playGamePanel.setVisible(false); } } } }); playGameBtnPlayGame.setBounds(10, 328, 194, 44); playGamePanel.add(playGameBtnPlayGame); JButton playGameBtnShowGames = new JButton("Show Games"); playGameBtnShowGames.setFont(new Font("Chiller", Font.BOLD, 18)); playGameBtnShowGames.setEnabled(false); playGameBtnShowGames.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { playGameSubjectList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); String selectedSubject = (String) playGameSubjectList.getSelectedValue(); //System.out.println("Selected :: " + selectedSubject); if(selectedSubject.isEmpty()) { JOptionPane.showMessageDialog(null, "Please Select the Subject"); }else{ int c = 0; if(gameTypeStr.equals("MCQ")) { c=2; } else if(gameTypeStr.equals("Match")) { c=1; } else if(gameTypeStr.equals("T/F")) { c=0; } Vector<Game> tmp = new Vector<Game>(); tmp = control.GetAllGame(c,selectedSubject ); Vector<String> nam = new Vector<String>(); for(Game s : tmp){ nam.addElement(s.getName()); } //nam.add("FIFA"); //nam.add("PES"); DefaultListModel dlm2 = new DefaultListModel(); for(int i = 0 ; i < nam.size() ; i++) { dlm2.addElement(nam.get(i)); } playGameSubjectList.setModel(dlm2); playGameBtnShowGames.setEnabled(false); playGameBtnPlayGame.setEnabled(true); } } }); playGameBtnShowGames.setBounds(10, 272, 194, 45); playGamePanel.add(playGameBtnShowGames); playGameBtnGetSubjects.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Enumeration<AbstractButton> buto4 = PlayGameGameTypeButtonGroup.getElements(); while(buto4.hasMoreElements()) { JRadioButton jrd4 = (JRadioButton) buto4.nextElement(); if(jrd4.isSelected()){ gameTypeStr = jrd4.getText(); } } int c = 0; if(gameTypeStr.equals("MCQ")) { c=2; } else if(gameTypeStr.equals("Match")) { c=1; } else if(gameTypeStr.equals("T/F")) { c=0; } Vector<String> tmp = new Vector<String>(); tmp = control.GetallSubject(c); //tmp.add("Math"); //tmp.add("Code"); DefaultListModel dlm = new DefaultListModel(); for(int i = 0 ; i < tmp.size() ; i++) { dlm.addElement(tmp.get(i)); } playGameSubjectList.setModel(dlm); playGameBtnGetSubjects.setEnabled(false); playGameBtnShowGames.setEnabled(true); //playGameBtnPlayGame.setEnabled(false); ////////////////////////////////////////////////////////////////////////////// } }); playGameBtnGetSubjects.setBounds(10, 216, 194, 45); playGamePanel.add(playGameBtnGetSubjects); JPanel playGameGameTypeInternalPanel = new JPanel(); playGameGameTypeInternalPanel.setLayout(null); playGameGameTypeInternalPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Game Type", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0))); playGameGameTypeInternalPanel.setBounds(10, 71, 194, 117); playGamePanel.add(playGameGameTypeInternalPanel); JRadioButton playGameRdBtnMcq = new JRadioButton("MCQ"); PlayGameGameTypeButtonGroup.add(playGameRdBtnMcq); playGameRdBtnMcq.setSelected(true); playGameRdBtnMcq.setBounds(20, 36, 111, 25); playGameGameTypeInternalPanel.add(playGameRdBtnMcq); JRadioButton playGameRdBtnMatch = new JRadioButton("Match"); PlayGameGameTypeButtonGroup.add(playGameRdBtnMatch); playGameRdBtnMatch.setBounds(20, 64, 111, 25); playGameGameTypeInternalPanel.add(playGameRdBtnMatch); JRadioButton playGameRdBtnT_F = new JRadioButton("T/F"); PlayGameGameTypeButtonGroup.add(playGameRdBtnT_F); playGameRdBtnT_F.setBounds(20, 87, 111, 25); playGameGameTypeInternalPanel.add(playGameRdBtnT_F); JLabel lblNewLabel_11 = new JLabel("Play Game"); lblNewLabel_11.setFont(new Font("Chiller", Font.BOLD, 40)); lblNewLabel_11.setBounds(304, 11, 144, 51); playGamePanel.add(lblNewLabel_11); JButton button_1 = new JButton("Profile"); button_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(theAccount.isType()) { playGamePanel.setVisible(false); sProfilePanel.setVisible(true); } else { playGamePanel.setVisible(false); tProfilePanel.setVisible(true); } } }); button_1.setFont(new Font("Chiller", Font.BOLD, 20)); button_1.setBounds(0, 0, 88, 45); playGamePanel.add(button_1); } }
a5ccb78a09cf3cce2d18eeb30caeea7f39b871b3
096db8f6d742a3aac8b6a587802176db7658831e
/app/src/main/java/com/pweschmidt/healthapps/AddHIVDrugsActivity.java
3afd0e62f0c6db85dde5d246b77ec30ab02b9bee
[]
no_license
pweschmidt/iStayHealthy-AndroidStudio
4b83fe19ec328b32a878246760905ece15341e60
4deb477b3a3ae190c9d350bd2849f77bbcc95141
refs/heads/master
2021-01-14T13:21:53.074516
2015-11-17T06:23:36
2015-11-17T06:23:36
35,329,027
0
0
null
null
null
null
UTF-8
Java
false
false
12,367
java
package com.pweschmidt.healthapps; import android.app.Activity; import android.app.DatePickerDialog; import android.app.Dialog; import android.content.Intent; import android.graphics.Color; import android.graphics.Typeface; import android.os.Bundle; import android.text.format.DateFormat; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.widget.CheckBox; import android.widget.DatePicker; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TableRow.LayoutParams; import android.widget.TextView; import com.pweschmidt.healthapps.datamodel.Medication; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Vector; //import android.util.Log; //import android.content.DialogInterface; public class AddHIVDrugsActivity extends Activity implements View.OnClickListener, DatePickerDialog.OnDateSetListener { // private static final String TAG = "AddResultActivity"; public static final int LINK_ACTIVITY_REQUEST_CODE = 100; private TableLayout medTable; private StringMap medHashMap; private Vector<String> selectedList; private Date startDate; private TextView dateText; private TableRow dateRow; private static final int DATE_DIALOG_ID = 0; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Log.d(TAG, "onCreate"); setContentView(R.layout.add_hiv_drugs); medTable = (TableLayout)findViewById(R.id.medTable); medHashMap = new StringMap(); selectedList = new Vector<String>(); startDate = new Date(); ImageButton cancelButton = (ImageButton)findViewById(R.id.BackButton); cancelButton.setOnClickListener(this); TextView titleText = (TextView)findViewById(R.id.TitleMainTitle); String title = getResources().getString(R.string.AddHIVDrugs); titleText.setText(title); ImageButton saveButton = (ImageButton)findViewById(R.id.SaveButton); saveButton.setOnClickListener(this); ImageButton delete = (ImageButton)findViewById(R.id.TrashButton); delete.setOnClickListener(this); delete.setVisibility(View.GONE); TableRow infoRow = (TableRow)findViewById(R.id.glossaryRow); infoRow.setOnClickListener(this); dateRow = (TableRow)findViewById(R.id.setDateTimeRow); dateRow.setOnClickListener(this); dateText = (TextView)findViewById(R.id.dateTimeText); dateText.setText(DateFormat.format("dd MMM yyyy", startDate)); String[] combiList = getResources().getStringArray(R.array.CombiMeds); String combiTitle = getResources().getString(R.string.combinationtablets); Vector<String> combiMeds = new Vector<String>(Arrays.asList(combiList)); setUpTitle(combiTitle); fillMedicationRows(combiMeds, FileMaps.combiMeds); String[] nnRTIList = getResources().getStringArray(R.array.NNRTI); String NNRTITitle = getResources().getString(R.string.NNRTIDrugs); Vector<String> nnRTIMeds = new Vector<String>(Arrays.asList(nnRTIList)); setUpTitle(NNRTITitle); fillMedicationRows(nnRTIMeds, FileMaps.nnRTI); String[] nRTIList = getResources().getStringArray(R.array.NRTI); String NRTITitle = getResources().getString(R.string.NRTIDrugs); Vector<String> nRTIMeds = new Vector<String>(Arrays.asList(nRTIList)); setUpTitle(NRTITitle); fillMedicationRows(nRTIMeds, FileMaps.nRTI); String[] piList = getResources().getStringArray(R.array.ProteaseInhibitors); String PITitle = getResources().getString(R.string.PIDrugs); Vector<String> pIMeds = new Vector<String>(Arrays.asList(piList)); setUpTitle(PITitle); fillMedicationRows(pIMeds, FileMaps.proteaseInhibitors); String[] entryList = getResources().getStringArray(R.array.EntryInhibitors); String entryTitle = getResources().getString(R.string.EntryDrugs); Vector<String> entryMeds = new Vector<String>(Arrays.asList(entryList)); setUpTitle(entryTitle); fillMedicationRows(entryMeds, FileMaps.entryInhibitors); String[] integraseList = getResources().getStringArray(R.array.IntegraseInhibitors); String integraseTitle = getResources().getString(R.string.IntegraseDrugs); Vector<String> integraseMeds = new Vector<String>(Arrays.asList(integraseList)); setUpTitle(integraseTitle); fillMedicationRows(integraseMeds, FileMaps.integraseInhibitors); String[] boosterList = getResources().getStringArray(R.array.Boosters); String boosterTitle = getResources().getString(R.string.Booster); Vector<String> boosterMeds = new Vector<String>(Arrays.asList(boosterList)); setUpTitle(boosterTitle); fillMedicationRows(boosterMeds, FileMaps.boosters); String[] otherList = getResources().getStringArray(R.array.OtherInhibitors); String otherTitle = getResources().getString(R.string.OtherInhibitors); Vector<String> otherMeds = new Vector<String>(Arrays.asList(otherList)); setUpTitle(otherTitle); fillMedicationRows(otherMeds, FileMaps.otherInhibitors); } /** * */ protected Dialog onCreateDialog(int id) { if(DATE_DIALOG_ID != id) return null; Calendar c = Calendar.getInstance(); int cyear = c.get(Calendar.YEAR); int cmonth = c.get(Calendar.MONTH); int cday = c.get(Calendar.DAY_OF_MONTH); DatePickerDialog dialog = new DatePickerDialog(this, this, cyear, cmonth, cday); dialog.setCancelable(false); return dialog; } /** * */ public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { startDate = new Date(year - 1900, monthOfYear, dayOfMonth); dateText.setText(DateFormat.format("dd MMM yyyy", startDate)); } /** * */ public void onClick(View view) { int resID = view.getId(); if(R.id.BackButton == resID) { setResult(RESULT_CANCELED, null); finish();//do nothing } else if(R.id.SaveButton == resID) { Iterator <String> iterator = selectedList.iterator(); while(iterator.hasNext()) { String medString = (String)iterator.next(); String[] medStrings = medString.split(":"); Medication medication = new Medication(); medication.setName(medStrings[1]); medication.setDrug(medStrings[2]); medication.setMedicationForm(medStrings[3]); medication.setTime(startDate.getTime()); getContentResolver().insert(iStayHealthyContentProvider.MEDS_CONTENT_URI, medication.contentValuesForMedication()); // Log.d(TAG,"new medication table added at row "+rowIndexAdded); } setResult(RESULT_OK, null); finish(); } else if(R.id.glossaryRow == resID) { Intent bannerIntent = new Intent(this, WebViewActivity.class); String url = getResources().getString(R.string.medslist); bannerIntent.putExtra("url", url); startActivityForResult(bannerIntent,LINK_ACTIVITY_REQUEST_CODE); } else if(R.id.setDateTimeRow == resID) { showDialog(DATE_DIALOG_ID); } else { CheckBox checkBox = (CheckBox)view; String key = medHashMap.getStringForCheckBox(checkBox); if( null != key ) { if(checkBox.isChecked()) { selectedList.add(key); } else { if(selectedList.contains(key)) selectedList.remove(key); } } } } /** * * @param title */ private void setUpTitle(String title) { TableRow combiRowTitle = new TableRow(this); combiRowTitle.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); TextView combiTitleView = new TextView(this); combiTitleView.setText(title); combiTitleView.setTextColor(Color.DKGRAY); combiTitleView.setTextSize(TypedValue.COMPLEX_UNIT_PT, 8); combiTitleView.setTypeface(Typeface.SERIF, Typeface.BOLD); combiTitleView.setGravity(Gravity.CENTER); combiTitleView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); LayoutParams params = new LayoutParams(); params.span = 3; combiRowTitle.addView(combiTitleView,params); medTable.addView(combiRowTitle, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); } private void fillMedicationRows(Vector <String> medVector, HashMap<String, Integer>imageMap) { Iterator <String>iterator = medVector.iterator(); while(iterator.hasNext()) { String key = (String)iterator.next(); String[] strings = key.split(":"); String imageName = strings[0]; int resId = R.drawable.combi; if(imageMap.containsKey(imageName)) resId = imageMap.get(imageName).intValue(); String commercialName = strings[1]; String drugs = strings[2]; String form = strings[3]; TableRow tableRow = new TableRow(this); tableRow.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); if(0 != resId) { ImageView imageView = new ImageView(this); imageView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); imageView.setImageResource(resId); imageView.setMaxHeight(55); imageView.setMaxWidth(55); tableRow.addView(imageView); } TableLayout textLayout = new TableLayout(this); textLayout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); TableRow commercialRow = new TableRow(this); commercialRow.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); TextView commercialLabel = new TextView(this); commercialLabel.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); commercialLabel.setText(commercialName); commercialLabel.setTextColor(Color.DKGRAY); commercialLabel.setTextSize(12); commercialRow.addView(commercialLabel); TableRow drugRow = new TableRow(this); drugRow.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); TextView drugLabel = new TextView(this); drugLabel.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); drugLabel.setText(drugs); drugLabel.setTextColor(Color.LTGRAY); drugLabel.setTextSize(10); drugRow.addView(drugLabel); TableRow formRow = new TableRow(this); formRow.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); TextView formLabel = new TextView(this); formLabel.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); formLabel.setText(form); formLabel.setTextColor(Color.RED); formLabel.setTextSize(8); formRow.addView(formLabel); textLayout.addView(commercialRow, new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); textLayout.addView(drugRow, new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); textLayout.addView(formRow, new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); tableRow.addView(textLayout); CheckBox checkBox = new CheckBox(this); checkBox.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); checkBox.setChecked(false); checkBox.setOnClickListener(this); tableRow.addView(checkBox); medHashMap.put(key, checkBox); medTable.addView(tableRow, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); } } /** * entry point when returning to ResultsActivity */ public void onResume(){ super.onResume(); // Log.d(TAG,"onResume"); } /** * called when activity is paused - e.g. when we move to another one */ public void onPause(){ super.onPause(); // Log.d(TAG,"onPause"); } }
72492426559413a0493ca75cfe0fc632aadb4885
8e73d0d597c7c916321b2b7b36d1e44f056cd4a8
/platforms/android/src/com/transistorsoft/cordova/bggeo/CDVBackgroundGeolocation.java
e350292aa5bbc161dfa1482b4522e6546cc8e0f6
[]
no_license
crohacz/trackSaguaro
9a8d18c6b003389df1f65913ae24a9de578d9383
e267e7f6c16642dbc9c44fa0227279776f81b4b6
refs/heads/master
2016-09-13T12:44:57.159619
2016-06-04T16:58:16
2016-06-04T16:58:16
57,152,981
1
1
null
null
null
null
UTF-8
Java
false
false
48,932
java
package com.transistorsoft.cordova.bggeo; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; import java.util.HashMap; import java.util.Map; import java.util.ArrayList; import java.util.Iterator; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; import org.apache.cordova.PluginResult; import org.json.JSONArray; import org.json.JSONObject; import org.json.JSONException; import android.Manifest; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import com.google.android.gms.common.GoogleApiAvailability; import com.google.android.gms.location.DetectedActivity; import com.transistorsoft.locationmanager.BackgroundGeolocationService; import com.transistorsoft.locationmanager.Settings; import com.google.android.gms.location.GeofencingEvent; import android.app.AlertDialog; import android.content.DialogInterface; import de.greenrobot.event.EventBus; import de.greenrobot.event.Subscribe; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.location.Location; import android.os.Environment; import android.util.Log; import android.media.AudioManager; import android.media.ToneGenerator; import android.widget.Toast; public class CDVBackgroundGeolocation extends CordovaPlugin { private static final String TAG = "TSLocationManager"; public static final String ACCESS_COARSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION; public static final String ACCESS_FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION; public static final int REQUEST_ACTION_START = 1; public static final int REQUEST_ACTION_GET_CURRENT_POSITION = 2; private static CordovaWebView gWebView; public static Boolean forceReload = false; /** * Timeout in millis for a getCurrentPosition request to give up. * TODO make configurable. */ private static final long GET_CURRENT_POSITION_TIMEOUT = 30000; public static final String ACTION_FINISH = "finish"; public static final String ACTION_ERROR = "error"; public static final String ACTION_CONFIGURE = "configure"; public static final String ACTION_SET_CONFIG = "setConfig"; public static final String ACTION_ADD_MOTION_CHANGE_LISTENER = "addMotionChangeListener"; public static final String ACTION_ADD_LOCATION_LISTENER = "addLocationListener"; public static final String ACTION_ON_GEOFENCE = "onGeofence"; public static final String ACTION_PLAY_SOUND = "playSound"; public static final String ACTION_ACTIVITY_RELOAD = "activityReload"; public static final String ACTION_GET_STATE = "getState"; public static final String ACTION_ADD_HTTP_LISTENER = "addHttpListener"; public static final String ACTION_GET_LOG = "getLog"; public static final String ACTION_EMAIL_LOG = "emailLog"; private SharedPreferences settings; private Boolean isStarting = false; private Boolean isEnabled = false; private Boolean stopOnTerminate = false; private Boolean isMoving; private Boolean isAcquiringCurrentPosition = false; private Intent backgroundServiceIntent; private JSONObject mConfig; private DetectedActivity currentActivity; private CallbackContext startCallback; // Geolocation callback private CallbackContext getLocationsCallback; private CallbackContext syncCallback; private CallbackContext paceChangeCallback; private CallbackContext getGeofencesCallback; private ToneGenerator toneGenerator; private List<CallbackContext> locationCallbacks = new ArrayList<CallbackContext>(); private List<CallbackContext> motionChangeCallbacks = new ArrayList<CallbackContext>(); private List<CallbackContext> geofenceCallbacks = new ArrayList<CallbackContext>(); private List<CallbackContext> currentPositionCallbacks = new ArrayList<CallbackContext>(); private Map<String, CallbackContext> addGeofenceCallbacks = new HashMap<String, CallbackContext>(); private List<CallbackContext> httpResponseCallbacks = new ArrayList<CallbackContext>(); private Map<String, CallbackContext> insertLocationCallbacks = new HashMap<String, CallbackContext>(); private List<CallbackContext> getCountCallbacks = new ArrayList<CallbackContext>(); public static boolean isActive() { return gWebView != null; } @Override protected void pluginInitialize() { gWebView = this.webView; Activity activity = this.cordova.getActivity(); settings = activity.getSharedPreferences("TSLocationManager", 0); Settings.init(settings); toneGenerator = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100); Intent launchIntent = activity.getIntent(); if (launchIntent.hasExtra("forceReload")) { // When Activity is launched due to forceReload, minimize the app. activity.moveTaskToBack(true); } } public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException { Log.d(TAG, "$ " + action + "()"); Boolean result = false; if (BackgroundGeolocationService.ACTION_START.equalsIgnoreCase(action)) { result = true; if (!isStarting) { this.start(callbackContext); } else { callbackContext.error("- Waiting for previous start action to complete"); } } else if (BackgroundGeolocationService.ACTION_STOP.equalsIgnoreCase(action)) { // No implementation to stop background-tasks with Android. Just say "success" result = true; this.stop(); callbackContext.success(0); } else if (ACTION_FINISH.equalsIgnoreCase(action)) { result = true; callbackContext.success(); } else if (ACTION_ERROR.equalsIgnoreCase(action)) { result = true; this.onError(data.getString(1)); callbackContext.success(); } else if (ACTION_CONFIGURE.equalsIgnoreCase(action)) { result = true; configure(data.getJSONObject(0), callbackContext); } else if (ACTION_ADD_LOCATION_LISTENER.equalsIgnoreCase(action)) { result = true; addLocationListener(callbackContext); } else if (BackgroundGeolocationService.ACTION_CHANGE_PACE.equalsIgnoreCase(action)) { result = true; if (!isEnabled) { Log.w(TAG, "- Cannot change pace while disabled"); callbackContext.error("Cannot #changePace while disabled"); } else { changePace(callbackContext, data); } } else if (BackgroundGeolocationService.ACTION_SET_CONFIG.equalsIgnoreCase(action)) { result = true; JSONObject config = data.getJSONObject(0); setConfig(config); callbackContext.success(); } else if (ACTION_GET_STATE.equalsIgnoreCase(action)) { result = true; JSONObject state = this.getState(); PluginResult response = new PluginResult(PluginResult.Status.OK, state); response.setKeepCallback(false); callbackContext.sendPluginResult(response); } else if (ACTION_ADD_MOTION_CHANGE_LISTENER.equalsIgnoreCase(action)) { result = true; this.addMotionChangeListener(callbackContext); } else if (BackgroundGeolocationService.ACTION_GET_LOCATIONS.equalsIgnoreCase(action)) { result = true; getLocations(callbackContext); } else if (BackgroundGeolocationService.ACTION_SYNC.equalsIgnoreCase(action)) { result = true; sync(callbackContext); } else if (BackgroundGeolocationService.ACTION_GET_ODOMETER.equalsIgnoreCase(action)) { result = true; getOdometer(callbackContext); } else if (BackgroundGeolocationService.ACTION_RESET_ODOMETER.equalsIgnoreCase(action)) { result = true; resetOdometer(callbackContext); } else if (BackgroundGeolocationService.ACTION_ADD_GEOFENCE.equalsIgnoreCase(action)) { result = true; addGeofence(callbackContext, data.getJSONObject(0)); } else if (BackgroundGeolocationService.ACTION_ADD_GEOFENCES.equalsIgnoreCase(action)) { result = true; addGeofences(callbackContext, data.getJSONArray(0)); } else if (BackgroundGeolocationService.ACTION_REMOVE_GEOFENCE.equalsIgnoreCase(action)) { result = removeGeofence(data.getString(0)); if (result) { callbackContext.success(); } else { callbackContext.error("Failed to add geofence"); } } else if (BackgroundGeolocationService.ACTION_REMOVE_GEOFENCES.equalsIgnoreCase(action)) { result = removeGeofences(); if (result) { callbackContext.success(); } else { callbackContext.error("Failed to add geofence"); } } else if (BackgroundGeolocationService.ACTION_ON_GEOFENCE.equalsIgnoreCase(action)) { result = true; addGeofenceListener(callbackContext); } else if (BackgroundGeolocationService.ACTION_GET_GEOFENCES.equalsIgnoreCase(action)) { result = true; getGeofences(callbackContext); } else if (ACTION_PLAY_SOUND.equalsIgnoreCase(action)) { result = true; playSound(data.getInt(0)); callbackContext.success(); } else if (BackgroundGeolocationService.ACTION_GET_CURRENT_POSITION.equalsIgnoreCase(action)) { result = true; JSONObject options = data.getJSONObject(0); getCurrentPosition(callbackContext, options); } else if (BackgroundGeolocationService.ACTION_BEGIN_BACKGROUND_TASK.equalsIgnoreCase(action)) { // Android doesn't do background-tasks. This is an iOS thing. Just return a number. result = true; callbackContext.success(1); } else if (BackgroundGeolocationService.ACTION_CLEAR_DATABASE.equalsIgnoreCase(action)) { result = true; clearDatabase(callbackContext); } else if (ACTION_ADD_HTTP_LISTENER.equalsIgnoreCase(action)) { result = true; addHttpListener(callbackContext); } else if (ACTION_GET_LOG.equalsIgnoreCase(action)) { result = true; getLog(callbackContext); } else if (ACTION_EMAIL_LOG.equalsIgnoreCase(action)) { result = true; emailLog(callbackContext, data.getString(0)); } else if (BackgroundGeolocationService.ACTION_INSERT_LOCATION.equalsIgnoreCase(action)) { result = true; insertLocation(data.getJSONObject(0), callbackContext); } else if (BackgroundGeolocationService.ACTION_GET_COUNT.equalsIgnoreCase(action)) { result = true; getCount(callbackContext); } return result; } private void configure(JSONObject config, CallbackContext callbackContext) { mConfig = config; boolean result = applyConfig(); if (result) { boolean willEnable = settings.getBoolean("enabled", isEnabled); if (willEnable) { start(null); } PluginResult response = new PluginResult(PluginResult.Status.OK, this.getState()); response.setKeepCallback(false); callbackContext.sendPluginResult(response); } else { callbackContext.error("- Configuration error!"); } } private void start(CallbackContext callback) { isStarting = true; startCallback = callback; backgroundServiceIntent = new Intent(cordova.getActivity(), BackgroundGeolocationService.class); if (hasPermission(ACCESS_COARSE_LOCATION) && hasPermission(ACCESS_FINE_LOCATION)) { setEnabled(true); } else { String[] permissions = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION}; requestPermissions(REQUEST_ACTION_START, permissions); } } private void stop() { startCallback = null; isStarting = false; setEnabled(false); } private void changePace(CallbackContext callbackContext, JSONArray data) throws JSONException { paceChangeCallback = callbackContext; Bundle event = new Bundle(); event.putString("name", BackgroundGeolocationService.ACTION_CHANGE_PACE); event.putBoolean("request", true); event.putBoolean("isMoving", data.getBoolean(0)); postEvent(event); } private void startService(int requestCode) { if (hasPermission(ACCESS_FINE_LOCATION) && hasPermission(ACCESS_COARSE_LOCATION)) { Activity activity = cordova.getActivity(); if (backgroundServiceIntent == null) { backgroundServiceIntent = new Intent(activity, BackgroundGeolocationService.class); } activity.startService(backgroundServiceIntent); } else { String[] permissions = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION}; requestPermissions(requestCode, permissions); } } private void onStarted(Bundle event) { isStarting = false; if (event.getBoolean("response") && !event.getBoolean("success")) { Toast.makeText(cordova.getActivity(), event.getString("message"), Toast.LENGTH_LONG).show(); if (startCallback != null) { startCallback.error(event.getString("message")); } } else if (startCallback != null) { startCallback.success(); } startCallback = null; } private void getLocations(CallbackContext callbackContext) { final Bundle event = new Bundle(); event.putString("name", BackgroundGeolocationService.ACTION_GET_LOCATIONS); event.putBoolean("request", true); getLocationsCallback = callbackContext; postEventInBackground(event); } private void getCount(CallbackContext callbackContext) { final Bundle event = new Bundle(); event.putString("name", BackgroundGeolocationService.ACTION_GET_COUNT); event.putBoolean("request", true); getCountCallbacks.add(callbackContext); postEventInBackground(event); } private void sync(CallbackContext callbackContext) { syncCallback = callbackContext; Activity activity = this.cordova.getActivity(); EventBus eventBus = EventBus.getDefault(); if (!eventBus.isRegistered(this)) { eventBus.register(this); } if (!BackgroundGeolocationService.isInstanceCreated()) { Intent syncIntent = new Intent(activity, BackgroundGeolocationService.class); syncIntent.putExtra("command", BackgroundGeolocationService.ACTION_SYNC); activity.startService(syncIntent); } else { final Bundle event = new Bundle(); event.putString("name", BackgroundGeolocationService.ACTION_SYNC); event.putBoolean("request", true); postEventInBackground(event); } } private void getCurrentPosition(CallbackContext callbackContext, JSONObject options) { isAcquiringCurrentPosition = true; addCurrentPositionListener(callbackContext); if (!isEnabled) { EventBus eventBus = EventBus.getDefault(); if (!eventBus.isRegistered(this)) { eventBus.register(this); } if (!BackgroundGeolocationService.isInstanceCreated()) { Activity activity = cordova.getActivity(); backgroundServiceIntent = new Intent(activity, BackgroundGeolocationService.class); backgroundServiceIntent.putExtra("command", BackgroundGeolocationService.ACTION_GET_CURRENT_POSITION); backgroundServiceIntent.putExtra("options", options.toString()); startService(REQUEST_ACTION_GET_CURRENT_POSITION); } } else { final Bundle event = new Bundle(); event.putString("name", BackgroundGeolocationService.ACTION_GET_CURRENT_POSITION); event.putBoolean("request", true); event.putString("options", options.toString()); postEventInBackground(event); } } private void addGeofence(CallbackContext callbackContext, JSONObject config) { try { String identifier = config.getString("identifier"); final Bundle event = new Bundle(); event.putString("name", BackgroundGeolocationService.ACTION_ADD_GEOFENCE); event.putBoolean("request", true); event.putFloat("radius", (float) config.getLong("radius")); event.putDouble("latitude", config.getDouble("latitude")); event.putDouble("longitude", config.getDouble("longitude")); event.putString("identifier", identifier); if (config.has("notifyOnEntry")) { event.putBoolean("notifyOnEntry", config.getBoolean("notifyOnEntry")); } if (config.has("notifyOnExit")) { event.putBoolean("notifyOnExit", config.getBoolean("notifyOnExit")); } if (config.has("notifyOnDwell")) { event.putBoolean("notifyOnDwell", config.getBoolean("notifyOnDwell")); } if (config.has("loiteringDelay")) { event.putInt("loiteringDelay", config.getInt("loiteringDelay")); } addGeofenceCallbacks.put(identifier, callbackContext); postEvent(event); } catch (JSONException e) { e.printStackTrace(); callbackContext.error(e.getMessage()); } } private void addGeofences(CallbackContext callbackContext, JSONArray geofences) { final Bundle event = new Bundle(); event.putString("name", BackgroundGeolocationService.ACTION_ADD_GEOFENCES); event.putBoolean("request", true); event.putString("geofences", geofences.toString()); addGeofenceCallbacks.put(BackgroundGeolocationService.ACTION_ADD_GEOFENCES, callbackContext); postEvent(event); } private void getGeofences(CallbackContext callbackContext) { getGeofencesCallback = callbackContext; Bundle event = new Bundle(); event.putString("name", BackgroundGeolocationService.ACTION_GET_GEOFENCES); event.putBoolean("request", true); postEventInBackground(event); } private void getOdometer(CallbackContext callbackContext) { Float value = settings.getFloat("odometer", 0); PluginResult result = new PluginResult(PluginResult.Status.OK, value); callbackContext.sendPluginResult(result); } private void resetOdometer(CallbackContext callbackContext) { SharedPreferences.Editor editor = settings.edit(); editor.putFloat("odometer", 0); editor.apply(); if (BackgroundGeolocationService.isInstanceCreated()) { Bundle event = new Bundle(); event.putString("name", BackgroundGeolocationService.ACTION_RESET_ODOMETER); event.putBoolean("request", true); postEventInBackground(event); } callbackContext.success(); } private void onResetOdometer(Bundle event) { // Received event from BackgroundService. Do Nothing. Callback already callced in #resetOdometer. } private void onAddGeofence(Bundle event) { boolean success = event.getBoolean("success"); String identifier = event.getString("identifier"); if (addGeofenceCallbacks.containsKey(identifier)) { CallbackContext callbackContext = addGeofenceCallbacks.get(identifier); if (success) { callbackContext.success(); } else { callbackContext.error(event.getString("error")); } addGeofenceCallbacks.remove(identifier); } } private void addGeofenceListener(CallbackContext callbackContext) { geofenceCallbacks.add(callbackContext); Activity activity = this.cordova.getActivity(); Intent launchIntent = activity.getIntent(); if (launchIntent.hasExtra("forceReload") && launchIntent.hasExtra("geofencingEvent")) { try { JSONObject geofencingEvent = new JSONObject(launchIntent.getStringExtra("geofencingEvent")); handleGeofencingEvent(geofencingEvent); } catch (JSONException e) { Log.w(TAG, e); } } } private void addCurrentPositionListener(CallbackContext callbackContext) { currentPositionCallbacks.add(callbackContext); } private void addLocationListener(CallbackContext callbackContext) { locationCallbacks.add(callbackContext); } private void addMotionChangeListener(CallbackContext callbackContext) { motionChangeCallbacks.add(callbackContext); Activity activity = this.cordova.getActivity(); Intent launchIntent = activity.getIntent(); if (launchIntent.hasExtra("forceReload")) { if (launchIntent.getStringExtra("name").equalsIgnoreCase(BackgroundGeolocationService.ACTION_ON_MOTION_CHANGE)) { Bundle event = launchIntent.getExtras(); this.onEventMainThread(event); } launchIntent.removeExtra("forceReload"); launchIntent.removeExtra("location"); } } private void addHttpListener(CallbackContext callbackContext) { httpResponseCallbacks.add(callbackContext); } private Boolean removeGeofence(String identifier) { final Bundle event = new Bundle(); event.putString("name", BackgroundGeolocationService.ACTION_REMOVE_GEOFENCE); event.putBoolean("request", true); event.putString("identifier", identifier); postEvent(event); return true; } private Boolean removeGeofences() { final Bundle event = new Bundle(); event.putString("name", BackgroundGeolocationService.ACTION_REMOVE_GEOFENCES); event.putBoolean("request", true); postEvent(event); return true; } private void insertLocation(JSONObject params, CallbackContext callbackContext) { if (!BackgroundGeolocationService.isInstanceCreated()) { Log.i(TAG, "Cannot insertLocation when the BackgroundGeolocationService is not running. Plugin must be started first"); return; } if (!params.has("uuid")) { callbackContext.error("insertLocation params must contain uuid"); return; } if (!params.has("timestamp")) { callbackContext.error("insertLocation params must contain timestamp"); return; } if (!params.has("coords")) { callbackContext.error("insertLocation params must contains a coords {}"); return; } Bundle event = new Bundle(); event.putString("name", BackgroundGeolocationService.ACTION_INSERT_LOCATION); event.putBoolean("request", true); try { String uuid = params.getString("uuid"); event.putString("location", params.toString()); insertLocationCallbacks.put(uuid, callbackContext); } catch (JSONException e) { e.printStackTrace(); } postEvent(event); } private void setEnabled(boolean value) { // Don't set a state that we're already in. Log.i(TAG, "- Enable: " + isEnabled + " → " + value); Activity activity = cordova.getActivity(); boolean wasEnabled = isEnabled; isEnabled = value; isMoving = null; Intent launchIntent = activity.getIntent(); if (launchIntent.hasExtra("forceReload")) { if (launchIntent.hasExtra("location")) { try { JSONObject location = new JSONObject(launchIntent.getStringExtra("location")); onLocationChange(location); } catch (JSONException e) { Log.w(TAG, e); } } } SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("enabled", isEnabled); editor.apply(); EventBus eventBus = EventBus.getDefault(); if (isEnabled) { synchronized(eventBus) { if (!eventBus.isRegistered(this)) { eventBus.register(this); } } if (!BackgroundGeolocationService.isInstanceCreated()) { activity.startService(backgroundServiceIntent); } else { final Bundle event = new Bundle(); if (!wasEnabled) { event.putString("name", BackgroundGeolocationService.ACTION_START); } else { event.putString("name", BackgroundGeolocationService.ACTION_GET_CURRENT_POSITION); } event.putBoolean("request", true); postEvent(event); onStarted(event); } } else { Bundle event = new Bundle(); event.putString("name", BackgroundGeolocationService.ACTION_STOP); event.putBoolean("request", true); postEvent(event); synchronized(eventBus) { if (eventBus.isRegistered(this)) { eventBus.unregister(this); } } //activity.stopService(backgroundServiceIntent); backgroundServiceIntent = null; } } private boolean setConfig(JSONObject config) { try { JSONObject merged = new JSONObject(); JSONObject[] objs = new JSONObject[] { mConfig, config }; for (JSONObject obj : objs) { Iterator it = obj.keys(); while (it.hasNext()) { String key = (String)it.next(); merged.put(key, obj.get(key)); } } mConfig = merged; } catch (JSONException e) { e.printStackTrace(); return false; } cordova.getThreadPool().execute(new Runnable() { public void run() { applyConfig(); Bundle event = new Bundle(); event.putString("name", BackgroundGeolocationService.ACTION_SET_CONFIG); event.putBoolean("request", true); postEvent(event); } }); return true; } private boolean applyConfig() { if (mConfig.has("stopOnTerminate")) { try { stopOnTerminate = mConfig.getBoolean("stopOnTerminate"); } catch (JSONException e) { e.printStackTrace(); } } SharedPreferences.Editor editor = settings.edit(); try { if (preferences.contains("cordova-background-geolocation-license")) { mConfig.put("license", preferences.getString("cordova-background-geolocation-license", null)); } if (preferences.contains("cordova-background-geolocation-orderId")) { mConfig.put("orderId", preferences.getString("cordova-background-geolocation-orderId", null)); } if (mConfig.has("isMoving")) { editor.putBoolean("isMoving", mConfig.getBoolean("isMoving")); } } catch (JSONException e) { e.printStackTrace(); Log.w(TAG, "- Failed to apply license"); } editor.putString("config", mConfig.toString()); editor.apply(); return true; } private void clearDatabase(CallbackContext callbackContext) { final Bundle event = new Bundle(); event.putString("name", BackgroundGeolocationService.ACTION_CLEAR_DATABASE); event.putBoolean("request", true); postEventInBackground(event); callbackContext.success(); } private String readLog() { try { Process process = Runtime.getRuntime().exec("logcat -d"); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); StringBuilder log = new StringBuilder(); String line = ""; while ((line = bufferedReader.readLine()) != null) { log.append(line + "\n"); } return log.toString(); } catch (IOException e) { e.printStackTrace(); return null; } } private void getLog(final CallbackContext callback) { cordova.getThreadPool().execute(new Runnable() { public void run() { String log = readLog(); if (log != null) { callback.success(log); } else { callback.error("Failed to read logs"); } } }); } private void emailLog(final CallbackContext callback, final String email) { cordova.getThreadPool().execute(new Runnable() { public void run() { String log = readLog(); if (log == null) { callback.error(500); return; } Intent mailer = new Intent(Intent.ACTION_SEND); mailer.setType("message/rfc822"); mailer.putExtra(Intent.EXTRA_EMAIL, new String[]{email}); mailer.putExtra(Intent.EXTRA_SUBJECT, "BackgroundGeolocation log"); try { JSONObject state = getState(); if (state.has("license")) { state.put("license", "<SECRET>"); } if (state.has("orderId")) { state.put("orderId", "<SECRET>"); } mailer.putExtra(Intent.EXTRA_TEXT, state.toString(4)); } catch (JSONException e) { Log.w(TAG, "- Failed to write state to email body"); e.printStackTrace(); } File file = new File(Environment.getExternalStorageDirectory(), "background-geolocation.log"); try { FileOutputStream stream = new FileOutputStream(file); try { stream.write(log.getBytes()); stream.close(); mailer.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file)); file.deleteOnExit(); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { Log.i(TAG, "FileNotFound"); e.printStackTrace(); } try { cordova.getActivity().startActivityForResult(Intent.createChooser(mailer, "Send log: " + email + "..."), 1); callback.success(); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(cordova.getActivity(), "There are no email clients installed.", Toast.LENGTH_SHORT).show(); callback.error("There are no email clients installed"); } } }); } public void onPause(boolean multitasking) { Log.i(TAG, "- onPause"); if (isEnabled) { } } public void onResume(boolean multitasking) { Log.i(TAG, "- onResume"); if (isEnabled) { } } /** * EventBus listener for Event Bundle * @param {Bundle} event */ @Subscribe public void onEventMainThread(Bundle event) { if (event.containsKey("request")) { return; } String name = event.getString("name"); if (BackgroundGeolocationService.ACTION_START.equalsIgnoreCase(name)) { onStarted(event); } else if (BackgroundGeolocationService.ACTION_ON_MOTION_CHANGE.equalsIgnoreCase(name)) { boolean nowMoving = event.getBoolean("isMoving"); try { JSONObject locationData = new JSONObject(event.getString("location")); onMotionChange(nowMoving, locationData); } catch (JSONException e) { Log.e(TAG, "Error decoding JSON"); e.printStackTrace(); } } else if (BackgroundGeolocationService.ACTION_GET_LOCATIONS.equalsIgnoreCase(name)) { try { JSONObject params = new JSONObject(); params.put("locations", new JSONArray(event.getString("data"))); params.put("taskId", "android-bg-task-id"); PluginResult result = new PluginResult(PluginResult.Status.OK, params); getLocationsCallback.sendPluginResult(result); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); PluginResult result = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage()); getLocationsCallback.sendPluginResult(result); } } else if (BackgroundGeolocationService.ACTION_SYNC.equalsIgnoreCase(name)) { Boolean success = event.getBoolean("success"); if (success) { try { JSONObject params = new JSONObject(); params.put("locations", new JSONArray(event.getString("data"))); params.put("taskId", "android-bg-task-id"); PluginResult result = new PluginResult(PluginResult.Status.OK, params); syncCallback.sendPluginResult(result); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { PluginResult result = new PluginResult(PluginResult.Status.IO_EXCEPTION, event.getString("message")); syncCallback.sendPluginResult(result); } } else if (BackgroundGeolocationService.ACTION_RESET_ODOMETER.equalsIgnoreCase(name)) { this.onResetOdometer(event); } else if (BackgroundGeolocationService.ACTION_CHANGE_PACE.equalsIgnoreCase(name)) { this.onChangePace(event); } else if (BackgroundGeolocationService.ACTION_GET_GEOFENCES.equalsIgnoreCase(name)) { try { JSONArray json = new JSONArray(event.getString("data")); PluginResult result = new PluginResult(PluginResult.Status.OK, json); getGeofencesCallback.sendPluginResult(result); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); PluginResult result = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage()); getGeofencesCallback.sendPluginResult(result); } } else if (name.equalsIgnoreCase(BackgroundGeolocationService.ACTION_GOOGLE_PLAY_SERVICES_CONNECT_ERROR)) { GoogleApiAvailability.getInstance().getErrorDialog(this.cordova.getActivity(), event.getInt("errorCode"), 1001).show(); } else if (name.equalsIgnoreCase(BackgroundGeolocationService.ACTION_LOCATION_ERROR)) { this.onLocationError(event); } else if (name.equalsIgnoreCase(BackgroundGeolocationService.ACTION_ADD_GEOFENCE)) { this.onAddGeofence(event); } else if (name.equalsIgnoreCase(BackgroundGeolocationService.ACTION_ADD_GEOFENCES)) { this.onAddGeofence(event); } else if (name.equalsIgnoreCase(BackgroundGeolocationService.ACTION_HTTP_RESPONSE)) { this.onHttpResponse(event); } else if (name.equalsIgnoreCase(BackgroundGeolocationService.ACTION_GET_CURRENT_POSITION)) { this.onLocationError(event); } else if (name.equalsIgnoreCase(BackgroundGeolocationService.ACTION_INSERT_LOCATION)) { this.onInsertLocation(event); } else if (name.equalsIgnoreCase(BackgroundGeolocationService.ACTION_GET_COUNT)) { this.onGetCount(event); } } private void finishAcquiringCurrentPosition(boolean success) { // Current position has arrived: release the hounds. isAcquiringCurrentPosition = false; // When currentPosition is explicitly requested while plugin is stopped, shut Service down again and stop listening to EventBus if (!isEnabled) { EventBus eventBus = EventBus.getDefault(); synchronized(eventBus) { if (eventBus.isRegistered(this)) { eventBus.unregister(this); } } } } public void onHttpResponse(Bundle event) { PluginResult result; try { JSONObject params = new JSONObject(); params.put("status", event.getInt("status")); params.put("responseText", event.getString("responseText")); result = new PluginResult(PluginResult.Status.OK, params); } catch (JSONException e) { e.printStackTrace(); result = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage()); } result.setKeepCallback(true); for (CallbackContext callback : httpResponseCallbacks) { callback.sendPluginResult(result); } } private void onInsertLocation(Bundle event) { String uuid = event.getString("uuid"); Log.i(TAG, "- Cordova plugin: onInsertLocation: " + uuid); if (insertLocationCallbacks.containsKey(uuid)) { CallbackContext callback = insertLocationCallbacks.get(uuid); callback.success(); } else { Log.i(TAG, "- onInsertLocation failed to find its success-callback for " + uuid); } } private void onGetCount(Bundle event) { int count = event.getInt("count"); Log.i(TAG, "- Cordova plugin: getCount: " + count); for (CallbackContext callback : getCountCallbacks) { callback.success(count); } getCountCallbacks.clear(); } private void onMotionChange(boolean nowMoving, JSONObject location) { isMoving = nowMoving; PluginResult result; try { JSONObject params = new JSONObject(); params.put("location", location); params.put("isMoving", isMoving); params.put("taskId", "android-bg-task-id"); result = new PluginResult(PluginResult.Status.OK, params); } catch (JSONException e) { e.printStackTrace(); result = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage()); } result.setKeepCallback(true); for (CallbackContext callback : motionChangeCallbacks) { callback.sendPluginResult(result); } } private void onChangePace(Bundle event) { Boolean success = event.getBoolean("success"); if (success) { int state = event.getBoolean("isMoving") ? 1 : 0; paceChangeCallback.success(state); } else { paceChangeCallback.error(event.getInt("code")); } } private JSONObject getState() { JSONObject state = new JSONObject(); try { if (settings.contains("config")) { state = new JSONObject(settings.getString("config", "{}")); } state.put("enabled", isEnabled); state.put("isMoving", isMoving); } catch (JSONException e) { e.printStackTrace(); } return state; } /** * EventBus listener * @param {Location} location */ @Subscribe public void onEventMainThread(Location location) { JSONObject locationData = BackgroundGeolocationService.locationToJson(location, currentActivity); Bundle meta = location.getExtras(); if (meta != null) { String action = meta.getString("action"); boolean motionChanged = action.equalsIgnoreCase(BackgroundGeolocationService.ACTION_ON_MOTION_CHANGE); if (motionChanged) { boolean nowMoving = meta.getBoolean("isMoving"); onMotionChange(nowMoving, locationData); } } this.onLocationChange(locationData); } private void onLocationChange(JSONObject location) { PluginResult result = new PluginResult(PluginResult.Status.OK, location); result.setKeepCallback(true); for (CallbackContext callback : locationCallbacks) { callback.sendPluginResult(result); } if (isAcquiringCurrentPosition) { finishAcquiringCurrentPosition(true); // Execute callbacks. result = new PluginResult(PluginResult.Status.OK, location); result.setKeepCallback(false); for (CallbackContext callback : currentPositionCallbacks) { callback.sendPluginResult(result); } currentPositionCallbacks.clear(); } } /** * EventBus handler for Geofencing events */ @Subscribe public void onEventMainThread(GeofencingEvent geofenceEvent) { Log.i(TAG, "- Rx GeofencingEvent: " + geofenceEvent); if (!geofenceCallbacks.isEmpty()) { JSONObject params = BackgroundGeolocationService.geofencingEventToJson(geofenceEvent, currentActivity); handleGeofencingEvent(params); } } private void handleGeofencingEvent(JSONObject params) { PluginResult result = new PluginResult(PluginResult.Status.OK, params); result.setKeepCallback(true); for (CallbackContext callback : geofenceCallbacks) { callback.sendPluginResult(result); } } private void playSound(int soundId) { int duration = 1000; toneGenerator = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100); toneGenerator.startTone(soundId, duration); } private void postEvent(Bundle event) { EventBus.getDefault().post(event); } private void postEventInBackground(final Bundle event) { cordova.getThreadPool().execute(new Runnable() { public void run() { EventBus.getDefault().post(event); } }); } private Boolean isDebugging() { return settings.contains("debug") && settings.getBoolean("debug", false); } private void onError(String error) { String message = "BG Geolocation caught a Javascript exception while running in background-thread:\n".concat(error); Log.e(TAG, message); // Show alert popup with js error if (isDebugging()) { playSound(68); AlertDialog.Builder builder = new AlertDialog.Builder(this.cordova.getActivity()); builder.setMessage(message) .setCancelable(false) .setNegativeButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { //do things } }); AlertDialog alert = builder.create(); alert.show(); } } private void onGetCurrentPositionFailure(Bundle event) { finishAcquiringCurrentPosition(false); for (CallbackContext callback : currentPositionCallbacks) { callback.error(408); // aka HTTP 408 Request Timeout } currentPositionCallbacks.clear(); } private void onLocationError(Bundle event) { Integer code = event.getInt("code"); if (code == BackgroundGeolocationService.LOCATION_ERROR_DENIED) { if (isDebugging()) { Toast.makeText(this.cordova.getActivity(), "Location services disabled!", Toast.LENGTH_SHORT).show(); } } PluginResult result = new PluginResult(PluginResult.Status.ERROR, code); result.setKeepCallback(true); for (CallbackContext callback : locationCallbacks) { callback.sendPluginResult(result); } if (isAcquiringCurrentPosition) { finishAcquiringCurrentPosition(false); for (CallbackContext callback : currentPositionCallbacks) { callback.error(code); } currentPositionCallbacks.clear(); } } private boolean hasPermission(String action) { try { Method methodToFind = cordova.getClass().getMethod("hasPermission", String.class); if (methodToFind != null) { try { return (Boolean) methodToFind.invoke(cordova, action); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } catch(NoSuchMethodException e) { // Probably SDK < 23 (MARSHMALLOW implmements fine-grained, user-controlled permissions). return true; } return true; } private void requestPermissions(int requestCode, String[] action) { try { Method methodToFind = cordova.getClass().getMethod("requestPermissions", CordovaPlugin.class, int.class, String[].class); if (methodToFind != null) { try { methodToFind.invoke(cordova, this, requestCode, action); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } catch(NoSuchMethodException e) { e.printStackTrace(); } } public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) throws JSONException { for(int r:grantResults) { if(r == PackageManager.PERMISSION_DENIED) { int errorCode = BackgroundGeolocationService.LOCATION_ERROR_DENIED; PluginResult result = new PluginResult(PluginResult.Status.ERROR, errorCode); if (requestCode == REQUEST_ACTION_START) { if (startCallback != null) { startCallback.sendPluginResult(result); startCallback = null; } } else if (requestCode == REQUEST_ACTION_GET_CURRENT_POSITION) { Bundle event = new Bundle(); event.putString("name", BackgroundGeolocationService.ACTION_GET_CURRENT_POSITION); event.putInt("code", errorCode); onLocationError(event); } return; } } switch(requestCode) { case REQUEST_ACTION_START: setEnabled(true); break; case REQUEST_ACTION_GET_CURRENT_POSITION: startService(requestCode); break; } } /** * Override method in CordovaPlugin. * Checks to see if it should turn off */ public void onDestroy() { Log.i(TAG, "- onDestroy"); Log.i(TAG, " stopOnTerminate: " + stopOnTerminate); Log.i(TAG, " isEnabled: " + isEnabled); Activity activity = this.cordova.getActivity(); EventBus eventBus = EventBus.getDefault(); synchronized(eventBus) { if (eventBus.isRegistered(this)) { eventBus.unregister(this); } } if(isEnabled && stopOnTerminate) { this.cordova.getActivity().stopService(backgroundServiceIntent); } } }
5d774cf943a93e68a5177888989783a6b98760d7
cb843b45cf1b4edb0992845d5fd571dd93dc2da3
/myportal2/src/main/java/com/bitacademy/myportal2/service/FileUploadService.java
d2f2712c09527e83eeb466e62489d5160a9244ef
[]
no_license
jihoonigogo/myportal2
3f8ecbf69204a5192cf1d29f54e70e9599676d21
5fe67e21a6d811829c5da786ca393d7b89c96f3c
refs/heads/master
2023-04-07T22:19:50.669924
2021-04-22T00:58:17
2021-04-22T00:58:17
357,468,452
0
0
null
null
null
null
UTF-8
Java
false
false
1,781
java
package com.bitacademy.myportal2.service; import java.io.FileOutputStream; import java.io.IOException; import java.util.Calendar; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; @Service public class FileUploadService { private static String SAVE_PATH = "d:/upload"; private static Logger logger =LoggerFactory.getLogger(FileUploadService.class); public String store(MultipartFile multipartFile) { String saveFilename =""; try { String originalFileName = multipartFile.getOriginalFilename(); Long size =multipartFile.getSize(); logger.debug("multipart-원본파일명:" +originalFileName); logger.debug("multipart-파일사이즈:"+ size); //확장자 분리 String extName = originalFileName .substring(originalFileName.lastIndexOf(".")); logger.debug("파일확장자" + extName); //저장된 실제 파일명 얻어오기 saveFilename=getSaveFilename(extName); logger.debug("실제저장될 파일명 :" + saveFilename); // 멀티파트파일을 save path writeFile(multipartFile,saveFilename); } catch (IOException e) { e.printStackTrace(); } return saveFilename; } private String getSaveFilename(String ext) { // 확장자를 인자값으로? Calendar cal = Calendar.getInstance(); return String.valueOf(cal.getTimeInMillis()/1000) + ext.toLowerCase(); } private void writeFile(MultipartFile mFile,String saveFilename) throws IOException { //mfile을 savefilename으로 저장 byte[] fileData =mFile.getBytes(); // 실제 2진 파일 정보배열 FileOutputStream fos = new FileOutputStream(SAVE_PATH+"/"+saveFilename); fos.write(fileData); fos.flush(); fos.close(); } }
d840709c196569d5cdad2f41bb491dc72f703051
48e835e6f176a8ac9ae3ca718e8922891f1e5a18
/benchmark/training/io/confluent/kafkarest/unit/ConsumerResourceAvroTest.java
a1752485fb62e5f6ba3869c599009930f3db492c
[]
no_license
STAMP-project/dspot-experiments
f2c7a639d6616ae0adfc491b4cb4eefcb83d04e5
121487e65cdce6988081b67f21bbc6731354a47f
refs/heads/master
2023-02-07T14:40:12.919811
2019-11-06T07:17:09
2019-11-06T07:17:09
75,710,758
14
19
null
2023-01-26T23:57:41
2016-12-06T08:27:42
null
UTF-8
Java
false
false
5,785
java
/** * Copyright 2018 Confluent Inc. * * Licensed under the Confluent Community License (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.confluent.io/confluent-community-license * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package io.confluent.kafkarest.unit; import Invocation.Builder; import com.fasterxml.jackson.databind.JsonNode; import io.confluent.kafkarest.AvroConsumerState; import io.confluent.kafkarest.TestUtils; import io.confluent.kafkarest.Versions; import io.confluent.kafkarest.entities.AvroConsumerRecord; import io.confluent.kafkarest.entities.ConsumerRecord; import io.confluent.kafkarest.entities.CreateConsumerInstanceResponse; import io.confluent.kafkarest.entities.EmbeddedFormat; import io.confluent.kafkarest.entities.TopicPartitionOffset; import io.confluent.rest.RestConfigException; import java.util.Arrays; import java.util.List; import javax.ws.rs.client.Entity; import javax.ws.rs.client.Invocation; import javax.ws.rs.core.Response; import org.easymock.EasyMock; import org.junit.Assert; import org.junit.Test; public class ConsumerResourceAvroTest extends AbstractConsumerResourceTest { public ConsumerResourceAvroTest() throws RestConfigException { super(); } @Test public void testReadCommit() { List<? extends ConsumerRecord<JsonNode, JsonNode>> expectedReadLimit = Arrays.asList(new AvroConsumerRecord(AbstractConsumerResourceTest.topicName, TestUtils.jsonTree("\"key1\""), TestUtils.jsonTree("\"value1\""), 0, 10)); List<? extends ConsumerRecord<JsonNode, JsonNode>> expectedReadNoLimit = Arrays.asList(new AvroConsumerRecord(AbstractConsumerResourceTest.topicName, TestUtils.jsonTree("\"key2\""), TestUtils.jsonTree("\"value2\""), 1, 15), new AvroConsumerRecord(AbstractConsumerResourceTest.topicName, TestUtils.jsonTree("\"key3\""), TestUtils.jsonTree("\"value3\""), 2, 20)); List<TopicPartitionOffset> expectedOffsets = Arrays.asList(new TopicPartitionOffset(AbstractConsumerResourceTest.topicName, 0, 10, 10), new TopicPartitionOffset(AbstractConsumerResourceTest.topicName, 1, 15, 15), new TopicPartitionOffset(AbstractConsumerResourceTest.topicName, 2, 20, 20)); for (TestUtils.RequestMediaType mediatype : TestUtils.V1_ACCEPT_MEDIATYPES_AVRO) { for (String requestMediatype : TestUtils.V1_REQUEST_ENTITY_TYPES) { expectCreateGroup(new io.confluent.kafkarest.entities.ConsumerInstanceConfig(EmbeddedFormat.AVRO)); expectReadTopic(AbstractConsumerResourceTest.topicName, AvroConsumerState.class, 10, expectedReadLimit, null); expectReadTopic(AbstractConsumerResourceTest.topicName, AvroConsumerState.class, expectedReadNoLimit, null); expectCommit(expectedOffsets, null); EasyMock.replay(consumerManager); Response response = request(("/consumers/" + (AbstractConsumerResourceTest.groupName)), mediatype.header).post(Entity.entity(new io.confluent.kafkarest.entities.ConsumerInstanceConfig(EmbeddedFormat.AVRO), requestMediatype)); TestUtils.assertOKResponse(response, mediatype.expected); final CreateConsumerInstanceResponse createResponse = TestUtils.tryReadEntityOrLog(response, CreateConsumerInstanceResponse.class); // Read with size limit String readUrl = ((instanceBasePath(createResponse)) + "/topics/") + (AbstractConsumerResourceTest.topicName); Invocation.Builder builder = getJerseyTest().target(readUrl).queryParam("max_bytes", 10).request(); if ((mediatype.header) != null) { builder.accept(mediatype.header); } Response readLimitResponse = builder.get(); // Most specific default is different when retrieving embedded data String expectedMediatype = ((mediatype.header) != null) ? mediatype.expected : Versions.KAFKA_V1_JSON_AVRO; TestUtils.assertOKResponse(readLimitResponse, expectedMediatype); final List<AvroConsumerRecord> readLimitResponseRecords = TestUtils.tryReadEntityOrLog(readLimitResponse, new javax.ws.rs.core.GenericType<List<AvroConsumerRecord>>() {}); Assert.assertEquals(expectedReadLimit, readLimitResponseRecords); // Read without size limit Response readResponse = request(readUrl, mediatype.header).get(); TestUtils.assertOKResponse(readResponse, expectedMediatype); final List<AvroConsumerRecord> readResponseRecords = TestUtils.tryReadEntityOrLog(readResponse, new javax.ws.rs.core.GenericType<List<AvroConsumerRecord>>() {}); Assert.assertEquals(expectedReadNoLimit, readResponseRecords); String commitUrl = (instanceBasePath(createResponse)) + "/offsets/"; Response commitResponse = request(commitUrl, mediatype.header).post(Entity.entity(null, requestMediatype)); TestUtils.assertOKResponse(response, mediatype.expected); final List<TopicPartitionOffset> committedOffsets = TestUtils.tryReadEntityOrLog(commitResponse, new javax.ws.rs.core.GenericType<List<TopicPartitionOffset>>() {}); Assert.assertEquals(expectedOffsets, committedOffsets); EasyMock.verify(consumerManager); EasyMock.reset(consumerManager); } } } }
cba4ed74315f61c60ee4472981868c453f14512a
9623f83defac3911b4780bc408634c078da73387
/powercraft/temp/src/minecraft/net/minecraft/src/KeyBinding.java
94d094f89be68a8b47c12ce31a12345db2e474f8
[]
no_license
BlearStudio/powercraft-legacy
42b839393223494748e8b5d05acdaf59f18bd6c6
014e9d4d71bd99823cf63d4fbdb65c1b83fde1f8
refs/heads/master
2021-01-21T21:18:55.774908
2015-04-06T20:45:25
2015-04-06T20:45:25
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,029
java
package net.minecraft.src; import cpw.mods.fml.common.Side; import cpw.mods.fml.common.asm.SideOnly; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import net.minecraft.src.IntHashMap; @SideOnly(Side.CLIENT) public class KeyBinding { public static List field_74516_a = new ArrayList(); public static IntHashMap field_74514_b = new IntHashMap(); public String field_74515_c; public int field_74512_d; public boolean field_74513_e; public int field_74511_f = 0; public static void func_74507_a(int p_74507_0_) { KeyBinding var1 = (KeyBinding)field_74514_b.func_76041_a(p_74507_0_); if(var1 != null) { ++var1.field_74511_f; } } public static void func_74510_a(int p_74510_0_, boolean p_74510_1_) { KeyBinding var2 = (KeyBinding)field_74514_b.func_76041_a(p_74510_0_); if(var2 != null) { var2.field_74513_e = p_74510_1_; } } public static void func_74506_a() { Iterator var0 = field_74516_a.iterator(); while(var0.hasNext()) { KeyBinding var1 = (KeyBinding)var0.next(); var1.func_74505_d(); } } public static void func_74508_b() { field_74514_b.func_76046_c(); Iterator var0 = field_74516_a.iterator(); while(var0.hasNext()) { KeyBinding var1 = (KeyBinding)var0.next(); field_74514_b.func_76038_a(var1.field_74512_d, var1); } } public KeyBinding(String p_i3003_1_, int p_i3003_2_) { this.field_74515_c = p_i3003_1_; this.field_74512_d = p_i3003_2_; field_74516_a.add(this); field_74514_b.func_76038_a(p_i3003_2_, this); } public boolean func_74509_c() { if(this.field_74511_f == 0) { return false; } else { --this.field_74511_f; return true; } } private void func_74505_d() { this.field_74511_f = 0; this.field_74513_e = false; } }
[ "[email protected]@ed9f5d1b-00bb-0f29-faab-e8ebad1a710c" ]
[email protected]@ed9f5d1b-00bb-0f29-faab-e8ebad1a710c
9a69ea12e8913d32c45d018204541a2dbf782efe
2c3b7e69e9414d1b708b4722fa3ec1485d5109bc
/SI-gRPC assignment/src/main/java/service/StudentServiceImpl.java
869fa6a3c0ba07586086aeeeed0214352474701d
[]
no_license
cycloniccornet/gRPC-Microservice
c7bd13ca58800f3ade4d1072452289bc40dd66a1
ac16b1d5fba701952206b9b41d50ab264e77950f
refs/heads/main
2023-07-26T21:20:47.541287
2021-09-12T13:39:01
2021-09-12T13:39:01
405,651,405
0
0
null
null
null
null
UTF-8
Java
false
false
3,565
java
package service; import client.ResultClient; import com.students_management.stubs.student.*; import dao.StudentDao; import domain.Student; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.Status; import io.grpc.stub.StreamObserver; import java.util.List; import java.util.NoSuchElementException; import java.util.logging.Level; import java.util.logging.Logger; public class StudentServiceImpl extends StudentServiceGrpc.StudentServiceImplBase { // We need to have an instance of the dao class to work with the database private StudentDao studentDao = new StudentDao(); // Let's use a logger to log everything that we want private static final Logger logger = Logger.getLogger(StudentServiceImpl.class.getName()); // We have to override the getStudentInfo that was defined in the StudentService class // The StudentService class is an autogenerated class by the proto file // So, let's override the getStudentInfo method here. @Override public void getStudentInfo(StudentRequest request, StreamObserver<StudentResponse> responseObserver) { String studentId = request.getStudentId();// the student ID should be passed with the request message try{ Student student = studentDao.findById(studentId); // Let's find the student information from the student table /* The getResults method will help us to fetch the results for the student from the result service. this method will call the result service through its client and bring back the result as a list of strings */ List<String> resultResponse = getResults(studentId); // Once all the results are clear, we can build our response message StudentResponse studentResponse = StudentResponse.newBuilder() .setStudentId(studentId) .setName(student.getName()) .setAge(student.getAge()) .setGender(Gender.valueOf(student.getGender())) .setMaths(Grade.valueOf(resultResponse.get(0))) .setArt(Grade.valueOf(resultResponse.get(1))) .setChemistry(Grade.valueOf(resultResponse.get(2))) .build(); /* gRPC works in an asynchronous manner, so if you have ever worked with asynchronous programming you would know what will happen with following two methods. with the onNext method we send the response, once the response is sent we use onCompleted() */ responseObserver.onNext(studentResponse); responseObserver.onCompleted(); }catch (NoSuchElementException e){ logger.log(Level.SEVERE, "NO STUDENT FOUND WITH THE STUDENT ID :- "+studentId); // If some error occurs we sent an error with the following status which is not_found responseObserver.onError(Status.NOT_FOUND.asRuntimeException()); } } public List<String> getResults(String studentId){ // To connect with the ResultClient we need something called a channel // This is how you create a channel, ManagedChannel channel = ManagedChannelBuilder.forTarget("localhost:8080") .usePlaintext() .build(); ResultClient resultClient = new ResultClient(channel); return resultClient.getResults(studentId); } }
b13a7cad46c73f6b2d0a3533ee9755c7c966f3f1
5344e76be0bac56beb896069a841476ee5c23f20
/src/main/java/com/owncloud/android/utils/DisplayUtils.java
a2dfb90aaab37c489428c02a93a37a58ad231a05
[]
no_license
Sanchit517/drone-CA
6bf4d3781bff46fe6a932c43b578419c4fa150b7
ac2fdffeecaa7b9773a0369f1e561a0bc0a023b7
refs/heads/master
2022-04-28T19:32:17.930127
2020-04-19T14:34:40
2020-04-19T14:34:40
257,022,126
0
0
null
null
null
null
UTF-8
Java
false
false
11,394
java
/* * ownCloud Android client application * * @author Bartek Przybylski * @author David A. Velasco * @author David González Verdugo * Copyright (C) 2011 Bartek Przybylski * Copyright (C) 2019 ownCloud GmbH. * <p> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * <p> * 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. * <p> * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.owncloud.android.utils; import android.accounts.Account; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.graphics.Point; import android.graphics.PorterDuff; import android.os.Build; import android.text.format.DateUtils; import android.view.Display; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.SeekBar; import androidx.core.content.ContextCompat; import com.google.android.material.snackbar.Snackbar; import com.owncloud.android.MainApp; import com.owncloud.android.R; import com.owncloud.android.datamodel.OCFile; import com.owncloud.android.datamodel.ThumbnailsCacheManager; import java.math.BigDecimal; import java.net.IDN; import java.text.DateFormat; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * A helper class for some string operations. */ public class DisplayUtils { private static final String OWNCLOUD_APP_NAME = "ownCloud"; private static final String[] sizeSuffixes = {"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}; private static final int[] sizeScales = {0, 0, 1, 1, 1, 2, 2, 2, 2}; private static Map<String, String> mimeType2HumanReadable; static { mimeType2HumanReadable = new HashMap<>(); // images mimeType2HumanReadable.put("image/jpeg", "JPEG image"); mimeType2HumanReadable.put("image/jpg", "JPEG image"); mimeType2HumanReadable.put("image/png", "PNG image"); mimeType2HumanReadable.put("image/bmp", "Bitmap image"); mimeType2HumanReadable.put("image/gif", "GIF image"); mimeType2HumanReadable.put("image/svg+xml", "JPEG image"); mimeType2HumanReadable.put("image/tiff", "TIFF image"); // music mimeType2HumanReadable.put("audio/mpeg", "MP3 music file"); mimeType2HumanReadable.put("application/ogg", "OGG music file"); } /** * Converts the file size in bytes to human readable output. * <ul> * <li>appends a size suffix, e.g. B, KB, MB etc.</li> * <li>rounds the size based on the suffix to 0,1 or 2 decimals</li> * </ul> * * @param bytes Input file size * @return Like something readable like "12 MB" */ public static String bytesToHumanReadable(long bytes, Context context) { if (bytes < 0) { return context.getString(R.string.common_pending); } else { double result = bytes; int attachedSuff = 0; while (result >= 1024 && attachedSuff < sizeSuffixes.length) { result /= 1024.; attachedSuff++; } BigDecimal readableResult = new BigDecimal(result).setScale( sizeScales[attachedSuff], BigDecimal.ROUND_HALF_UP ).stripTrailingZeros(); // Unscale only values with ten exponent return (readableResult.scale() < 0 ? readableResult.setScale(0) : readableResult ) + " " + sizeSuffixes[attachedSuff]; } } /** * Converts MIME types like "image/jpg" to more end user friendly output * like "JPG image". * * @param mimetype MIME type to convert * @return A human friendly version of the MIME type */ public static String convertMIMEtoPrettyPrint(String mimetype) { if (mimeType2HumanReadable.containsKey(mimetype)) { return mimeType2HumanReadable.get(mimetype); } if (mimetype.split("/").length >= 2) { return mimetype.split("/")[1].toUpperCase() + " file"; } return "Unknown type"; } /** * Converts Unix time to human readable format * * @param milliseconds that have passed since 01/01/1970 * @return The human readable time for the users locale */ public static String unixTimeToHumanReadable(long milliseconds) { Date date = new Date(milliseconds); DateFormat df = DateFormat.getDateTimeInstance(); return df.format(date); } public static int getSeasonalIconId() { if (Calendar.getInstance().get(Calendar.DAY_OF_YEAR) >= 354 && MainApp.Companion.getAppContext().getString(R.string.app_name).equals(OWNCLOUD_APP_NAME)) { return R.drawable.winter_holidays_icon; } else { return R.mipmap.icon; } } /** * Converts an internationalized domain name (IDN) in an URL to and from ASCII/Unicode. * * @param url the URL where the domain name should be converted * @param toASCII if true converts from Unicode to ASCII, if false converts from ASCII to Unicode * @return the URL containing the converted domain name */ public static String convertIdn(String url, boolean toASCII) { String urlNoDots = url; String dots = ""; while (urlNoDots.startsWith(".")) { urlNoDots = url.substring(1); dots = dots + "."; } // Find host name after '//' or '@' int hostStart = 0; if (urlNoDots.contains("//")) { hostStart = url.indexOf("//") + "//".length(); } else if (url.contains("@")) { hostStart = url.indexOf("@") + "@".length(); } int hostEnd = url.substring(hostStart).indexOf("/"); // Handle URL which doesn't have a path (path is implicitly '/') hostEnd = (hostEnd == -1 ? urlNoDots.length() : hostStart + hostEnd); String host = urlNoDots.substring(hostStart, hostEnd); host = (toASCII ? IDN.toASCII(host) : IDN.toUnicode(host)); return dots + urlNoDots.substring(0, hostStart) + host + urlNoDots.substring(hostEnd); } /** * calculates the relative time string based on the given modificaion timestamp. * * @param context the app's context * @param modificationTimestamp the UNIX timestamp of the file modification time. * @return a relative time string */ public static CharSequence getRelativeTimestamp(Context context, long modificationTimestamp) { return getRelativeDateTimeString(context, modificationTimestamp, DateUtils.SECOND_IN_MILLIS, DateUtils.WEEK_IN_MILLIS, 0); } public static CharSequence getRelativeDateTimeString( Context c, long time, long minResolution, long transitionResolution, int flags ) { CharSequence dateString; // in Future if (time > System.currentTimeMillis()) { return DisplayUtils.unixTimeToHumanReadable(time); } // < 60 seconds -> seconds ago else if ((System.currentTimeMillis() - time) < 60 * 1000) { return c.getString(R.string.file_list_seconds_ago); } else { dateString = DateUtils.getRelativeDateTimeString(c, time, minResolution, transitionResolution, flags); } String[] parts = dateString.toString().split(","); if (parts.length == 2) { if (parts[1].contains(":") && !parts[0].contains(":")) { return parts[0]; } else if (parts[0].contains(":") && !parts[1].contains(":")) { return parts[1]; } } //dateString contains unexpected format. fallback: use relative date time string from android api as is. return dateString.toString(); } /** * Update the passed path removing the last "/" if it is not the root folder * * @param path */ public static String getPathWithoutLastSlash(String path) { // Remove last slash from path if (path.length() > 1 && path.charAt(path.length() - 1) == OCFile.PATH_SEPARATOR.charAt(0)) { path = path.substring(0, path.length() - 1); } return path; } /** * Gets the screen size in pixels in a backwards compatible way * * @param caller Activity calling; needed to get access to the {@link android.view.WindowManager} * @return Size in pixels of the screen, or default {@link Point} if caller is null */ public static Point getScreenSize(Activity caller) { Point size = new Point(); if (caller != null) { Display display = caller.getWindowManager().getDefaultDisplay(); display.getSize(size); } return size; } /** * set the owncloud standard colors for the snackbar. * * @param context the context relevant for setting the color according to the context's theme * @param snackbar the snackbar to be colored */ public static void colorSnackbar(Context context, Snackbar snackbar) { // Changing action button text color snackbar.setActionTextColor(ContextCompat.getColor(context, R.color.white)); } /** * Show the avatar corresponding to the received account in an {@ImageView}. * <p> * The avatar is shown if available locally in {@link ThumbnailsCacheManager}. The avatar is not * fetched from the server if not available. * <p> * If there is no avatar stored, a colored icon is generated with the first letter of the account username. * <p> * If this is not possible either, a predefined user icon is shown instead. * * @param account OC account which avatar will be shown. * @param displayView The image view to set the avatar on. * @param displayRadius The radius of the circle where the avatar will be clipped into. * @param fetchFromServer When 'true', if there is no avatar stored in the cache, it's fetched from * the server. When 'false', server is not accessed, the fallback avatar is * generated instead. USE WITH CARE, probably to be removed in the future. */ public static void showAccountAvatar( Account account, ImageView displayView, float displayRadius, boolean fetchFromServer ) { if (account != null) { // not just accessibility support, used to know what account is bound to each imageView displayView.setContentDescription(account.name); final ThumbnailsCacheManager.GetAvatarTask task = new ThumbnailsCacheManager.GetAvatarTask( displayView, account, displayRadius, fetchFromServer ); task.execute(); } } }
f4d5c5e4fe8fbd2bbeb2ba8ffa9c6761834e72bb
80f5543ee81c474a2c94347d45226723934f0043
/practice/src/main/java/com/xianyue/basictype/CmdUtil.java
6054c74792d007db5d69390b8bba91c7b50611bb
[ "MIT" ]
permissive
lys091112/javapiers
f57c156e7b847d245f65a319ed580ebec8a76963
0aff780dea42836331706261294e1f7aef821722
refs/heads/master
2021-10-07T17:22:11.219117
2021-10-03T04:37:51
2021-10-03T04:37:51
73,296,273
0
0
null
null
null
null
UTF-8
Java
false
false
604
java
package com.xianyue.basictype; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; /** * @author Xianyue */ public class CmdUtil { public static void main(String[] args) throws IOException { Process process = Runtime.getRuntime().exec("ping www.baidu.com",null, null); InputStream inputStream = process.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); reader.lines().forEach(t -> System.out.println(t)); } }
ac2e372692190071e011a8bddb100259f87bb72b
3d1a1b0114f3e51d2602c6bb82bd1628c9772154
/app/src/main/java/gr/nikolis/novibetgame/models/game/Market.java
a5a60c8d72358bed045553f63e21f31f7912788a
[]
no_license
nimakos/Game
52acdbb4d8ba855e93aad45ec101418422d2e0dc
cade340ec216922d23858d966abae9e47ca90dea
refs/heads/master
2020-08-12T03:39:07.371582
2019-11-05T13:39:12
2019-11-05T13:39:12
214,680,661
0
0
null
null
null
null
UTF-8
Java
false
false
936
java
package gr.nikolis.novibetgame.models.game; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.List; public class Market { @SerializedName("marketId") @Expose private long marketId; @SerializedName("betTypeSysname") @Expose private String betTypeSysname; @SerializedName("betItems") @Expose private List<BetItem> betItems; public long getMarketId() { return marketId; } public void setMarketId(long marketId) { this.marketId = marketId; } public String getBetTypeSysname() { return betTypeSysname; } public void setBetTypeSysname(String betTypeSysname) { this.betTypeSysname = betTypeSysname; } public List<BetItem> getBetItems() { return betItems; } public void setBetItems(List<BetItem> betItems) { this.betItems = betItems; } }
ac65ed9031323279b64599e7082350a50da9f141
7f076a3d0b4961d19c584fceaa434c6ac3e01ea1
/uebung1/src/main/java/ch/hsr/skapferer/vss/uebung1/aufgabe2/URLReader.java
490fbc4749fc8e478fb799a5a9eb8c6070bcf826
[]
no_license
stefan-ka/HSR-VSS
97a8c4b54168757f3ce34e7fd8e9baff3bf05fd3
58a431ffd07966850668eced5f5ab5eefa67d11a
refs/heads/master
2021-01-19T18:10:40.745540
2015-07-25T15:33:36
2015-07-25T15:33:36
31,703,035
0
0
null
null
null
null
UTF-8
Java
false
false
532
java
package ch.hsr.skapferer.vss.uebung1.aufgabe2; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; public class URLReader { public static void readURL(String url) throws Exception { try (BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream()))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } } public static void main(String[] args) throws Exception { readURL("http://www.kapferer.ch"); } }
a8ab92f7e5add7c4ff1e86998e54946cecda3497
a26efea1cef9fc275cde6ab3a8097eee88fd3272
/src/main/java/bishi/qianxin/Solution.java
1650df7f943ddb277cd8df69fe477a5a60d0d9e9
[]
no_license
GenaGeng/written-examination
2fb0bf0284e9137887581e71794dbd75a1acf5da
152b6cd9fed0b4bbc0aaac6cdb6ca7091744b3d4
refs/heads/master
2022-12-08T01:26:07.528472
2020-09-02T11:47:47
2020-09-02T11:47:47
292,232,828
0
0
null
null
null
null
UTF-8
Java
false
false
1,129
java
package bishi.qianxin; import java.util.Scanner; /** * @author Gena * @description * @date 2020/9/2 0002 */ public class Solution { public static int house (int[] person){ int[] newhouse = new int[person.length]; int count = 0; newhouse[0] = 1; for (int j=1;j<person.length;j++){ if (person[j]>person[j-1]){ newhouse[j]=newhouse[j-1]+1; }else if (person[j]==person[j-1]){ newhouse[j]=1; }else { newhouse[j]=newhouse[j-1]; newhouse[j-1]++; } } for (int i=0;i<newhouse.length;i++){ count+=newhouse[i]; System.out.println(newhouse[i]); } return count; } public static void main(String[] args){ Scanner in =new Scanner(System.in); String str=in.nextLine(); String[] strings = str.split(" "); int[] person = new int[strings.length]; for (int i=0;i<strings.length;i++){ person[i]= Integer.valueOf(strings[i]); } int num = house(person); System.out.println(num); } }
f91940987281a82e6848db3809cb28f70fa780f9
8cd02be7d04a68f4884c3f6225088e0ba7a45f85
/src/main/java/com/bitnationcode/topflies/repository/IFlyRepository.java
cad1646fa858b1fda747522571a760ea5c1a22ee
[ "Apache-2.0" ]
permissive
mtbittle/top-flies
afdbaa664439282643253f4f533496e4b6d5876d
99cc416884520e17fc50250bb6b58f7959ac0bfe
refs/heads/master
2020-08-30T15:17:43.228292
2019-12-08T15:56:29
2019-12-08T15:56:29
218,419,357
0
0
Apache-2.0
2019-12-08T15:56:30
2019-10-30T01:41:50
Java
UTF-8
Java
false
false
644
java
package com.bitnationcode.topflies.repository; import com.bitnationcode.topflies.model.Fly; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.querydsl.QuerydslPredicateExecutor; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface IFlyRepository extends JpaRepository<Fly, Long>, QuerydslPredicateExecutor<Fly> { /** * Uses Spring's built-in projections, returning an interface consisting of id and name columsn * @return list of row Id and name columns from the Fly repository */ List<FlyIdAndName> findAllProjectedBy(); }
d4ddd931733a679b40cdec53fbc7892ccf194ab7
b5f1658f65c1961aa98206b3d5f9257880fb731a
/app/src/main/java/com/example/myapplication/MManagePackage.java
274a6906922ae8c3a09ae8b6cfdae089586e1278
[]
no_license
malakajayaw/HotelsApp
4924b0a02d44c9d55b12b69ef0328e6a281b9f8c
2ccd1d35255c868dcc1ce53c40ac411eed180a67
refs/heads/master
2020-06-28T23:59:00.588139
2019-09-24T19:40:55
2019-09-24T19:40:55
200,377,466
0
0
null
null
null
null
UTF-8
Java
false
false
542
java
package com.example.myapplication; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; public class MManagePackage extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mmanage_package); } public void toHomeP(View view) { Intent redirect = new Intent(this, MHome.class); startActivity(redirect); } }
00083caefcdb40071b0c321ffa70f25c99fba2e2
82baf55acc406489bdc44866d8405aa35dc2852b
/app/src/main/java/com/p8/inspection/mvp/ui/MainActivity.java
a74cb708f585f8f0028de50f6e3d6dc1d6083a5f
[]
no_license
YannisYwx/P8Inspection
15c4a8e30baae5f00e689eb82dc845ee1b2307f0
2252550052823aecdcba37f4a32d5b68abe133b2
refs/heads/main
2023-03-30T06:12:01.390059
2020-11-03T07:34:46
2020-11-03T07:34:46
303,320,018
0
0
null
null
null
null
UTF-8
Java
false
false
1,381
java
package com.p8.inspection.mvp.ui; import android.content.Context; import android.content.Intent; import android.view.View; import com.p8.common.base.BaseActivity; import com.p8.inspection.R; import com.p8.inspection.mvp.ui.main.MainFragment; import com.p8.inspection.mvp.ui.entry.fragment.LoginFragment; import me.yokeyword.fragmentation.anim.DefaultHorizontalAnimator; import me.yokeyword.fragmentation.anim.FragmentAnimator; /** * @author : WX.Y * date : 2020/10/23 18:21 * description : */ public class MainActivity extends BaseActivity { public static void start(Context context){ context.startActivity(new Intent(context,MainActivity.class)); } @Override public void initData() { } @Override public int bindLayout() { return R.layout.fl_container; } @Override public void initView(View view) { if (findFragment(LoginFragment.class) == null) { loadRootFragment(R.id.fl_container, MainFragment.newInstance()); } } @Override public FragmentAnimator onCreateFragmentAnimator() { // 设置横向(和安卓4.x动画相同) return new DefaultHorizontalAnimator(); } @Override public void setListener() { } @Override public void doBusiness(Context mContext) { } }
410f87059383c242ae6f4f48e5659b2902cb8c44
a69e542af3400acde7a0452261cf701c317c629f
/String1.java
3b12d55ddf4d23d7d8dcc15e9c1b4a783a03280b
[]
no_license
IamDhanush/Eclipse
63ffff6daf685d75618f9df6cb98a5b2e9ba5c8b
cd4234bbdf3e9ea22247c339990825612c69b0ae
refs/heads/master
2021-08-19T17:49:43.314698
2017-11-27T04:22:43
2017-11-27T04:22:43
108,033,238
0
0
null
null
null
null
UTF-8
Java
false
false
310
java
package com.strings; public class String1 { public static void main(String[] args) { String s = "Dhanush"; s = s.concat(" Pulyala"); System.out.println(s); for(int i=0,k=0;i<s.length();i++) { if(s.charAt(i)=='a') { k++; if(k==2) { System.out.println(i); }} }} }
dad57f7f47c7c71b923b99b867531377fa3cec75
9dfbbf5a335da4fede138fb839f705287c36cd6e
/fmis-framework/src/main/java/com/fmis/framework/datasource/DynamicDataSourceContextHolder.java
3032cff2c8af2749f5245705ff20af903a490997
[ "MIT" ]
permissive
TaoWang4446/fmis
e1d91673be73b22cd17b9c23d8469d743edc35c5
25ac5cc85926e654e7802766d0c707b0fba649c7
refs/heads/master
2023-01-10T03:56:34.263648
2020-11-10T05:10:47
2020-11-10T05:10:47
311,552,080
0
0
null
null
null
null
UTF-8
Java
false
false
1,115
java
package com.fmis.framework.datasource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 数据源切换处理 * * @author fmis */ public class DynamicDataSourceContextHolder { public static final Logger log = LoggerFactory.getLogger(DynamicDataSourceContextHolder.class); /** * 使用ThreadLocal维护变量,ThreadLocal为每个使用该变量的线程提供独立的变量副本, * 所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。 */ private static final ThreadLocal<String> CONTEXT_HOLDER = new ThreadLocal<>(); /** * 设置数据源的变量 */ public static void setDataSourceType(String dsType) { log.info("切换到{}数据源", dsType); CONTEXT_HOLDER.set(dsType); } /** * 获得数据源的变量 */ public static String getDataSourceType() { return CONTEXT_HOLDER.get(); } /** * 清空数据源变量 */ public static void clearDataSourceType() { CONTEXT_HOLDER.remove(); } }
6f29fb9ee2443534f8aba6ff3710c284f13e65ca
07f197547919ddb1cb2ed4af1de5fcf9d4ed82f5
/app/src/main/java/com/example/banner/transformer/RotateYTransformer.java
d8c4b3f603da01cfafe40c5e6c9fa7904e5f54c4
[]
no_license
shaoruichao/Banner
6234aafd5e7468fcdc89433b4ef8f71ee0f4f267
1a9b487fa4be453c080461f19521591b6296d667
refs/heads/master
2020-12-02T22:53:44.660409
2017-07-21T08:49:42
2017-07-21T08:49:42
96,198,288
0
0
null
null
null
null
UTF-8
Java
false
false
1,996
java
package com.example.banner.transformer; import android.annotation.TargetApi; import android.os.Build; import android.support.v4.view.ViewPager; import android.view.View; public class RotateYTransformer extends BasePageTransformer { private static final float DEFAULT_MAX_ROTATE = 35f; private float mMaxRotate = DEFAULT_MAX_ROTATE; public RotateYTransformer() { } public RotateYTransformer(float maxRotate) { this(maxRotate, NonPageTransformer.INSTANCE); } public RotateYTransformer( ViewPager.PageTransformer pageTransformer) { this(DEFAULT_MAX_ROTATE, pageTransformer); } public RotateYTransformer(float maxRotate, ViewPager.PageTransformer pageTransformer) { mMaxRotate = maxRotate; mPageTransformer = pageTransformer; } @TargetApi(Build.VERSION_CODES.HONEYCOMB) public void pageTransform(View view, float position) { view.setPivotY(view.getHeight()/2); if (position < -1) { // [-Infinity,-1) // This page is way off-screen to the left. view.setRotationY(-1 * mMaxRotate); view.setPivotX(view.getWidth()); } else if (position <= 1) { // [-1,1] // Modify the default slide transition to shrink the page as well view.setRotationY(position * mMaxRotate); if (position < 0)//[0,-1] { view.setPivotX(view.getWidth() * (DEFAULT_CENTER + DEFAULT_CENTER * (-position))); view.setPivotX(view.getWidth()); } else//[1,0] { view.setPivotX(view.getWidth() * DEFAULT_CENTER * (1 - position)); view.setPivotX(0); } // Scale the page down (between MIN_SCALE and 1) } else { // (1,+Infinity] // This page is way off-screen to the right. view.setRotationY(1 * mMaxRotate); view.setPivotX(0); } } }
1a04cddab800247d104688b9053b6bb8a1b79421
720247d2eb9872163f97e02b84e7a30e5f9cecb2
/src/main.java
2e9d63f75c4c91da303830026dce4558dbe77251
[]
no_license
kyanshoma/Report4
8028d93c0d217c410f8576b192d396f0f882a88a
7de6ccff4d62017de80ada4718ec55cd1235d1f1
refs/heads/master
2020-09-27T21:03:23.166252
2019-12-08T04:04:58
2019-12-08T04:04:58
226,465,355
0
0
null
null
null
null
UTF-8
Java
false
false
152
java
public class main { public static void main(String[] args){ String str = "百二十三"; int value = Integer.parseInt(str); } }
53e7df4f5c711da846fa30a55beaf0fbc726fb26
87a5c4ffa47e69e5ac649440a2cf4e33cc2531c6
/src/main/java/com/app/dao/UserDAO.java
f8a9d19135e167f92275f2f829af1569c9c17d52
[]
no_license
xomrayno1/fastfood
db7faeeaef99e940144c00fd16c740582fa0407d
94094f7007567160d67fb5d9a600efcbd84eb45b
refs/heads/main
2023-05-07T13:22:45.379494
2021-05-31T14:54:06
2021-05-31T14:54:06
371,951,925
0
0
null
null
null
null
UTF-8
Java
false
false
143
java
package com.app.dao; import com.app.entity.Users; public interface UserDAO<E> extends BaseDAO<E> { Users findByUsername(String username); }
ea0e4b5f9bac7bcdd8d910b4b9a5e9304dcb76b1
3cd69da4d40f2d97130b5bf15045ba09c219f1fa
/sources/kotlinx/coroutines/channels/ProduceKt$awaitClose$1.java
1e152d61b412c38114477aa7d3c4747b7dd91c22
[]
no_license
TheWizard91/Album_base_source_from_JADX
946ea3a407b4815ac855ce4313b97bd42e8cab41
e1d228fc2ee550ac19eeac700254af8b0f96080a
refs/heads/master
2023-01-09T08:37:22.062350
2020-11-11T09:52:40
2020-11-11T09:52:40
311,927,971
0
0
null
null
null
null
UTF-8
Java
false
false
1,588
java
package kotlinx.coroutines.channels; import kotlin.Metadata; import kotlin.Unit; import kotlin.coroutines.Continuation; import kotlin.coroutines.jvm.internal.ContinuationImpl; import kotlin.coroutines.jvm.internal.DebugMetadata; import kotlin.jvm.functions.Function0; @Metadata(mo33669bv = {1, 0, 3}, mo33670d1 = {"\u0000\u001a\n\u0000\n\u0002\u0010\u0000\n\u0002\u0018\u0002\n\u0000\n\u0002\u0018\u0002\n\u0002\u0010\u0002\n\u0000\n\u0002\u0018\u0002\u0010\u0000\u001a\u0004\u0018\u00010\u0001*\u0006\u0012\u0002\b\u00030\u00022\u000e\b\u0002\u0010\u0003\u001a\b\u0012\u0004\u0012\u00020\u00050\u00042\f\u0010\u0006\u001a\b\u0012\u0004\u0012\u00020\u00050\u0007H‡@"}, mo33671d2 = {"awaitClose", "", "Lkotlinx/coroutines/channels/ProducerScope;", "block", "Lkotlin/Function0;", "", "continuation", "Lkotlin/coroutines/Continuation;"}, mo33672k = 3, mo33673mv = {1, 1, 15}) @DebugMetadata(mo34304c = "kotlinx.coroutines.channels.ProduceKt", mo34305f = "Produce.kt", mo34306i = {0, 0}, mo34307l = {145}, mo34308m = "awaitClose", mo34309n = {"$this$awaitClose", "block"}, mo34310s = {"L$0", "L$1"}) /* compiled from: Produce.kt */ final class ProduceKt$awaitClose$1 extends ContinuationImpl { Object L$0; Object L$1; int label; /* synthetic */ Object result; ProduceKt$awaitClose$1(Continuation continuation) { super(continuation); } public final Object invokeSuspend(Object obj) { this.result = obj; this.label |= Integer.MIN_VALUE; return ProduceKt.awaitClose((ProducerScope<?>) null, (Function0<Unit>) null, this); } }
be1a02c8ef75e34935f19c1da9f6e37b25124def
6384d3199811af7c8a0ed74450772e437cde334c
/room/integration-tests/testapp/src/androidTest/java/androidx/room/integration/testapp/dao/UserHouseDao.java
b12f4ad77a6fdfc950513a9982abbec5a10b125d
[ "Apache-2.0" ]
permissive
androidx/androidx
1cf2c063d530d2c6cf63899af796c44005ba38f4
7c7be981f7b980738c571998db1128f7a9a1195a
refs/heads/androidx-main
2023-09-06T07:55:17.232185
2023-09-06T06:22:19
2023-09-06T06:22:19
256,589,781
5,035
940
Apache-2.0
2023-09-14T17:59:59
2020-04-17T19:17:41
Kotlin
UTF-8
Java
false
false
1,297
java
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.integration.testapp.dao; import androidx.room.Dao; import androidx.room.Insert; import androidx.room.Query; import androidx.room.Transaction; import androidx.room.integration.testapp.vo.House; import androidx.room.integration.testapp.vo.UserAndAllHouses; import androidx.room.integration.testapp.vo.UserAndPetsAndHouses; import java.util.List; @Dao public interface UserHouseDao { @Transaction @Query("SELECT * FROM user") List<UserAndAllHouses> getUsersAndTheirHouses(); @Transaction @Query("SELECT * FROM user") List<UserAndPetsAndHouses> getUsersAndTheirPetsAndHouses(); @Insert void insertAll(House[] houses); }
0f40e7538f1e8bca48ffeec3606852d4ec38bf3d
4e2eb950bafec1af5a78ecc0e7da20e7be92947b
/Q0220_Contains_Duplicate_III/Solution.java
f44f0fb4f8566a7d84267524bfb40c45c8641cb8
[]
no_license
zhijian-pro/MyLeetCode
49458d996fac79efdfe8a1e2b1d6212df3172aee
4d65b69134b0a542a675e9d66944e4634ec23079
refs/heads/master
2022-01-30T00:10:37.859666
2019-05-29T03:28:40
2019-05-29T03:28:40
176,062,802
1
0
null
null
null
null
UTF-8
Java
false
false
945
java
package Q0220_Contains_Duplicate_III; import java.util.TreeSet; /** * @ Description: * @ Date: Created in 14:46 2019-04-05 * @ Author: Anthony_Duan */ public class Solution { public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) { TreeSet<Long> treeSet = new TreeSet<>(); for (int i = 0; i < nums.length; i++) { Long ceiling = treeSet.ceiling((long) nums[i] - (long) t); if (ceiling != null && treeSet.ceiling((long) nums[i] - t) <= (long) nums[i] + (long) t) { return true; } treeSet.add((long) nums[i]); if (treeSet.size() == k + 1) { treeSet.remove((long) nums[i - k]); } } return false; } public static void main(String[] args) { int[] arr = {1, 5, 9, 1, 5, 9}; System.out.println(new Solution().containsNearbyAlmostDuplicate(arr, 2, 3)); } }
6eb464e851d5a5ae79b9f1f2196614c053d96741
147ffd7a7ec412584fac3f9a5f68dbc748be7e51
/app/src/main/java/com/example/nesrine/projetmobile/User.java
6718346abac63dcfae048f6698661200c50d1642
[]
no_license
nesrine94/ProjetMobile
4d1044c62248fbb1eea9310027192d90efc8fab0
6d26e170b8003a8c132e625ec1084f830a9f5a5f
refs/heads/master
2021-01-18T03:32:11.774531
2017-06-28T04:04:29
2017-06-28T04:04:29
85,810,417
0
0
null
null
null
null
UTF-8
Java
false
false
708
java
package com.example.nesrine.projetmobile; import java.io.Serializable; /** * Created by Nesrine on 16/06/2017. */ public class User implements Serializable { private String email; private String mot_de_passe; private String status; public void setEmail(String email) { this.email = email; } public void setMot_de_passe(String mot_de_passe) { this.mot_de_passe = mot_de_passe; } public String getEmail() { return email; } public String getMot_de_passe() { return mot_de_passe; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
c257c9732ec7a1fb6209d76ca8a722371b2edde8
46f00d16ceaa6453fd95663e6712b76140d1a31c
/source/at/helios/common/PersonPanel.java
70e90be928fc2aa391e6c48cbe38514ef61af062
[]
no_license
markusscherer/helios
8cad913c5cb09f721601ca409ca44c8414ea196c
25362b74f52024013a22afddf76523e182e792f5
refs/heads/master
2020-04-08T21:54:15.917067
2015-03-09T10:02:49
2015-03-09T10:02:49
31,887,818
0
0
null
null
null
null
UTF-8
Java
false
false
7,130
java
package at.helios.common; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.Page; import org.zkoss.zk.ui.Sessions; import org.zkoss.zk.ui.event.Event; import org.zkoss.zk.ui.event.ForwardEvent; import org.zkoss.zk.ui.event.InputEvent; import org.zkoss.zul.Label; import org.zkoss.zul.Listbox; import org.zkoss.zul.Listcell; import org.zkoss.zul.Listhead; import org.zkoss.zul.Listheader; import org.zkoss.zul.Listitem; import org.zkoss.zul.Panel; import org.zkoss.zul.Panelchildren; import org.zkoss.zul.Textbox; import org.zkoss.zul.Toolbar; import at.helios.model.Department; import at.helios.model.Person; /** * Panel zur Auswahl von Personen * @author * <PRE> * ID date description * mas 29.03.2009 Erstkommentierung * </PRE> **/ @SuppressWarnings("serial") public class PersonPanel extends Panel { Listbox _oListBox; Textbox _oTextbox; private PersonBox _oRegistered; /** * Standard KOnstruktor, füllt GUI-Komponente **/ public PersonPanel() { this.setId("PersonPanel"); Toolbar oToolbar = new Toolbar(); Label oLabel = new Label(); oLabel.setValue("Suche "); oLabel.setParent(oToolbar); Component oFutureRoot = (Component) Sessions.getCurrent().getAttribute("PersonPanelOwner"); _oTextbox = new Textbox(); _oTextbox.setFocus(true); _oTextbox.setParent(oToolbar); _oTextbox.addForward("onChanging", this, "onTextboxChange"); oToolbar.setParent(this); List<Person> coPersons = Person.getPersonsByDepartment((Department) Sessions.getCurrent() .getAttribute("department")); //Panelchildren Panelchildren oPanelChildren = new Panelchildren(); _oListBox = new Listbox(); _oListBox.setHeight("743px"); //Header setzten Listhead oListhead = new Listhead(); Listheader oListheader = new Listheader(); oListheader.setSort("auto"); oListheader.setLabel("Nr."); oListheader.setParent(oListhead); oListheader = new Listheader(); oListheader.setSort("auto"); oListheader.setLabel("Nachname"); oListheader.setParent(oListhead); oListheader = new Listheader(); oListheader.setSort("auto"); oListheader.setLabel("Vorname"); oListheader.setParent(oListhead); oListhead.setParent(_oListBox); Listitem oListitem; Listcell oListcell; Collections.sort(coPersons, new Comparator<Person>() { public int compare(Person oPerson1, Person oPerson2) { return oPerson1.getEMTNumber().compareTo(oPerson2.getEMTNumber()); } }); for (Person oPerson : coPersons) { oListitem = new Listitem(); oListitem.addForward("onClick", oFutureRoot, "onSelectPerson"); oListitem.addForward("onOK", oFutureRoot, "onSelectPerson"); oListitem.addForward("onClick", this, "onSelectPerson"); oListitem.addForward("onOK", this, "onSelectPerson"); oListitem.setValue(oPerson); oListcell = new Listcell(); oListcell.setLabel(oPerson.getEMTNumber()); oListcell.setParent(oListitem); oListcell = new Listcell(); oListcell.setLabel(oPerson.getSurname()); oListcell.setParent(oListitem); oListcell = new Listcell(); oListcell.setLabel(oPerson.getForename()); oListcell.setParent(oListitem); oListitem.setParent(_oListBox); } _oListBox.setParent(oPanelChildren); oPanelChildren.setParent(this); } @Override public void onPageAttached(Page coNewpage, Page coOldpage) { super.onPageAttached(coNewpage, coOldpage); } /** * Wird ausgeführt, wenn im Suchfenster eine Eingabe getätigt wird * @param oEvent Event mit Informationen **/ @SuppressWarnings("unchecked") public void onTextboxChange(Event oEvent) { oEvent = ((ForwardEvent) oEvent).getOrigin(); InputEvent oInputEvent; if (oEvent instanceof InputEvent) { oInputEvent = (InputEvent) oEvent; } else { return; } Pattern oPattern = Pattern.compile("[0-9]*"); Matcher oMatcher = oPattern.matcher(oInputEvent.getValue()); if (oMatcher.matches()) { for (Component oComponent : (List<Listitem>) _oListBox.getChildren()) { if (oComponent instanceof Listitem) { if (!((Person) ((Listitem) oComponent).getValue()).getEMTNumber().startsWith( oInputEvent.getValue())) { oComponent.setVisible(false); } else { oComponent.setVisible(true); } } } } else { for (Component oComponent : (List<Listitem>) _oListBox.getChildren()) { if (oComponent instanceof Listitem) { if (!(((Person) ((Listitem) oComponent).getValue()).getForename().toLowerCase() .startsWith(oInputEvent.getValue().toLowerCase()) || ((Person) ((Listitem) oComponent) .getValue()).getSurname().toLowerCase().startsWith( oInputEvent.getValue().toLowerCase()))) { oComponent.setVisible(false); } else { oComponent.setVisible(true); } } } } } /** * Wird ausgeführt, wenn Person ausgewählt wird **/ public void onSelectPerson() { Person oPerson = (Person) _oListBox.getSelectedItem().getValue(); if (_oRegistered != null) { _oRegistered.setSelectedByValue(oPerson); _oRegistered = null; } } /** * Gibt ausgewählte Person zurück * @return ausgewählte Person **/ public Person getSelectedPerson() { try { return (Person) _oListBox.getSelectedItem().getValue(); } catch (NullPointerException e) { return null; } } /** * Registiert PersonCombobox * @param oComboBox PersonComboBox **/ public void register(PersonBox oComboBox) { _oRegistered = oComboBox; } /** * Überprüft ob PersonComboBox registriert ist * @return Ist eine PersonComboBox registriert? **/ public boolean hasRegistration() { return _oRegistered != null; } }
509bc88568a5dcae10cce7b6d68e7bc47c09a6a9
e960b5962a3122ea8384a51e1120e5429632afe9
/app/src/main/java/com/example/postersliderapp/MainActivity.java
321a11fd14f2c73114a1911141c1a677d6a6af7d
[]
no_license
vamshivasa/PosterSliderApp
c4d72d97f73424bc90fc7a5540abbab18aa1acd5
6d9e9cb1c15a466b291de731d841e8641e3e1d17
refs/heads/master
2020-07-14T01:06:18.747866
2019-08-29T17:04:47
2019-08-29T17:04:47
205,197,086
0
0
null
null
null
null
UTF-8
Java
false
false
565
java
package com.example.postersliderapp; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { ViewPager viewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); viewPager = (ViewPager)findViewById(R.id.ViewPager); ImageAdapter adapter = new ImageAdapter(this); viewPager.setAdapter(adapter); } }
bf4b6712e15aa0ecb69938f9b396df5002b211a7
8d670a880d3aae67842b89a66f2cf2682d8b6360
/turma12c/ws/universidadexyz/src/br/com/universidadexyz/beans/Professor.java
84fb8733de2002aa521b00cd78d866fb847aba96
[]
no_license
mdcp14/projetoitau
4cb3cc471e021be8bddd40f2e70d91d7b51992f6
f2230340df7e6fa2df62e6ca8dd6d66e20cf1871
refs/heads/master
2023-02-05T16:47:21.041397
2020-12-18T15:24:16
2020-12-18T15:24:16
322,629,435
0
0
null
null
null
null
ISO-8859-1
Java
false
false
1,439
java
package br.com.universidadexyz.beans; public class Professor { private int id; private String apelido; private String formacao; private float valorHora; public Professor(int i, String string, String string2, int j, Endereco endereco) { } public Professor(int id, String apelido, String formacao, float valorHora) { this.id = id; this.apelido = apelido; this.formacao = formacao; this.valorHora = valorHora; } public Professor() { } public void setAll(int id, String apelido, String formacao, float valorHora) { this.id = id; this.apelido = apelido; this.formacao = formacao; this.valorHora = valorHora; } public String getAll() { return "ID: " + id + "\n" + "Apelido: " + apelido + "\n"+ "Formacao: " + formacao + "\n" + "Valor Hora: " + valorHora; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getApelido() { return apelido; } public void setApelido(String apelido) { this.apelido = apelido; } public String getFormação() { return formacao; } public void setFormação(String formacao) { this.formacao = formacao; } public float getValorHora() { return valorHora; } public void setValorHora(float valorHora) { this.valorHora = valorHora; } public void setEndereco(Endereco e) { } public String getEndereco(String endereco) { return endereco; } }
059f7aa3da5b50baa46d3a088e668484027230e5
c5422e830e80ae108b2b3a9686a9c31d3163dd55
/src/org/fco/gdelt/hadoop/MapperTest.java
e4714d0fa6b43699ec5904aa1201988f1ddb7b42
[]
no_license
carrillo/Gdelt
c3a151382b611d7187d188277b45341860b428b8
bc540b5b880401916d1836d79f409529432eb07a
refs/heads/master
2021-01-01T17:28:03.706378
2015-09-22T14:00:03
2015-09-22T14:00:03
18,897,496
4
4
null
null
null
null
UTF-8
Java
false
false
668
java
package org.fco.gdelt.hadoop; import java.io.IOException; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; public class MapperTest extends Mapper<LongWritable, Text, Text, IntWritable> { @Override protected void map(LongWritable key, Text value, Context context ) throws IOException, InterruptedException { final String[] entries = value.toString().split("\t"); final String year = entries[ 3 ]; final int quadClass = Integer.parseInt( entries[ 30 ] ); context.write( new Text( year ) , new IntWritable( quadClass ) ); } }
8184410cdc3f4f54f234586c8e8bc8f5d784ae21
ed93e618ce708fc7794fb8a6756a4d707bcfde09
/hapi-fhir-structures-r4/src/main/java/org/hl7/fhir/r4/model/codesystems/CoverageLevel.java
7ecef0d228dc86de29bcbb5eb07644b18930188a
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
CMSgov/hapi-fhir
6009f18d18d970c48b46fde5044b3e76fd63f394
ecf570ced9d40fa32a78f4646dd15571b441ccc7
refs/heads/master
2023-06-24T17:40:18.539391
2018-03-01T12:25:35
2018-03-01T12:25:35
49,209,900
0
2
Apache-2.0
2023-09-05T22:40:59
2016-01-07T14:40:27
Java
UTF-8
Java
false
false
4,870
java
package org.hl7.fhir.r4.model.codesystems; /* Copyright (c) 2011+, HL7, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Generated on Tue, Jan 9, 2018 14:51-0500 for FHIR v3.2.0 import org.hl7.fhir.exceptions.FHIRException; public enum CoverageLevel { /** * An employee group */ GROUP, /** * A sub-group of an employee group */ SUBGROUP, /** * A specific suite of benefits. */ PLAN, /** * A subset of a specific suite of benefits. */ SUBPLAN, /** * A class of benefits. */ CLASS, /** * A subset of a class of benefits. */ SUBCLASS, /** * A sequence number associated with repeating short-term continuence of the converage. */ SEQUENCE, /** * added to help the parsers */ NULL; public static CoverageLevel fromCode(String codeString) throws FHIRException { if (codeString == null || "".equals(codeString)) return null; if ("group".equals(codeString)) return GROUP; if ("subgroup".equals(codeString)) return SUBGROUP; if ("plan".equals(codeString)) return PLAN; if ("subplan".equals(codeString)) return SUBPLAN; if ("class".equals(codeString)) return CLASS; if ("subclass".equals(codeString)) return SUBCLASS; if ("sequence".equals(codeString)) return SEQUENCE; throw new FHIRException("Unknown CoverageLevel code '"+codeString+"'"); } public String toCode() { switch (this) { case GROUP: return "group"; case SUBGROUP: return "subgroup"; case PLAN: return "plan"; case SUBPLAN: return "subplan"; case CLASS: return "class"; case SUBCLASS: return "subclass"; case SEQUENCE: return "sequence"; default: return "?"; } } public String getSystem() { return "http://hl7.org/fhir/coverage-level"; } public String getDefinition() { switch (this) { case GROUP: return "An employee group"; case SUBGROUP: return "A sub-group of an employee group"; case PLAN: return "A specific suite of benefits."; case SUBPLAN: return "A subset of a specific suite of benefits."; case CLASS: return "A class of benefits."; case SUBCLASS: return "A subset of a class of benefits."; case SEQUENCE: return "A sequence number associated with repeating short-term continuence of the converage."; default: return "?"; } } public String getDisplay() { switch (this) { case GROUP: return "Group"; case SUBGROUP: return "SubGroup"; case PLAN: return "Plan"; case SUBPLAN: return "SubPlan"; case CLASS: return "Class"; case SUBCLASS: return "SubClass"; case SEQUENCE: return "Sequence"; default: return "?"; } } }
22cc3bd10bcf4e193751fcf3716f7ffea1293a7d
c83bc1b62ff5c8fc42720cd0aa3c8afcb3e77022
/library/sync/src/main/java/com/amatkivskiy/gitter/sdk/sync/client/SyncGitterApiClient.java
af1d674ac901226f526771eb1d1d0c1665de6b13
[ "MIT" ]
permissive
asantibanez/GitterJavaSDK
943b55b61011150c426314469ad039ad10bbf251
4cbd0ca2f5394d6820f057f41aed17dfa9a5dbaf
refs/heads/master
2021-01-11T04:28:35.526156
2016-05-07T12:28:27
2016-05-07T12:28:27
69,082,105
0
0
null
2016-09-24T05:24:08
2016-09-24T05:24:08
null
UTF-8
Java
false
false
5,372
java
package com.amatkivskiy.gitter.sdk.sync.client; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.amatkivskiy.gitter.sdk.Constants; import com.amatkivskiy.gitter.sdk.api.builder.GitterApiBuilder; import com.amatkivskiy.gitter.sdk.converter.UserJsonDeserializer; import com.amatkivskiy.gitter.sdk.model.request.ChatMessagesRequestParams; import com.amatkivskiy.gitter.sdk.model.request.UnreadRequestParam; import com.amatkivskiy.gitter.sdk.model.request.UpdateRoomRequestParam; import com.amatkivskiy.gitter.sdk.model.request.UserAccountType; import com.amatkivskiy.gitter.sdk.model.response.BooleanResponse; import com.amatkivskiy.gitter.sdk.model.response.OrgResponse; import com.amatkivskiy.gitter.sdk.model.response.RepoResponse; import com.amatkivskiy.gitter.sdk.model.response.SearchUsersResponse; import com.amatkivskiy.gitter.sdk.model.response.UserResponse; import com.amatkivskiy.gitter.sdk.model.response.message.MessageResponse; import com.amatkivskiy.gitter.sdk.model.response.message.UnReadMessagesResponse; import com.amatkivskiy.gitter.sdk.model.response.room.RoomResponse; import com.amatkivskiy.gitter.sdk.model.response.room.SearchRoomsResponse; import com.amatkivskiy.gitter.sdk.sync.api.SyncGitterApi; import java.util.List; import retrofit.converter.GsonConverter; import static com.amatkivskiy.gitter.sdk.util.RequestUtils.convertChatMessagesParamsToMap; public class SyncGitterApiClient { private SyncGitterApi api; public SyncGitterApiClient(SyncGitterApi api) { this.api = api; } public MessageResponse sendMessage(String roomId, String text) { return api.sendMessage(roomId, text); } public UserResponse getCurrentUser() { return api.getCurrentUser(); } public RoomResponse getUserRooms(String userId) { return api.getUserRooms(userId); } public List<OrgResponse> getUserOrgs(String userId) { return api.getUserOrgs(userId); } public List<RepoResponse> getUserRepos(String userId) { return api.getUserRepos(userId); } public List<RoomResponse> getUserChannels(String userId) { return api.getUserChannels(userId); } public List<UserResponse> getRoomUsers(String roomId) { return api.getRoomUsers(roomId); } public List<RoomResponse> getRoomChannels(String roomId) { return api.getRoomChannels(roomId); } public RoomResponse joinRoom(String roomUri) { return api.joinRoom(roomUri); } public RoomResponse updateRoom(String roomId, UpdateRoomRequestParam params) { return api.updateRoom(roomId, params); } /** * Removes specified user from the room. It can be used to leave room. * * @param roomId Id of the room. * @param userId Id of the user to remove. * @return true if successful. */ public BooleanResponse leaveRoom(String roomId, String userId) { return api.leaveRoom(roomId, userId); } public List<RoomResponse> searchRooms(String searchTerm) { SearchRoomsResponse response = api.searchRooms(searchTerm); return response.results; } /** * @return suggested rooms for the current user. */ public List<RoomResponse> getSuggestedRooms() { return api.getSuggestedRooms(); } public List<RoomResponse> searchRooms(String searchTerm, int limit) { SearchRoomsResponse response = api.searchRooms(searchTerm, limit); return response.results; } public List<UserResponse> searchUsers(UserAccountType type, String searchTerm) { SearchUsersResponse response = api.searchUsers(type, searchTerm); return response.results; } public List<UserResponse> searchUsers(String searchTerm) { SearchUsersResponse response = api.searchUsers(searchTerm); return response.results; } public List<RoomResponse> getCurrentUserRooms() { return api.getCurrentUserRooms(); } public List<MessageResponse> getRoomMessages(String roomId, ChatMessagesRequestParams params) { return api.getRoomMessages(roomId, convertChatMessagesParamsToMap(params)); } public List<MessageResponse> getRoomMessages(String roomId) { return getRoomMessages(roomId, null); } public MessageResponse getRoomMessageById(String roomId, String messageId) { return api.getRoomMessageById(roomId, messageId); } public MessageResponse updateMessage(String roomId, String chatMessageId, String text) { return api.updateMessage(roomId, chatMessageId, text); } public BooleanResponse markReadMessages(String userId, String roomId, List<String> chatIds) { return api.markReadMessages(userId, roomId, new UnreadRequestParam(chatIds)); } public UnReadMessagesResponse getUnReadMessages(String userId, String roomId) { return api.getUnReadMessages(userId, roomId); } public static class Builder extends GitterApiBuilder<Builder, SyncGitterApiClient> { protected String getFullEndpointUrl() { return Constants.GitterEndpoints.GITTER_API_ENDPOINT + "/" + apiVersion + "/"; } @Override public SyncGitterApiClient build() { prepareDefaultBuilderConfig(); Gson gson = new GsonBuilder() .registerTypeAdapter(UserResponse.class, new UserJsonDeserializer()) .create(); restAdapterBuilder.setConverter(new GsonConverter(gson)); SyncGitterApi api = restAdapterBuilder.build().create(SyncGitterApi.class); return new SyncGitterApiClient(api); } } }
be2e08d8301f4daa814e0b1e0a8c19f2947a4cf2
461d040664f15bb7052dbadb89b58ca505cab4de
/app/src/main/java/miranda/sean/androiddetechtouch/K.java
18f56c240c439ca3a78c39078bea74516112edcc
[]
no_license
javadkamizy/Alphabets-An-Android-application-as-a-game-based-learning-medium
c19063f9070b817711404b5b79e691eb94f780e5
ef57a64ee440ad646229bac4c98ad1a482cf1efb
refs/heads/master
2020-08-31T17:32:45.119430
2017-05-06T19:11:56
2017-05-06T19:11:56
218,744,848
0
1
null
2019-10-31T10:53:41
2019-10-31T10:53:41
null
UTF-8
Java
false
false
14,422
java
package miranda.sean.androiddetechtouch; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; public class K extends Activity { TextView msg; DrawingView dv ; private Paint mPaint; TextView textSource; ImageView imageResult; Bitmap bitmapMaster; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_k); startService(new Intent(getBaseContext(),MyService.class)); textSource = (TextView)findViewById(R.id.sourceuri); imageResult = (ImageView)findViewById(R.id.result); RelativeLayout mtile=(RelativeLayout)findViewById(R.id.mtile); dv = new DrawingView(this); mtile.addView(dv); mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setDither(true); mPaint.setColor(Color.GREEN); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeJoin(Paint.Join.ROUND); mPaint.setStrokeCap(Paint.Cap.ROUND); mPaint.setStrokeWidth(12); } public class DrawingView extends View { public int width; public int height; private Bitmap mBitmap; private Canvas mCanvas; private Path mPath; private Paint mBitmapPaint; Context context; private Paint circlePaint; private Path circlePath; int colour; int reset = 0; int count = 0; int check = 0; int start_outside = 0; int start_inside = 0; int N = 20; int count_complete = 0; int set = 0; int z = 0; int clear = 0; int flag[][] = new int[10][2]; float boxes[][] = new float[10][4]; public void resetFlags() { flag[0][1] = 1; for(int i =1;i<10;i++) { flag[i][1] = 0; } } public void setTracingOrder() { flag[0][0] = 0; flag[1][0] = 1; flag[2][0] = 2; flag[3][0] = 3; flag[4][0] = 4; flag[5][0] = 5; flag[6][0] = 6; flag[7][0] = 7; flag[8][0] = 8; flag[9][0] = 9; } public void setBoxes() { boxes[0][0] = 0.0f; boxes[0][1] = 275.0f; boxes[0][2] = 0.0f; boxes[0][3] = 165.0f; boxes[1][0] = 0.0f; boxes[1][1] = 275.0f; boxes[1][2] = 165.0f; boxes[1][3] = 269.0f; boxes[2][0] = 0.0f; boxes[2][1] = 275.0f; boxes[2][2] = 269.0f; boxes[2][3] = 377.0f; boxes[3][0] = 0.0f; boxes[3][1] = 275.0f; boxes[3][2] = 377.0f; boxes[3][3] = 480.0f; boxes[4][0] = 0.0f; boxes[4][1] = 275.0f; boxes[4][2] = 480.0f; boxes[4][3] = 666.0f; boxes[5][0] = 275.0f; boxes[5][1] = 1170.0f; boxes[5][2] = 0.0f; boxes[5][3] = 165.0f; boxes[6][0] = 275.0f; boxes[6][1] = 1170.0f; boxes[6][2] = 165.0f; boxes[6][3] = 269.0f; boxes[7][0] = 275.0f; boxes[7][1] = 1170.0f; boxes[7][2] = 269.0f; boxes[7][3] = 377.0f; boxes[8][0] = 275.0f; boxes[8][1] = 1170.0f; boxes[8][2] = 377.0f; boxes[8][3] = 480.0f; boxes[9][0] = 275.0f; boxes[9][1] = 1170.0f; boxes[9][2] = 480.0f; boxes[9][3] = 666.0f; } public DrawingView(Context c) { super(c); context=c; mPath = new Path(); mBitmapPaint = new Paint(Paint.DITHER_FLAG); circlePaint = new Paint(); circlePath = new Path(); circlePaint.setAntiAlias(true); circlePaint.setColor(Color.BLUE); circlePaint.setStyle(Paint.Style.STROKE); circlePaint.setStrokeJoin(Paint.Join.MITER); circlePaint.setStrokeWidth(4f); setBoxes(); resetFlags(); setTracingOrder(); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); mCanvas = new Canvas(mBitmap); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawBitmap( mBitmap, 0, 0, mBitmapPaint); canvas.drawPath( mPath, mPaint); canvas.drawPath( circlePath, circlePaint); } public float mX, mY; public static final float TOUCH_TOLERANCE = 4; public void touch_start(float x, float y) { mPath.reset(); mPath.moveTo(x, y); mX = x; mY = y; Log.d("start xy==>", x + "," + y); } public void touch_move(float x, float y) { Log.d("move xy==>", x+","+y); float dx = Math.abs(x - mX); float dy = Math.abs(y - mY); if ((dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE)) { mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2); mX = x; mY = y; circlePath.reset(); circlePath.addCircle(mX, mY, 30, Path.Direction.CW); } } public void touch_up() { mPath.lineTo(mX, mY); Log.d("end xy", mX+","+mY); circlePath.reset(); // commit the path to our offscreen mCanvas.drawPath(mPath, mPaint); // kill this so we don't double draw mPath.reset(); } private int getProjectedColor(ImageView iv, Bitmap bm, int x, int y){ int projectedX = (int)((double)x * ((double)bm.getWidth()/(double)iv.getWidth())); int projectedY = (int)((double)y * ((double)bm.getHeight()/(double)iv.getHeight())); return bm.getPixel(projectedX, projectedY); } public boolean insideBoundary(int color) { if (color != 0) //inside boundary return true; else return false; //outside boundary color = 0 impales transparent } public void clearScreen() { /*mPath.reset(); circlePath.reset(); mCanvas.drawColor(0); postInvalidate();*/ resetFlags(); count_complete = 0; z = 0; count = 0; Paint paint1 = new Paint(); paint1.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); Rect rect = new Rect(0, 0, mCanvas.getWidth(), mCanvas.getHeight()); mCanvas.drawRect(rect, paint1); //Toast.makeText(getApplicationContext(), "Trace Again", Toast.LENGTH_SHORT).show(); } public void imageCache() { /*imageResult.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)); imageResult.layout(0, 0, imageResult.getMeasuredWidth(), imageResult.getMeasuredHeight());*/ imageResult.buildDrawingCache(); bitmapMaster = imageResult.getDrawingCache(); } public int findBox(float x, float y) { for(int i =0;i<10;i++) { if(x >= boxes[i][0] && x< boxes[i][1] && y >= boxes[i][2] && y< boxes[i][3]) return (i); } return (50); } @Override public boolean onTouchEvent(MotionEvent event) { float x = event.getX(); float y = event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: touch_start(x, y); textSource.setText("ACTION_DOWN- " + x + " : " + y); imageCache(); colour = getProjectedColor(imageResult, bitmapMaster,(int) x,(int) y); textSource.setText("color is " + colour + "box is" +findBox(x,y)); textSource.setBackgroundColor(colour); if(insideBoundary(colour)) { textSource.setText("color is " + colour + "box is" +findBox(x,y)); textSource.setBackgroundColor(colour); start_inside = 1; } else { start_outside = 1; start_inside = 0; } if(colour != -59111){ count++; } /*if(flag[z][0] != findBox(x,y)){ clear = 1; }*/ if(findBox(x,y)!= flag[z][0] && flag[findBox(x,y)][1] == 0) { clear = 1; } if(flag[z][0] == findBox(x,y) && flag[z][1] == 1) { flag[z][1] = 2; if(z<9) { flag[z + 1][1] = 1; z++; } } /*else{ clear = 1; }*/ invalidate(); break; case MotionEvent.ACTION_MOVE: touch_move(x, y); textSource.setText("ACTION_MOVE- " + x + " : " + y); imageCache(); colour = getProjectedColor(imageResult, bitmapMaster,(int) x,(int) y); textSource.setText("color is " + colour+ "box is" +findBox(x,y)); textSource.setBackgroundColor(colour); if(insideBoundary(colour)) { textSource.setText("color is " + colour + "box is" +findBox(x,y)); textSource.setBackgroundColor(colour); } if (colour == -59111) reset = 0; if (reset == 0) { if (colour != -59111) {//if (colour == -14034428) reset = 1; count++; } } if(!insideBoundary(colour)) clear = 1; if(findBox(x,y)!= flag[z][0] && flag[findBox(x,y)][1] == 0) { clear = 1; } if(flag[z][0] == findBox(x,y) && flag[z][1] == 1) { flag[z][1] = 2; if(z<9) { flag[z + 1][1] = 1; z++; } } /*else{ clear = 1; }*/ invalidate(); break; case MotionEvent.ACTION_UP: touch_up(); textSource.setText("ACTION_UP- " + x + " : " + y); imageCache(); colour = getProjectedColor(imageResult, bitmapMaster,(int) x,(int) y); textSource.setText("color is " + colour + "box is" +findBox(x,y)); textSource.setBackgroundColor(colour); /*if(insideBoundary(colour)) { textSource.setText("color is " + colour); textSource.setBackgroundColor(colour); }*/ if((insideBoundary(colour) && start_outside == 1) ||!insideBoundary(colour) ) { clearScreen(); start_outside = 0; start_inside = 0; } if(clear == 1) { clearScreen(); clear = 0; } reset = 0; count_complete = 0; for(int i=0;i<10;i++) { if(flag[i][1] == 2) count_complete++; } //Toast.makeText(getApplicationContext()," "+count_complete, Toast.LENGTH_SHORT).show(); if(count_complete == 10) { //Toast.makeText(getApplicationContext(), "Congratulations", Toast.LENGTH_SHORT).show(); Intent b = new Intent(K.this, Ltrace.class); SharedPreferences access = getSharedPreferences("access file",MODE_PRIVATE); SharedPreferences.Editor edit = access.edit(); edit.putInt("l",1); edit.commit(); startActivity(b); finish(); } invalidate(); break; } return true; } } public void updateMsg(String tMsg, int color){ msg.setTextColor(color); msg.setText(tMsg+ "color is"+ color); } @Override public void onBackPressed() { super.onBackPressed(); startActivity(new Intent(K.this, Alphabets_numbers.class)); finish(); } }
[ "Omkar Vaidya" ]
Omkar Vaidya
d5e155745de88833befeb24d7ded486c7a005851
b3082559372bffa7e4105ec620bd9fc5a9a3cd12
/src/br/com/ligaesporteamador/service/impl/QuadraCampoServiceImpl.java
8b9514795af67ab56f64511661df84fc12297ddc
[]
no_license
reitak85/LigaEsporteAmadorWEB
1762630cc13124dd0641c1e464ea40eeae5ca7a4
7f8b61dbc7602f955dbe7357863a2a321feb0ca4
refs/heads/master
2021-01-20T11:34:15.112209
2013-12-13T18:09:56
2013-12-13T18:09:56
null
0
0
null
null
null
null
UTF-8
Java
false
false
970
java
package br.com.ligaesporteamador.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import br.com.ligaesporteamador.dao.QuadraCampoDao; import br.com.ligaesporteamador.model.QuadraCampo; import br.com.ligaesporteamador.service.QuadraCampoService; @Service public class QuadraCampoServiceImpl implements QuadraCampoService{ @Autowired QuadraCampoDao campoDao; @Override public QuadraCampo insertQuadraCampo(QuadraCampo campo) throws Exception { return campoDao.insertQuadraCampo(campo); } @Override public QuadraCampo updateQuadraCampo() throws Exception { // TODO Auto-generated method stub return null; } @Override public void deleteQuadraCampo() throws Exception { // TODO Auto-generated method stub } @Override public QuadraCampo selectQuadraCampo(Long id) throws Exception { return campoDao.selectQuadraCampo(id); } }
[ "lu864703" ]
lu864703
f28edbb4324993caf818588e5dfbbb31eecfbe1a
b88e6782c44ccf7a44d3684a395facc72558e126
/src/Practice07/Quiz18.java
60b49ddaacc078cf910ae048c5f4e5573b6df4fe
[]
no_license
mr-joo/brain-storming
5e33516ce250df9e1735cdd2b83cc5d7d6b2773f
82e198bc0bcea3c4b365ff5266a0c7cb937df292
refs/heads/master
2021-09-03T08:22:13.096873
2018-01-07T13:52:45
2018-01-07T13:52:45
114,743,459
0
0
null
null
null
null
UTF-8
Java
false
false
933
java
package Practice07; public class Quiz18 { //action메서드 작성 public static void action(Robot r) { if (r instanceof DanceRobot) { ((DanceRobot) r).dance(); }else if (r instanceof SingRobot) { ((SingRobot) r).sing(); }else if (r instanceof DrawRobot) { ((DrawRobot) r).draw(); } } public static void main(String[] args) { Robot[] arr = {new DanceRobot(), new SingRobot(), new DrawRobot()}; for (int i = 0; i < arr.length; i++) { action(arr[i]); } } } class Robot {} class DanceRobot extends Robot { void dance() { System.out.println("춤을 춥니다."); } } class SingRobot extends Robot { void sing() { System.out.println("노래를 합니다."); } } class DrawRobot extends Robot { void draw() { System.out.println("그림을 그립니다."); } }
f8e1c5c34c71047fdaa19d1eed209385a108cebd
3c6f4bb030a42d19ce8c25a931138641fb6fd495
/finance-vas/finance-vas-service/src/main/java/com/hongkun/finance/vas/service/impl/SysAppVersionRuleServiceImpl.java
a021e2e430b2ed2857167cffa6a23a9304400b47
[]
no_license
happyjianguo/finance-hkjf
93195df26ebb81a8b951a191e25ab6267b73aaca
0389a6eac966ee2e4887b6db4f99183242ba2d4e
refs/heads/master
2020-07-28T13:42:40.924633
2019-08-03T00:22:19
2019-08-03T00:22:19
null
0
0
null
null
null
null
UTF-8
Java
false
false
9,714
java
package com.hongkun.finance.vas.service.impl; import com.alibaba.dubbo.config.annotation.Service; import com.hongkun.finance.vas.constants.AppVersionConstants; import com.hongkun.finance.vas.dao.SysAppVersionRuleDao; import com.hongkun.finance.vas.model.SysAppVersionRule; import com.hongkun.finance.vas.service.SysAppVersionRuleService; import com.yirun.framework.core.commons.Constants; import com.yirun.framework.core.exception.GeneralException; import com.yirun.framework.core.model.ResponseEntity; import com.yirun.framework.core.utils.DateUtils; import com.yirun.framework.core.utils.PropertiesHolder; import com.yirun.framework.core.utils.pager.Pager; import com.yirun.framework.oss.OSSLoader; import com.yirun.framework.oss.model.OSSBuckets; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.InputStreamResource; import org.springframework.core.io.support.EncodedResource; import org.springframework.core.io.support.PropertiesLoaderUtils; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import static com.yirun.framework.core.commons.Constants.ERROR; import static com.yirun.framework.core.commons.Constants.SUCCESS; /** * @Project : finance * @Program Name : com.hongkun.finance.vas.service.impl.SysAppVersionRuleServiceImpl.java * @Class Name : SysAppVersionRuleServiceImpl.java * @Description : GENERATOR SERVICE实现类 * @Author : generator */ @Service public class SysAppVersionRuleServiceImpl implements SysAppVersionRuleService { private static final Logger logger = LoggerFactory.getLogger(SysAppVersionRuleServiceImpl.class); /** * SysAppVersionRuleDAO */ @Autowired private SysAppVersionRuleDao sysAppVersionRuleDao; @Override @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, readOnly = false) public int insertSysAppVersionRule(SysAppVersionRule sysAppVersionRule) { try{ return this.sysAppVersionRuleDao.save(sysAppVersionRule); }catch (Exception e){ logger.error("insertSysAppVersionRule, 添加app版本更新规则异常, 规则信息: {}, 异常信息: ", sysAppVersionRule.toString(), e); throw new GeneralException("添加app版本更新规则异常!"); } } @Override @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, readOnly = false) public int insertSysAppVersionRuleBatch(List<SysAppVersionRule> list) { return this.sysAppVersionRuleDao.insertBatch(SysAppVersionRule.class, list); } @Override @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, readOnly = false) public int insertSysAppVersionRuleBatch(List<SysAppVersionRule> list, int count) { if(logger.isDebugEnabled()){ logger.debug("default batch insert size is " + count); } return this.sysAppVersionRuleDao.insertBatch(SysAppVersionRule.class, list, count); } @Override @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, readOnly = false) public int updateSysAppVersionRule(SysAppVersionRule sysAppVersionRule) { try{ return this.sysAppVersionRuleDao.update(sysAppVersionRule); }catch (Exception e){ logger.error("updateSysAppVersionRule, 更新app版本更新规则异常, 规则信息: {}, 异常信息: ",sysAppVersionRule.toString(), e); throw new GeneralException("更新app版本更新规则异常!"); } } @Override @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, readOnly = false) public int updateSysAppVersionRuleBatch(List<SysAppVersionRule> list, int count) { return this.sysAppVersionRuleDao.updateBatch(SysAppVersionRule.class, list, count); } @Override public SysAppVersionRule findSysAppVersionRuleById(int id) { return this.sysAppVersionRuleDao.findByPK(Long.valueOf(id), SysAppVersionRule.class); } @Override public List<SysAppVersionRule> findSysAppVersionRuleList(SysAppVersionRule sysAppVersionRule) { return this.sysAppVersionRuleDao.findByCondition(sysAppVersionRule); } @Override public List<SysAppVersionRule> findSysAppVersionRuleList(SysAppVersionRule sysAppVersionRule, int start, int limit) { return this.sysAppVersionRuleDao.findByCondition(sysAppVersionRule, start, limit); } @Override public Pager findSysAppVersionRuleList(SysAppVersionRule sysAppVersionRule, Pager pager) { return this.sysAppVersionRuleDao.findByCondition(sysAppVersionRule, pager); } @Override public int findSysAppVersionRuleCount(SysAppVersionRule sysAppVersionRule){ return this.sysAppVersionRuleDao.getTotalCount(sysAppVersionRule); } @Override public Pager findSysAppVersionRuleList(SysAppVersionRule sysAppVersionRule, Pager pager, String sqlName){ return this.sysAppVersionRuleDao.findByCondition(sysAppVersionRule, pager, sqlName); } @Override public Integer findSysAppVersionRuleCount(SysAppVersionRule sysAppVersionRule, String sqlName){ return this.sysAppVersionRuleDao.getTotalCount(sysAppVersionRule, sqlName); } @Override public ResponseEntity findRuleCountByVersion(String platform, String version) { ResponseEntity result = new ResponseEntity(SUCCESS); Map<String,Object> params = new HashMap<>(2); Map<String,String> versionAndDescribe = getLatestVersionAndDescribe(platform); //1.获取最新版本号 String latestVersion = versionAndDescribe.get("version"); //如果最新版本号为null,说明配置文件异常 if(StringUtils.isBlank(latestVersion)){ return new ResponseEntity(ERROR); } //如果当前版本号不小于最新版本号则不需要更新 if (Integer.valueOf(version.replace(".","").trim()) >= Integer.valueOf(latestVersion.replace(".", "").trim())){ //无需更新 params.put("state",3); }else { //2.在判断是否有强制更新 SysAppVersionRule condition = new SysAppVersionRule(); condition.setVersion(version); condition.setPlatform(platform); condition.setState(AppVersionConstants.APP_VERSION_STATE_UP); SysAppVersionRule sysAppVersionRule = this.sysAppVersionRuleDao.findRule(condition); //sysAppVersionRule有内容表示该版本的app需要进行强制更新,否则提示普通更新 params.put("version",latestVersion); if (sysAppVersionRule != null){ params.put("content",sysAppVersionRule.getContent()); params.put("state",1); }else { params.put("content",versionAndDescribe.get("describe")); params.put("state",2); } //如果为安卓手机返回app下载地址 if (platform.equals(AppVersionConstants.APP_VERSION_PLATFORM_ANDROID)){ //判断apk包是否存在 String key = "android/apk/HKJF_ANDROID.apk"; if (OSSLoader.getInstance().doesObjectExist(OSSBuckets.HKJF,key)){ params.put("androidApkKey",key); } } } result.setParams(params); return result; } private Map<String,String> getLatestVersionAndDescribe(String platform){ Map<String,String> result = new HashMap<>(2); if (OSSLoader.getInstance().doesObjectExist(OSSBuckets.HKJF,"android/hkjf_version.properties")){ InputStreamResource isr = new InputStreamResource(OSSLoader.getInstance(). getOSSObject(OSSBuckets.HKJF,"android/hkjf_version.properties").getObjectContent()); EncodedResource encodedResource = new EncodedResource(isr,"UTF-8"); Properties properties = null; try { properties = PropertiesLoaderUtils.loadProperties(encodedResource); } catch (IOException e) { e.printStackTrace(); } if (properties != null){ if (platform.equals(AppVersionConstants.APP_VERSION_PLATFORM_ANDROID)){ result.put("version",properties.getProperty("android.latest.version")); result.put("describe",properties.getProperty("android.latest.version.describe")); } if (platform.equals(AppVersionConstants.APP_VERSION_PLATFORM_IOS)){ result.put("version",properties.getProperty("ios.latest.version")); result.put("describe",properties.getProperty("ios.latest.version.describe")); } } }else { logger.error("oss端app相关配置文件缺失,请及时补充!"); } return result; } @Override public ResponseEntity updateAppVersionRuleState(int id, int state) { SysAppVersionRule rule = new SysAppVersionRule(); rule.setId(id); rule.setState(state); if (AppVersionConstants.APP_VERSION_STATE_UP == state){ rule.setUptime(DateUtils.getCurrentDate()); }else { rule.setDowntime(DateUtils.getCurrentDate()); } try { if (this.sysAppVersionRuleDao.update(rule) > 0){ return new ResponseEntity(SUCCESS); } }catch (Exception e){ logger.error("updateAppVersionRuleState, 上架或下架app版本规则异常, 规则id: {}, 更新状态: {}", id, state); throw new GeneralException("上架或下架app版本规则异常!"); } return new ResponseEntity(ERROR); } @Override public ResponseEntity getIosAuditVersion(String version) { ResponseEntity result = new ResponseEntity(Constants.SUCCESS); Map<String,Object> params = new HashMap<>(2); //默认为审核通过 params.put("state",1); //判断版本是否为审核版本,若为审核版本则返回0-审核中,否则返回1-审核通过 String iosAuditVersion = PropertiesHolder.getProperty("ios.audit.version"); if (iosAuditVersion != null && iosAuditVersion.equals(version)){ params.put("state",0); } result.setParams(params); return result; } }
6924f36c080107f1a3f454b7aa40b03493a4b0d6
6494431bcd79c7de8e465481c7fc0914b5ef89d5
/src/main/java/com/coinbase/Coinbase$$Lambda$12.java
e3b3fb696900440c04cf5b89b3c32fb5efc7b6ce
[]
no_license
maisamali/coinbase_decompile
97975a22962e7c8623bdec5c201e015d7f2c911d
8cb94962be91a7734a2182cc625efc64feae21bf
refs/heads/master
2020-06-04T07:10:24.589247
2018-07-18T05:11:02
2018-07-18T05:11:02
191,918,070
2
0
null
2019-06-14T09:45:43
2019-06-14T09:45:43
null
UTF-8
Java
false
false
516
java
package com.coinbase; import android.util.Pair; import retrofit2.Response; import retrofit2.Retrofit; import rx.functions.Func2; final /* synthetic */ class Coinbase$$Lambda$12 implements Func2 { private static final Coinbase$$Lambda$12 instance = new Coinbase$$Lambda$12(); private Coinbase$$Lambda$12() { } public static Func2 lambdaFactory$() { return instance; } public Object call(Object obj, Object obj2) { return new Pair((Response) obj, (Retrofit) obj2); } }
5bf575f090a5754d20fe59751406e8af813fc12b
e07bb764864d7f618a245b242489e5f55acd879a
/code/tdt-vip-main/src/main/java/com/tdt/modular/storage/model/result/AllocationDetailResult.java
6f143ec569daa341c1e219ba44f2b030b7bfff1b
[]
no_license
gechangjiang/wms
b61e7aed8a983a6bfbf4044289d8cf2dd67561d1
45d9ba6f6c0ca6d3ebee617a625199073b29b345
refs/heads/main
2023-07-03T21:21:21.464250
2021-08-09T08:53:14
2021-08-09T08:53:14
393,873,738
0
0
null
null
null
null
UTF-8
Java
false
false
1,194
java
package com.tdt.modular.storage.model.result; import lombok.Data; import java.util.Date; import java.io.Serializable; /** * <p> * * </p> * * @author gcj * @since 2019-08-28 */ @Data public class AllocationDetailResult implements Serializable { private static final long serialVersionUID = 1L; /** * 编号 */ private Long id; /** * 调拨id */ private Long pid; /** * 货位id */ private Long locatorid; /** * 商品id */ private Long commodityid; /** * 商品编码 */ private String commoditybar; /** * 商品名称 */ private String commodityname; /** * 数量 */ private Integer qty; /** * 锁定库存的id */ private Long lockstockid; /** * 创建人id */ private Long createid; /** * 创建人 */ private String creator; /** * 创建时间 */ private Date createtime; /** * 修改人id */ private Long updateid; /** * 修改人 */ private String updator; /** * 修改时间 */ private Date updatetime; }
272bbc63973a4fe3f6ad18b0901dd1abe59b7205
324f5e79ea8109cd7ac7e5c84b37dfb679302554
/app/src/main/java/com/example/pan/myapplication/messenger/MessengerActivity.java
39b3c524e762f407605411605edbbd3a28ea5ba5
[]
no_license
panq-jack/BinderDemo
014e03094dd6055556fd04f01007ac57376f5a50
9a5aa1b29c18bb7f427a67f0f952b2438873d979
refs/heads/master
2020-03-09T02:39:48.516333
2018-04-07T17:32:50
2018-04-07T17:32:50
128,545,473
0
0
null
null
null
null
UTF-8
Java
false
false
3,797
java
package com.example.pan.myapplication.messenger; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.Messenger; import android.os.RemoteException; import android.support.annotation.Nullable; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.example.pan.myapplication.R; /** * Created by pan on 2018/4/7. */ public class MessengerActivity extends AppCompatActivity { public static final int MSG_FROM_SERVER=1; private boolean mBound=false; private Messenger messenger; /** Defines callbacks for service binding, passed to bindService() */ private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { // We've bound to LocalService, cast the IBinder and get LocalService instance messenger=new Messenger(service); mBound = true; } @Override public void onServiceDisconnected(ComponentName arg0) { mBound = false; } }; private Handler clientHandler=new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what){ case MSG_FROM_SERVER: Bundle bundle=msg.getData(); String str=bundle.getString("msg",""); Toast.makeText(MessengerActivity.this,"msg from server: "+str,Toast.LENGTH_SHORT).show(); break; default: break; } } }; private Messenger clientMessenger=new Messenger(clientHandler); @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_messenger); ActionBar actionBar=getSupportActionBar(); actionBar.setTitle("Messenger Test"); actionBar.setDisplayHomeAsUpEnabled(true); } @Override protected void onStart() { super.onStart(); init(); } private void init(){ // Bind to LocalService Intent intent = new Intent(this, MessengerService.class); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } public void action(View view){ if (null!=messenger && mBound){ //发送消息,并设置接收消息处理器 Message message=Message.obtain(); message.what=MessengerService.MSG_FROM_CLIENT; Bundle bundle=new Bundle(); bundle.putString("msg","msg from client by Messenger author jackpanq"); message.setData(bundle); message.replyTo=clientMessenger; try{ messenger.send(message); }catch (RemoteException e){ e.printStackTrace(); } } } @Override protected void onStop() { super.onStop(); // Unbind from the service if (mBound) { unbindService(mConnection); mBound = false; } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: this.finish(); // back button return true; } return super.onOptionsItemSelected(item); } }