text
stringlengths
10
2.72M
package com.shangcai.action.customer.design; import java.io.IOException; public interface IDesignerAction { /** * 设置个人信息-设计师 */ public void upd() throws IOException; /** * 获取个人信息-设计师 */ public void get() throws IOException; }
#include <iostream> #include <bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--) { int n,k; cin>>n>>k; int a[n],min; for(int i=0;i<n;i++) cin>>a[i]; sort(a,a+n); int sumc=0,sumf=0; for(int i=0;i<n;i++) { if(k<=(n/2)) { if(i<k)sumc+=a[i]; else sumf+=a[i]; } else { if(i<n-k)sumc+=a[i]; else sumf+=a[i]; } } cout<<sumf-sumc<<endl; } return 0; }
package com.example.myapplication; import android.os.Build; import androidx.annotation.RequiresApi; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.apache.commons.lang3.ArrayUtils; public class DecompBCNf { @RequiresApi(api = Build.VERSION_CODES.N) public Set<String> decompbcnf(HashMap<String, String> fds, String rls, Set<String> ckset){ Set<Set<Character>> ckSetSet = ckset.stream().map(s -> s.chars().mapToObj(c -> (char) c).collect(Collectors.toSet())).collect(Collectors.toSet()); Set<Character> ckSetCons = ckSetSet.stream().reduce(new HashSet<>(), (s, e) -> {s.addAll(e); return s;}, (s1, s2) -> {s1.addAll(s2); return s1;}); Map<Set<Character>, Set<Character>> mspSets = new HashMap<>(); fds.forEach((k, v) -> { mspSets.put(k.chars().mapToObj(c -> (char) c).collect(Collectors.toSet()), v.chars().mapToObj(c -> (char) c).collect(Collectors.toSet())); }); Set<Character> rlsSet = rls.chars().mapToObj(c -> (char) c).collect(Collectors.toSet()); Set<String> dec = new HashSet<>(); mspSets.forEach((k,v) -> { // if(!ckSetCons.containsAll(v)) { if(ckSetSet.stream().noneMatch(e -> e.equals(k))) { v.removeAll(k); rlsSet.removeAll(v); v.addAll(k); dec.add(v.stream().map(String::valueOf).collect(Collectors.joining())); } // } }); dec.add(rlsSet.stream().map(String::valueOf).collect(Collectors.joining())); return dec; } // { // Set<String> relations = new HashSet<String>(); // Character[] rlsarr = ArrayUtils.toObject(rls.toCharArray()); // Set<Character> rlsset = new HashSet<Character>(Arrays.asList(rlsarr)); // String x; // String temp=""; // int flag; // relations.add(rls); // for(Map.Entry<String, String> entry : fds.entrySet()) // { // x = entry.getKey(); // int flagx = 0; // for(String s : ckset) // { // if(checksubstring(entry.getKey(),s)) // { // flagx = 1; // } // } // // if(flagx == 0) // { // for(String s : relations) // { // flag = 0; // if(checksubstring(s,x.concat(entry.getValue()))) // { // Set<Character> tempset = new HashSet<Character>(Arrays.asList(ArrayUtils.toObject(entry.getValue().toCharArray()))); // Set<Character> sset = new HashSet<>(Arrays.asList(ArrayUtils.toObject(s.toCharArray()))); // sset.removeAll(tempset); // Character[] sarr = new Character[sset.size()]; // sset.toArray(sarr); // temp = new String(ArrayUtils.toPrimitive(sarr)); // flag = 1; // relations.add(x.concat(entry.getValue())); // } // if(flag==1) // { // relations.remove(s); // relations.add(temp); // } // } // } // } // // for(String ck : ckset) // { // int f = 0; // for(String st : relations) // { // if(checksubstring(st,ck)) // { // f = 1; // break; // } // } // if(f==0) // relations.add(ck); // } // // System.out.println(relations.toString()); // return relations; // // } // // public boolean checksubstring(String s1, String s2) // { // char[] first = s1.toCharArray(); // char[] second = s2.toCharArray(); // int flag = 0; // for(char c : second) // { // if(s1.indexOf(c)==-1) // { // flag = 1; // } // } // return (flag==0); // } }
package com.accp.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.accp.entity.SysPermissions; import com.accp.entity.SysUsers; import com.accp.service.ISysPermissionsService; import com.alibaba.fastjson.JSON; @Controller @RequestMapping("/index") public class IndexController { @Autowired ISysPermissionsService iSysPermissionsService; @RequestMapping("/index") @ResponseBody public List<SysPermissions> toIndex() { List<SysPermissions> list = iSysPermissionsService.list(null); System.out.println("list: " + JSON.toJSON(list)+"============="); return list; } @RequestMapping("/byUser") @ResponseBody public List<SysPermissions> byUser(@RequestBody SysUsers sysUsers) { List<SysPermissions> list = iSysPermissionsService.queryCatalogByUserName(sysUsers.getUsername()); System.out.println("list: " + JSON.toJSON(list)); return list; } }
package com.example.userportal.controller; import com.example.userportal.requestmodel.payu.PayUOrderCreateResponse; import com.example.userportal.service.PayUClient; import com.example.userportal.service.dto.GooglePayOrderDTO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; @RestController @RequestMapping(value = "payment/googlepay") public class GooglePayController { private final PayUClient payUClient; @Autowired GooglePayController(PayUClient payUClient) { this.payUClient = payUClient; } @PreAuthorize("hasRole('ROLE_USER')") @PostMapping public PayUOrderCreateResponse makePaymentWithGooglePay(@Valid @RequestBody GooglePayOrderDTO googlePayOrder) { return payUClient.payForOrderWithGooglePay(googlePayOrder); } }
package questao13; /** * NumberUtils */ public class NumberUtils { int n; public NumberUtils(int n) { this.n = n; } public boolean isPair() { if (n%2 == 0) { return true; } return false; } public boolean isOdd() { if (n % 2 == 0) { return false; } return true; } public boolean isPrime() { if (n == 0 || n == 1) { return false; } else { if (n == 2) { return true; } else { for (int i=2; i<=n; i++) { int mod = n%i; if ((mod == 0)) { return false; } } } } return true; } public void printCount() { for (int i=0; i<=n; i++) { System.out.println(i); } } public void printReverseCount() { for (int i=n; i>=0; i--) { System.out.println(i); } } }
/*....................Pour parser le fichier modéle de donnée et de creer un JtreeModel qu'on va appeler dans la classe principale........................ */ //La récursivité : package javaapplication; import static java.awt.SystemColor.info; import java.io.File; import java.io.IOException; import javax.swing.JFrame; // import javax.swing.JScrollPane; // import javax.swing.JTree; import javax.swing.event.TreeSelectionEvent; import javax.swing.tree.DefaultMutableTreeNode; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.ErrorHandler; // import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; /** * * @author moussa */ public class type2{ public static void main(String[] args) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setIgnoringComments(true); factory.setIgnoringElementContentWhitespace(true); //Les exceptions... try { factory.setValidating(true); DocumentBuilder builder = factory.newDocumentBuilder(); // ErrorHandler errHandler = new SimpleErrorHandler(); // builder.setErrorHandler(errHandler); File fileXML = new File("OntologieTest.xml"); Document xml; try { xml = builder.parse(fileXML); Element racine = xml.getDocumentElement(); DefaultMutableTreeNode root = new DefaultMutableTreeNode(racine.getNodeName()); //examine le parent et les enfants d'un noeud // Le noeud sans parent est la racine de l'arbre et un noeud sans enfant est une feuille DefaultMutableTreeNode n = null; createJTree(racine, root, n);//noeud sans parent // Il saute et part les fils de balise1 et les balises catégories JFrame fenetre = new JFrame(); fenetre.setLocationRelativeTo(null); fenetre.setSize(300, 400); fenetre.add(new JScrollPane(new JTree(root))); fenetre.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); fenetre.setVisible(true); } catch (SAXParseException e) { } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /*public void valueChanged(TreeSelectionEvent tsl) { if (tsl.getNewLeadSelectionPath() != null ) { info.setViewportView(jList1)(tsl.getNewLeadSelectionPath().getLastPathComponent().toString()); } }*/ /** * Méthode qui va parser le contenu d'un noeud * @param n * @param tab * @return */ // Methode qui parse et qui remplit l'arbre... public static void createJTree(Node n, DefaultMutableTreeNode treeNode, DefaultMutableTreeNode noeuds){ if(n instanceof Element){ Element element = (Element)n; //nous contrôlons la liste des attributs présents if(n.getAttributes() != null && n.getAttributes().getLength() > 0){ //Pour récupérer la liste des attributs dans une Map NamedNodeMap att = n.getAttributes(); int nbAtt = att.getLength(); //Pour parcourir tous les noeuds pour les afficher for(int j = 0; j < nbAtt; j++){ // Récupération attribut Node noeud = att.item(j); //On récupère le nom de l'attribut et sa valeur grâce à ces deux méthodes DefaultMutableTreeNode attribut = new DefaultMutableTreeNode ( noeud.getNodeValue()); noeuds = attribut;//ajoute plante dans attribut // S'il y'avait plusieurs attribut il allez tout prendre // Les balises catégories } } //Pour maintenant traiter les noeuds enfants du noeud en cours de traitement int nbChild = n.getChildNodes().getLength(); //Nous récupérons la liste des noeuds enfants // Les balises type NodeList list = n.getChildNodes(); //Pour parcourir la liste des noeuds for(int i = 0; i < nbChild; i++){ // Parcourir les fils et ajouter à leurs parent Node n2 = list.item(i); //si le noeud enfant est un Element, nous le traitons if (n2 instanceof Element){ if((n2.getTextContent() != null) && !n2.getTextContent().trim().equals("") && (n2.getChildNodes().getLength() == 1)) // recupére les valuers entres types { DefaultMutableTreeNode value = new DefaultMutableTreeNode(n2.getTextContent()); noeuds.add(value);// ajouté dans noeuds } //appel récursif à la méthode pour le traitement du noeud et de ses enfants createJTree(n2, treeNode, noeuds);// n2 c la balise type, treenode=la racine balise1, je lui passe la varibale noeuds parent de n2 (nom latin ici) if(noeuds != null) treeNode.add(noeuds); // Ajout des noeuds } } if(noeuds != null) treeNode.add(noeuds); // Ajout des noeuds } } }
package com.frantzoe.phonebook.contacts; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; // This will be AUTO IMPLEMENTED by Spring into a Bean called userRepository // CRUD refers Create, Read, Update, Delete @Repository public interface ContactRepository extends JpaRepository<Contact, Long> { // }
package shangguigu; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Lock lock = new ReentrantLock(true):指定该锁为公平锁,此时线程会有序执行,而不是抢占式执行 */ public class Thread19 { // Lock lock = new ReentrantLock(true); Lock lock = new ReentrantLock(true); public void m1(){ for(int i=0;i<100;i++){ lock.lock(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()); lock.unlock(); } } public static void main(String[] args) { Thread19 thread19 = new Thread19(); new Thread(()->thread19.m1(),"t1").start(); new Thread(()->thread19.m1(),"t2").start(); } }
package be.kestro.io.core.api; /** * Service definition to control PWM pins. (Pulse-Width-Modulation) * */ public interface PwmService extends IOService { /** * Sets the percentage by which pulses will be sent. * * @param percentage value from 0 to 100 to control the PWM. */ void setPulsePercentage(int percentage); /** * Gets the last set PWM percentage. * * @return the PWM percentage. */ int getPulsePercentage(); /** * Increases the current PWM percentage. */ void increase(); /** * Decreases the current PWM percentage. */ void decrease(); }
package com.atgem.googleplay; import java.util.ArrayList; import java.util.List; import cn.jpush.android.api.JPushInterface; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.widget.ListAdapter; public class MyReceiver extends BroadcastReceiver { public static final String TAG="JPush"; @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub List<String>list=new ArrayList<String>(); Bundle bundle = intent.getExtras(); Log.d(TAG, "onReceive - " + intent.getAction()); if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) { }else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) { System.out.println("�յ����Զ�����Ϣ����Ϣ�����ǣ�" + bundle.getString(JPushInterface.EXTRA_MESSAGE)); // �Զ�����Ϣ����չʾ��֪ͨ������ȫҪ������д����ȥ���� } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) { System.out.println("�յ���֪ͨ,֪ͨ��������"+ bundle.getString(JPushInterface.EXTRA_ALERT)); list.add(bundle.getString(JPushInterface.EXTRA_ALERT)); // �����������Щͳ�ƣ�������Щ������ } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) { System.out.println("�û��������֪ͨ"); // ����������Լ�д����ȥ�����û���������Ϊ Intent i = new Intent(context, Notify.class); //������͵Ľ�������ĸ����� i.putExtra("a",bundle.getString(JPushInterface.EXTRA_ALERT)); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(i); } else { Log.d(TAG, "Unhandled intent - " + intent.getAction()); } } }
package com.dxt2.dagger2demo2; import dagger.Module; import dagger.Provides; /** * Created by Administrator on 2018/6/6 0006. */ //使用该注解来指定应该注入一个怎么样的鼠标, //我们在MouseModule中分别指定两个方法返回一个怎样的鼠标, // 再在Computer类中声明Mouse对象时指定它应该被注入一个什么类型的鼠标 @Module public class WMouseModule { @Provides @WMouseType("wired")//指定该方法返回一个有线鼠标 WMouse provideWireMouse(){ return new WiredMouse();//返回有线鼠标 } @Provides @WMouseType("wireless")//指定该方法返回一个无线鼠标 WMouse provideWirelessMouse(){ return new WirelessMouse();//返回无线鼠标 } }
package kr.ko.nexmain.server.MissingU.membership.model; import kr.ko.nexmain.server.MissingU.common.model.CommReqVO; import org.hibernate.validator.constraints.NotEmpty; public class MemberRegisterReqVO extends CommReqVO { private static final long serialVersionUID = 1L; private Integer memberId; private String status; @NotEmpty private String loginId; @NotEmpty private String loginPw; private String gcmRegId; private String gcmUseYn; private String nickName; private String sex; private String bloodTypeCd; private String birthDate; private String birthTime; private String lunarSolarCd; private String appearanceTypeCd; private String bodyTypeCd; private String areaCd; private String purposeCd; private String hobbyCd; private String drinkingHabitCd; private String smokingHabitCd; private String mainPhoto; private String subPhoto01; private String subPhoto02; private String subPhoto03; private String subPhoto04; private String subPhoto05; private String subPhoto06; private String subPhoto07; private String subPhoto08; private String selfPr; private String etcHn; private String hpNm; /** * @return the memberId */ public Integer getMemberId() { return memberId; } /** * @param memberId the memberId to set */ public void setMemberId(Integer memberId) { this.memberId = memberId; } /** * @return the loginId */ public String getLoginId() { return loginId; } /** * @param loginId the loginId to set */ public void setLoginId(String loginId) { this.loginId = loginId; } /** * @return the loginPw */ public String getLoginPw() { return loginPw; } /** * @param loginPw the loginPw to set */ public void setLoginPw(String loginPw) { this.loginPw = loginPw; } /** * @return the gcmRegId */ public String getGcmRegId() { return gcmRegId; } /** * @param gcmRegId the gcmRegId to set */ public void setGcmRegId(String gcmRegId) { this.gcmRegId = gcmRegId; } /** * @return the nickName */ public String getNickName() { return nickName; } /** * @param nickName the nickName to set */ public void setNickName(String nickName) { this.nickName = nickName; } /** * @return the sex */ public String getSex() { return sex; } /** * @param sex the sex to set */ public void setSex(String sex) { this.sex = sex; } /** * @return the bloodTypeCd */ public String getBloodTypeCd() { return bloodTypeCd; } /** * @param bloodTypeCd the bloodTypeCd to set */ public void setBloodTypeCd(String bloodTypeCd) { this.bloodTypeCd = bloodTypeCd; } /** * @return the birthDate */ public String getBirthDate() { return birthDate; } /** * @param birthDate the birthDate to set */ public void setBirthDate(String birthDate) { this.birthDate = birthDate; } /** * @return the birthTime */ public String getBirthTime() { return birthTime; } /** * @param birthTime the birthTime to set */ public void setBirthTime(String birthTime) { this.birthTime = birthTime; } /** * @return the lunarSolarCd */ public String getLunarSolarCd() { return lunarSolarCd; } /** * @param lunarSolarCd the lunarSolarCd to set */ public void setLunarSolarCd(String lunarSolarCd) { this.lunarSolarCd = lunarSolarCd; } /** * @return the appearanceTypeCd */ public String getAppearanceTypeCd() { return appearanceTypeCd; } /** * @param appearanceTypeCd the appearanceTypeCd to set */ public void setAppearanceTypeCd(String appearanceTypeCd) { this.appearanceTypeCd = appearanceTypeCd; } /** * @return the bodyTypeCd */ public String getBodyTypeCd() { return bodyTypeCd; } /** * @param bodyTypeCd the bodyTypeCd to set */ public void setBodyTypeCd(String bodyTypeCd) { this.bodyTypeCd = bodyTypeCd; } /** * @return the areaCd */ public String getAreaCd() { return areaCd; } /** * @param areaCd the areaCd to set */ public void setAreaCd(String areaCd) { this.areaCd = areaCd; } /** * @return the purposeCd */ public String getPurposeCd() { return purposeCd; } /** * @param purposeCd the purposeCd to set */ public void setPurposeCd(String purposeCd) { this.purposeCd = purposeCd; } /** * @return the hobbyCd */ public String getHobbyCd() { return hobbyCd; } /** * @param hobbyCd the hobbyCd to set */ public void setHobbyCd(String hobbyCd) { this.hobbyCd = hobbyCd; } /** * @return the drinkingHabitCd */ public String getDrinkingHabitCd() { return drinkingHabitCd; } /** * @param drinkingHabitCd the drinkingHabitCd to set */ public void setDrinkingHabitCd(String drinkingHabitCd) { this.drinkingHabitCd = drinkingHabitCd; } /** * @return the smokingHabitCd */ public String getSmokingHabitCd() { return smokingHabitCd; } /** * @param smokingHabitCd the smokingHabitCd to set */ public void setSmokingHabitCd(String smokingHabitCd) { this.smokingHabitCd = smokingHabitCd; } /** * @return the mainPhoto */ public String getMainPhoto() { return mainPhoto; } /** * @param mainPhoto the mainPhoto to set */ public void setMainPhoto(String mainPhoto) { this.mainPhoto = mainPhoto; } /** * @return the subPhoto01 */ public String getSubPhoto01() { return subPhoto01; } /** * @param subPhoto01 the subPhoto01 to set */ public void setSubPhoto01(String subPhoto01) { this.subPhoto01 = subPhoto01; } /** * @return the subPhoto02 */ public String getSubPhoto02() { return subPhoto02; } /** * @param subPhoto02 the subPhoto02 to set */ public void setSubPhoto02(String subPhoto02) { this.subPhoto02 = subPhoto02; } /** * @return the subPhoto03 */ public String getSubPhoto03() { return subPhoto03; } /** * @param subPhoto03 the subPhoto03 to set */ public void setSubPhoto03(String subPhoto03) { this.subPhoto03 = subPhoto03; } /** * @return the subPhoto04 */ public String getSubPhoto04() { return subPhoto04; } /** * @param subPhoto04 the subPhoto04 to set */ public void setSubPhoto04(String subPhoto04) { this.subPhoto04 = subPhoto04; } /** * @return the subPhoto05 */ public String getSubPhoto05() { return subPhoto05; } /** * @param subPhoto05 the subPhoto05 to set */ public void setSubPhoto05(String subPhoto05) { this.subPhoto05 = subPhoto05; } /** * @return the subPhoto06 */ public String getSubPhoto06() { return subPhoto06; } /** * @param subPhoto06 the subPhoto06 to set */ public void setSubPhoto06(String subPhoto06) { this.subPhoto06 = subPhoto06; } /** * @return the subPhoto07 */ public String getSubPhoto07() { return subPhoto07; } /** * @param subPhoto07 the subPhoto07 to set */ public void setSubPhoto07(String subPhoto07) { this.subPhoto07 = subPhoto07; } /** * @return the subPhoto08 */ public String getSubPhoto08() { return subPhoto08; } /** * @param subPhoto08 the subPhoto08 to set */ public void setSubPhoto08(String subPhoto08) { this.subPhoto08 = subPhoto08; } /** * @return the selfPr */ public String getSelfPr() { return selfPr; } /** * @param selfPr the selfPr to set */ public void setSelfPr(String selfPr) { this.selfPr = selfPr; } /** * @return the status */ public String getStatus() { return status; } /** * @param status the status to set */ public void setStatus(String status) { this.status = status; } /** * @return the gcmUseYn */ public String getGcmUseYn() { return gcmUseYn; } /** * @param gcmUseYn the gcmUseYn to set */ public void setGcmUseYn(String gcmUseYn) { this.gcmUseYn = gcmUseYn; } /** * @return the etcHn */ public String getEtcHn() { return etcHn; } /** * @param etcHn the etcHn to set */ public void setEtcHn(String etcHn) { this.etcHn = etcHn; } /** * @return the hpNm */ public String getHpNm() { return hpNm; } /** * @param hpNm the hpNm to set */ public void setHpNm(String hpNm) { this.hpNm = hpNm; } }
package com.study.jpa.entity; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.*; /** * Created by francis on 2015. 12. 1.. */ @Entity @Table(name = "parent", catalog = "study") public class Parent { @Id @GeneratedValue(strategy = IDENTITY) private @Column(name = "pid", nullable = false) Long pid; private @Column(name = "name", nullable = false) String name; public Long getPid() { return pid; } public void setPid(Long pid) { this.pid = pid; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { final StringBuilder sb = new StringBuilder("Parent{"); sb.append("pid=").append(pid); sb.append(", name='").append(name).append('\''); sb.append('}'); return sb.toString(); } }
package Shapes; import util.Input; public class Circle { private double radius; public Circle(){ radius = Input.getDouble(); System.out.println("The radius is: " + getArea()); System.out.println("The circumference is "+ getCircumference()); new Circle(); } public double getArea(){ return Math.PI*radius*radius; } public double getCircumference(){ return Math.PI*2*radius; } }
package com.view; import java.util.SortedMap; import java.awt.GridLayout; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.border.LineBorder; import javax.swing.event.ChangeListener; import javax.swing.event.ChangeEvent; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.data.time.FixedMillisecond; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesCollection; import com.model.Model; import com.model.PolyMLStatistics; /** * The panel for all the graphs */ public class ProcessGraphs extends JPanel implements ChangeListener { private MainWindow mainWindow; private Integer selectedProcess; private JLabel noProcessSelectedLabel; private ChartPanel timePanel; private ChartPanel sizePanel; private ChartPanel threadsPanel; private ChartPanel userPanel; TimeSeries gcFullGCs; TimeSeries gcPartialGCs; TimeSeries sizeAllocation; TimeSeries sizeAllocationFree; TimeSeries sizeHeap; TimeSeries sizeHeapFreeLastFullGC; TimeSeries sizeHeapFreeLastGC; TimeSeries threadsInML; TimeSeries threadsTotal; TimeSeries threadsWaitCondVar; TimeSeries threadsWaitIO; TimeSeries threadsWaitMutex; TimeSeries threadsWaitSignal; TimeSeries timeGCSystem; TimeSeries timeGCUser; TimeSeries timeNonGCSystem; TimeSeries timeNonGCUser; TimeSeries[] userCounters = new TimeSeries[8]; public ProcessGraphs(MainWindow mainWindow) { if (mainWindow == null) { throw new NullPointerException(); } this.mainWindow = mainWindow; setOpaque(true); setBorder(LineBorder.createBlackLineBorder()); // noProcessSelectedLabel noProcessSelectedLabel = new JLabel("Please select a process.", JLabel.CENTER); // data series gcFullGCs = new TimeSeries("Full GCs"); gcPartialGCs = new TimeSeries("Partial GCs"); sizeAllocation = new TimeSeries("Allocation"); sizeAllocationFree = new TimeSeries("Allocation Free"); sizeHeap = new TimeSeries("Heap"); sizeHeapFreeLastFullGC = new TimeSeries("Heap Free (Last Full GC)"); sizeHeapFreeLastGC = new TimeSeries("Heap Free (Last GC)"); threadsInML = new TimeSeries("In ML"); threadsTotal = new TimeSeries("Total"); threadsWaitCondVar = new TimeSeries("Waiting for CondVar"); threadsWaitIO = new TimeSeries("Waiting for I/O"); threadsWaitMutex = new TimeSeries("Waiting for Mutex"); threadsWaitSignal = new TimeSeries("Waiting for Signal"); timeGCSystem = new TimeSeries("GC System"); timeGCUser = new TimeSeries("GC User"); timeNonGCSystem = new TimeSeries("Non-GC System"); timeNonGCUser = new TimeSeries("Non-GC User"); for (int i = 0; i < userCounters.length; i++) { userCounters[i] = new TimeSeries("Counter " + i); } // timePanel TimeSeriesCollection timeCollection = new TimeSeriesCollection(); timeCollection.addSeries(timeNonGCUser); timeCollection.addSeries(timeNonGCSystem); timeCollection.addSeries(timeGCUser); timeCollection.addSeries(timeGCSystem); timePanel = new ChartPanel(ChartFactory.createTimeSeriesChart("Time", null, null, timeCollection, true, true, true)); ValueAxis axis = timePanel.getChart().getXYPlot().getRangeAxis(); axis.setLabelFont(axis.getTickLabelFont()); axis.setLabel("seconds"); // sizePanel TimeSeriesCollection sizeCollection = new TimeSeriesCollection(); sizeCollection.addSeries(sizeAllocation); sizeCollection.addSeries(sizeAllocationFree); sizeCollection.addSeries(sizeHeap); sizeCollection.addSeries(sizeHeapFreeLastFullGC); sizeCollection.addSeries(sizeHeapFreeLastGC); sizePanel = new ChartPanel(ChartFactory.createTimeSeriesChart("Size", null, null, sizeCollection, true, true, true)); axis = sizePanel.getChart().getXYPlot().getRangeAxis(); axis.setLabelFont(axis.getTickLabelFont()); axis.setLabel("bytes"); axis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); // threadsPanel TimeSeriesCollection threadsCollection = new TimeSeriesCollection(); threadsCollection.addSeries(threadsTotal); threadsCollection.addSeries(threadsInML); threadsCollection.addSeries(threadsWaitCondVar); threadsCollection.addSeries(threadsWaitIO); threadsCollection.addSeries(threadsWaitMutex); threadsCollection.addSeries(threadsWaitSignal); threadsCollection.addSeries(gcFullGCs); threadsCollection.addSeries(gcPartialGCs); threadsPanel = new ChartPanel(ChartFactory.createTimeSeriesChart("Threads and GC", null, null, threadsCollection, true, true, true)); axis = threadsPanel.getChart().getXYPlot().getRangeAxis(); axis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); // userPanel TimeSeriesCollection userCollection = new TimeSeriesCollection(); for (TimeSeries userCounter : userCounters) { userCollection.addSeries(userCounter); } userPanel = new ChartPanel(ChartFactory.createTimeSeriesChart("User Counters", null, null, userCollection, true, true, true)); axis = userPanel.getChart().getXYPlot().getRangeAxis(); axis.setAutoRangeMinimumSize(2.0); axis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); // initial state add(noProcessSelectedLabel); update(); mainWindow.getModel().addChangeListener(this); } private void update() { Model model = mainWindow.getModel(); Integer selectedProcessNow = model.getSelectedProcess(); if (selectedProcess != selectedProcessNow) { gcFullGCs.clear(); gcPartialGCs.clear(); sizeAllocation.clear(); sizeAllocationFree.clear(); sizeHeap.clear(); sizeHeapFreeLastFullGC.clear(); sizeHeapFreeLastGC.clear(); threadsInML.clear(); threadsTotal.clear(); threadsWaitCondVar.clear(); threadsWaitIO.clear(); threadsWaitMutex.clear(); threadsWaitSignal.clear(); timeGCSystem.clear(); timeGCUser.clear(); timeNonGCSystem.clear(); timeNonGCUser.clear(); for (TimeSeries userCounter : userCounters) { userCounter.clear(); } } if (selectedProcessNow != null) { // copy actual data from model into charts SortedMap<Long, PolyMLStatistics> processData = model.getProcessData().get(selectedProcessNow); assert (processData != null); long lastTime; int itemCount = gcFullGCs.getItemCount(); if (itemCount > 0) { lastTime = gcFullGCs.getTimePeriod(itemCount-1).getFirstMillisecond(); assert (lastTime == gcFullGCs.getTimePeriod(itemCount-1).getLastMillisecond()); lastTime++; processData = processData.tailMap(new Long(lastTime)); } for (SortedMap.Entry<Long, PolyMLStatistics> entry : processData.entrySet()) { FixedMillisecond key = new FixedMillisecond(entry.getKey().longValue()); PolyMLStatistics value = entry.getValue(); gcFullGCs.add(key, value.getGcFullGCs()); gcPartialGCs.add(key, value.getGcPartialGCs()); sizeAllocation.add(key, value.getSizeAllocation()); sizeAllocationFree.add(key, value.getSizeAllocationFree()); sizeHeap.add(key, value.getSizeHeap()); sizeHeapFreeLastFullGC.add(key, value.getSizeHeapFreeLastFullGC()); sizeHeapFreeLastGC.add(key, value.getSizeHeapFreeLastGC()); threadsInML.add(key, value.getThreadsInML()); threadsTotal.add(key, value.getThreadsTotal()); threadsWaitCondVar.add(key, value.getThreadsWaitCondVar()); threadsWaitIO.add(key, value.getThreadsWaitIO()); threadsWaitMutex.add(key, value.getThreadsWaitMutex()); threadsWaitSignal.add(key, value.getThreadsWaitSignal()); timeGCSystem.add(key, value.getTimeGCSystem()); timeGCUser.add(key, value.getTimeGCUser()); timeNonGCSystem.add(key, value.getTimeNonGCSystem()); timeNonGCUser.add(key, value.getTimeNonGCUser()); long [] valueUserCounters = value.getUserCounters(); assert (valueUserCounters.length == userCounters.length); for (int i = 0; i < userCounters.length; i++) { userCounters[i].add(key, valueUserCounters[i]); } } if (selectedProcess == null) { remove(noProcessSelectedLabel); // add chart panels setLayout(new GridLayout(4,1)); add(timePanel); add(sizePanel); add(threadsPanel); add(userPanel); validate(); } } selectedProcess = selectedProcessNow; } public void stateChanged(ChangeEvent e) { update(); } }
/*Serialization is converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Design an algorithm to serialize and deserialize a binary search tree. There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure. The encoded string should be as compact as possible. Example 1: Input: root = [2,1,3] Output: [2,1,3] Example 2: Input: root = [] Output: [] Constraints: The number of nodes in the tree is in the range [0, 104]. 0 <= Node.val <= 104 The input tree is guaranteed to be a binary search tree.*/ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Codec { // Encodes a tree to a single string. public String serialize(TreeNode root) { if(root == null) return null; Stack<TreeNode> s = new Stack<>(); s.push(root); StringBuilder sb = new StringBuilder(); while(!s.isEmpty()) { TreeNode h = s.pop(); if(h != null) { sb.append(h.val + ","); s.push(h.right); s.push(h.left); } else sb.append("#,"); } return sb.toString().substring(0, sb.length() - 1); } // Decodes your encoded data to tree. public TreeNode deserialize(String data) { if(data == null) return null; int[] t = {0}; String[] a = data.split(","); return helper(a, t); } public TreeNode helper(String[] a, int[] t) { if(a[t[0]].equals("#")) return null; TreeNode root = new TreeNode(Integer.parseInt(a[t[0]])); t[0]++; root.left = helper(a, t); t[0]++; root.right = helper(a, t); return root; } } // Your Codec object will be instantiated and called as such: // Codec ser = new Codec(); // Codec deser = new Codec(); // String tree = ser.serialize(root); // TreeNode ans = deser.deserialize(tree); // return ans;
// Generated by data binding compiler. Do not edit! package tkhub.project.kesbewa.databinding; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.widget.AppCompatImageView; import androidx.appcompat.widget.AppCompatTextView; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.constraintlayout.widget.Guideline; import androidx.core.widget.NestedScrollView; import androidx.databinding.Bindable; import androidx.databinding.DataBindingUtil; import androidx.databinding.ViewDataBinding; import androidx.recyclerview.widget.RecyclerView; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView; import com.robinhood.ticker.TickerView; import java.lang.Deprecated; import java.lang.Object; import tkhub.project.kesbewa.R; import tkhub.project.kesbewa.data.model.Products; import tkhub.project.kesbewa.viewmodels.home.HomeViewModel; public abstract class FragmentProductDetailBinding extends ViewDataBinding { @NonNull public final AppCompatTextView appCompatTextView; @NonNull public final AppCompatTextView appCompatTextView12; @NonNull public final AppCompatTextView appCompatTextView2; @NonNull public final AppCompatTextView appCompatTextView333; @NonNull public final ConstraintLayout clProImageLeft; @NonNull public final ConstraintLayout clProImageRight; @NonNull public final ConstraintLayout constraintLayout; @NonNull public final ConstraintLayout constraintLayout2; @NonNull public final ConstraintLayout constraintLayoutLoadingGuestusersave; @NonNull public final View divider3; @NonNull public final FloatingActionButton fabCart; @NonNull public final Guideline guidelineBottom; @NonNull public final AppCompatImageView imageView55; @NonNull public final ConstraintLayout imageViewCart; @NonNull public final AppCompatImageView imageviewNavigation; @NonNull public final RecyclerView recyclerViewProductImages; @NonNull public final RecyclerView recyclerViewProductLargeImages; @NonNull public final RelativeLayout rl1; @NonNull public final RelativeLayout rl2; @NonNull public final NestedScrollView scrollView; @NonNull public final AppCompatTextView textView; @NonNull public final TickerView textViewCartCount; @NonNull public final AppCompatTextView textviewProCode; @NonNull public final YouTubePlayerView youtubePlayerView; @Bindable protected Products mProduct; @Bindable protected HomeViewModel mProductDetails; protected FragmentProductDetailBinding(Object _bindingComponent, View _root, int _localFieldCount, AppCompatTextView appCompatTextView, AppCompatTextView appCompatTextView12, AppCompatTextView appCompatTextView2, AppCompatTextView appCompatTextView333, ConstraintLayout clProImageLeft, ConstraintLayout clProImageRight, ConstraintLayout constraintLayout, ConstraintLayout constraintLayout2, ConstraintLayout constraintLayoutLoadingGuestusersave, View divider3, FloatingActionButton fabCart, Guideline guidelineBottom, AppCompatImageView imageView55, ConstraintLayout imageViewCart, AppCompatImageView imageviewNavigation, RecyclerView recyclerViewProductImages, RecyclerView recyclerViewProductLargeImages, RelativeLayout rl1, RelativeLayout rl2, NestedScrollView scrollView, AppCompatTextView textView, TickerView textViewCartCount, AppCompatTextView textviewProCode, YouTubePlayerView youtubePlayerView) { super(_bindingComponent, _root, _localFieldCount); this.appCompatTextView = appCompatTextView; this.appCompatTextView12 = appCompatTextView12; this.appCompatTextView2 = appCompatTextView2; this.appCompatTextView333 = appCompatTextView333; this.clProImageLeft = clProImageLeft; this.clProImageRight = clProImageRight; this.constraintLayout = constraintLayout; this.constraintLayout2 = constraintLayout2; this.constraintLayoutLoadingGuestusersave = constraintLayoutLoadingGuestusersave; this.divider3 = divider3; this.fabCart = fabCart; this.guidelineBottom = guidelineBottom; this.imageView55 = imageView55; this.imageViewCart = imageViewCart; this.imageviewNavigation = imageviewNavigation; this.recyclerViewProductImages = recyclerViewProductImages; this.recyclerViewProductLargeImages = recyclerViewProductLargeImages; this.rl1 = rl1; this.rl2 = rl2; this.scrollView = scrollView; this.textView = textView; this.textViewCartCount = textViewCartCount; this.textviewProCode = textviewProCode; this.youtubePlayerView = youtubePlayerView; } public abstract void setProduct(@Nullable Products product); @Nullable public Products getProduct() { return mProduct; } public abstract void setProductDetails(@Nullable HomeViewModel product_details); @Nullable public HomeViewModel getProductDetails() { return mProductDetails; } @NonNull public static FragmentProductDetailBinding inflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup root, boolean attachToRoot) { return inflate(inflater, root, attachToRoot, DataBindingUtil.getDefaultComponent()); } /** * This method receives DataBindingComponent instance as type Object instead of * type DataBindingComponent to avoid causing too many compilation errors if * compilation fails for another reason. * https://issuetracker.google.com/issues/116541301 * @Deprecated Use DataBindingUtil.inflate(inflater, R.layout.fragment_product_detail, root, attachToRoot, component) */ @NonNull @Deprecated public static FragmentProductDetailBinding inflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup root, boolean attachToRoot, @Nullable Object component) { return ViewDataBinding.<FragmentProductDetailBinding>inflateInternal(inflater, R.layout.fragment_product_detail, root, attachToRoot, component); } @NonNull public static FragmentProductDetailBinding inflate(@NonNull LayoutInflater inflater) { return inflate(inflater, DataBindingUtil.getDefaultComponent()); } /** * This method receives DataBindingComponent instance as type Object instead of * type DataBindingComponent to avoid causing too many compilation errors if * compilation fails for another reason. * https://issuetracker.google.com/issues/116541301 * @Deprecated Use DataBindingUtil.inflate(inflater, R.layout.fragment_product_detail, null, false, component) */ @NonNull @Deprecated public static FragmentProductDetailBinding inflate(@NonNull LayoutInflater inflater, @Nullable Object component) { return ViewDataBinding.<FragmentProductDetailBinding>inflateInternal(inflater, R.layout.fragment_product_detail, null, false, component); } public static FragmentProductDetailBinding bind(@NonNull View view) { return bind(view, DataBindingUtil.getDefaultComponent()); } /** * This method receives DataBindingComponent instance as type Object instead of * type DataBindingComponent to avoid causing too many compilation errors if * compilation fails for another reason. * https://issuetracker.google.com/issues/116541301 * @Deprecated Use DataBindingUtil.bind(view, component) */ @Deprecated public static FragmentProductDetailBinding bind(@NonNull View view, @Nullable Object component) { return (FragmentProductDetailBinding)bind(component, view, R.layout.fragment_product_detail); } }
package leetcode_easy; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Question_118 { public List<List<Integer>> generate(int numRows) { List<List<Integer>> result = new ArrayList<>(); Integer[] upperLevel = null; for (int i = 1; i <= numRows; i++) { Integer[] layer = null; if (upperLevel == null) { layer = new Integer[]{1}; upperLevel = layer; } else { layer = new Integer[i]; for (int j = 0; j < i; j++) { if (j == 0 || j == i -1) { layer[j] = 1; } else { layer[j] = upperLevel[j] + upperLevel[j-1]; } } upperLevel = layer; } result.add(Arrays.asList(upperLevel)); } return result; } public void solve() { List<List<Integer>> result = generate(5); for (List<Integer> array : result) { System.out.println(array); } } }
package com.jiuzhe.app.hotel.service.impl; import com.jiuzhe.app.hotel.dao.CountDao; import com.jiuzhe.app.hotel.service.CountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Map; /** * @Description:统计功能 * @author:郑鹏宇 * @date: 2018/5/22 */ @Service public class CountServiceImpl implements CountService { @Autowired CountDao dao; @Override public Map<String, String> getIndexCount(String merchantId, String storeId) { Map<String, String> map = dao.getOrderNumIncome(merchantId, storeId); Map<String, String> map1 = dao.getDirtyNum(merchantId, storeId); map.put("dirtyNum", map1.get("dirtyNum")); return map; } @Override public Map getManageCountInfo(String storeId) { Map map= dao.getManageCountInfo(storeId); Map mapDirty = dao.getDirtyRoom(storeId); System.out.println(mapDirty +"========================"); map.putAll(mapDirty); return map; } }
package com.yixin.kepler.common.enums; /** * 资产状态枚举 * Package : com.yixin.kepler.common.enums * * @author YixinCapital -- wangwenlong * 2018年7月10日 下午3:26:39 * */ public enum AssetStateEnum { INIT(0), //初始化 SUCCESS(1), //成功 FAILD(2),//失败 DOING(3),//进行中 REJECT(4),//驳回 ACCEPT_FAILD(5);//受理失败 private Integer state; private AssetStateEnum(Integer state){ this.state = state; } public Integer getState() { return state; } /** * 获取当前状态的中文名称 * @param state 状态 * @return 对应的名称 * @author YixinCapital -- chenjiacheng * 2018/7/19 17:20 */ public static String getNameByState(Integer state) { if (state == null) { return null; } if (0 == state) { return "初始化中"; } else if (1 == state) { return "成功"; } else if (2 == state) { return "失败"; } else if (3 == state) { return "进行中"; } else if (4 == state) { return "驳回"; } else { return "未知"; } } }
package com.zhowin.miyou.mine.activity; import android.app.Dialog; import android.view.View; import com.zhowin.base_library.callback.OnCenterHitMessageListener; import com.zhowin.base_library.model.UserInfo; import com.zhowin.base_library.utils.ActivityManager; import com.zhowin.base_library.utils.AppUtils; import com.zhowin.base_library.utils.CacheDataUtils; import com.zhowin.base_library.view.CenterHitMessageDialog; import com.zhowin.miyou.R; import com.zhowin.miyou.base.BaseBindActivity; import com.zhowin.miyou.databinding.ActivitySettingBinding; import com.zhowin.miyou.login.activity.LoginActivity; import com.zhowin.miyou.main.activity.MainActivity; import com.zhowin.miyou.recommend.callback.OnHitCenterClickListener; import com.zhowin.miyou.recommend.dialog.HitCenterDialog; import io.rong.imkit.RongIM; /** * 设置 */ public class SettingActivity extends BaseBindActivity<ActivitySettingBinding> { @Override public int getLayoutId() { return R.layout.activity_setting; } @Override public void initView() { setOnClick(R.id.clAccountAndSecurity, R.id.clUserAgreement, R.id.clCommunityNorms, R.id.clContactUs, R.id.clBlackList, R.id.clPrivacySetting, R.id.clCheckVersion, R.id.clClearCache, R.id.clAboutUs, R.id.tvOutLogin ); } @Override public void initData() { String cacheValue = CacheDataUtils.getTotalCacheSize(mContext); mBinding.tvCacheText.setText(cacheValue); mBinding.tvAppVersion.setText("V" + AppUtils.getVersionName(mContext)); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.clAccountAndSecurity: startActivity(AccountSecurityActivity.class); break; case R.id.clUserAgreement: break; case R.id.clCommunityNorms: break; case R.id.clContactUs: startActivity(ContactUsActivity.class); break; case R.id.clBlackList: startActivity(BlackListActivity.class); break; case R.id.clPrivacySetting: startActivity(PrivacySettingActivity.class); break; case R.id.clCheckVersion: break; case R.id.clClearCache: showClearCacheDialog(); break; case R.id.clAboutUs: break; case R.id.tvOutLogin: showOutLoginDialog(); break; } } private void showClearCacheDialog() { HitCenterDialog hitCenterDialog = new HitCenterDialog(mContext); hitCenterDialog.setDialogTitle("确定要清除缓存吗?"); hitCenterDialog.show(); hitCenterDialog.setOnHitCenterClickListener(new OnHitCenterClickListener() { @Override public void onCancelClick() { } @Override public void onDetermineClick() { CacheDataUtils.clearAllCache(mContext); mBinding.tvCacheText.setText("0.0KB"); } }); } private void showOutLoginDialog() { String title = "确定要退出吗?"; new CenterHitMessageDialog(mContext, title, new OnCenterHitMessageListener() { @Override public void onNegativeClick(Dialog dialog) { } @Override public void onPositiveClick(Dialog dialog) { UserInfo.setUserInfo(new UserInfo()); ActivityManager.getAppInstance().finishActivity(MainActivity.class); RongIM.getInstance().disconnect(); startActivity(LoginActivity.class); // ActivityManager.getAppInstance().finishActivity(); } }).show(); } }
package hu.bme.aut.exhibitionexplorer.fragment; import android.os.AsyncTask; import android.os.Bundle; import android.provider.ContactsContract; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.View; import android.view.ViewGroup; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.HashMap; import hu.bme.aut.exhibitionexplorer.R; import hu.bme.aut.exhibitionexplorer.adapter.CatalogAdapter; import hu.bme.aut.exhibitionexplorer.data.Artifact; import hu.bme.aut.exhibitionexplorer.data.Exhibition; import hu.bme.aut.exhibitionexplorer.interfaces.OnArtifactItemClickListener; /** * Created by Adam on 2016. 10. 29.. */ public class CatalogFragment extends Fragment { protected CatalogAdapter adapter; protected RecyclerView recyclerView; public static final String TAG = "CatalogFragment"; public static final String ExhibitionTag = "ExhibitionID"; FirebaseDatabase database; DatabaseReference mArtifactsReference; private Exhibition exhibition; private HashMap<String, Boolean> artifactsHere; OnArtifactItemClickListener onItemClickListener; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); FragmentActivity activity = getActivity(); if (activity instanceof OnArtifactItemClickListener) { onItemClickListener = (OnArtifactItemClickListener) activity; } else { throw new RuntimeException("Activity(" +activity.toString() +") must implement OnArtifactItemClickListener interface"); } } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_catalog, container, false); database = FirebaseDatabase.getInstance(); mArtifactsReference = database.getReference("artifacts"); exhibition = getArguments().getParcelable(Exhibition.KEY_EXHIBITION_PARCELABLE); artifactsHere = exhibition.getArtifactsHere(); setHasOptionsMenu(true); mArtifactsReference.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { asyncTask.execute(dataSnapshot); } @Override public void onCancelled(DatabaseError databaseError) { } }); recyclerView = (RecyclerView) rootView.findViewById(R.id.CatalogRecyclerView); recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); adapter = new CatalogAdapter(getContext(), onItemClickListener); recyclerView.setAdapter(adapter); return rootView; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.explorer_with_no_exhibition_menu, menu); super.onCreateOptionsMenu(menu, inflater); } final AsyncTask<DataSnapshot, Void, CatalogAdapter> asyncTask = new AsyncTask<DataSnapshot, Void, CatalogAdapter>() { @Override protected CatalogAdapter doInBackground(DataSnapshot... params) { if (artifactsHere != null){ for (DataSnapshot datasnapshot: params[0].getChildren()){ if(artifactsHere.containsKey(datasnapshot.getKey())){ Artifact artifact = datasnapshot.getValue(Artifact.class); artifact.setUuID(datasnapshot.getKey()); adapter.addArtifact(artifact); } } } return adapter; } @Override protected void onPostExecute(CatalogAdapter catalogAdapter) { catalogAdapter.notifyDataSetChanged(); } }; }
package com.example.mefirst; import java.util.ArrayList; import java.util.Iterator; import android.graphics.Color; public class ChildManager { private static ChildManager ChildManager = null; private ArrayList<Child> Children = null; private ChildManager() { Children = new ArrayList<Child>(); } public static ChildManager Get() { if (ChildManager == null) { ChildManager = new ChildManager(); ChildManager.LoadChildren(); } return ChildManager; } private void LoadChildren() { Children = new ArrayList<Child>(); Child newChild; Color c = new Color(); newChild = new Child("Emily"); newChild.setBColour(c.rgb(0, 200, 0)); Children.add(newChild); newChild = new Child("William"); newChild.setBColour(c.rgb(0, 0, 200)); Children.add(newChild); newChild = new Child("Henry"); newChild.setBColour(c.rgb(0, 128, 255)); Children.add(newChild); newChild = new Child("Katie"); newChild.setBColour(c.rgb(230, 230, 0)); Children.add(newChild); newChild = new Child("Lucy"); newChild.setBColour(c.rgb(0, 128, 0)); Children.add(newChild); newChild = new Child("Daisy"); newChild.setBColour(c.rgb(0, 200, 255)); Children.add(newChild); newChild = new Child("Daddy"); newChild.setBColour(c.rgb(255, 0, 0)); Children.add(newChild); } public Child FindChild(String name) { for (Child child : Children) { if (child.getName().equals(name)) { return child; } } return null; } public Iterator<Child> GetChildIterator() { return Children.iterator(); } }
package com.tencent.mm.plugin.soter.b; import com.tencent.d.b.e.b; import com.tencent.d.b.e.e; import com.tencent.d.b.e.e.a; import com.tencent.mm.ab.l; import com.tencent.mm.kernel.g; import com.tencent.mm.network.k; import com.tencent.mm.network.q; import com.tencent.mm.sdk.platformtools.x; public final class f extends l implements e, k { private q dJM; private com.tencent.mm.ab.e diJ; private b<e.b> jgZ = null; public final /* synthetic */ void bx(Object obj) { a aVar = (a) obj; this.dJM = new b(); c.a aVar2 = (c.a) this.dJM.KV(); aVar2.onv.srU = aVar.vmd; aVar2.onv.srV = aVar.vmc; } protected final int Cc() { return 3; } protected final int a(q qVar) { return l.b.dJm; } public final int getType() { return 627; } public final int a(com.tencent.mm.network.e eVar, com.tencent.mm.ab.e eVar2) { this.diJ = eVar2; return a(eVar, this.dJM, this); } public final void a(int i, int i2, int i3, String str, q qVar, byte[] bArr) { x.i("MicroMsg.NetSceneUploadSoterASKRsa", "alvinluo errType: %d, errCode: %d, errMsg: %s", new Object[]{Integer.valueOf(i2), Integer.valueOf(i3), str}); if (this.diJ != null) { this.diJ.a(i2, i3, str, this); } if (i2 == 0 && i3 == 0) { x.i("MicroMsg.NetSceneUploadSoterASKRsa", "netscene upload soter ask rsa successfully"); if (this.jgZ != null) { this.jgZ.cG(new e.b(true)); return; } return; } x.e("MicroMsg.NetSceneUploadSoterASKRsa", "netscene upload soter ask rsa failed"); if (this.jgZ != null) { this.jgZ.cG(new e.b(false)); } } public final void execute() { x.v("MicroMsg.NetSceneUploadSoterASKRsa", "alvinluo NetSceneUploadSoterASKRsa doScene"); g.DF().a(this, 0); } public final void a(b<e.b> bVar) { this.jgZ = bVar; } }
/** * Copyright (c) 2016, 指端科技. */ package com.rofour.baseball.dao.manager.mapper; import java.util.List; import java.util.Map; import javax.inject.Named; import com.rofour.baseball.controller.model.manager.RoleInfo; import com.rofour.baseball.dao.manager.bean.RoleBean; /** * @ClassName: RoleMapper * @Description: 角色管理操作接口 * @author WW * @date 2016年3月26日 下午1:34:48 */ @Named("roleMapper") public interface RoleMapper { /** * @Description: 新增角色 * @param roleInfo * @return int **/ int insert(RoleInfo roleInfo); /** * @Description: 按主键ID删除角色 * @param roleId * @return 删除的数量 **/ int deleteByPrimaryKey(Long roleId); /** * @Description: 修改角色 * @param record * @return 更新的数量 **/ int updateByPrimaryKey(RoleInfo record); /** * @Description: 按主键ID查找角色 * @param roleId * @return RoleBean **/ RoleBean selectByPrimaryKey(Long roleId); /** * @Description: 查看所有角色列表 * @param roleInfo TODO * @return List<RoleBean> **/ List<RoleBean> selectAllRole(RoleInfo roleInfo); /** * @Description: 查看所有角色列表 * @param roleInfo TODO * @return List<RoleBean> **/ List<RoleBean> selectAllRoleSelect(); /** * @Description: 返回已存在的roleName条数,理论上是唯一 * @param map 条件 * @return 重复的数量 **/ int ifNameExist(Map<String, Object> map); List<RoleBean> selectAllRoleByUserName(String userName); Integer getTotal(RoleInfo roleInfo); }
package com.company.bank.controllers; import java.io.*; import java.util.ArrayList; import java.util.List; public class FileManager { private static FileManager instance; private FileManager() { } public static FileManager getInstance() { if (instance == null) { instance = new FileManager(); } return instance; } public void removeFile(String path) { new File(path).delete(); } public boolean isFileExist(String path) { File file = new File(path); return file.exists() && file.isFile(); } public void openFile(String path) throws IOException, RuntimeException { new File(path).createNewFile(); } public void saveToFile(String path, String contents) throws IOException, RuntimeException { try { FileWriter writer = new FileWriter(path, true); PrintWriter printWriter = new PrintWriter(writer); printWriter.write(contents + "\r\n"); printWriter.close(); } catch (IOException ex) { throw ex; } } public List<String> readFromFile(String path) throws IOException, RuntimeException { List<String> content = new ArrayList<>(); FileReader reader = new FileReader(path); BufferedReader bufferedReader = new BufferedReader(reader); String line; while ((line = bufferedReader.readLine()) != null) { content.add(line); } bufferedReader.close(); return content; } }
package com.atguigu.gmall.pms.service.impl; import com.atguigu.gmall.pms.dao.AttrAttrgroupRelationDao; import com.atguigu.gmall.pms.dao.AttrDao; import com.atguigu.gmall.pms.dao.ProductAttrValueDao; import com.atguigu.gmall.pms.entity.AttrAttrgroupRelationEntity; import com.atguigu.gmall.pms.entity.AttrEntity; import com.atguigu.gmall.pms.entity.ProductAttrValueEntity; import com.atguigu.gmall.pms.vo.AttrGroupVO; import com.atguigu.gmall.pms.vo.ItemGroupVO; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.stream.Collectors; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.atguigu.core.bean.PageVo; import com.atguigu.core.bean.Query; import com.atguigu.core.bean.QueryCondition; import com.atguigu.gmall.pms.dao.AttrGroupDao; import com.atguigu.gmall.pms.entity.AttrGroupEntity; import com.atguigu.gmall.pms.service.AttrGroupService; import org.springframework.util.CollectionUtils; @Service("attrGroupService") public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService { @Autowired private AttrGroupDao attrGroupDao; @Autowired private AttrDao attrDao; @Autowired private AttrAttrgroupRelationDao attrAttrgroupRelationDao; @Autowired private ProductAttrValueDao productAttrValueDao; @Override public PageVo queryPage(QueryCondition params) { IPage<AttrGroupEntity> page = this.page( new Query<AttrGroupEntity>().getPage(params), new QueryWrapper<AttrGroupEntity>() ); return new PageVo(page); } /** * 查询三级分类的业务方法 * * @param catid * @param condition * @return */ @Override public PageVo queryByCidPage(Long catid, QueryCondition condition) { /** * 业务逻辑说明 * IPage 自己封装的Ipage对象 (以前是这样 QueryWrapper<AddressEntity> queryWrapper = new QueryWrapper();) * 第一个参数 是查询分页的条件,第二参数通过分类id查询 */ IPage<AttrGroupEntity> pageVo = this.page( new Query<AttrGroupEntity>().getPage(condition), new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catid)); //返回的是自己封装的PageVo工具 把pageVo拷贝给PageVo return new PageVo(pageVo); } /** * 查询分组的下面的规格参数 * 设计到了 attrAttrgroupRelationDao * arrtDao、attrGroup * * @param gid * @return */ @Override public AttrGroupVO queryById(Long gid) { // 创建自定义的分组。 AttrGroupVO attrGroupVO = new AttrGroupVO(); //先查询出分组 通过分组attr_group_id (gid)查询出分组 AttrGroupEntity attrGroupEntity = this.attrGroupDao.selectById(gid); //然后把查询到的结果拷贝给AttrGroup BeanUtils.copyProperties(attrGroupEntity, attrGroupVO); //查询分组下的关联关系 List<AttrAttrgroupRelationEntity> relations = this.attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", gid)); //判断关联关系是否为空,如果为空,直接返回 if (CollectionUtils.isEmpty(relations)) { return attrGroupVO; } attrGroupVO.setRelations(relations); //收集分组下的所有规格id 分组表和属性表 有个中间表关联的 //查询中间获得规格表(属性)的attrId List<Long> attrIds = relations.stream().map(relation -> relation.getAttrId() ).collect(Collectors.toList() ); //通过中间得到属性表的后,查询出关联的数据 //查询分组下所有规格(属性)的参数,批量查询 List<AttrEntity> attrEntities = attrDao.selectBatchIds(attrIds); //attrGroupVO 然后把查询的结果设置给AttrGroupVO attrGroupVO.setAttrEntities(attrEntities); return attrGroupVO; } //查询分类下的分组及其规格参数 @Override public List<AttrGroupVO> queryByCid(Long catId) { //通过分类id查询所有分组 List<AttrGroupEntity> attrGroupEntities = this.list(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catId)); //在通过分组查出分组下的每一组的规格参数 //利用stream流的 map方法把一个list集合转换成 List<AttrGroupVO> attrGroupVOs = attrGroupEntities.stream().map(attrGroupEntity -> { return this.queryById(attrGroupEntity.getAttrGroupId()); }).collect(Collectors.toList()); return attrGroupVOs; } @Override public List<ItemGroupVO> queryItemGroupsBySpuIdAndCid(Long spuId, Long cid) { //先根据cid查询分组 List<AttrGroupEntity> attrGroupEntities = this.list(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", cid)); if (CollectionUtils.isEmpty(attrGroupEntities)) { return null; } //2遍历每个组下attr return attrGroupEntities.stream().map(group -> { ItemGroupVO itemGroupVO = new ItemGroupVO(); itemGroupVO.setGroupId(group.getAttrGroupId()); itemGroupVO.setGroupName(group.getAttrGroupName()); //通过分组的id查询中间表的信息 List<AttrAttrgroupRelationEntity> relationEntities = this.attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", group.getAttrGroupId())); //判断是否为空中间的数据是否为null if (!CollectionUtils.isEmpty(relationEntities)) { //通过中间表获取属性的attrId List<Long> attIds = relationEntities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList()); //根据获取的属性attrId 和spuId 查询规格参数对应的值 List<ProductAttrValueEntity> productAttrValueEntities = this.productAttrValueDao.selectList(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId).in("attr_id", attIds)); itemGroupVO.setBaseAttrValues(productAttrValueEntities); } return itemGroupVO; }).collect(Collectors.toList()); } }
/** * OpenKM, Open Document Management System (http://www.openkm.com) * Copyright (c) 2006-2015 Paco Avila & Josep Llort * * No bytes were intentionally harmed during the development of this application. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.openkm.frontend.client.widget.properties; import java.util.HashSet; import java.util.Set; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Anchor; import com.google.gwt.user.client.ui.FlexTable; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HTMLTable.CellFormatter; import com.google.gwt.user.client.ui.HasAlignment; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Widget; import com.openkm.frontend.client.Main; import com.openkm.frontend.client.bean.GWTDocument; import com.openkm.frontend.client.bean.GWTFolder; import com.openkm.frontend.client.bean.GWTMail; import com.openkm.frontend.client.extension.event.HasDocumentEvent; import com.openkm.frontend.client.extension.event.HasFolderEvent; import com.openkm.frontend.client.extension.event.HasMailEvent; import com.openkm.frontend.client.service.OKMPropertyService; import com.openkm.frontend.client.service.OKMPropertyServiceAsync; import com.openkm.frontend.client.util.CommonUI; import com.openkm.frontend.client.util.OKMBundleResources; import com.openkm.frontend.client.util.Util; import com.openkm.frontend.client.widget.ConfirmPopup; /** * CategoryManager * * @author jllort * */ public class CategoryManager { private final OKMPropertyServiceAsync propertyService = (OKMPropertyServiceAsync) GWT.create(OKMPropertyService.class); public static final int ORIGIN_FOLDER = 1; public static final int ORIGIN_DOCUMENT = 2; public static final int ORIGIN_MAIL = 3; private Image categoriesImage; private HTML categoriesText; private FlexTable tableSubscribedCategories; private HorizontalPanel hPanelCategories; private boolean remove; private Set<GWTFolder> categories = new HashSet<GWTFolder>(); private String path = ""; private Object object; private int origin; private boolean removeCategoryEnabled = false; /** * CategoryManager */ public CategoryManager(int origin) { this.origin = origin; tableSubscribedCategories = new FlexTable(); hPanelCategories = new HorizontalPanel(); categoriesText = new HTML("<b>"+Main.i18n("document.categories")+"</b>"); categoriesImage = new Image(OKMBundleResources.INSTANCE.tableKeyIcon()); categoriesImage.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { Main.get().mainPanel.desktop.navigator.categoriesTree.categoriesSelectPopup.show(); } }); hPanelCategories.add(categoriesText); hPanelCategories.add(new HTML("&nbsp;")); hPanelCategories.add(categoriesImage); hPanelCategories.setCellVerticalAlignment(categoriesText, HasAlignment.ALIGN_MIDDLE); setRowWordWarp(0, 0,true, tableSubscribedCategories); tableSubscribedCategories.setStyleName("okm-DisableSelect"); categoriesImage.addStyleName("okm-Hyperlink"); categoriesImage.setVisible(false); } /** * setObject * * @param object * @param remove */ public void setObject(Object object, boolean remove) { this.object = object; this.remove = remove; categories = new HashSet<GWTFolder>(); if (object instanceof GWTDocument) { categories = ((GWTDocument) object).getCategories(); path = ((GWTDocument) object).getPath(); } else if (object instanceof GWTFolder) { categories = ((GWTFolder) object).getCategories(); path = ((GWTFolder) object).getPath(); } else if (object instanceof GWTMail) { categories = ((GWTMail) object).getCategories(); path = ((GWTMail) object).getPath(); } } /** * getPanelCategories * * @return */ public Widget getPanelCategories() { return hPanelCategories; } /** * getSubscribedCategoriesTable * * @return */ public FlexTable getSubscribedCategoriesTable() { return tableSubscribedCategories; } /** * removeAllRows */ public void removeAllRows() { while(tableSubscribedCategories.getRowCount()>0) { tableSubscribedCategories.removeRow(0); } } /** * setVisible * * @param visible */ public void setVisible(boolean visible) { categoriesImage.setVisible(visible); } /** * drawAll */ public void drawAll() { for (GWTFolder category : categories) { drawCategory(category, remove); } } /** * drawCategory * * @param category */ private void drawCategory(final GWTFolder category, boolean remove) { int row = tableSubscribedCategories.getRowCount(); Anchor anchor = new Anchor(); // Looks if must change icon on parent if now has no childs and properties with user security atention String path = category.getPath().substring(16); // Removes /okm:categories if (category.isHasChildren()) { anchor.setHTML(Util.imageItemHTML("img/menuitem_childs.gif", path, "top")); } else { anchor.setHTML(Util.imageItemHTML("img/menuitem_empty.gif", path, "top")); } anchor.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent arg0) { CommonUI.openPath(category.getPath(), null); } }); anchor.setStyleName("okm-KeyMap-ImageHover"); Image delete = new Image(OKMBundleResources.INSTANCE.deleteIcon()); delete.setStyleName("okm-KeyMap-ImageHover"); delete.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { switch (origin) { case ORIGIN_FOLDER: Main.get().confirmPopup.setConfirm(ConfirmPopup.CONFIRM_DELETE_CATEGORY_FOLDER); break; case ORIGIN_DOCUMENT: Main.get().confirmPopup.setConfirm(ConfirmPopup.CONFIRM_DELETE_CATEGORY_DOCUMENT); break; case ORIGIN_MAIL: Main.get().confirmPopup.setConfirm(ConfirmPopup.CONFIRM_DELETE_CATEGORY_MAIL); break; } CategoryToRemove ctr = new CategoryToRemove(category, tableSubscribedCategories.getCellForEvent(event).getRowIndex()); Main.get().confirmPopup.setValue(ctr); Main.get().confirmPopup.show(); } }); tableSubscribedCategories.setWidget(row, 0, anchor); if (remove && removeCategoryEnabled) { tableSubscribedCategories.setWidget(row, 1, delete); } else { tableSubscribedCategories.setWidget(row, 1, new HTML("")); } tableSubscribedCategories.setHTML(row, 2, category.getUuid()); tableSubscribedCategories.getCellFormatter().setVisible(row, 2, false); setRowWordWarp(row, 1, true, tableSubscribedCategories); } /** * Callback addCategory document */ final AsyncCallback<Object> callbackAddCategory = new AsyncCallback<Object>() { public void onSuccess(Object result) { Main.get().mainPanel.desktop.browser.tabMultiple.status.unsetCategories(); if (object instanceof GWTDocument) { Main.get().mainPanel.desktop.browser.tabMultiple.tabDocument.fireEvent(HasDocumentEvent.CATEGORY_ADDED); } else if (object instanceof GWTFolder) { Main.get().mainPanel.desktop.browser.tabMultiple.tabFolder.fireEvent(HasFolderEvent.CATEGORY_ADDED); } else if (object instanceof GWTMail) { Main.get().mainPanel.desktop.browser.tabMultiple.tabMail.fireEvent(HasMailEvent.CATEGORY_ADDED); } } public void onFailure(Throwable caught) { Main.get().mainPanel.desktop.browser.tabMultiple.status.unsetCategories(); Main.get().showError("AddCategory", caught); } }; /** * addCategory document */ public void addCategory(GWTFolder category) { if (!existCategory(category.getUuid())) { categories.add(category); drawCategory(category,remove); Main.get().mainPanel.desktop.browser.tabMultiple.status.setCategories(); propertyService.addCategory(path, category.getUuid(), callbackAddCategory); } } /** * removeCategory document */ public void removeCategory(final String UUID) { Main.get().mainPanel.desktop.browser.tabMultiple.status.setCategories(); propertyService.removeCategory(path, UUID, new AsyncCallback<Object>() { public void onSuccess(Object result) { Main.get().mainPanel.desktop.browser.tabMultiple.status.unsetCategories(); if (object instanceof GWTDocument) { Main.get().mainPanel.desktop.browser.tabMultiple.tabDocument.fireEvent(HasDocumentEvent.CATEGORY_REMOVED); } else if (object instanceof GWTFolder) { Main.get().mainPanel.desktop.browser.tabMultiple.tabFolder.fireEvent(HasFolderEvent.CATEGORY_REMOVED); } else if (object instanceof GWTMail) { Main.get().mainPanel.desktop.browser.tabMultiple.tabMail.fireEvent(HasMailEvent.CATEGORY_REMOVED); } // removing row for (int row=0; row<tableSubscribedCategories.getRowCount();row++) { if (tableSubscribedCategories.getHTML(row, 2).equals(UUID)) { tableSubscribedCategories.removeRow(row); break; } } // removing category for (GWTFolder category : categories) { if (category.getUuid().equals(UUID)) { categories.remove(category); break; } } } public void onFailure(Throwable caught) { Main.get().mainPanel.desktop.browser.tabMultiple.status.unsetCategories(); Main.get().showError("RemoveCategory", caught); } }); } /** * removeCategory * * @param category */ public void removeCategory(CategoryToRemove obj) { categories.remove(obj.getCategory()); removeCategory(obj.getCategory().getUuid()); tableSubscribedCategories.removeRow(obj.getRow()); } /** * existCategory * * @param Uuid * @return */ private boolean existCategory(String Uuid) { boolean found = false; for (GWTFolder category : categories) { if (category.getUuid().equals(Uuid)) { found = true; break; } } return found; } /** * Set the WordWarp for all the row cells * * @param row The row cell * @param columns Number of row columns * @param warp * @param table The table to change word wrap */ private void setRowWordWarp(int row, int columns, boolean warp, FlexTable table) { CellFormatter cellFormatter = table.getCellFormatter(); for (int i=0; i<columns; i++) { cellFormatter.setWordWrap(row, i, warp); } } /** * Lang refresh */ public void langRefresh() { categoriesText.setHTML("<b>"+Main.i18n("document.categories")+"</b>"); } /** * showAddCategory */ public void showAddCategory() { categoriesImage.setVisible(true); } /** * showRemoveCategory */ public void showRemoveCategory() { removeCategoryEnabled = true; } /** * CategoryToRemove * * @author jllort * */ public class CategoryToRemove { private GWTFolder category; private int row; public CategoryToRemove(GWTFolder category, int row) { this.category = category; this.row = row; } public GWTFolder getCategory() { return category; } public void setCategory(GWTFolder category) { this.category = category; } public int getRow() { return row; } public void setRow(int row) { this.row = row; } } }
package cpracticeF; public class a5 { public static void main(String[] args) { // 객체 생성 Artist kim = new Artist("뮤지션 김씨"); Architect lee = new Architect("건축가 이씨"); Developer park = new Developer("개발자 박씨"); Lawyer choi = new Lawyer("변호사 최씨"); // 그룹화: 인터페이스 기준 Friend[] friends = { kim, lee, park, choi }; for(Friend f : friends) { f.dearFriend(); } } } /* 1. 해당 인터페이스를 완성하시오. */ interface Friend { void dearFriend(); } /* 2. 아래 모든 클래스를 완성하시오. */ class Artist implements Friend { String name; public Artist(String n) { // TODO Auto-generated constructor stub name = n; } @Override public void dearFriend() { // TODO Auto-generated method stub System.out.printf("%s -> 칭구 아이가!\n", name); } } class Architect implements Friend { String name; public Architect(String n) { // TODO Auto-generated constructor stub name = n; } @Override public void dearFriend() { // TODO Auto-generated method stub System.out.printf("%s -> 칭구 아이가!\n", name); } } class Developer implements Friend { String name; public Developer(String n) { // TODO Auto-generated constructor stub name = n; } @Override public void dearFriend() { // TODO Auto-generated method stub System.out.printf("%s -> 칭구 아이가!\n", name); } } class Lawyer implements Friend { String name; public Lawyer(String n) { // TODO Auto-generated constructor stub name = n; } @Override public void dearFriend() { // TODO Auto-generated method stub System.out.printf("%s -> 칭구 아이가!\n", name); } }
package app; import controller.ListaTelefonicaController; public class ListaTelefonicaArvoreBinaria { public static void main(String[] args) { ListaTelefonicaController objController = new ListaTelefonicaController(); objController.start(); } }
package eg.edu.alexu.csd.oop.draw; import java.awt.Color; import java.awt.Graphics; import java.awt.Point; import java.util.Map; public class AbstractShape implements Shape { @Override public void setPosition(Point position) { // TODO Auto-generated method stub } @Override public Point getPosition() { // TODO Auto-generated method stub return null; } @Override public void setProperties(Map<String, Double> properties) { // TODO Auto-generated method stub } @Override public Map<String, Double> getProperties() { // TODO Auto-generated method stub return null; } @Override public void setColor(Color color) { // TODO Auto-generated method stub } @Override public Color getColor() { // TODO Auto-generated method stub return null; } @Override public void setFillColor(Color color) { // TODO Auto-generated method stub } @Override public Color getFillColor() { // TODO Auto-generated method stub return null; } @Override public void draw(Graphics canvas) { // TODO Auto-generated method stub } public Object clone() throws CloneNotSupportedException { // TODO Auto-generated method stub return null; } }
package com.claycorp.nexstore.api.entity; public class Price { private String currency; private Double amount; public Price() { } public String getCurrency() { return currency; } public Price setCurrency(String currency) { this.currency = currency; return this; } public Double getAmount() { return amount; } public Price setAmount(Double amount) { this.amount = amount; return this; } @Override public String toString() { return "Price [currency=" + currency + ", amount=" + amount + "]"; } }
package Utils; import android.location.Address; import android.location.Geocoder; import java.io.IOException; import AsyncTask.AddressAst; /** * Created by lequan on 5/18/2016. */ public class AddressUtils { public static String getAddress(Geocoder geocoder, double latitude, double longitude) { String currentAddress = ""; try { Address address = geocoder.getFromLocation(latitude, longitude, 1).get(0); for (int i = 0; i < address.getMaxAddressLineIndex() - 1; i++) { currentAddress += address.getAddressLine(i) + ", "; } currentAddress += address.getAddressLine(address.getMaxAddressLineIndex() - 1); } catch (IOException e) { e.printStackTrace(); } return currentAddress; } }
package edu.progmatic.messageapp.filter; import org.springframework.stereotype.Component; import javax.servlet.*; import java.io.IOException; import java.util.Arrays; @Component public class FilterConfig implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { servletRequest.getParameterMap() .forEach((k, v) -> System.out.println(k + ": " + Arrays.toString(v))); filterChain.doFilter(servletRequest, servletResponse); } }
/* * Copyright 2017 University of Michigan * * 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 edu.umich.verdict.dbms; import java.util.List; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import com.google.common.base.Joiner; import edu.umich.verdict.VerdictContext; import edu.umich.verdict.datatypes.SampleParam; import edu.umich.verdict.datatypes.TableUniqueName; import edu.umich.verdict.exceptions.VerdictException; import edu.umich.verdict.util.StringManipulations; public class DbmsHive extends DbmsJDBC { public DbmsHive(VerdictContext vc, String dbName, String host, String port, String schema, String user, String password, String jdbcClassName) throws VerdictException { super(vc, dbName, host, port, schema, user, password, jdbcClassName); } @Override public void insertEntry(TableUniqueName tableName, List<Object> values) throws VerdictException { StringBuilder sql = new StringBuilder(1000); sql.append(String.format("insert into table %s select * from (select ", tableName)); String with = "'"; sql.append(Joiner.on(", ").join(StringManipulations.quoteString(values, with))); sql.append(") s"); executeUpdate(sql.toString()); } @Override public String getQuoteString() { return "`"; } @Override protected String modOfRand(int mod) { return String.format("abs(rand(unix_timestamp())) %% %d", mod); } @Override public String modOfHash(String col, int mod) { return String.format("crc32(cast(%s%s%s as string)) %% %d", getQuoteString(), col, getQuoteString(), mod); } @Override public String modOfHash(List<String> columns, int mod) { String concatStr = ""; for (int i = 0; i < columns.size(); ++i) { String col = columns.get(i); String castStr = String.format("cast(%s%s%s as string)", getQuoteString(), col, getQuoteString()); if (i < columns.size() - 1) { castStr += ","; } concatStr += castStr; } return String.format("crc32(concat_ws('%s', %s)) %% %d", HASH_DELIM, concatStr, mod); } @Override protected String randomNumberExpression(SampleParam param) { String expr = "rand(unix_timestamp())"; return expr; } @Override protected String randomPartitionColumn() { int pcount = partitionCount(); return String.format("pmod(round(rand(unix_timestamp())*%d), %d) AS %s", pcount, pcount, partitionColumnName()); } @Override public Dataset<Row> getDataset() { // TODO Auto-generated method stub return null; } }
package ecutb.fishingtrip.service; import ecutb.fishingtrip.data.AppUserRepository; import ecutb.fishingtrip.data.FishingTripRepository; import ecutb.fishingtrip.dto.CreateFishingTrip; import ecutb.fishingtrip.entity.AppUser; import ecutb.fishingtrip.entity.FishingTrip; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.List; import java.util.Optional; import java.util.Set; @Service public class FishingTripServiceImpl implements FishingTripService { private FishingTripRepository fishingTripRepository; private AppUserRepository appUserRepository; @Autowired public FishingTripServiceImpl(FishingTripRepository fishingTripRepository, AppUserRepository appUserRepository) { this.fishingTripRepository = fishingTripRepository; this.appUserRepository = appUserRepository; } @Override public Set<FishingTrip> findAll() { return fishingTripRepository.findAll(); } @Override public Optional<FishingTrip> findByFishingTripId(String id) { return fishingTripRepository.findByFishingTripId(id); } @Override @Transactional(rollbackFor = RuntimeException.class) public FishingTrip newFishingTrip(CreateFishingTrip form, String userName) { AppUser loggedInUser = appUserRepository.findByUserNameIgnoreCase(userName).orElseThrow(() -> new UsernameNotFoundException("Requested user could not be found")); FishingTrip newFishingTrip = new FishingTrip(form.getFishingMethod(), form.getWaterType(), form.getCheckLocationIsEmpty(), LocalDate.now()); newFishingTrip.setAppUser(loggedInUser); return fishingTripRepository.save(newFishingTrip); } @Override public FishingTrip saveAndUpdate(FishingTrip fishingTrip) { return fishingTripRepository.save(fishingTrip); } @Override public Set<FishingTrip> findByAppUser(String userName) { return fishingTripRepository.findByAppUser(userName); } @Override public boolean delete(String fishingTripId) { fishingTripRepository.deleteById(fishingTripId); return fishingTripRepository.existsById(fishingTripId); } }
package com.cache.entity; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.apache.ignite.cache.query.annotations.QuerySqlField; import java.io.Serializable; @Data @AllArgsConstructor @NoArgsConstructor @Builder public class Person implements Serializable { private static final long serialVersionUID = 3235823406453902677L; @QuerySqlField(index = true) private Long id; @QuerySqlField private String firstName; @QuerySqlField private String lastName; @QuerySqlField private int age; /** Organization ID (indexed). */ @QuerySqlField(index = true) public Long orgId; }
package pl.ark.chr.buginator.repository.core; import org.springframework.data.jpa.repository.JpaRepository; import pl.ark.chr.buginator.domain.core.UserAgentData; //TODO: check possibility to be removed and managed by Error (using cascade from JPA) public interface UserAgentDataRepository extends JpaRepository<UserAgentData, Long> { }
package com.xiaoxiao.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class XiaoxiaoUserHobby { private Long userId; private String hobbyId; }
package com.example.userportal.service.mapper; import com.example.userportal.domain.Shop; import com.example.userportal.service.dto.ShopDTO; import org.mapstruct.Mapper; import java.util.List; @Mapper(componentModel = "spring") public interface ShopMapper { ShopDTO toShopDto(Shop shop); Shop toShop(ShopDTO shopDTO); List<ShopDTO> toShopDtos(List<Shop> shops); List<Shop> toShops(List<ShopDTO> shopDTOS); }
package com.greenfoxacademy.springsecuritytest; import com.greenfoxacademy.springsecuritytest.interfaces.ApiInterface; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; @SpringBootApplication public class SpringsecuritytestApplication { public static void main(String[] args) { SpringApplication.run(SpringsecuritytestApplication.class, args); } }
package isden.mois.magellanlauncher; /** * Created by isden on 05.01.17. */ public class Constants { /** * Updater constants. */ public final static String VERSION_CHECK_URL = "https://api.github.com/repos/isdenmois/fibook/releases/latest"; public final static String UPDATES_PREFERENCES = "ISDEN_MAGELLAN_SHARED_PREFERENCES"; /** * HTTPD shared constants. */ public final static String JSON = "application/json"; public final static String SUCCESS_MESSAGE = "{\"message\": \"OK\"}"; }
package MoveAroundBoard; import java.util.ArrayList; public class Board { private ArrayList<Square> contents = new ArrayList<Square>(); Board(){ } public void addSquare(Square square) { contents.add(square); } public Square getSquare(int index) { return contents.get(index); } public int size() { return contents.size(); } }
package pdx.module.janitorial; public class CleaningRequests { public static String[] columns = {"Floor", "Room", "Time", "Elapsed"}; public static String[][] placeholder = { {"1", "102", "9:20 AM", "35 Minutes"}, {"4", "406", "9:32 AM", "23 Minutes"}, {"3", "308", "9:50 AM", "5 Minutes"} }; }
public class Perfectno { public static void main(String[] args) { int s=0,n=28; for(int i=1;i<n;i++) { if(n%i==0) s=s+i; } if(s==n) System.out.println("It's a perfect number"); else System.out.println("Not a perfect number"); } }
/*************************************************************************** * * * Page details: This is the step definition file for shopping * cart page * Author: Venukrishnan VR * * * * * ***************************************************************************/ package amazon.com.qa.stepDefinitions; import org.junit.Assert; import amazon.com.qa.base.TestBase; import amazon.com.qa.pages.ShoppingCart; import cucumber.api.java.en.And; public class shoppingCart extends TestBase{ public ShoppingCart sc; @And("^Verify product details$") public void Verify_product_details() { sc=new ShoppingCart(); Assert.assertTrue(sc.getProductTitle(productDetailPage.productTitle)); double val=productDetailPage.unitProdPrice*productDetailPage.product_qty; System.out.println("Total price "+val); Assert.assertTrue(sc.verifyTotalPrice(val)); } }
package jp.astra.cameramap; import jp.astra.cameramap.helper.BaseActivity; import jp.astra.cameramap.helper.CameraMapException; import jp.astra.cameramap.helper.Logger; import jp.astra.cameramap.helper.Util; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; /** * @author Lau */ public class CameraMap extends BaseActivity { private Intent intent; private boolean isStartup = true; public boolean hasMessage = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Thread.setDefaultUncaughtExceptionHandler(new ThreadExceptionHandler(this.getString(R.string.app_name))); this.setContentView(R.layout.splash_view); if (Util.isMediaAvailable(this)) { this.run(this.startup); } } @Override public void onResume() { super.onResume(); if (!this.isStartup) { this.finish(); } this.isStartup = false; } @Override public void onDestroy() { super.onDestroy(); try { if (this.intent != null) { this.stopService(this.intent); } } catch (Throwable t) { new CameraMapException(this, "CamEditor.onDestroy", t); } System.exit(0); } @Override public boolean onCreateOptionsMenu(Menu menu) { return false; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_SEARCH) { return true; } else if (keyCode == KeyEvent.KEYCODE_BACK) { this.showMainHandler.removeMessages(0); return super.onKeyDown(keyCode, event); } else { return super.onKeyDown(keyCode, event); } } @Override protected void run(Runnable function) { new Thread(function).start(); } private final Runnable startup = new Runnable() { @Override public void run() { CameraMap.this.showMainHandler.sendEmptyMessageDelayed(0, 1500); } }; public final Handler showMainHandler = new Handler() { @Override public void handleMessage(Message msg) { Intent intent = new Intent(CameraMap.this, GalleryListView.class); intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); CameraMap.this.startActivity(intent); super.handleMessage(msg); } }; private final class ThreadExceptionHandler implements Thread.UncaughtExceptionHandler { private String title; public ThreadExceptionHandler(String title) { this.title = title; } @Override public void uncaughtException(Thread thread, Throwable ex) { //Something got messed up... String message = ex.getLocalizedMessage(); StackTraceElement stack[] = ex.getStackTrace(); for (int i = 0; i < stack.length; i++) { message = message + "\n Stack " + i + ": " + stack[i].getClassName() + ":" + stack[i].getMethodName() + "(" + stack[i].getFileName() + ":" + stack[i].getLineNumber() + ")"; } try { Logger.error(CameraMap.this, message); } catch (Throwable t) { Log.e(this.title, message); } System.exit(0); } } }
package com.tencent.mm.plugin.sns.f; import android.view.View; class b$2 implements Runnable { final /* synthetic */ View ntO; final /* synthetic */ b ntP; final /* synthetic */ View val$view; b$2(b bVar, View view, View view2) { this.ntP = bVar; this.val$view = view; this.ntO = view2; } public final void run() { b.a(this.ntP, this.val$view, this.ntO); } }
package com.tencent.mm.plugin.appbrand.dynamic.b; import android.graphics.Bitmap; import android.graphics.Rect; import android.os.Bundle; import android.os.Parcelable; import android.text.TextUtils; import com.tencent.mm.ipcinvoker.f; import com.tencent.mm.modelappbrand.b.b; import com.tencent.mm.modelappbrand.b.b$h; import com.tencent.mm.plugin.appbrand.appstorage.AppBrandLocalMediaObject; import com.tencent.mm.plugin.appbrand.appstorage.AppBrandLocalMediaObjectManager; import com.tencent.mm.plugin.appbrand.canvas.g; import com.tencent.mm.plugin.appbrand.canvas.g.a; import com.tencent.mm.plugin.appbrand.dynamic.i; final class c implements g { c() { } public final Bitmap aY(String str, String str2) { return a(str, str2, null); } public final Bitmap a(String str, String str2, a aVar) { return a(str, str2, null, aVar); } public final Bitmap a(final String str, final String str2, Rect rect, final a aVar) { if (str2.startsWith("wxfile://")) { AppBrandLocalMediaObject itemByLocalId = AppBrandLocalMediaObjectManager.getItemByLocalId(str, str2); if (itemByLocalId == null || TextUtils.isEmpty(itemByLocalId.dDG)) { return null; } String str3 = itemByLocalId.dDG; if (!str3.startsWith("file://")) { str3 = "file://" + str3; } return b.Ka().a(str3, null); } else if (!str2.startsWith("https://") && !str2.startsWith("http://")) { return a.aY(str, str2); } else { Bitmap a = b.Ka().a(str2, null); if (a != null) { return a; } b.Ka().a(new b$h() { public final void Kc() { } public final void n(Bitmap bitmap) { if (aVar != null && bitmap != null && !bitmap.isRecycled()) { aVar.adn(); } } public final void Kd() { Parcelable bundle = new Bundle(); bundle.putString("id", str); bundle.putInt("widgetState", 2103); f.a(i.aeT().sz(str), bundle, com.tencent.mm.plugin.appbrand.dynamic.f.a.class, null); } public final String Ke() { return "WxaWidgetIcon"; } }, str2, null, null); return a; } } }
package com.tencent.mm.plugin.exdevice.model; import com.tencent.mm.bt.h.d; import com.tencent.mm.plugin.exdevice.f.b.b.b; class ad$6 implements d { ad$6() { } public final String[] xb() { return b.diD; } }
package com.module.model.entity; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; import javax.xml.bind.annotation.XmlTransient; import java.util.UUID; @Entity @Table(name = "work_places") public class WorkPlaceEntity { @Column(name = "hr_number") private String hrNumber; @Column(name = "locality") private String locality; @Column(name = "organization") private String organization; @Column(name = "position") private String position; @Id @GeneratedValue(generator = "uuid2") @GenericGenerator(name = "uuid2", strategy = "com.module.helpers.UuidAutoGenerator") @Column(name = "uuid") private UUID uuid; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "veteran_uuid") private VeteranEntity veteran; public WorkPlaceEntity() { this(null, null, null, null, null); } public WorkPlaceEntity(String organization, String locality, String position, String hrNumber, VeteranEntity veteran) { this.organization = organization; this.locality = locality; this.position = position; this.hrNumber = hrNumber; this.veteran = veteran; } public boolean equals(Object object) { if (object == this) return true; if ((object == null) || !(object instanceof WorkPlaceEntity)) return false; final WorkPlaceEntity b = (WorkPlaceEntity) object; return uuid != null && b.getUuid() != null && uuid.equals(b.getUuid()); } public String getHrNumber() { return hrNumber; } public void setHrNumber(String hrNumber) { this.hrNumber = hrNumber; } public String getLocality() { return locality; } public void setLocality(String locality) { this.locality = locality; } public String getOrganization() { return organization; } public void setOrganization(String organization) { this.organization = organization; } public String getPosition() { return position; } public void setPosition(String post) { this.position = post; } public UUID getUuid() { return uuid; } public void setUuid(UUID uuid) { this.uuid = uuid; } public VeteranEntity getVeteran() { return veteran; } @XmlTransient public void setVeteran(VeteranEntity veteran) { this.veteran = veteran; } public String toString() { return "Место работы: " + organization + " " + locality + " " + position + " " + hrNumber; } }
package com.ojas.service; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import com.ojas.model.User; import com.ojas.response.UserResponse; @Service public interface UserService { public ResponseEntity<Object> saveUser(User user); }
package com.lux.netcracker.homework.homework.service.bookService; import com.lux.netcracker.homework.homework.model.Book; import java.util.ArrayList; import java.util.List; public interface BookService { Book addBook(Book book); void delete(long id); Book getByName(String name); Book editBook(Book book); List<Book> getAll(); Book createBook(String bookName, String authorName, String publisherName); ArrayList<Book> findByAuthor(String authorName); ArrayList<Book> findByPublisher(String publisherName); }
package sso.ojdbc.dao; import java.util.List; /** * @author Ken * @version 創建時間:2016-02-02 */ public interface PagingDao { List query(final String sql) throws Exception; List query(String sql, Object[] args) throws Exception; public List query2(final String sql, final Object[] args) throws Exception; /** * zero base */ List query(String sql, Object[] args, int startPage, int pageCount) throws Exception; /** * zero base */ List query(String sql, int startPage, int pageCount) throws Exception; }
package com.bingo.code.example.design.observer.rewrite; /** * �����Ķ��ߣ�Ϊ�˼򵥾�����һ������ */ public class Reader implements Observer{ /** * ���ߵ����� */ private String name; public void update(Subject subject) { //���Dz������ķ�ʽ System.out.println(name+"�յ���ֽ�ˣ��Ķ��ȡ�������==="+((NewsPaper)subject).getContent()); } public String getName() { return name; } public void setName(String name) { this.name = name; } }
package ec.com.yacare.y4all.lib.dto; public class TiempoAudio { private Long tiempo; private short[] audio; public Long getTiempo() { return tiempo; } public void setTiempo(Long tiempo) { this.tiempo = tiempo; } public short[] getAudio() { return audio; } public void setAudio(short[] audio) { this.audio = audio; } }
package com.BasicLearn.四种权限; public class Demo { /* * private , (default) , protected , public * 权限说明 * private : 类内部 * default : 类内部 , 同一个包 * protected : 类内部 , 同一个包, 不同包的子类 * public : 类内部, 同一个包 , 不同的包的子类 , 同一个工程 * * 四种都可修饰任意的属性方法。 * public , default --> 修饰类 * private --> 可以用再内部类中 * */ public static void main(String[] args) { } }
package cz.kojotak.udemy.vertx.stockBroker.api.quote; import java.math.BigDecimal; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cz.kojotak.udemy.vertx.stockBroker.db.DbHandler; import cz.kojotak.udemy.vertx.stockBroker.dto.Asset; import cz.kojotak.udemy.vertx.stockBroker.dto.Quote; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.util.internal.ThreadLocalRandom; import io.vertx.core.Handler; import io.vertx.core.json.JsonObject; import io.vertx.ext.web.RoutingContext; public class GetQuoteHandler implements Handler<RoutingContext> { private static final Logger LOG = LoggerFactory.getLogger(GetQuoteHandler.class); private final Map<String, Quote> cachedQuotes = new HashMap<>(); public GetQuoteHandler(List<String> assets) { super(); assets.forEach( a$$ ->{ cachedQuotes.put(a$$, randomQuote(a$$)); }); } @Override public void handle(RoutingContext ctx) { var assetParam = ctx.pathParam("asset"); var maybeQuote = Optional.ofNullable(cachedQuotes.get(assetParam)); if(maybeQuote.isEmpty()) { DbHandler.error(ctx, "no assets found"); return; } JsonObject response = maybeQuote.get().toJsonObject(); ctx.response().end(response.toBuffer()); LOG.debug("asset parameter {} and response {}", assetParam, response); } private static Quote randomQuote(String name) { Quote quote = new Quote(); quote.setAsset(new Asset(name)); quote.setVolume(randomBigDecimal()); quote.setAsk(randomBigDecimal()); quote.setBid(randomBigDecimal()); quote.setLastPrice(randomBigDecimal()); return quote; } private static BigDecimal randomBigDecimal() { return BigDecimal.valueOf(ThreadLocalRandom.current().nextDouble(1,100)); } }
package View; import Connection.DB_Connection; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.Tab; import javafx.scene.control.TextField; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.paint.Color; import javafx.scene.text.Font; public class Parts extends Tab { private DB_Connection connection; private void closeProgram(){ Boolean answer = ConfirmBox.display("Quit", "Are you Sure"); if(answer) Platform.exit(); } private void createButtonActionPerformed(String partNo, String Description, Integer price, String orderNo ) { int result = connection.addParts(partNo, Description, price, orderNo); if ( result == 1 ){ AlertBox.display("Parts", "Part Added!"); } else { AlertBox.display("Parts", "Part Not Added!"); } } private void updateButtonActionPerformed(String partNo, String Description, Integer price, String orderNo) { int result = connection.updateParts( partNo, Description, price, orderNo ); if ( result == 1 ){ AlertBox.display("Parts", "Part Updated!"); } else { AlertBox.display("Parts", "Part Not Updated!"); } } public Parts() { connection = new DB_Connection(); setText("Parts"); BorderPane border = new BorderPane(); Label title = new Label("Part Details"); title.setFont(new Font("Arial", 25)); title.setTextFill(Color.BLUE); BorderPane.setAlignment(title, Pos.CENTER); border.setTop(title); GridPane grid = new GridPane(); grid.setHgap(10); grid.setVgap(10); grid.setPadding(new Insets(0, 10, 0, 10)); Label part = new Label("Part No:"); GridPane.setConstraints(part, 1, 0); TextField partTextFld = new TextField(); GridPane.setConstraints(partTextFld, 2, 0); Label desc = new Label("Description:"); GridPane.setConstraints(desc, 1, 1); TextField descTextFld = new TextField(); GridPane.setConstraints(descTextFld, 2, 1); Label cost = new Label("Price:"); GridPane.setConstraints(cost, 1, 2); TextField priceTextFld = new TextField(); GridPane.setConstraints(priceTextFld, 2, 2); Label order = new Label("OrderNo:"); GridPane.setConstraints(order, 1, 3); TextField orderTextFld = new TextField(); GridPane.setConstraints(orderTextFld, 2, 3); grid.getChildren().addAll(part, partTextFld, desc, descTextFld, cost, priceTextFld, order, orderTextFld); border.setCenter(grid); Button create = new Button ("Create"); create.setOnAction((ActionEvent event) ->{ String partNo = partTextFld.getText(); if(partNo.equals("")) { AlertBox.display("Error", "Part No can not be blank!"); } else{ String Description = descTextFld.getText(); Integer price = Integer.valueOf(priceTextFld.getText()); String orderNo = orderTextFld.getText(); createButtonActionPerformed(partNo, Description, price, orderNo); } }); Button update = new Button("Update"); update.setOnAction((ActionEvent event) ->{ String partNo = partTextFld.getText(); if(partNo.equals("")) { AlertBox.display("Error", "Part No can not be blank!"); } else{ String Description = descTextFld.getText(); Integer price = Integer.valueOf(priceTextFld.getText()); String orderNo = orderTextFld.getText(); updateButtonActionPerformed(partNo, Description, price, orderNo); } }); Button delete = new Button("Delete"); delete.setOnAction((ActionEvent event) ->{ RemoveBox.display("Remove", "Enter details of Parts you want to remove!", "Part No"); }); Button quit = new Button ("Quit"); quit.setOnAction(e -> closeProgram()); //********************************************************** // Creating the new layout HBox and adding the Reset and // Quit button to it //********************************************************** HBox hbox = new HBox(5); hbox.getChildren().addAll(create, delete, update, quit); BorderPane.setMargin(hbox, new Insets(10)); hbox.setAlignment(Pos.BOTTOM_RIGHT); border.setBottom(hbox); setContent(border); } }
package com.hlf.java7features; import org.junit.Test; import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.*; import java.nio.file.attribute.FileAttribute; import java.nio.file.attribute.PosixFilePermission; import java.nio.file.attribute.PosixFilePermissions; import java.util.ArrayList; import java.util.List; import java.util.Date; import java.util.Set; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Created by howard.fackrell on 11/6/15. */ public class FileWatcherTest { static final long SHORT_SLEEP_MILLIS = 10000; static final long LONG_SLEEP_MILLIS = 40000; static final String FILENAME = "watched.txt"; final String DIRECTORY = "watched"; static void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) {} } private static void createDirectory(String directoryName) { FileAttribute<Set<PosixFilePermission>> permissions = PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwxrwxr-x")); try { Files.createDirectory(Paths.get(directoryName), permissions); } catch (IOException e) { e.printStackTrace(); } } private static void deleteDirectory(String directoryName) { try { Files.deleteIfExists(Paths.get(directoryName)); } catch (IOException e) { e.printStackTrace(); } } @Test public void testFileWatch() { deleteDirectory(DIRECTORY); createDirectory(DIRECTORY); FileWatcher watcher = new FileWatcher(DIRECTORY); new Thread(watcher).start(); sleep(SHORT_SLEEP_MILLIS); FileUpdater updater = new FileUpdater(DIRECTORY, FILENAME); new Thread(updater).start(); sleep(LONG_SLEEP_MILLIS); watcher.stop(); sleep(SHORT_SLEEP_MILLIS); assertTrue(watcher.events.size() == 3); assertTrue(watcher.events.contains(StandardWatchEventKinds.ENTRY_CREATE)); assertTrue(watcher.events.contains(StandardWatchEventKinds.ENTRY_MODIFY)); assertTrue(watcher.events.contains(StandardWatchEventKinds.ENTRY_DELETE)); } } class FileUpdater implements Runnable { Path path; FileUpdater(String directoryName, String filename) { path = Paths.get(directoryName, filename); } private void updateFile(OpenOption openOption) { try (BufferedWriter writer = Files.newBufferedWriter(path.toAbsolutePath(), openOption)) { writer.write(new Date().toString()); } catch (IOException e) { fail("Couldn't write to file"); } } private void deleteFile() { try { Files.deleteIfExists(path); } catch (IOException e) { fail("couldn't delete the file"); } } @Override public void run() { updateFile(StandardOpenOption.CREATE); FileWatcherTest.sleep(FileWatcherTest.SHORT_SLEEP_MILLIS); updateFile(StandardOpenOption.APPEND); FileWatcherTest.sleep(FileWatcherTest.SHORT_SLEEP_MILLIS); deleteFile(); } } class FileWatcher implements Runnable { Path watchedDirectory; boolean running = true; List<WatchEvent.Kind<?>> events = new ArrayList<>(); public FileWatcher(String fileName) { watchedDirectory = Paths.get(fileName); } public void stop() { running = false; } @Override public void run() { System.out.println("Watching " + watchedDirectory.toAbsolutePath() ); try { WatchService watchService = FileSystems.getDefault().newWatchService(); watchedDirectory.register( watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); WatchKey key = null; while (running) { try { key = watchService.take(); for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); System.out.println(event.context().toString() + "->" + kind + " @ " + new Date()); events.add(kind); } } catch (InterruptedException e) { e.printStackTrace(); } if (!key.reset()) break; } }catch (IOException e) { e.printStackTrace(); fail("Couldn't watch the file for changes"); } System.out.println("done Watching " + watchedDirectory.toAbsolutePath() ); } }
package com.javateam.SpringBootBoard.config; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import com.zaxxer.hikari.HikariDataSource; @Configuration @EnableTransactionManagement public class ProjectConfig extends WebMvcConfigurationSupport { // DBCP @Bean public DataSource dataSource(DataSourceProperties properties) { HikariDataSource dataSource = new HikariDataSource(); dataSource.setJdbcUrl(properties.getUrl()); dataSource.setUsername(properties.getUsername()); dataSource.setPassword(properties.getPassword()); dataSource.setDriverClassName(properties.getDriverClassName()); return new LazyConnectionDataSourceProxy(dataSource); } // transaction config @Bean(name = "transactionManager") public PlatformTransactionManager transactionManager(@Autowired @Qualifier("dataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } // CSS, webjars config @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); registry.addResourceHandler("/static/**") .addResourceLocations("classpath:/static/"); registry.addResourceHandler("/ckeditor4/**") .addResourceLocations("classpath:/static/ckeditor4/"); registry.addResourceHandler("/upload_image/**") .addResourceLocations("classpath:/static/upload/upload_image/"); } }
package inventory.service; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import todo.entity.Role; import com.mysql.jdbc.Statement; public class RoleDaoList { private Statement stmt; private List<Role> roles; private static RoleDaoList roleList; private RoleDaoList() { roles = new ArrayList<Role>(); try { stmt = StatementManager.getStatement(); String query = "SELECT * FROM Role"; ResultSet rs = stmt.executeQuery(query); while (rs.next()) { roles.add(new Role(Integer.parseInt(rs.getString("roleID")), rs .getString("roleName"))); } } catch (SQLException e) { System.out.println("Cannot create ItemDaoList"); } } public static RoleDaoList getInstance() { if (roleList == null) roleList = new RoleDaoList(); return roleList; } public List<Role> findAll() { return roles; } public Role findByID(int id) { for (int i = 0; i < roles.size(); i++) { if (roles.get(i).getRoleID() == id) return roles.get(i); } return new Role(); } public List<Role> findByName(String name) { List<Role> result = new ArrayList<Role>(); for (int i = 0; i < roles.size(); i++) { if (roles.get(i).getRoleName().equals(name)) result.add(roles.get(i)); } return result; } public void createNewRole(String roleName) { String query = "INSERT INTO Role VALUES(NULL,'" + roleName + "')"; try { stmt.executeUpdate(query); } catch (SQLException e) { System.out.println("Cannot insert new role into database"); System.out.println(e); } roles.add(new Role(roles.size() + 1, roleName)); } }
package android.support.v7.widget; public abstract class RecyclerView$c { public void onChanged() { } public void ab(int i, int i2) { } public void c(int i, int i2, Object obj) { ab(i, i2); } public void ac(int i, int i2) { } public void ad(int i, int i2) { } public void ae(int i, int i2) { } }
package com.bnr.android.criminalintent; import android.support.v4.app.Fragment; /** * Created by winters on 1/10/16. */ public class CrimeCameraActivity extends SingleFragmentActivity { @Override protected Fragment createFragment() { //return new CrimeCameraActivity(); return null; } }
package com.tencent.mm.plugin.wallet.balance.ui.lqt; import android.view.View; import android.view.View.OnClickListener; import android.widget.LinearLayout; import android.widget.TextView; import com.tencent.mm.plugin.wxpay.a.f; import com.tencent.mm.plugin.wxpay.a.g; import com.tencent.mm.plugin.wxpay.a.i; import com.tencent.mm.protocal.c.awx; import com.tencent.mm.protocal.c.sj; import com.tencent.mm.ui.base.h; import java.util.Iterator; class WalletLqtSaveFetchUI$11 implements OnClickListener { final /* synthetic */ WalletLqtSaveFetchUI pcc; final /* synthetic */ awx pci; WalletLqtSaveFetchUI$11(WalletLqtSaveFetchUI walletLqtSaveFetchUI, awx awx) { this.pcc = walletLqtSaveFetchUI; this.pci = awx; } public final void onClick(View view) { View linearLayout = new LinearLayout(this.pcc); linearLayout.setOrientation(1); Iterator it = this.pci.rZY.iterator(); while (it.hasNext()) { sj sjVar = (sj) it.next(); if (!(sjVar == null || sjVar.title == null)) { LinearLayout linearLayout2 = (LinearLayout) View.inflate(this.pcc, g.wallet_lqt_fetch_info, null); ((TextView) linearLayout2.findViewById(f.title)).setText(sjVar.title); ((TextView) linearLayout2.findViewById(f.desc)).setText(sjVar.desc); linearLayout.addView(linearLayout2); } } h.a(this.pcc.mController.tml, "", this.pcc.getString(i.wallet_i_know_it), linearLayout, new 1(this)); } }
package com.rc.portal.vo; import java.util.Date; public class TMemberCertificates { private Long id; private Long memberId; private String idcardJustUrl; private String idcardBackUrl; private Integer idcardType; private String idcardCode; private String idcardAddress; private Date createDt; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getMemberId() { return memberId; } public void setMemberId(Long memberId) { this.memberId = memberId; } public String getIdcardJustUrl() { return idcardJustUrl; } public void setIdcardJustUrl(String idcardJustUrl) { this.idcardJustUrl = idcardJustUrl; } public String getIdcardBackUrl() { return idcardBackUrl; } public void setIdcardBackUrl(String idcardBackUrl) { this.idcardBackUrl = idcardBackUrl; } public Integer getIdcardType() { return idcardType; } public void setIdcardType(Integer idcardType) { this.idcardType = idcardType; } public String getIdcardCode() { return idcardCode; } public void setIdcardCode(String idcardCode) { this.idcardCode = idcardCode; } public String getIdcardAddress() { return idcardAddress; } public void setIdcardAddress(String idcardAddress) { this.idcardAddress = idcardAddress; } public Date getCreateDt() { return createDt; } public void setCreateDt(Date createDt) { this.createDt = createDt; } }
package com.database.endingCredit.domain.movie.dto; import java.util.List; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; @Getter @NoArgsConstructor @AllArgsConstructor public class MovieBlobDTO { private List<MovieList> wholeMovieList; private List<MovieBestSeller> bestSellerList; /** * @return List<MovieList> return the wholeMovieList */ public List<MovieList> getWholeMovieList() { return wholeMovieList; } /** * @param wholeMovieList the wholeMovieList to set */ public void setWholeMovieList(List<MovieList> wholeMovieList) { this.wholeMovieList = wholeMovieList; } /** * @return List<MovieBestSeller> return the bestSellerList */ public List<MovieBestSeller> getBestSellerList() { return bestSellerList; } /** * @param bestSellerList the bestSellerList to set */ public void setBestSellerList(List<MovieBestSeller> bestSellerList) { this.bestSellerList = bestSellerList; } }
package de.jmda.gen.java.impl; import static org.junit.Assert.assertTrue; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.Test; import de.jmda.gen.Generator; import de.jmda.gen.GeneratorException; import de.jmda.gen.java.TypeKindGenerator; public class JUTDefaultTypeKindGenerator { private final static Logger LOGGER = LogManager.getLogger(JUTDefaultTypeKindGenerator.class); /** * @throws GeneratorException */ @Test public void testDefaultTypeKindGenerator() throws GeneratorException { Generator generator = TypeKindGenerator.CLASS; StringBuffer generated = generator.generate(); LOGGER.debug("generated [" + generated + "]"); assertTrue( "unexpected type kind [" + generated + "]", TypeKindGenerator.CLASS.getTypeKind().contentEquals(generated)); } }
package com.tencent.mm.plugin.topstory.ui.video; import com.tencent.mars.cdn.CdnLogic; import com.tencent.mars.cdn.CdnLogic.C2CDownloadRequest; import com.tencent.mm.modelcdntran.f; import com.tencent.mm.modelcdntran.g; import com.tencent.mm.modelvideo.b; import com.tencent.mm.modelvideo.o; import com.tencent.mm.plugin.topstory.a.b.a; import com.tencent.mm.protocal.c.btj; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; class o$b implements b { final /* synthetic */ o oCk; private btj oCp; private o$b(o oVar) { this.oCk = oVar; } /* synthetic */ o$b(o oVar, byte b) { this(oVar); } public final void q(String str, String str2, String str3) { btj btj; o$a o_a; x.i("MicroMsg.TopStory.TopStoryVideoViewMgr", "startHttpStream %s %s", new Object[]{str, str2}); g bHV = this.oCk.oAb.bHV(); a aVar = bHV.oAb.bHU().oAm; if (aVar != null && bHV.oAd.containsKey(str)) { btj = (btj) bHV.oAd.get(str); if (btj.srg >= 5) { x.i("MicroMsg.TopStory.TopStoryPreloadMgr", "hit preload cache %s percent %d offset %s", new Object[]{str, Long.valueOf(btj.srg), bi.gc(btj.srf)}); aVar.oyY = 1; aVar.oyZ = btj.srg; aVar.oza = btj.srf; com.tencent.mm.plugin.websearch.api.a.a.kB(25); this.oCp = btj; o_a = new o$a(this.oCk, (byte) 0); if (this.oCp == null) { boolean queryVideoMoovInfo; long[] jArr = new long[2]; if (this.oCp.srg < 100) { o.Tb().a(o.a(str, str3, str2, o_a), false); C2CDownloadRequest c2CDownloadRequest = new C2CDownloadRequest(); c2CDownloadRequest.fileKey = str; c2CDownloadRequest.fileType = 90; c2CDownloadRequest.url = str3; c2CDownloadRequest.savePath = str2; queryVideoMoovInfo = CdnLogic.queryVideoMoovInfo(c2CDownloadRequest, jArr); } else { queryVideoMoovInfo = true; jArr[0] = new com.tencent.mm.plugin.a.b().oY(str2); } x.i("MicroMsg.TopStory.TopStoryVideoViewMgr", "moov check mediaId %s ret %b", new Object[]{str, Boolean.valueOf(queryVideoMoovInfo)}); if (queryVideoMoovInfo && !o_a.oCl) { o_a.onMoovReady(str, (int) jArr[0], (int) jArr[1]); } if (o.G(this.oCp.srg, this.oCp.srf)) { o_a.bIC(); } if (this.oCp.srg == 100) { o_a.h(str, (int) this.oCp.srf, (int) this.oCp.srg); o_a.L(str, 0); } } o.Tb().a(o.a(str, str3, str2, o_a), false); return; } x.i("MicroMsg.TopStory.TopStoryPreloadMgr", "hit preload cache %s but preload percent too small %d offset %s", new Object[]{str, Long.valueOf(btj.srg), bi.gc(btj.srf)}); aVar.oyY = 3; } for (String lx : bHV.oAd.keySet()) { g.ND().lx(lx); } btj = null; this.oCp = btj; o_a = new o$a(this.oCk, (byte) 0); if (this.oCp == null) { o.Tb().a(o.a(str, str3, str2, o_a), false); return; } boolean queryVideoMoovInfo2; long[] jArr2 = new long[2]; if (this.oCp.srg < 100) { o.Tb().a(o.a(str, str3, str2, o_a), false); C2CDownloadRequest c2CDownloadRequest2 = new C2CDownloadRequest(); c2CDownloadRequest2.fileKey = str; c2CDownloadRequest2.fileType = 90; c2CDownloadRequest2.url = str3; c2CDownloadRequest2.savePath = str2; queryVideoMoovInfo2 = CdnLogic.queryVideoMoovInfo(c2CDownloadRequest2, jArr2); } else { queryVideoMoovInfo2 = true; jArr2[0] = new com.tencent.mm.plugin.a.b().oY(str2); } x.i("MicroMsg.TopStory.TopStoryVideoViewMgr", "moov check mediaId %s ret %b", new Object[]{str, Boolean.valueOf(queryVideoMoovInfo2)}); if (queryVideoMoovInfo2 && !o_a.oCl) { o_a.onMoovReady(str, (int) jArr2[0], (int) jArr2[1]); } if (o.G(this.oCp.srg, this.oCp.srf)) { o_a.bIC(); } if (this.oCp.srg == 100) { o_a.h(str, (int) this.oCp.srf, (int) this.oCp.srg); o_a.L(str, 0); } } public final void ny(String str) { o.Tb().k(str, null); } public final void j(String str, int i, int i2) { o.Tb(); f.g(str, i, i2); } public final boolean isVideoDataAvailable(String str, int i, int i2) { boolean isVideoDataAvailable = o.Tb().isVideoDataAvailable(str, i, i2); if (!(isVideoDataAvailable || this.oCp == null || ((long) (i + i2)) > this.oCp.srf)) { isVideoDataAvailable = true; } if (i == 0 && isVideoDataAvailable && this.oCk.oAb != null) { a aVar = this.oCk.oAb.bHU().oAm; if (aVar != null && aVar.ozg == 0) { aVar.ozg = System.currentTimeMillis() - aVar.oyQ; aVar.ozh = (long) i; aVar.ozi = (long) (i + i2); x.i("MicroMsg.TopStory.TopStoryVideoViewMgr", "firstDataAvailable %d %d %d", new Object[]{Long.valueOf(aVar.ozd), Integer.valueOf(i), Integer.valueOf(i2)}); } } return isVideoDataAvailable; } public final void a(b.a aVar) { } }
package com.tencent.mm.protocal; public class c$jo extends c$g { public c$jo() { super("unbindBankCard", "unbindBankCard", 216, true); } }
package org.fog.test.perfeval; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import org.cloudbus.cloudsim.Host; import org.cloudbus.cloudsim.Log; import org.cloudbus.cloudsim.Pe; import org.cloudbus.cloudsim.Storage; import org.cloudbus.cloudsim.core.CloudSim; import org.cloudbus.cloudsim.power.PowerHost; import org.cloudbus.cloudsim.provisioners.RamProvisionerSimple; import org.cloudbus.cloudsim.sdn.overbooking.BwProvisionerOverbooking; import org.cloudbus.cloudsim.sdn.overbooking.PeProvisionerOverbooking; import org.fog.application.AppEdge; import org.fog.application.AppLoop; import org.fog.application.MyApplication; import org.fog.application.selectivity.FractionalSelectivity; import org.fog.entities.FogBroker; import org.fog.entities.FogDeviceCharacteristics; import org.fog.entities.MyActuator; import org.fog.entities.MyFogDevice; import org.fog.entities.MySensor; import org.fog.entities.Tuple; import org.fog.placement.ModuleMapping; import org.fog.placement.MyController; import org.fog.placement.MyController_A; import org.fog.placement.MyModulePlacement; import org.fog.placement.MyModulePlacementBF; import org.fog.policy.AppModuleAllocationPolicy; import org.fog.scheduler.StreamOperatorScheduler; import org.fog.utils.FogLinearPowerModel; import org.fog.utils.FogUtils; import org.fog.utils.TimeKeeper; import org.fog.utils.distribution.DeterministicDistribution; public class Application_A { static List<MyFogDevice> fogDevices = new ArrayList<MyFogDevice>(); static Map<Integer,MyFogDevice> deviceById = new HashMap<Integer,MyFogDevice>(); static List<MySensor> sensors = new ArrayList<MySensor>(); static List<MyActuator> actuators = new ArrayList<MyActuator>(); static List<Integer> idOfEndDevices = new ArrayList<Integer>(); static Map<Integer, Map<String, Double>> deadlineInfo = new HashMap<Integer, Map<String, Double>>(); static Map<Integer, Map<String, Integer>> additionalMipsInfo = new HashMap<Integer, Map<String, Integer>>(); static boolean CLOUD = false; static int numOfGateways = 2; static int numOfEndDevPerGateway = 4; static double sensingInterval = 5; public static void main(String[] args) { Log.printLine("Starting TestApplication..."); try { Log.disable(); int num_user = 1; Calendar calendar = Calendar.getInstance(); boolean trace_flag = false; CloudSim.init(num_user, calendar, trace_flag); String appId = "test_app"; FogBroker broker = new FogBroker("broker"); createFogDevices(broker.getId(), appId); MyApplication application = createApplication(appId, broker.getId()); application.setUserId(broker.getId()); ModuleMapping moduleMapping = ModuleMapping.createModuleMapping(); // Aqui começa o mapeamento dos módulos para execução da aplicação // Primeiro os módulos de armazenamento é alocado na nuvem. moduleMapping.addModuleToDevice("storageModule", "cloud"); // Em seguida, cada end device recebe o módulo clientModule for(int i=0;i<idOfEndDevices.size();i++) { MyFogDevice fogDevice = deviceById.get(idOfEndDevices.get(i)); moduleMapping.addModuleToDevice("clientModule", fogDevice.getName()); } MyController_A controller = new MyController_A("master-controller", fogDevices, sensors, actuators); ////////////////////////////////////// //Estratégias de placement // MyModulePlacement // Aqui o módulo principal é enviado para o ambiente de execução para ser distribuído entre os fog nodes //controller.submitApplication(application, 0, new MyModulePlacement(fogDevices, sensors, actuators, application, moduleMapping,"mainModule")); // Best Fit // Aqui o módulo principal é enviado para o ambiente de execução para ser distribuído entre os fog nodes controller.submitApplication(application, 0, new MyModulePlacementBF(fogDevices, sensors, actuators, application, moduleMapping,"mainModule")); //controller.submitApplication(application, 0, new MyModulePlacementBF(fogDevices, sensors, actuators, application, moduleMapping,"mainModule")); // GA // Aqui o módulo principal é enviado para o ambiente de execução para ser distribuído entre os fog nodes //controller.submitApplication(application, 0, new MyModulePlacementBF(fogDevices, sensors, actuators, application, moduleMapping,"mainModule")); TimeKeeper.getInstance().setSimulationStartTime(Calendar.getInstance().getTimeInMillis()); CloudSim.startSimulation(); CloudSim.stopSimulation(); Log.printLine("TestApplication finished!"); } catch (Exception e) { e.printStackTrace(); Log.printLine("Unwanted errors happen"); } } private static double getvalue(double min, double max) { Random r = new Random(); double randomValue = min + (max - min) * r.nextDouble(); return randomValue; } private static int getvalue(int min, int max) { Random r = new Random(); int randomValue = min + r.nextInt()%(max - min); return randomValue; } private static void createFogDevices(int userId, String appId) { MyFogDevice cloud = createFogDevice("cloud", 44800, 40000, 100, 10000, 0, 0.01, 16*103, 16*83.25); cloud.setParentId(-1); fogDevices.add(cloud); deviceById.put(cloud.getId(), cloud); for(int i=0;i<numOfGateways;i++){ addGw(i+"", userId, appId, cloud.getId()); } } private static void addGw(String gwPartialName, int userId, String appId, int parentId){ MyFogDevice gw = createFogDevice("g-"+gwPartialName, 2800, 4000, 10000, 10000, 1, 0.0, 107.339, 83.4333); fogDevices.add(gw); deviceById.put(gw.getId(), gw); gw.setParentId(parentId); gw.setUplinkLatency(4); for(int i=0;i<numOfEndDevPerGateway;i++){ String endPartialName = gwPartialName+"-"+i; MyFogDevice end = addEnd(endPartialName, userId, appId, gw.getId()); end.setUplinkLatency(2); fogDevices.add(end); deviceById.put(end.getId(), end); } } private static MyFogDevice addEnd(String endPartialName, int userId, String appId, int parentId){ MyFogDevice end = createFogDevice("e-"+endPartialName, 3200, 1000, 10000, 270, 2, 0, 87.53, 82.44); end.setParentId(parentId); idOfEndDevices.add(end.getId()); MySensor sensor = new MySensor("s-"+endPartialName, "IoTSensor", userId, appId, new DeterministicDistribution(sensingInterval)); // inter-transmission time of EEG sensor follows a deterministic distribution sensors.add(sensor); MyActuator actuator = new MyActuator("a-"+endPartialName, userId, appId, "IoTActuator"); actuators.add(actuator); sensor.setGatewayDeviceId(end.getId()); sensor.setLatency(6.0); // latency of connection between EEG sensors and the parent Smartphone is 6 ms actuator.setGatewayDeviceId(end.getId()); actuator.setLatency(1.0); // latency of connection between Display actuator and the parent Smartphone is 1 ms return end; } private static MyFogDevice createFogDevice(String nodeName, long mips, int ram, long upBw, long downBw, int level, double ratePerMips, double busyPower, double idlePower) { List<Pe> peList = new ArrayList<Pe>(); peList.add(new Pe(0, new PeProvisionerOverbooking(mips))); int hostId = FogUtils.generateEntityId(); long storage = 1000000; int bw = 10000; PowerHost host = new PowerHost( hostId, new RamProvisionerSimple(ram), new BwProvisionerOverbooking(bw), storage, peList, new StreamOperatorScheduler(peList), new FogLinearPowerModel(busyPower, idlePower) ); List<Host> hostList = new ArrayList<Host>(); hostList.add(host); String arch = "x86"; String os = "Linux"; String vmm = "Xen"; double time_zone = 10.0; double cost = 3.0; double costPerMem = 0.05; double costPerStorage = 0.001; double costPerBw = 0.0; LinkedList<Storage> storageList = new LinkedList<Storage>(); FogDeviceCharacteristics characteristics = new FogDeviceCharacteristics( arch, os, vmm, host, time_zone, cost, costPerMem, costPerStorage, costPerBw); MyFogDevice fogdevice = null; try { fogdevice = new MyFogDevice(nodeName, characteristics, new AppModuleAllocationPolicy(hostList), storageList, 10, upBw, downBw, 0, ratePerMips); } catch (Exception e) { e.printStackTrace(); } fogdevice.setLevel(level); fogdevice.setMips((int) mips); return fogdevice; } @SuppressWarnings({"serial" }) private static MyApplication createApplication(String appId, int userId){ MyApplication application = MyApplication.createApplication(appId, userId); application.addAppModule("clientModule",10, 1000, 1000, 100); application.addAppModule("mainModule", 50, 1500, 4000, 800); application.addAppModule("storageModule", 10, 50, 12000, 100); application.addAppModule("storageModule2", 10, 50, 12000, 100); application.addAppEdge("IoTSensor", "clientModule", 100, 200, "IoTSensor", Tuple.UP, AppEdge.SENSOR); application.addAppEdge("clientModule", "mainModule", 6000, 600 , "RawData", Tuple.UP, AppEdge.MODULE); application.addAppEdge("mainModule", "storageModule", 1000, 300, "StoreData", Tuple.UP, AppEdge.MODULE); application.addAppEdge("mainModule", "storageModule", 1000, 300, "StoreData", Tuple.UP, AppEdge.MODULE); application.addAppEdge("mainModule", "storageModule", 1000, 300, "StoreData", Tuple.DOWN, AppEdge.MODULE); application.addAppEdge("mainModule", "clientModule", 100, 50, "ResultData", Tuple.DOWN, AppEdge.MODULE); application.addAppEdge("clientModule", "IoTActuator", 100, 50, "Response", Tuple.DOWN, AppEdge.ACTUATOR); application.addTupleMapping("clientModule", "IoTSensor", "RawData", new FractionalSelectivity(1.0)); application.addTupleMapping("mainModule", "RawData", "ResultData", new FractionalSelectivity(1.0)); application.addTupleMapping("mainModule", "RawData", "StoreData", new FractionalSelectivity(1.0)); application.addTupleMapping("clientModule", "ResultData", "Response", new FractionalSelectivity(1.0)); // Aqui é criado um deadline aleatório para o módulo principal, isso faz com que a necessidade de deadline de // cada módulo seja alterada a cada execução. for(int id:idOfEndDevices) { Map<String,Double>moduleDeadline = new HashMap<String,Double>(); moduleDeadline.put("mainModule", getvalue(3.00, 5.00)); Map<String,Integer>moduleAddMips = new HashMap<String,Integer>(); moduleAddMips.put("mainModule", getvalue(0, 500)); deadlineInfo.put(id, moduleDeadline); additionalMipsInfo.put(id,moduleAddMips); } final AppLoop loop1 = new AppLoop(new ArrayList<String>(){{add("IoTSensor");add("clientModule");add("mainModule");add("clientModule");add("IoTActuator");}}); List<AppLoop> loops = new ArrayList<AppLoop>(){{add(loop1);}}; application.setLoops(loops); application.setDeadlineInfo(deadlineInfo); application.setAdditionalMipsInfo(additionalMipsInfo); return application; } }
package org.jboss.forge.addon.deltaspike.commands; import java.util.Arrays; import java.util.List; import javax.inject.Inject; import org.jboss.forge.addon.deltaspike.CoordinateVersionConverter; import org.jboss.forge.addon.deltaspike.DeltaSpikeModule; import org.jboss.forge.addon.deltaspike.DeltaSpikeModules; import org.jboss.forge.addon.deltaspike.facets.DeltaSpikeFacet; import org.jboss.forge.addon.dependencies.Coordinate; import org.jboss.forge.addon.dependencies.DependencyQuery; import org.jboss.forge.addon.dependencies.DependencyRepository; import org.jboss.forge.addon.dependencies.DependencyResolver; import org.jboss.forge.addon.dependencies.builder.DependencyQueryBuilder; import org.jboss.forge.addon.dependencies.util.NonSnapshotDependencyFilter; import org.jboss.forge.addon.facets.FacetFactory; import org.jboss.forge.addon.facets.FacetNotFoundException; import org.jboss.forge.addon.javaee.cdi.CDIFacet; import org.jboss.forge.addon.javaee.cdi.ui.CDISetupCommand; import org.jboss.forge.addon.projects.Project; import org.jboss.forge.addon.projects.ProjectFactory; import org.jboss.forge.addon.projects.ui.AbstractProjectCommand; import org.jboss.forge.addon.ui.command.PrerequisiteCommandsProvider; import org.jboss.forge.addon.ui.context.UIBuilder; import org.jboss.forge.addon.ui.context.UIContext; import org.jboss.forge.addon.ui.context.UIExecutionContext; import org.jboss.forge.addon.ui.input.UISelectMany; import org.jboss.forge.addon.ui.input.UISelectOne; import org.jboss.forge.addon.ui.metadata.UICommandMetadata; import org.jboss.forge.addon.ui.metadata.WithAttributes; import org.jboss.forge.addon.ui.result.NavigationResult; import org.jboss.forge.addon.ui.result.Result; import org.jboss.forge.addon.ui.result.Results; import org.jboss.forge.addon.ui.result.navigation.NavigationResultBuilder; import org.jboss.forge.addon.ui.util.Categories; import org.jboss.forge.addon.ui.util.Metadata; public class DeltaSpikeSetupCommand extends AbstractProjectCommand implements PrerequisiteCommandsProvider { @Inject private ProjectFactory projectFactory; @Inject private FacetFactory facetFactory; @Inject private DependencyResolver dependencyResolver; @Inject @WithAttributes(label = "DeltaSpike version", required = true, name = "version") private UISelectOne<Coordinate> dsVersions; @Inject @WithAttributes(label = "DeltaSpike modules", name = "modules") private UISelectMany<DeltaSpikeModule> dsModules; private DependencyRepository mavenCentral = new DependencyRepository("maven-cetral", "http://central.maven.org/maven2"); @Override public UICommandMetadata getMetadata(UIContext context) { return Metadata.forCommand(DeltaSpikeSetupCommand.class) .name("DeltaSpike: Setup") .description("Install DeltaSpike Core and its modules") .category(Categories.create("DeltaSpike")); } @Override public void initializeUI(UIBuilder builder) throws Exception { // DeltaSpike Versions DependencyQuery dependencyQuery = DependencyQueryBuilder .create("org.apache.deltaspike.core:deltaspike-core-api") .setFilter(new NonSnapshotDependencyFilter()) .setRepositories(mavenCentral); List<Coordinate> versions = dependencyResolver.resolveVersions(dependencyQuery); dsVersions.setValueChoices(versions); dsVersions.setItemLabelConverter(CoordinateVersionConverter.INSTANCE); dsVersions.setDefaultValue(versions.get(versions.size() - 1)); dsModules.setValueChoices(Arrays.<DeltaSpikeModule> asList(DeltaSpikeModules.values())); builder .add(dsVersions) .add(dsModules); } @Override public Result execute(UIExecutionContext context) throws Exception { Coordinate dsVersionToInstall = dsVersions.getValue(); Project project = getSelectedProject(context); DeltaSpikeFacet deltaSpikeFacet = facetFactory.install(project, DeltaSpikeFacet.class); deltaSpikeFacet.setDeltaSpikeVersion(dsVersionToInstall.getVersion()); // Modules Install Iterable<DeltaSpikeModule> selectedModules = dsModules.getValue(); for (DeltaSpikeModule dsModule : selectedModules) { deltaSpikeFacet.install(dsModule); } return Results.success("DeltaSpike core and selected modules installed!"); } /* * (non-Javadoc) * * @see org.jboss.forge.addon.projects.ui.AbstractProjectCommand#getProjectFactory() */ @Override protected ProjectFactory getProjectFactory() { return projectFactory; } /* * (non-Javadoc) * * @see org.jboss.forge.addon.projects.ui.AbstractProjectCommand#isProjectRequired() */ @Override protected boolean isProjectRequired() { return true; } /* * (non-Javadoc) * * @see org.jboss.forge.addon.projects.ui.AbstractProjectCommand#isEnabled(org.jboss.forge.addon.ui.context.UIContext) */ @Override public boolean isEnabled(UIContext context) { if (super.isEnabled(context)) { try { Project project = getSelectedProject(context); // It's only enabled if DeltaSpike is not installed return !project.hasFacet(DeltaSpikeFacet.class); } catch (FacetNotFoundException e) { return true; } } else { return false; } } @Override public NavigationResult getPrerequisiteCommands(UIContext context) { NavigationResultBuilder navigationResultBuilder = NavigationResultBuilder.create(); Project project = getSelectedProject(context); if (project != null) { if (!project.hasFacet(CDIFacet.class)) { navigationResultBuilder.add(CDISetupCommand.class); } } return navigationResultBuilder.build(); } }
package kh.picsell.project; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import kh.picsell.dto.MemberDTO; import kh.picsell.service.DeleteService; import kh.picsell.service.MemberService; @Controller @RequestMapping("/member") public class MemberController { @Autowired private HttpSession session; @Autowired private DeleteService delete; @Autowired private MemberService service; @RequestMapping("/signup.do") //회원가입페이지로이동 public String toSignup() { return "member/signup"; } @RequestMapping("/findid.do") //아디찾기페이지로이동 public String findid() { return "member/find_id_pw"; } @RequestMapping("/findpw.do") //비번찾기페이지로이동 public String findpw() { return "member/find_id_pw"; } @RequestMapping("/login.do") //로그인페이지로이동 public String login() { return "member/login"; } @RequestMapping(value="/signupProc.do", produces="text/html; charset=UTF-8") //회원가입 @ResponseBody public String signupProc(MemberDTO dto) { String deal_sort = "회원가입"; // 날짜 Date today = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String point_date = sdf.format(today); int point = 1000; String money_sort = "포인트"; try { int result = service.insert(dto, deal_sort, point_date, point, money_sort); if(result>0) { return"ㅇㅋ"; }else { return"ㄴㄴ"; } } catch (Exception e) { e.printStackTrace(); return "서버에러"; } } @RequestMapping(value="/idCheck.do", produces="text/html; charset=UTF-8") @ResponseBody public String idCheck(String id) { //아디중복확인 try { System.out.println(id); int result = service.idCheck(id); System.out.println(result); if(result >0) {return"중복"; } else {return"가능";} } catch (Exception e) { e.printStackTrace(); } return "서버에러입니다."; } @RequestMapping(value="/mailCheck.do", produces="text/html; charset=UTF-8") @ResponseBody public String mailCheck(String email) { //메일중복확인 try { System.out.println(email); int result = service.mailCheck(email); System.out.println(result); if(result >0) {return"중복된 메일주소입니다."; } else {return"사용 가능한 메일주소입니다.";} } catch (Exception e) { e.printStackTrace(); } return"서버에러입니다."; } @RequestMapping(value="/nickCheck.do", produces="text/html; charset=UTF-8") @ResponseBody public String nickCheck(String nickname) { //닉네임 중복확인 System.out.println(nickname); try { int result = service.nickCheck(nickname); int result1 = service.nickCheck2(nickname); System.out.println("멤버에 : "+result+"사진에 : "+result1); int val = result + result1; System.out.println(val); if(val>0) { return"중복된 별명입니다."; }else {return"사용가능한 별명입니다.";} }catch(Exception e) { e.printStackTrace(); } return"서버에러입니다"; } @RequestMapping(value="/loginProc.do", produces="text/html; charset=UTF-8") @ResponseBody public String loginProc(String id, String pw, HttpServletRequest request) { System.out.println(id+" : "+pw); try { MemberDTO dto = service.getnick(id); if(dto==null) { return"로그인실패!"; }else { String nickname = dto.getNickname(); System.out.println(nickname); int result = service.login(id, pw); MemberDTO black1 = service.getblack(id); int black = black1.getBlack(); System.out.println(result); if(result>0) { if(black==0) { int result1 = service.managercheck(id, pw); //매니저로그인 if(result1 > 0) { session.setAttribute("adminInfo", nickname); return "관리자로그인성공"; }else { //mav.addObject("로그인성공", ok); //일반회원로그인 session.setAttribute("loginInfo", nickname); return "로그인성공"; } }else if(black==1) { //블랙1단계로그인 //mav.addObject("로그인성공", ok); //session = request.getSession(); session.setAttribute("loginInfo", nickname); return "블랙1"; }else if(black==2) { //블랙2단계로그인(안되게) return "블랙2"; } }else { return "로그인실패!"; } } } catch (Exception e) { e.printStackTrace(); return "서버에러입니다 관리자에게 문의하세요"; } return ""; } @RequestMapping(value="/findidProc.do", produces="text/html; charset=UTF-8") @ResponseBody public String idfindProc(String name, String email, HttpServletRequest request) { //아디찾기 try { MemberDTO dto = service.idfind(name, email); String id = dto.getId(); return id; } catch (Exception e) { e.printStackTrace(); return "회원목록없음"; } } @RequestMapping("/Logout.do") public String logout(HttpServletRequest request) { //로그아웃 // String adminInfo = (String)session.getAttribute("adminInfo"); // String loginInfo = (String)session.getAttribute("loginInfo"); request.getSession().invalidate(); //request.get //session.invalidate(); return "redirect:/home"; } @RequestMapping(value="/pwchange.do", produces="text/html; charset=UTF-8") @ResponseBody public String pwchange(String id, String input, String email, HttpServletRequest request) { // 패스워드찾기 System.out.println("입력값:"+input); String pw = (String)session.getAttribute("AuthenticationKey"); //메일인증코드 System.out.println("바뀔값:"+pw); System.out.println(email); MemberDTO dto = new MemberDTO(); dto.setPw(pw); System.out.println(dto.getPw()); try { if(input.contentEquals(pw)) { //입력값과 메일인증코드가 같다면 System.out.println("같음"); int result = service.pwchange(pw, id, email); if(result>0) { System.out.println("변경완료"); return"변경완료";} else { System.out.println("변경실패"); return"변경실패"; } }else { System.out.println("다름"); return"인증번호"; } } catch (Exception e) { e.printStackTrace(); return"실패했습니다"; } } @RequestMapping("/memout.do") public String memout(HttpServletRequest request) { String nickname = (String)session.getAttribute("loginInfo"); //닉네임으로 회원탈퇴 try { int result = delete.delete1(nickname); delete.delete2(nickname); delete.delete3(nickname); delete.delete4(nickname); delete.delete5(nickname); delete.delete6(nickname); delete.delete7(nickname); delete.delete8(nickname); delete.delete9(nickname); delete.delete10(nickname); delete.delete11(nickname); delete.delete12(nickname); delete.delete13(nickname); delete.delete14(nickname); delete.delete15(nickname); int imgresult = service.changemem(nickname); System.out.println(imgresult); System.out.println(request); session.invalidate(); if(result>0) { System.out.println("성공"); }else { System.out.println("실패"); } } catch (Exception e) { e.printStackTrace(); } return "home"; } @RequestMapping("/manage.do") public String manage_adminAop(MemberDTO dto, HttpServletRequest request) { //회원관리(목록조회) List<MemberDTO> list; try { list = service.getList(); request.setAttribute("list", list); } catch(Exception e) { e.printStackTrace(); } return "member/manage"; } @RequestMapping(value="/leavecheck.do", produces="text/html; charset=UTF-8") @ResponseBody public String leavecheck(String nickname, String pw) { try { int result = service.leavecheck((String)session.getAttribute("loginInfo"), pw); if(result>0) { return "확인"; }else { return "ss"; } }catch(Exception e) { e.printStackTrace(); return "ser"; } } @RequestMapping(value="/blackup.do", produces="text/html; charset=UTF-8") @ResponseBody public String blackup(String id, HttpServletRequest request) { //블랙1업 int result; try { result = service.blackup(id); if(result>0) { return "블랙업"; }else { return "실패"; } } catch (Exception e) { e.printStackTrace(); return "서버"; } } @RequestMapping(value="/blackdown.do", produces="text/html; charset=UTF-8") @ResponseBody public String blackdown(String id, HttpServletRequest request) { //블랙1다운 int result; try { result = service.blackdown(id); if(result>0) { return "블랙다운"; }else { return "실패"; } } catch (Exception e) { e.printStackTrace(); return "서버"; } } }
package dao; import java.util.ArrayList; import entity.CartItem; import exception.DAOException; public interface ICartItemDAO { public ArrayList<CartItem> queryByCartId(int cartId) throws DAOException; public CartItem queryByItemId(int id) throws DAOException; public void delete(int id) throws DAOException; public void update(CartItem item) throws DAOException; public void insert(CartItem item) throws DAOException; public void deleteByCartId(int cartId) throws DAOException; }
package com.budget.hibernate.dao; import com.budget.spring.beans.AdminJoin; import com.budget.spring.beans.UserJoin; public interface DAO { String insertAdminDetails(AdminJoin joinNow); String insertUserDetails(UserJoin userjoin); void myUsers(); }
package com.base.ifocus.myapplication.Adapter; /** * Created by iFocus on 11-09-2015. */ import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.base.ifocus.myapplication.R; import java.util.ArrayList; /** * Created by iFocus on 10-09-2015. */ public class EventListAdapter extends RecyclerView.Adapter<EventListAdapter.ViewHolder> { private ArrayList<String> mDataset; private String[] dataSet; // Provide a reference to the views for each data item // Complex data items may need more than one view per item, and // you provide access to all the views for a data item in a view holder public static class ViewHolder extends RecyclerView.ViewHolder { // each data item is just a string in this case public View mView; public ViewHolder(View v) { super(v); mView = v; } } // Provide a suitable constructor (depends on the kind of dataset) public EventListAdapter(ArrayList<String> myDataset, Context context) { if (myDataset != null) { mDataset = myDataset; } else { dataSet = context.getResources().getStringArray(R.array.eventList); } } // Create new views (invoked by the layout manager) @Override public EventListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // create a new view View v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.event_card_row, parent, false); ViewHolder vh = new ViewHolder(v); return vh; } @Override public void onBindViewHolder(EventListAdapter.ViewHolder holder, int position) { // - get element from your dataset at this position // - replace the contents of the view with that element try { TextView v = (TextView) holder.mView.findViewById(R.id.info_text); if (mDataset != null) { v.setText(mDataset.get(position)); } else { v.setText(dataSet[position]); } } catch (Exception e) { e.printStackTrace(); } } // Return the size of your dataset (invoked by the layout manager) @Override public int getItemCount() { return mDataset.size(); } }
package musicspring; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; @Controller public class MusicController { String message = "Welcome to MusicHub!!!"; @RequestMapping("/") public ModelAndView showMessage( @RequestParam(value = "name", required = false, defaultValue = "World") String name) { System.out.println("in controller"); ModelAndView mv = new ModelAndView("helloworld"); mv.addObject("message", message); mv.addObject("name", name); return mv; } @RequestMapping("/register") public ModelAndView Reg() { ModelAndView mv = new ModelAndView("register"); return mv; } @RequestMapping("/angproduct") public ModelAndView angular() { ModelAndView mv = new ModelAndView("angproduct"); return mv; } @RequestMapping("/andr") public ModelAndView android() { ModelAndView mv = new ModelAndView("andr"); return mv; } @RequestMapping("/moto") public ModelAndView byParameter(@RequestParam("mname") String mname ){//,@RequestParam("mprice") String mprice) { System.out.println("in controller-moto"); return new ModelAndView("moto");//, "message", mname+mprice); } @RequestMapping(value = "/m") public String get(){// ResponseEntity<MotoMob> get() { MotoMob m = new MotoMob(); m.setPid(1); m.setAvail(4); m.setCost(10000); m.setPname("moto x play"); System.out.println("json data "+new ResponseEntity<MotoMob>(m, HttpStatus.OK)); return "m"; // return new ResponseEntity<MotoMob>(m, HttpStatus.OK); } /* @RequestMapping(value = "/moto", method = RequestMethod.GET) public String viewLogin() { return "moto"; } */ }
package org.alienideology.jcord.event.guild.member; import org.alienideology.jcord.Identity; import org.alienideology.jcord.handle.guild.IGuild; import org.alienideology.jcord.handle.guild.IMember; import org.alienideology.jcord.handle.guild.IRole; import java.util.List; /** * @author AlienIdeology */ public class GuildMemberRemoveRoleEvent extends GuildMemberEvent { private List<IRole> removedRoles; public GuildMemberRemoveRoleEvent(Identity identity, IGuild guild, int sequence, IMember member, List<IRole> removedRoles) { super(identity, guild, sequence, member); this.removedRoles = removedRoles; } public List<IRole> getRemovedRoles() { return removedRoles; } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mapred; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.LinkedList; import java.util.List; import org.apache.hadoop.mapred.JobStatus; import org.apache.hadoop.mapreduce.JobID; import org.apache.hadoop.mapreduce.test.system.JobInfo; /** * Concrete implementation of the JobInfo interface which is exposed to the * clients. * Look at {@link JobInfo} for further details. */ class JobInfoImpl implements JobInfo { private List<String> blackListedTracker; private String historyUrl; private JobID id; private boolean setupLaunched; private boolean setupFinished; private boolean cleanupLaunched; private JobStatus status; private int runningMaps; private int runningReduces; private int waitingMaps; private int waitingReduces; private int finishedMaps; private int finishedReduces; private int numMaps; private int numReduces; private boolean historyCopied; public JobInfoImpl() { id = new JobID(); status = new JobStatus(); blackListedTracker = new LinkedList<String>(); historyUrl = ""; } public JobInfoImpl( JobID id, boolean setupLaunched, boolean setupFinished, boolean cleanupLaunched, int runningMaps, int runningReduces, int waitingMaps, int waitingReduces, int finishedMaps, int finishedReduces, JobStatus status, String historyUrl, List<String> blackListedTracker, boolean isComplete, int numMaps, int numReduces, boolean historyCopied) { super(); this.blackListedTracker = blackListedTracker; this.historyUrl = historyUrl; this.id = id; this.setupLaunched = setupLaunched; this.setupFinished = setupFinished; this.cleanupLaunched = cleanupLaunched; this.status = status; this.runningMaps = runningMaps; this.runningReduces = runningReduces; this.waitingMaps = waitingMaps; this.waitingReduces = waitingReduces; this.finishedMaps = finishedMaps; this.finishedReduces = finishedReduces; this.numMaps = numMaps; this.numReduces = numReduces; this.historyCopied = historyCopied; } @Override public List<String> getBlackListedTrackers() { return blackListedTracker; } @Override public String getHistoryUrl() { return historyUrl; } @Override public JobID getID() { return id; } @Override public JobStatus getStatus() { return status; } @Override public boolean isCleanupLaunched() { return cleanupLaunched; } @Override public boolean isSetupLaunched() { return setupLaunched; } @Override public boolean isSetupFinished() { return setupFinished; } @Override public int runningMaps() { return runningMaps; } @Override public int runningReduces() { return runningReduces; } @Override public int waitingMaps() { return waitingMaps; } @Override public int waitingReduces() { return waitingReduces; } @Override public int finishedMaps() { return finishedMaps; } @Override public int finishedReduces() { return finishedReduces; } @Override public int numMaps() { return numMaps; } @Override public int numReduces() { return numReduces; } @Override public boolean isHistoryFileCopied() { return historyCopied; } @Override public void readFields(DataInput in) throws IOException { id.readFields(in); setupLaunched = in.readBoolean(); setupFinished = in.readBoolean(); cleanupLaunched = in.readBoolean(); status.readFields(in); runningMaps = in.readInt(); runningReduces = in.readInt(); waitingMaps = in.readInt(); waitingReduces = in.readInt(); historyUrl = in.readUTF(); int size = in.readInt(); for (int i = 0; i < size; i++) { blackListedTracker.add(in.readUTF()); } finishedMaps = in.readInt(); finishedReduces = in.readInt(); numMaps = in.readInt(); numReduces = in.readInt(); historyCopied = in.readBoolean(); } @Override public void write(DataOutput out) throws IOException { id.write(out); out.writeBoolean(setupLaunched); out.writeBoolean(setupFinished); out.writeBoolean(cleanupLaunched); status.write(out); out.writeInt(runningMaps); out.writeInt(runningReduces); out.writeInt(waitingMaps); out.writeInt(waitingReduces); out.writeUTF(historyUrl); out.writeInt(blackListedTracker.size()); for (String str : blackListedTracker) { out.writeUTF(str); } out.writeInt(finishedMaps); out.writeInt(finishedReduces); out.writeInt(numMaps); out.writeInt(numReduces); out.writeBoolean(historyCopied); } }
package com.ilp.innovations.myapplication.Fragments; import android.app.Dialog; import android.app.ProgressDialog; import android.app.SearchManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.AlertDialog; import android.text.Editable; import android.text.TextWatcher; 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.AdapterView; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.SearchView; import android.widget.TextView; import android.widget.Toast; import com.ilp.innovations.myapplication.Beans.Slot; import com.ilp.innovations.myapplication.R; import com.ilp.innovations.myapplication.Services.BookingUpdaterService; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Iterator; public class SlotViewFragment extends Fragment{ private ProgressDialog pDialog; private ListView slotList; private ArrayList<Slot> slots; private SlotAdapter slotAdapter; public boolean searchBySlot; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); Toast.makeText(getActivity().getApplication(),"asd",Toast.LENGTH_SHORT).show(); } public SlotViewFragment newInstance() { SlotViewFragment fragment = new SlotViewFragment(); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); pDialog = new ProgressDialog(getActivity()); pDialog.setCancelable(false); pDialog.setTitle("Please wait"); pDialog.setMessage("Loading slot list"); showDialog(); slotList = (ListView) rootView.findViewById(R.id.slotList); slots = new ArrayList<>(); slotAdapter = new SlotAdapter(slots); slotList.setAdapter(slotAdapter); listner(); slotList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { final Slot selectedSlot = slots.get(position); Toast.makeText(getActivity().getApplicationContext(),String.valueOf(selectedSlot.isAllocated()),Toast.LENGTH_SHORT).show(); if(selectedSlot.isAllocated()) { //todo alertdialog for release slot AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("Release Slot"); builder.setMessage("Do you really want to release this slot?"); builder.setPositiveButton("YES", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //todo release the slot here showDialog(); Intent releaseIntent = new Intent(getActivity(),BookingUpdaterService.class); releaseIntent.setAction(BookingUpdaterService.ACTION_CLEAR_SLOT); releaseIntent.putExtra("slotId",selectedSlot.getSlotId()); getActivity().startService(releaseIntent); } }); builder.setNegativeButton("NO", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog alert = builder.create(); alert.show(); } else { //todo alertdialog for reserve slot AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("Reserve Slot"); builder.setMessage("Do you really want to reserve this slot?"); builder.setPositiveButton("YES", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //todo reserve the slot here showDialog(); new reserveslot(getActivity()).execute(selectedSlot.getSlotId()); } }); builder.setNegativeButton("NO", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog alert = builder.create(); alert.show(); } } }); Intent intent = new Intent(getActivity(),BookingUpdaterService.class); intent.setAction(BookingUpdaterService.ACTION_GET_ALL_SLOTS); getActivity().startService(intent); return rootView; } @Override public void onResume() { super.onResume(); IntentFilter filter = new IntentFilter(); filter.addAction(BookingUpdaterService.BROADCAST_ACTION_GET_ALL_SLOTS); filter.addAction(BookingUpdaterService.BROADCAST_ACTION_CLEAR_SLOT); filter.addAction(BookingUpdaterService.BROADCAST_ACTION_RESERVE_SLOT); getActivity().registerReceiver(receiver, filter); Log.d("myTag", "Broadcast receiver registered"); } @Override public void onPause() { getActivity().unregisterReceiver(receiver); Log.d("myTag", "Broadcast receiver unregistered"); super.onPause(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // Inflate the menu items for use in the action bar inflater.inflate(R.menu.menu_main, menu); menu.findItem(R.id.action_search).setVisible(false); menu.findItem(R.id.search_head).setVisible(false); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.search_slot: searchBySlot = true; getActivity().invalidateOptionsMenu(); break; case R.id.search_reg_num: searchBySlot = false; getActivity().invalidateOptionsMenu(); break; case R.id.action_refresh: showDialog(); Intent intent = new Intent(getActivity(),BookingUpdaterService.class); intent.setAction(BookingUpdaterService.ACTION_GET_ALL_SLOTS); getActivity().startService(intent); break; default: return super.onOptionsItemSelected(item); } return true; } private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String response = intent.getStringExtra("response"); Log.d("dataaaaaaaaaaaaaa",response); hideDialog(); if(response!=null) { String action = intent.getAction(); if (action.equals(BookingUpdaterService.BROADCAST_ACTION_GET_ALL_SLOTS)) { try { JSONObject jObj = new JSONObject(response); boolean error = jObj.getBoolean("error"); if (!error) { slots.clear(); slotAdapter = new SlotAdapter(slots); slotList.setAdapter(slotAdapter); JSONArray data = jObj.getJSONArray("values"); for (int i = 0; i < data.length(); i++) { JSONObject item = data.getJSONObject(i); if(BookingUpdaterService.LEVEL_ID==Integer.parseInt(item.getString("floorid"))) { Slot slot = new Slot(); String slotId = item.getString("slotid"); slot.setSlotId(slotId); slot.setSlot(item.getString("slotid")); // slot.setSlot(item.getString("slotname")); if (item.getString("status").equals("FREE")) { slot.setIsAllocated(false); } else { slot.setIsAllocated(true); } if (item.getString("isReserved").equals("YES")) { slot.setIsReserved(true); } else { slot.setIsReserved(false); } //slot.setIsReserved(false); slots.add(slot); } } slotAdapter.notifyDataSetChanged(); hideDialog(); } } catch (JSONException e) { e.printStackTrace(); } } else if(action.equals(BookingUpdaterService.BROADCAST_ACTION_CLEAR_SLOT) || action.equals(BookingUpdaterService.BROADCAST_ACTION_RESERVE_SLOT)) { try { JSONObject jObj = new JSONObject(response); boolean error = jObj.getBoolean("error"); if (!error) { slots.clear(); showDialog(); Intent updateIntent = new Intent(getActivity(), BookingUpdaterService.class); updateIntent.setAction(BookingUpdaterService.ACTION_GET_ALL_SLOTS); getActivity().startService(updateIntent); } else { Toast.makeText(getActivity(), jObj.getString("errorMsg"), Toast.LENGTH_SHORT).show(); } }catch (JSONException e) { e.printStackTrace(); } } } else { Toast.makeText(getActivity(), "Error in connection. Either not connected to internet or wrong server addr", Toast.LENGTH_LONG).show(); } } }; private void showDialog() { if (!pDialog.isShowing()) pDialog.show(); } private void hideDialog() { if (pDialog.isShowing()) pDialog.dismiss(); } public static TextView result=null; void listner() { result=new TextView(getActivity()); result.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable s) { try { hideDialog(); slots.clear(); slotAdapter.notifyDataSetChanged(); Intent intent = new Intent(getActivity(),BookingUpdaterService.class); intent.setAction(BookingUpdaterService.ACTION_GET_ALL_SLOTS); getActivity().startService(intent); showDialog(); } catch(Exception e) { final Dialog dialog = new Dialog(getActivity()); dialog.setContentView(R.layout.customerror); dialog.setTitle(""); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.argb(1, 26, 204, 194))); // dialog.getWindow().setTitleColor(R.color.titlecolor); // set the custom dialog components - text, image and button TextView text = (TextView) dialog.findViewById(R.id.text); text.setText("Internet Not Available"); Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK); // if button is clicked, close the custom dialog dialogButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); dialog.show(); } // startActivity(i); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } }); } private class SlotAdapter extends BaseAdapter { private ArrayList<Slot> adpaterList = new ArrayList<Slot>(); public SlotAdapter(ArrayList<Slot> adapterList) { this.adpaterList = adapterList; } @Override public int getCount() { return this.adpaterList.size(); } @Override public Slot getItem(int position) { return this.adpaterList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { //setting the view with list item convertView = View.inflate(getActivity(), R.layout.slot_item, null); // This class is necessary to identify the list item, in case convertView!=null new ViewHolder(convertView); } ViewHolder holder = (ViewHolder) convertView.getTag(); //getting view elements value from ArrayList Slot slot = getItem(position); holder.slotId.setText("Slot ID:"+String.valueOf(slot.getSlotId())); holder.slotName.setText(slot.getSlot()); holder.img.setVisibility(View.GONE); //if(slot.isAllocated()) { // holder.slotId.setTextColor(Color.GRAY); // } return convertView; } class ViewHolder { private TextView slotId; private TextView slotName; private ImageView img; ViewHolder(View view) { slotName = (TextView) view.findViewById(R.id.reg_id); slotId = (TextView) view.findViewById(R.id.slot); img = (ImageView) view.findViewById(R.id.avtar); view.setTag(this); } } } }
package com.ifre.entity.ruleengin; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Transient; import org.hibernate.annotations.DynamicInsert; import org.hibernate.annotations.DynamicUpdate; import org.hibernate.annotations.GenericGenerator; /** * @Title: Entity * @Description: 决策表 * @author zhangdaihao * @date 2016-05-31 10:09:51 * @version V1.0 * */ @Entity @Table(name = "brms_rule_table", schema = "") @DynamicUpdate(true) @DynamicInsert(true) @SuppressWarnings("serial") public class BrmsRuleTableEntity implements java.io.Serializable { /**ID*/ private java.lang.String id; /**组织机构ID*/ private java.lang.String orgId; /**知识库ID*/ private java.lang.String knowId; /**产品ID*/ private java.lang.String prodId; /**包ID*/ private java.lang.String pkgNo; /**包全名*/ private java.lang.String pkgAllName; /**名称*/ private java.lang.String name; /**注释*/ private java.lang.String note; /**优先级*/ private java.lang.Integer salience; /**条件总数*/ private java.lang.Integer condCount; /**动作总数*/ private java.lang.Integer actionCount; /**创建人*/ private java.lang.String createBy; /**创建人名字*/ private java.lang.String createName; /**创建时间*/ private java.util.Date createDate; /**修改人*/ private java.lang.String updateBy; /**修改时间*/ private java.util.Date updateDate; private java.lang.String mergedRegion; private String orgName; private String prodName; private String knowName; private String orgCode; /** *方法: 取得java.lang.String *@return: java.lang.String ID */ @Id @GeneratedValue(generator = "paymentableGenerator") @GenericGenerator(name = "paymentableGenerator", strategy = "uuid") @Column(name ="ID",nullable=false,length=36) public java.lang.String getId(){ return this.id; } /** *方法: 设置java.lang.String *@param: java.lang.String ID */ public void setId(java.lang.String id){ this.id = id; } /** *方法: 取得java.lang.String *@return: java.lang.String 组织机构ID */ @Column(name ="ORG_ID",nullable=false,length=36) public java.lang.String getOrgId(){ return this.orgId; } /** *方法: 设置java.lang.String *@param: java.lang.String 组织机构Code */ public void setOrgId(java.lang.String orgId){ this.orgId = orgId; } @Column(name ="ORG_CODE",nullable=false,length=36) public String getOrgCode() { return this.orgCode; } public void setOrgCode(String orgCode) { this.orgCode = orgCode; } /** *方法: 取得java.lang.String *@return: java.lang.String 知识库ID */ @Column(name ="KNOW_ID",nullable=false,length=36) public java.lang.String getKnowId(){ return this.knowId; } /** *方法: 设置java.lang.String *@param: java.lang.String 知识库ID */ public void setKnowId(java.lang.String knowId){ this.knowId = knowId; } /** *方法: 取得java.lang.String *@return: java.lang.String 产品ID */ @Column(name ="PROD_ID",nullable=false,length=36) public java.lang.String getProdId(){ return this.prodId; } /** *方法: 设置java.lang.String *@param: java.lang.String 产品ID */ public void setProdId(java.lang.String prodId){ this.prodId = prodId; } /** *方法: 取得java.lang.String *@return: java.lang.String 包ID */ @Column(name ="PKG_NO") public java.lang.String getPkgNo(){ return this.pkgNo; } /** *方法: 设置java.lang.String *@param: java.lang.String 包ID */ public void setPkgNo(java.lang.String pkgNo){ this.pkgNo = pkgNo; } /** *方法: 取得java.lang.String *@return: java.lang.String 包全名 */ @Column(name ="PKG_ALL_NAME",nullable=false,length=260) public java.lang.String getPkgAllName(){ return this.pkgAllName; } /** *方法: 设置java.lang.String *@param: java.lang.String 包全名 */ public void setPkgAllName(java.lang.String pkgAllName){ this.pkgAllName = pkgAllName; } /** *方法: 取得java.lang.String *@return: java.lang.String 名称 */ @Column(name ="NAME",nullable=false,length=200) public java.lang.String getName(){ return this.name; } /** *方法: 设置java.lang.String *@param: java.lang.String 名称 */ public void setName(java.lang.String name){ this.name = name; } /** *方法: 取得java.lang.Object *@return: java.lang.Object 注释 */ @Column(name ="NOTE",nullable=false,length=65535) public java.lang.String getNote(){ return this.note; } /** *方法: 设置java.lang.Object *@param: java.lang.Object 注释 */ public void setNote(java.lang.String note){ this.note = note; } /** *方法: 取得java.lang.Integer *@return: java.lang.Integer 优先级 */ @Column(name ="SALIENCE",nullable=true,precision=10,scale=0) public java.lang.Integer getSalience(){ return this.salience; } /** *方法: 设置java.lang.Integer *@param: java.lang.Integer 优先级 */ public void setSalience(java.lang.Integer salience){ this.salience = salience; } /** *方法: 取得java.lang.Integer *@return: java.lang.Integer 条件总数 */ @Column(name ="COND_COUNT",nullable=true,precision=10,scale=0) public java.lang.Integer getCondCount(){ return this.condCount; } /** *方法: 设置java.lang.Integer *@param: java.lang.Integer 条件总数 */ public void setCondCount(java.lang.Integer condCount){ this.condCount = condCount; } /** *方法: 取得java.lang.Integer *@return: java.lang.Integer 动作总数 */ @Column(name ="ACTION_COUNT",nullable=true,precision=10,scale=0) public java.lang.Integer getActionCount(){ return this.actionCount; } /** *方法: 设置java.lang.Integer *@param: java.lang.Integer 动作总数 */ public void setActionCount(java.lang.Integer actionCount){ this.actionCount = actionCount; } /** *方法: 取得java.lang.String *@return: java.lang.String 创建人 */ @Column(name ="CREATE_BY",nullable=true,length=36) public java.lang.String getCreateBy(){ return this.createBy; } /** *方法: 设置java.lang.String *@param: java.lang.String 创建人 */ public void setCreateBy(java.lang.String createBy){ this.createBy = createBy; } /** *方法: 取得java.lang.String *@return: java.lang.String 创建人名字 */ @Column(name ="CREATE_NAME",nullable=true,length=32) public java.lang.String getCreateName(){ return this.createName; } /** *方法: 设置java.lang.String *@param: java.lang.String 创建人名字 */ public void setCreateName(java.lang.String createName){ this.createName = createName; } /** *方法: 取得java.util.Date *@return: java.util.Date 创建时间 */ @Column(name ="CREATE_DATE",nullable=true) public java.util.Date getCreateDate(){ return this.createDate; } /** *方法: 设置java.util.Date *@param: java.util.Date 创建时间 */ public void setCreateDate(java.util.Date createDate){ this.createDate = createDate; } /** *方法: 取得java.lang.String *@return: java.lang.String 修改人 */ @Column(name ="UPDATE_BY",nullable=true,length=36) public java.lang.String getUpdateBy(){ return this.updateBy; } /** *方法: 设置java.lang.String *@param: java.lang.String 修改人 */ public void setUpdateBy(java.lang.String updateBy){ this.updateBy = updateBy; } /** *方法: 取得java.util.Date *@return: java.util.Date 修改时间 */ @Column(name ="UPDATE_DATE",nullable=true) public java.util.Date getUpdateDate(){ return this.updateDate; } /** *方法: 设置java.util.Date *@param: java.util.Date 修改时间 */ public void setUpdateDate(java.util.Date updateDate){ this.updateDate = updateDate; } @Column(name ="MERGED_REGION",nullable=false,length=65535) public java.lang.String getMergedRegion() { return mergedRegion; } public void setMergedRegion(java.lang.String mergedRegion) { this.mergedRegion = mergedRegion; } @Transient public String getOrgName() { return orgName; } public void setOrgName(String orgName) { this.orgName = orgName; } @Transient public String getProdName() { return prodName; } public void setProdName(String prodName) { this.prodName = prodName; } @Transient public String getKnowName() { return knowName; } public void setKnowName(String knowName) { this.knowName = knowName; } }
package org.denevell.natch.jsp.tests; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.List; import org.denevell.natch.io.posts.PostResource; import org.denevell.natch.utils.Pagination; import org.junit.Before; import org.junit.Test; import com.google.common.collect.Lists; public class PaginationTests { @Before public void setup() { } @Test public void shouldSetPaginationWithMoreAndFewerPosts() { // Arrange Pagination<PostResource> p = new Pagination<PostResource>(); List<PostResource> posts = new ArrayList<PostResource>(); posts.add(new PostResource("a", 1, 1, "b", "d", Lists.newArrayList("a"), false)); posts.add(new PostResource("a", 1, 1, "b", "d", Lists.newArrayList("a"), false)); posts.add(new PostResource("a", 1, 1, "b", "d", Lists.newArrayList("a"), false)); // Act p.initPosts(2, 2, posts, "p"); // Assert assertEquals(2, p.getPosts().size()); assertEquals(true, p.getHasFewerPages()); assertEquals(true, p.getHasMorePages()); assertEquals("?p=1", p.getPrevQueryString()); assertEquals("?p=3", p.getNextQueryString()); } @Test public void shouldSetPaginationWithOutMoreAndFewerPosts() { // Arrange Pagination<PostResource> p = new Pagination<PostResource>(); List<PostResource> posts = new ArrayList<PostResource>(); posts.add(new PostResource("a", 1, 1, "b", "d", Lists.newArrayList("a"), false)); posts.add(new PostResource("a", 1, 1, "b", "d", Lists.newArrayList("a"), false)); posts.add(new PostResource("a", 1, 1, "b", "d", Lists.newArrayList("a"), false)); // Act p.initPosts(0, 3, posts, "p"); // Assert assertEquals(3, p.getPosts().size()); assertEquals(false, p.getHasFewerPages()); assertEquals(false, p.getHasMorePages()); } }
package com.weekendproject.connectivly.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.stereotype.Repository; import com.weekendproject.connectivly.model.GrnPoProduct; @Repository public interface GrnPoProductRepository extends JpaRepository<GrnPoProduct, Long>, JpaSpecificationExecutor<GrnPoProduct> { List<GrnPoProduct> findAllByPoNumber(String poNumber); }
package com.ljw.vo; import com.ljw.pojo.ChemClassInfo; /** * @Description:化学商品种类VO * @Author Created by liangjunwei on 2018/8/2 17:39 */ public class ChemClassInfoVO extends ChemClassInfo{ private String menuName;//二级栏目名称 public String getMenuName() { return menuName; } public void setMenuName(String menuName) { this.menuName = menuName; } }
package com.learning.usercenter.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.learning.usercenter.dao.RoleMapper; import com.learning.usercenter.entity.param.RoleQueryParam; import com.learning.usercenter.entity.po.Role; import com.learning.usercenter.exception.RoleNotFoundException; import com.learning.usercenter.service.IRoleResourceService; import com.learning.usercenter.service.IRoleService; import com.learning.usercenter.service.IUserRoleService; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Objects; import java.util.Set; /** * @author Zzz * @date 2021年8月11日10:46:59 */ @Service @Slf4j public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService { @Autowired private IUserRoleService userRoleService; @Autowired private IRoleResourceService roleResourceService; @Override public boolean add(Role role) { boolean isSuccess = this.save(role); roleResourceService.saveBatch(role.getId(), role.getResourceIds()); return isSuccess; } @Override public boolean delete(Long id) { roleResourceService.removeByRoleId(id); return this.removeById(id); } @Override public boolean update(Role role) { boolean isSuccess = this.updateById(role); roleResourceService.saveBatch(role.getId(), role.getResourceIds()); return isSuccess; } @Override public Role get(Long id) { Role role = this.getById(id); if (Objects.isNull(role)) { throw new RoleNotFoundException("role not found with id:" + id); } role.setResourceIds(roleResourceService.queryByRoleId(id)); return role; } @Override public List<Role> getAll() { return this.list(); } @Override public List<Role> query(Long userId) { Set<Long> roleIds = userRoleService.queryByUserId(userId); return this.listByIds(roleIds); } @Override public Page query(Page page, RoleQueryParam roleQueryParam) { QueryWrapper<Role> queryWrapper = roleQueryParam.build(); queryWrapper.eq(StringUtils.isNotBlank(roleQueryParam.getName()), "name", roleQueryParam.getName()); queryWrapper.eq(StringUtils.isNotBlank(roleQueryParam.getCode()), "code", roleQueryParam.getCode()); return this.page(page, queryWrapper); } }
package com.example.android.automuteathome; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.Switch; import android.widget.Toast; import com.example.android.automuteathome.database.PlaceDatabase; import com.example.android.automuteathome.database.PlaceEntry; public class EditPlaceActivity extends AppCompatActivity { private PlaceEntry mPlaceEntry; private EditText mNameEditText; private EditText mAddressEditText; private Switch mEnterMuteSwitch; private Switch mExitMuteSwitch; private FloatingActionButton mSaveButton; private PlaceDatabase mDatabase; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_place); setTitle(getString(R.string.edit_place_activity_title)); //Get included parcelable, finish if not available Intent intent = getIntent(); if (intent.hasExtra(getString(R.string.edit_intent_parcelable_key))) { mPlaceEntry = intent.getParcelableExtra(getString(R.string.edit_intent_parcelable_key)); } else { finish(); Toast.makeText(this, getString(R.string.parcelable_not_available_error), Toast.LENGTH_LONG).show(); } //Confirm that parcelable is not null if (mPlaceEntry == null) { finish(); Toast.makeText(this, getString(R.string.parcelable_not_available_error), Toast.LENGTH_LONG).show(); } //Assign views mNameEditText = (EditText) findViewById(R.id.name_et); mAddressEditText = (EditText) findViewById(R.id.address_et); mEnterMuteSwitch = (Switch) findViewById(R.id.enter_mute_switch); mExitMuteSwitch = (Switch) findViewById(R.id.exit_mute_switch); mSaveButton = (FloatingActionButton) findViewById(R.id.save_fab); //Get instance of database mDatabase = PlaceDatabase.getInstance(this); //Set starting status of views //Text should be the user's choice, to allow editing. Hint should be Google's suggestion. mNameEditText.setText(mPlaceEntry.getUserInputName()); mNameEditText.setHint(mPlaceEntry.getPlaceName()); mAddressEditText.setText(mPlaceEntry.getUserInputAddress()); mAddressEditText.setHint(mPlaceEntry.getPlaceAddress()); mEnterMuteSwitch.setChecked(mPlaceEntry.isMuteOnEnter()); mExitMuteSwitch.setChecked(mPlaceEntry.isMuteOnExit()); //Set save functionality to save button mSaveButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Update PlaceEntry's values mPlaceEntry.setUserInputName(mNameEditText.getText().toString()); mPlaceEntry.setUserInputAddress(mAddressEditText.getText().toString()); mPlaceEntry.setMuteOnEnter(mEnterMuteSwitch.isChecked()); mPlaceEntry.setMuteOnExit(mExitMuteSwitch.isChecked()); //Make a database update call with the update PlaceEntry AppExecutors.getInstance().diskIO().execute(new Runnable() { @Override public void run() { mDatabase.placeDao().updateSavedPlace(mPlaceEntry); } }); Toast.makeText(EditPlaceActivity.this, getString(R.string.updated_entry), Toast.LENGTH_SHORT).show(); finish(); } }); } @Override public void onBackPressed() { super.onBackPressed(); Toast.makeText(this, getString(R.string.changes_discarded), Toast.LENGTH_SHORT).show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = this.getMenuInflater(); inflater.inflate(R.menu.edit_place_activity_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case (R.id.action_delete): { AppExecutors.getInstance().diskIO().execute(new Runnable() { @Override public void run() { mDatabase.placeDao().deletePlace(mPlaceEntry); } }); Toast.makeText(this, getString(R.string.deleted_entry), Toast.LENGTH_SHORT).show(); finish(); return true; } case (android.R.id.home) : { onBackPressed(); return true; } } return super.onOptionsItemSelected(item); } }
package eu.lsem.bakalarka.webfrontend.action.general; import eu.lsem.bakalarka.dao.ThesesDao; import eu.lsem.bakalarka.dao.DirectoriesDao; import eu.lsem.bakalarka.model.Thesis; import eu.lsem.bakalarka.model.ThesisSearch; import eu.lsem.bakalarka.service.ApplicationConfiguration; import eu.lsem.bakalarka.service.FileSystemUtils; import eu.lsem.bakalarka.service.ThesesService; import eu.lsem.bakalarka.webfrontend.action.BaseActionBean; import eu.lsem.bakalarka.webfrontend.customresolution.CustomErrorResolution; import eu.lsem.bakalarka.webfrontend.customresolution.CustomJavaScriptResolution; import eu.lsem.bakalarka.webfrontend.customresolution.TextResolution; import net.sourceforge.stripes.action.*; import net.sourceforge.stripes.controller.LifecycleStage; import net.sourceforge.stripes.integration.spring.SpringBean; import net.sourceforge.stripes.validation.Validate; import net.sourceforge.stripes.validation.ValidateNestedProperties; import org.apache.log4j.Logger; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringEscapeUtils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class ThesisDetailActionBean extends BaseActionBean { @SpringBean private ThesesDao thesesDao; @SpringBean private ApplicationConfiguration applicationConfiguration; @SpringBean private ThesesService thesesService; @SpringBean private FileSystemUtils fileSystemUtils; @SpringBean private DirectoriesDao directoriesDao; @Validate(encrypted = true) /** * bude se nastavovat pri AJAX eventech(stahovani dokumentu, parsovani textu z dokumentu */ private String documentPath; @ValidateNestedProperties({ @Validate(field = "query", encrypted = true), @Validate(field = "searchAnnotation", encrypted = true), @Validate(field = "searchAuthor", encrypted = true), @Validate(field = "searchFulltext", encrypted = true), @Validate(field = "searchResume", encrypted = true), @Validate(field = "searchSubject", encrypted = true) }) private ThesisSearch thesisSearch; private Thesis thesis; @Validate(encrypted = true) private Integer id; private final static Logger log = Logger.getLogger(ThesisDetailActionBean.class); public Thesis getThesis() { return thesis; } public void setId(Integer id) { this.id = id; } public void setDocumentPath(String documentPath) { this.documentPath = documentPath; } public ThesisSearch getThesisSearch() { //musi tady byt return thesisSearch; } public void setThesisSearch(ThesisSearch thesisSearch) { this.thesisSearch = thesisSearch; } @Before(on = {"downloadDocument", "getParsedText"}, stages = LifecycleStage.EventHandling) public Resolution interceptor1() { if (!fileSystemUtils.isPathSafe(documentPath)) return new CustomErrorResolution(403); return null; } @Before(on = {"detail", "ajaxGetDetails"}, stages = LifecycleStage.EventHandling) public void interceptor2() { if (thesisSearch != null && thesisSearch.getQuery() == null) { thesisSearch.setQuery(""); } } /** * event, ktery bere id a posle na stranku s detailem prace * * @return */ @DefaultHandler public Resolution detail() { if (thesisSearch != null && thesisSearch.isLikeSearch()) { //bylo hledani likem thesis = thesesDao.getThesis(id, null); thesesService.escapeThesis(thesis); thesesService.highlightThesisLikeSearch(thesis, thesisSearch); } else if (thesisSearch != null && !thesisSearch.isLikeSearch()) { //bylo hledani normalne thesis = thesesDao.getThesis(id, thesisSearch); thesesService.escapeThesis(thesis); thesesService.highlightThesis(thesis); } else { //tady vim, ze nebylo hledani thesis = thesesDao.getThesis(id, null); thesesService.escapeThesis(thesis); } Integer dirId = thesis.getDirectory() == null ? null : thesis.getDirectory().getId(); thesis.setDirPath(directoriesDao.getDirectoriesPath(dirId)); return new ForwardResolution("/WEB-INF/pages/secure/thesisDetails.jsp"); } /** * Archiv, ktery bere string documentPath a vrati danej dokument * * @return */ public Resolution downloadDocument() { File f = new File(thesesService.getDipstoreResourceAbsolutePath(documentPath)); try { StreamingResolution res = new StreamingResolution(null, new FileInputStream(f)); res.setFilename(f.getName()); res.setCharacterEncoding("UTF-8"); return res; } catch (FileNotFoundException e) { return new CustomErrorResolution(404); } } /** * Event, ktery bere id prace a vrati zavalenej zip s tou diplomkou * * @return */ public Resolution downloadThesis() throws IOException, InterruptedException { Thesis t = thesesDao.getThesis(id, null); String path = t.getRelativeThesisPath(); String absolutePath = thesesService.getDipstoreResourceAbsolutePath(path); return new StreamingResolution("application/zip", fileSystemUtils.getThesisArchiveInputStream(new File(absolutePath))).setFilename(t.getLogin() + ".zip"); } /** * AJAXový event, ktery vraci javascriptovy objekt s plnou diplomkou. Tady je nutne escapovat html tagy a obarvit hledane vyrazy * * @return */ public Resolution ajaxGetDetails() { Thesis t; if (thesisSearch != null && thesisSearch.isLikeSearch()) { //bylo hledani likem t = thesesDao.getThesis(id, null); thesesService.escapeThesis(t); thesesService.highlightThesisLikeSearch(t, thesisSearch); } else if (thesisSearch != null && !thesisSearch.isLikeSearch()) { //bylo hledani normalne t = thesesDao.getThesis(id, thesisSearch); thesesService.escapeThesis(t); thesesService.highlightThesis(t); } else { //tady vim, ze nebylo hledani t = thesesDao.getThesis(id, null); thesesService.escapeThesis(t); } return new CustomJavaScriptResolution(t); } /** * Dalsi AJAXovy event, kterej vyparsuje fulltext a vrati ho. Pouziva se pro nahled souboru * * @return */ public Resolution getParsedText() { final String file = thesesService.getDipstoreResourceAbsolutePath(documentPath); return new TextResolution(thesesService.parseDocument(file)); } }
package com.vines.mybatis.dao; import com.vines.mybatis.db.MybatisDaoTemplate; import com.vines.domain.User; import org.springframework.stereotype.Component; @Component public class UserDao extends MybatisDaoTemplate<User,Integer> { }
package avex.models; public class AthleteValue { Double athletevalue,price; public Double getAthletevalue() { return athletevalue; } public void setAthletevalue(Double athletevalue) { this.athletevalue = athletevalue; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } }
package com.example.nadir.buddycheckalarm; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.PersistableBundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.TimePicker; import java.util.Calendar; /** * Created by classykeyser on 5/17/16. */ public class NewAlarmActivity extends AppCompatActivity { // create UI variables AlarmManager alarm_manager; TimePicker alarm_timePicker; TextView alarm_status; Context context; PendingIntent myPendingIntent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_new_alarm); this.context = this; // initialise alarmManager alarm_manager = (AlarmManager) getSystemService(ALARM_SERVICE); // initialise timepicker alarm_timePicker = (TimePicker) findViewById(R.id.timePicker); // initialise alarmStatus alarm_status = (TextView) findViewById(R.id.alarm_status); // create calendar instance final Calendar calendar = Calendar.getInstance(); //create an intent to the alarm receiver class final Intent myIntent = new Intent(this.context, Alarm_Receiver.class); // intialise alarmOn button and onClick listener Button alarm_on = (Button) findViewById(R.id.alarm_on); final Intent mainActivityIntent = new Intent(this, MainActivity.class); alarm_on.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { calendar.set(Calendar.HOUR_OF_DAY, alarm_timePicker.getHour()); calendar.set(Calendar.MINUTE, alarm_timePicker.getMinute()); //Get hour int hour = alarm_timePicker.getHour(); int minute = alarm_timePicker.getMinute(); //add new alarm to firebase UserProfileManager.getInstance().addAlarm(new Alarm(new Time(hour, minute, 0))); //Convert to string String hourS = String.valueOf(hour); String minuteS = String.valueOf(minute); if (hour > 12) { hourS = String.valueOf(hour - 12); } if (minute < 10) { minuteS = "0" + minuteS; } // change alarmStatus set_alarm_status("Alarm set to: " + hourS + ":" + minuteS); //put in string into intent (tell clock we pressed alarm on button) myIntent.putExtra("extra", true); //Create pending intent that delays the intent until the specified calendar time myPendingIntent = PendingIntent.getBroadcast(NewAlarmActivity.this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT); //set the alarm manager alarm_manager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), myPendingIntent); // go back to Main Activity startActivity(mainActivityIntent); } }); // initialise alarmOff button and onClick listener Button alarm_off = (Button) findViewById(R.id.alarm_off); alarm_off.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { set_alarm_status("Alarm Off!"); //Cancel alarm alarm_manager.cancel(myPendingIntent); myIntent.putExtra("extra", false); //stop the ringtone sendBroadcast(myIntent); // go back to Main Activity startActivity(mainActivityIntent); } }); } private void set_alarm_status(String output) { alarm_status.setText(output); } }
package com.pointless; /** * Created by vaibh on 8/2/2017. */ public interface AdHandler { public void showAds(boolean show) ; }
package com.eazy.firda.eazy; import android.app.DatePickerDialog; import android.app.TimePickerDialog; import android.content.Intent; import android.content.SharedPreferences; import android.location.Location; import android.preference.PreferenceManager; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.CompoundButton; import android.widget.DatePicker; import android.widget.EditText; import android.widget.Switch; import android.widget.TextView; import android.widget.TimePicker; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import java.util.concurrent.TimeUnit; public class SearchActivity extends AppCompatActivity { Location location; SharedPreferences sharedPreferences; SharedPreferences.Editor editor; String memberId, logedAs, dateStart, timeStart, dateEnd, timeEnd, locationPickup, locationReturn; long diff, interval; EditText searchPlace, searchPlace2; TextView start_day, start_month, start_time, end_day, end_month, end_time; Button search; int year, month, dayofmonth, hour, min; String newMonth, newDay; SimpleDateFormat month_name, day_name, day_number, simpleDateFormat, anotherDate, sdf_time; Calendar c, c2; Date date, dt; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); this.getSupportActionBar().setTitle(""); sharedPreferences = PreferenceManager .getDefaultSharedPreferences(SearchActivity.this); editor = sharedPreferences.edit(); logedAs = sharedPreferences.getString("login_as", null); searchPlace = (EditText)findViewById(R.id.search_location); searchPlace2 = (EditText)findViewById(R.id.search_location2); locationPickup = sharedPreferences.getString("location_pickup",null); locationReturn = sharedPreferences.getString("location_return", null); searchPlace.setText(locationPickup); searchPlace2.setText(locationReturn); searchPlace.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent search = new Intent(SearchActivity.this, MapSearch.class); startActivity(search); } }); Switch switch_location = (Switch)findViewById(R.id.switch_location); switch_location.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked){ searchPlace2.setVisibility(View.GONE); } else{ searchPlace2.setVisibility(View.VISIBLE); } } }); c = Calendar.getInstance(TimeZone.getDefault()); date = c.getTime(); year = c.get(Calendar.YEAR); month = c.get(Calendar.MONTH); dayofmonth = c.get(Calendar.DAY_OF_MONTH); hour = c.get(Calendar.HOUR_OF_DAY); min = c.get(Calendar.MINUTE); month_name = new SimpleDateFormat("MMMM", Locale.ENGLISH); day_name = new SimpleDateFormat("EEE", Locale.ENGLISH); day_number = new SimpleDateFormat("dd", Locale.ENGLISH); simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); anotherDate = new SimpleDateFormat("M/d/yyyy", Locale.ENGLISH); sdf_time = new SimpleDateFormat("hh:mm", Locale.ENGLISH); start_day = (TextView)findViewById(R.id.start_day); start_month = (TextView)findViewById(R.id.start_month); start_time = (TextView)findViewById(R.id.start_time); start_day.setText(String.valueOf(dayofmonth)); start_month.setText(day_name.format(c.getTime()) + " | " + month_name.format(c.getTime())); start_time.setText("Time : " + sdf_time.format(date)); if((month+1) < 10){ newMonth = "0" + (month+1); }else{ newMonth = ""+ (month+1); } if(dayofmonth < 10){ newDay = "0" + dayofmonth; } else{ newDay = "" + dayofmonth; } dateStart = newMonth + "/" + newDay + "/" + String.valueOf(year); dateEnd = newMonth + "/" + newDay + "/" + String.valueOf(year); timeEnd = timeStart = sdf_time.format(date); start_day.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final Calendar calendar = Calendar.getInstance(); int yy = calendar.get(Calendar.YEAR); int mm = calendar.get(Calendar.MONTH); int dd = calendar.get(Calendar.DAY_OF_MONTH); DatePickerDialog datePickerDialog = new DatePickerDialog(SearchActivity.this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { String date = "Date " + String.valueOf(year) + "-" + String.valueOf(month + 1) + "-" + String.valueOf(dayOfMonth) + " " + (String.valueOf(day_name.format(dayOfMonth)) + " | " + String.valueOf(month_name.format(month + 1))); calendar.set(year, month, dayOfMonth); Log.v("sdf date", simpleDateFormat.format(calendar.getTime())); Log.v("sdf_date", month_name.format(calendar.getTime())); Log.v("sdf_date", day_name.format(calendar.getTime())); Log.v("date", date); start_day.setText(String.valueOf(dayOfMonth)); start_month.setText(day_name.format(calendar.getTime()) + " | " + month_name.format(calendar.getTime())); int duration = 2; String newMonth, newDay; calendar.setTime(calendar.getTime()); calendar.add(Calendar.MONTH, duration); if((month+1) < 10){ newMonth = "0" + (month+1); }else{ newMonth = ""+ (month+1); } if(dayOfMonth < 10){ newDay = "0" + dayOfMonth; } else{ newDay = "" + dayOfMonth; } dateStart = newMonth + "/" + newDay + "/" + String.valueOf(year); Log.v("dateStart", dateStart); } }, yy, mm, dd); datePickerDialog.show(); } }); start_time.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Calendar mcurrentTime = Calendar.getInstance(); int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY); int minute = mcurrentTime.get(Calendar.MINUTE); TimePickerDialog mTimePicker; mTimePicker = new TimePickerDialog(SearchActivity.this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) { String newHour, newMinute; if(selectedHour < 10){ newHour = "0" + selectedHour; }else{ newHour = ""+ selectedHour; } if(selectedMinute < 10) { newMinute = "0" + selectedMinute; }else{ newMinute = "" + selectedMinute; } start_time.setText("Time: " + newHour + ":" + newMinute); timeStart = newHour + ":" + newMinute; Log.v("timeStart", timeStart); } }, hour, minute, true);//Yes 24 hour time mTimePicker.setTitle("Select Time"); mTimePicker.show(); } }); end_day = (TextView)findViewById(R.id.end_day); end_month = (TextView)findViewById(R.id.end_month); end_time = (TextView)findViewById(R.id.end_time); dt = new Date(); c2 = Calendar.getInstance(); c2.setTime(dt); dt = c2.getTime(); end_day.setText(String.valueOf(dayofmonth)); end_month.setText(day_name.format(dt) + " | " + month_name.format(dt)); end_time.setText("Time : " + sdf_time.format(date)); end_day.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final Calendar calendar = Calendar.getInstance(); int yy = calendar.get(Calendar.YEAR); int mm = calendar.get(Calendar.MONTH); int dd = calendar.get(Calendar.DAY_OF_MONTH); DatePickerDialog datePickerDialog = new DatePickerDialog(SearchActivity.this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { String newMonth, newDay; String date = "Date " + String.valueOf(year) + "-" + String.valueOf(month + 1) + "-" + String.valueOf(dayOfMonth) + " " + (String.valueOf(day_name.format(dayOfMonth)) + " | " + String.valueOf(month_name.format(month + 1))); calendar.set(year, month, dayOfMonth); end_day.setText(String.valueOf(dayOfMonth)); if((month+1) < 10){ newMonth = "0" + (month+1); }else{ newMonth = ""+ (month+1); } if(dayOfMonth < 10){ newDay = "0" + dayOfMonth; } else{ newDay = "" + dayOfMonth; } dateEnd = newMonth+ "/" + newDay + "/" + String.valueOf(year); end_month.setText(day_name.format(calendar.getTime()) + " | " + month_name.format(calendar.getTime())); Log.v("dateEnd", dateEnd); } }, yy, mm, dd); datePickerDialog.show(); } }); end_time.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Calendar mcurrentTime = Calendar.getInstance(); int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY); int minute = mcurrentTime.get(Calendar.MINUTE); TimePickerDialog mTimePicker; mTimePicker = new TimePickerDialog(SearchActivity.this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) { String newHour, newMinute; if(selectedHour < 10){ newHour = "0" + selectedHour; }else{ newHour = ""+ selectedHour; } if(selectedMinute < 10) { newMinute = "0" + selectedMinute; }else{ newMinute = "" + selectedMinute; } end_time.setText("Time: " + newHour + ":" + newMinute); timeEnd = newHour + ":" + newMinute; Log.v("timeEnd", timeEnd); } }, hour, minute, true);//Yes 24 hour time mTimePicker.setTitle("Select Time"); mTimePicker.show(); } }); search = (Button)findViewById(R.id.search); search.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try{ Date date1 = anotherDate.parse(dateStart); Date date2 = anotherDate.parse(dateEnd); diff = date2.getTime() - date1.getTime(); interval = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS); Log.v("interval", String.valueOf(interval)); if(interval <= 1){ interval = 1; } }catch(ParseException e){ e.printStackTrace(); } if(searchPlace.getText().length() < 1){ Snackbar.make(v, "Please choose a location", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } else{ editor.putString("search_dateStart", dateStart); editor.putString("search_timeStart", timeStart); editor.putString("search_dateEnd", dateEnd); editor.putString("search_timeEnd", timeEnd); editor.putLong("search_timeInterval", interval); editor.putString("search_producer", "All"); editor.putInt("search_type1", 0); editor.putInt("search_type2", 0); editor.putInt("search_type3", 0); editor.putInt("search_type4", 0); editor.putString("search_transmission", "Both"); editor.putInt("search_minVal", 0); editor.putInt("search_maxVal", 1000000); editor.apply(); Log.v("interval2", String.valueOf(sharedPreferences.getLong("search_timeInterval", 0))); Intent search = new Intent(SearchActivity.this, SearchCar.class); startActivity(search); } } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { onBackPressed(); } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { super.onBackPressed(); // startActivity(new Intent(SearchActivity.this, SidebarActivity.class)); startActivity(new Intent(SearchActivity.this, HomeActivity.class)); finish(); } }
package com.tencent.mm.ui.base; public interface MultiTouchImageView$a { void bDv(); void bDw(); }
import java.time.Clock; import java.time.ZoneId; import java.time.ZonedDateTime; public class ZoneDateTimeDemo { public static void main(String[] args) { ZonedDateTime zonedDateTime1 = ZonedDateTime.now(Clock.systemUTC()); System.out.println(zonedDateTime1); ZonedDateTime zonedDateTime2 = ZonedDateTime.now(ZoneId.systemDefault()); System.out.println(zonedDateTime2); } }
package com.e6soft.bpm.controllers; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.e6soft.bpm.BpmController; import com.e6soft.bpm.BpmFactory; import com.e6soft.bpm.model.Flowlink; import com.e6soft.bpm.service.FlowlinkService; import com.e6soft.core.views.ViewMsg; @Controller @RequestMapping(value=BpmFactory.module+"/flowlink") public class FlowlinkController extends BpmController{ @Autowired private FlowlinkService flowlinkService; @RequestMapping(value = "ajaxgrid") @ResponseBody public String ajaxgrid(@RequestParam String id){ List<Flowlink> flowlinkList = this.flowlinkService.getFlowlinks(id); return this.toGridJson(flowlinkList); } @RequestMapping(value = "save") @ResponseBody public String save(@ModelAttribute Flowlink flowlink){ this.flowlinkService.save(flowlink); return flowlink.getId(); } @RequestMapping(value = "flowlinkbase") public String flowlinkbase(@RequestParam String linkid,@RequestParam String formid,Model model){ Flowlink flowlink = this.flowlinkService.getById(linkid); model.addAttribute("flowlinkbase",flowlink); return BpmFactory.modulePath+"/flowlinkbase"; } /** * 保存连线设置 * @param flowlink * @param model * @return * @author 王瑜 */ @RequestMapping(value = "saveflowlinkbase") public String saveflowlinkbase(@ModelAttribute Flowlink flowlink,Model model){ this.flowlinkService.save(flowlink); model.addAttribute("flowlinkbase",flowlink); return BpmFactory.modulePath+"/flowlinkbase"; } @RequestMapping(value = "delete") @ResponseBody public String delete(@RequestParam String linkid){ Flowlink flowlink = this.flowlinkService.getById(linkid); if(flowlink == null){ return new ViewMsg(-1,"该出口不存在").toString(); }else{ flowlinkService.deleteFlowlinkBylinkId(linkid); } return new ViewMsg(1,"删除成功").toString(); } }
/* * Copyright © 2014 YAOCHEN Corporation, All Rights Reserved. */ package com.yaochen.address.data.mapper.address; import com.easyooo.framework.sharding.annotation.Table; import com.yaochen.address.data.domain.address.AdRole; import com.yaochen.address.support.Repository; @Repository @Table("AD_ROLE") public interface AdRoleMapper { int deleteByPrimaryKey(Integer roleId); int insert(AdRole record); int insertSelective(AdRole record); AdRole selectByPrimaryKey(Integer roleId); int updateByPrimaryKeySelective(AdRole record); int updateByPrimaryKey(AdRole record); }
package chapter10.Exercise10_01; public class Time { private int hour; private int minute; private int second; public Time() { second = (int) ((System.currentTimeMillis() / 1_000) % 60); minute = (int) (((System.currentTimeMillis() / 1_000) / 60) % 60); hour = (int) ((System.currentTimeMillis() / (60_000 * 60)) % 24); } public Time(long elapsedTime) { setTime(elapsedTime); } public Time(int hour, int minute, int second) { this.hour = hour; this.minute = minute; this.second = second; } public void setTime(long elapsedTime) { second = (int) ((elapsedTime / 1_000) % 60); minute = (int) (((elapsedTime / 1_000) / 60) % 60); hour = (int) ((elapsedTime / (60_000 * 60)) % 24); } public int getHour() { return hour; } public int getMinute() { return minute; } public int getSecond() { return second; } }
package com.encore.exception; public class InvalidInputException extends Exception{ public InvalidInputException(){ this("Min and max are incorrect..."); } public InvalidInputException(String message){ super(message); } }
package hl.restauth.auth; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONObject; import hl.common.ImgUtil; import hl.common.http.HttpResp; import hl.common.http.RestApiUtil; public class FaceAuth { public JsonUser faceMatching(JsonUser aJsonUser, String aUserAttemptPwd, JSONObject aJsonConfig) throws IOException { StringBuffer sbPOIMatchingInfo = new StringBuffer(); String sUserID = aJsonUser.getUserID(); String sCompareRestApiUrl = aJsonConfig.getString(AuthConfig._FACEAPI_COMPARE_URL); String sCompareContentType = aJsonConfig.getString(AuthConfig._FACEAPI_COMPARE_POST_CONTENTTYPE); String sCompareContentTemplate = aJsonConfig.getString(AuthConfig._FACEAPI_COMPARE_POST_TEMPLATE); String sCompareTargetTemplatePath = aJsonConfig.getString(AuthConfig._FACEAPI_COMPARE_TARGET); aUserAttemptPwd = ImgUtil.removeBase64Header(AuthMgr.deobfuscate(aUserAttemptPwd)); String sAttemptFaceFeature = extractFaceFeature(aUserAttemptPwd, aJsonConfig); if(sAttemptFaceFeature!=null) { aUserAttemptPwd = sAttemptFaceFeature; } else { //no feature to compare return null; } List<String> listCompareTargetDataPaths = new ArrayList<String>(); if(sCompareTargetTemplatePath!=null) { sCompareTargetTemplatePath = sCompareTargetTemplatePath.replaceAll( AuthMgr.RegexEscapedParam(AuthMgr.KEY_USERID), sUserID); sCompareContentTemplate = sCompareContentTemplate.replaceAll( AuthMgr.RegexEscapedParam(AuthMgr.KEY_PASSWORD), aUserAttemptPwd); File f = new File(sCompareTargetTemplatePath); if(!f.exists()) { //try to look into same folder File folder = f.getParentFile(); convertAllJpgToBase64(folder); for(File fileJpg : folder.listFiles()) { convertAllJpgToBase64(fileJpg); } } if(f.isDirectory()) { for(File fileFace : f.listFiles()) { if(fileFace.getName().toLowerCase().endsWith(".base64")) listCompareTargetDataPaths.add(fileFace.getAbsolutePath()); } } else { listCompareTargetDataPaths.add(f.getAbsolutePath()); } } String sFaceMatchedTargetPath = null; boolean isRetryWIthFlippedImage = aJsonConfig.getBoolean(AuthConfig._FACEAPI_COMPARE_RETRY_HFLIP); double iCompareThreshold = aJsonConfig.getDouble(AuthConfig._FACEAPI_COMPARE_THRESHOLD); boolean isMatched = false; for(String sCompareTargetPath : listCompareTargetDataPaths) { if(!isMatched) { String sTargetFeature0 = null; try { sTargetFeature0 = getFaceFeature(sCompareTargetPath, aJsonConfig, false); } catch (IOException e1) { sTargetFeature0 = null; } String[] sCompareTargetDatas = new String[] {sTargetFeature0, null}; boolean isHFlipped = false; for(String sCompareTargetData : sCompareTargetDatas) { if(sCompareTargetData!=null) { sCompareTargetData = ImgUtil.removeBase64Header(sCompareTargetData); String sContentBody = sCompareContentTemplate.replaceAll( AuthMgr.RegexEscapedParam(AuthConfig._FACEAPI_COMPARE_TARGET), sCompareTargetData); if(sContentBody.indexOf(AuthMgr.PARAM_PREFIX)>-1) { throw new IOException("Invalid post content : "+sContentBody); } try { long lStartTime = System.currentTimeMillis(); HttpResp httpReq = null; try { httpReq = RestApiUtil.httpPost(sCompareRestApiUrl, sCompareContentType, sContentBody); }catch(IOException ex) { ex.printStackTrace(System.err); } long lElapsedTime = System.currentTimeMillis()-lStartTime; //success if(httpReq!=null && httpReq.getHttp_status()>=200 && httpReq.getHttp_status()<=299) { JSONObject json = new JSONObject(httpReq.getContent_data()); double iCompareResultScore = json.getDouble(AuthConfig._FACEAPI_COMPARE_RESULT_SCORE); if(iCompareResultScore>=iCompareThreshold) { sFaceMatchedTargetPath = sCompareTargetPath; isMatched = true; } if(isMatched) { sbPOIMatchingInfo.append("* [matched]: "); } else { sbPOIMatchingInfo.append("* [failed-skip]: "); } sbPOIMatchingInfo.append(new File(sCompareTargetPath).getName()); if(isHFlipped) { sbPOIMatchingInfo.append(" (hflip)"); } sbPOIMatchingInfo.append(" : actual:").append(iCompareResultScore).append(" -vs- threhold:").append(iCompareThreshold); sbPOIMatchingInfo.append(" (elapsed:").append(lElapsedTime).append("ms)"); sbPOIMatchingInfo.append("\n"); if(isMatched) break; } else { //not success call System.out.println("[WARNING] Non-success RestApi call from "+sCompareRestApiUrl+" :" +"\ncontent-type:"+sCompareContentType +"\nbody:"+sContentBody +"\nresponse:"+httpReq); } if(isRetryWIthFlippedImage) { isHFlipped = true; String sTargetFeature1 = getFaceFeature(sCompareTargetPath, aJsonConfig, true); if(sTargetFeature1!=null) { sCompareTargetDatas[1] = sTargetFeature1; } } } catch (Exception e) { JSONObject json = null; try{ json = new JSONObject(sContentBody); String srcImg = json.getString("SourceFeature"); String tarImg = json.getString("TargetFeature"); json.put("SourceFeature", srcImg.substring(0, 30)+" (more ...)"); json.put("TargetFeature", tarImg.substring(0, 30)+" (more ...)"); sContentBody = json.toString(); }catch(Exception ex) { ex.printStackTrace();} throw new IOException("Error occur when comsuming "+sCompareRestApiUrl+"\n"+sCompareContentType+"\n"+sContentBody, e); } } } } } System.out.println(sbPOIMatchingInfo.toString()); if(sFaceMatchedTargetPath==null) { if(sbPOIMatchingInfo.length()>0) { throw new IOException(sbPOIMatchingInfo.toString()); } return null; } else { if(!aJsonUser.has(JsonUser._ROLES)) { sFaceMatchedTargetPath = new File(sFaceMatchedTargetPath).getName(); int iExtPos = sFaceMatchedTargetPath.lastIndexOf("."); if(iExtPos>-1) { String sMatchedUserID = sFaceMatchedTargetPath.substring(0, iExtPos); JsonUser jsonMatchedUser = AuthMgr.getUser(sMatchedUserID); if(jsonMatchedUser!=null && jsonMatchedUser.has(JsonUser._ROLES)) { jsonMatchedUser.setUserAgent(aJsonUser.getUserName()); jsonMatchedUser.setAuthType(aJsonUser.getAuthType()); aJsonUser = jsonMatchedUser; } } } } return aJsonUser; } private String getFaceFeature(String aImageBase64Path, JSONObject aJsonConfig, boolean isFlipped) throws IOException { File fileImgBase64 = new File(aImageBase64Path); File fileCache = new File(fileImgBase64.getParentFile().getAbsolutePath()+"/.cache/"+fileImgBase64.getName()+"."+(isFlipped?"1":"0")); if(fileCache.exists() && fileCache.lastModified() < fileImgBase64.lastModified()) { fileCache.delete(); } if(!fileCache.exists()) { fileCache.getParentFile().mkdirs(); String sExtractedFeature = extractFaceFeature(ImgUtil.getBase64FromFile(fileImgBase64), aJsonConfig); if(sExtractedFeature!=null) { ImgUtil.writeBase64ToFile(fileCache, sExtractedFeature); } return sExtractedFeature; } return ImgUtil.getBase64FromFile(fileCache); } private String extractFaceFeature(String aImgBase64, JSONObject aJsonConfig) { if(!aJsonConfig.has(AuthConfig._FACEAPI_EXTRACT_URL) || !aJsonConfig.has(AuthConfig._FACEAPI_EXTRACT_POST_RETURN_ATTR) || !aJsonConfig.has(AuthConfig._FACEAPI_EXTRACT_POST_CONTENTTYPE) || !aJsonConfig.has(AuthConfig._FACEAPI_EXTRACT_POST_TEMPLATE)) return null; String sExtractRestApiUrl = aJsonConfig.getString(AuthConfig._FACEAPI_EXTRACT_URL); String sExtractContentType = aJsonConfig.getString(AuthConfig._FACEAPI_EXTRACT_POST_CONTENTTYPE); String sExtractContentTemplate = aJsonConfig.getString(AuthConfig._FACEAPI_EXTRACT_POST_TEMPLATE); String sExtractReturnAttr = aJsonConfig.getString(AuthConfig._FACEAPI_EXTRACT_POST_RETURN_ATTR); if(sExtractRestApiUrl.trim().length()==0 || sExtractContentTemplate.trim().length()==0 || sExtractReturnAttr.trim().length()==0) return null; aImgBase64 = ImgUtil.removeBase64Header(aImgBase64); String sExtractContentBody = sExtractContentTemplate.replaceAll( AuthMgr.RegexEscapedParam(AuthMgr.KEY_PASSWORD), aImgBase64); long lStartTime = System.currentTimeMillis(); HttpResp httpReq = null; try { httpReq = RestApiUtil.httpPost(sExtractRestApiUrl, sExtractContentType, sExtractContentBody); } catch (IOException e) { e.printStackTrace(System.err); } long lElapsedTime = System.currentTimeMillis()-lStartTime; if(httpReq!=null && httpReq.getHttp_status()>=200 && httpReq.getHttp_status()<=299) { String sData = httpReq.getContent_data().trim(); System.out.println(" [extract-feature] "+lElapsedTime+"ms : "+sData); if(sData.startsWith("[")) { JSONArray jsonArr = new JSONArray(sData); sData = jsonArr.getJSONObject(0).toString(); } JSONObject json = new JSONObject(sData); sData = json.getString(sExtractReturnAttr); if(sData!=null) return sData; } else { //not success call System.out.println("[WARNING] Non-success RestApi call from "+sExtractRestApiUrl+" :" +"\ncontent-type:"+sExtractContentType +"\nbody:"+sExtractContentBody +"\nresponse:"+httpReq); } return null; } private static void convertAllJpgToBase64(File f) { if(f!=null && f.isDirectory()) { for(File fileJpg : f.listFiles()) { String sFileName = fileJpg.getName(); if(sFileName.toLowerCase().endsWith(".jpg") && (sFileName.indexOf(".base64.")==-1)) { int iPos = sFileName.lastIndexOf('.'); if(iPos>-1) { String sExt = sFileName.substring(iPos+1); String sFileNameNoExt = sFileName.substring(0, iPos); String sJpgBase64FileName = fileJpg.getParent()+File.separatorChar+sFileNameNoExt+".base64"; File fileJpgBase64 = new File(sJpgBase64FileName); if(!fileJpgBase64.exists()) { String sJpgBase64 = null; try { sJpgBase64 = ImgUtil.imageFileToBase64(fileJpg.getAbsolutePath(), "JPEG"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if(sJpgBase64!=null) { ImgUtil.writeBase64ToFile(fileJpgBase64, sJpgBase64); } String sRenameJpg = sJpgBase64FileName +".jpg"; fileJpg.renameTo(new File(sRenameJpg)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } } } }