text
stringlengths
10
2.72M
package net.davoleo.javagui.forms.graphics; import javax.swing.*; import java.awt.*; /************************************************* * Author: Davoleo * Date / Hour: 30/01/2019 / 20:52 * Class: GFX * Project: JavaGUI * Copyright - © - Davoleo - 2018 **************************************************/ public class GFX extends JPanel { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); this.setBackground(Color.WHITE); g.setColor(Color.BLUE); g.fillRect(25, 25, 100, 30); g.setColor(new Color(190, 81, 215)); g.fillRect(25, 65, 100, 30); g.setColor(Color.RED); g.drawString("THIS IS A DRAWN STRING", 25, 120); g.setColor(Color.GREEN); g.drawLine(25, 140, 100, 200); g.setColor(Color.black); g.drawRect(25, 220, 100, 30); g.setColor(Color.PINK); g.fillOval(25, 260, 100, 30); g.setColor(Color.ORANGE); g.fill3DRect(25, 300, 100, 50, true); } }
package main.qkj.text; public class ColumnBean { private String name;//字段名 private String remark;//字段备注 private String type;//字段类型 private Integer isnull;//是否为为空 private Integer isSelect;//是否查询项 private String tablename; private String colName; private String colType; private String colLength; public String getTablename() { return tablename; } public void setTablename(String tablename) { this.tablename = tablename; } public String getColName() { return colName; } public void setColName(String colName) { this.colName = colName; } public String getColType() { return colType; } public void setColType(String colType) { this.colType = colType; } public String getColLength() { return colLength; } public void setColLength(String colLength) { this.colLength = colLength; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Integer getIsnull() { return isnull; } public void setIsnull(Integer isnull) { this.isnull = isnull; } public Integer getIsSelect() { return isSelect; } public void setIsSelect(Integer isSelect) { this.isSelect = isSelect; } }
package ch5; import java.util.Arrays; public class Exercise5_8 { public static void main(String[] args) { int[] answer = {1,4,4,3,1,4,4,2,1,3,2}; int[] counter = new int[4]; for(int i=0; i<answer.length; i++) { /*if(answer[i] == 1) { ++counter[0]; }else if(answer[i] == 2) { ++counter[1]; }else if(answer[i] == 3) { ++counter[2]; }else { ++counter[3]; }*/ counter[answer[i]-1]++; } for(int i=0; i<counter.length; i++) { System.out.print(counter[i]+" "); for(int j=0; j<counter[i]; j++) { System.out.print("*"); } System.out.println(); } } }
package com.adidas.microservices.subscriptionservice.service; import com.adidas.microservices.subscriptionservice.entity.Subscription; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public interface ISubscriptionService { Long save(Subscription subscription); Optional<Subscription> findOne(Long id); List<Subscription> findAll(); }
package com.burningfire.designpattern.lessonone; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Algorithm Assignment 1a Part 1:Fibonacci Series * * @author kristian delos reyes */ public class Fibonacci { private static final Logger LOGGER = LoggerFactory.getLogger(Fibonacci.class); private static List<Double> fib = new ArrayList<Double>(); @SuppressWarnings("resource") public static void main(String[] args) { // Get input from user Scanner scanner = new Scanner(System.in); // Get Result double result = solveFibonacci(fib, scanner.nextInt()); LOGGER.info("The fibonacci value is: {}", result); } /** * @param fib * @param nthTarget * @return */ private static Double solveFibonacci(List<Double> fib, int nthTarget) { for (int ctr = 0; ctr <= nthTarget; ctr++) { if (ctr <= 1) { fib.add(ctr, (double) ctr); } else { fib.add((double) fib.get(ctr - 1) + (double) fib.get(ctr - 2)); } } return fib.get(nthTarget); } }
package ejercicio14; import java.util.Scanner; import java.util.StringTokenizer; /** * * @author Javier */ public class Ejercicio14 { public static boolean comprobar(StringTokenizer ip) { boolean valido = true; if(ip.countTokens() != 4) valido = false; if (valido == true) { int[] numeros = new int[ip.countTokens()]; // definir el limite del for con ip.countTokens() para en el segundo token for (int i = 0; i < 4; i++) { numeros[i] = Integer.parseInt(ip.nextToken()); if (numeros[i] < 0 | numeros[i] > 255) valido = false; } } return valido; } public static void main(String[] args) { Scanner entrada = new Scanner(System.in); System.out.print("Introduce la IP: "); StringTokenizer ip = new StringTokenizer(entrada.next(), "."); boolean validez = comprobar(ip); if(validez) System.out.println("El numero IP es válido"); else System.out.println("El numero IP no es válido"); } }
package com.xi.json; import com.xi.util.ReadFileUtil; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2016/2/2. */ public class telDemo { public static void main(String[] args) { telDemo t = new telDemo(); List s = t.tel(); System.out.println(s); } public List tel() { List list=new ArrayList(); String name = null; String tel = null; String json = new ReadFileUtil().ReadFile("D:\\xm\\study\\git\\test\\study\\src\\test\\java\\com\\xi\\json\\tel.json"); if (StringUtils.isNotEmpty(json)) { JSONObject dataJson = JSONObject.fromObject(json); if (dataJson != null && dataJson.containsKey("Contacts")) { JSONObject root = dataJson.getJSONObject("Contacts"); if (root != null && root.containsKey("Contact")) { JSONArray location = root.getJSONArray("Contact"); // System.out.println("主人,您共有" + location.size() + "位手机联系人"); for (int i = 0; i < location.size(); i++) { if (location != null) { JSONObject linkman = location.getJSONObject(i); if (linkman != null && linkman.containsKey("Name")) { name = linkman.getString("Name"); } if (linkman != null && linkman.containsKey("PhoneList")) { JSONObject PhoneList = linkman.getJSONObject("PhoneList"); if (PhoneList != null && PhoneList.containsKey("Phone")) { //只有一个电话号码时是对象 JSONObject Phone = PhoneList.getJSONObject("Phone"); if (Phone != null) { tel = Phone.getString("tel"); // System.out.println("姓名:" + name + " tel:" + tel); String info = "姓名:" + name + " tel:" + tel; list.add(info); } } } } } } } } return list; } }
package at.wea5.geocaching.webserviceproxy; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.ws.RequestWrapper; import javax.xml.ws.ResponseWrapper; /** * This class was generated by the JAX-WS RI. * JAX-WS RI 2.2.8 * Generated source version: 2.2 * */ @WebService(name = "GeoCachingServiceSoap", targetNamespace = "http://GeoCaching.Services/") @XmlSeeAlso({ ObjectFactory.class }) public interface GeoCachingServiceSoap { /** * * @return * returns boolean */ @WebMethod(operationName = "IsServiceAvailable", action = "http://GeoCaching.Services/IsServiceAvailable") @WebResult(name = "IsServiceAvailableResult", targetNamespace = "http://GeoCaching.Services/") @RequestWrapper(localName = "IsServiceAvailable", targetNamespace = "http://GeoCaching.Services/", className = "at.wea5.geocaching.webserviceproxy.IsServiceAvailable") @ResponseWrapper(localName = "IsServiceAvailableResponse", targetNamespace = "http://GeoCaching.Services/", className = "at.wea5.geocaching.webserviceproxy.IsServiceAvailableResponse") public boolean isServiceAvailable(); /** * * @param username * @param password * @return * returns at.wea5.geocaching.webserviceproxy.User */ @WebMethod(operationName = "AuthenticateUser", action = "http://GeoCaching.Services/AuthenticateUser") @WebResult(name = "AuthenticateUserResult", targetNamespace = "http://GeoCaching.Services/") @RequestWrapper(localName = "AuthenticateUser", targetNamespace = "http://GeoCaching.Services/", className = "at.wea5.geocaching.webserviceproxy.AuthenticateUser") @ResponseWrapper(localName = "AuthenticateUserResponse", targetNamespace = "http://GeoCaching.Services/", className = "at.wea5.geocaching.webserviceproxy.AuthenticateUserResponse") public User authenticateUser( @WebParam(name = "username", targetNamespace = "http://GeoCaching.Services/") String username, @WebParam(name = "password", targetNamespace = "http://GeoCaching.Services/") String password); /** * * @param filter * @return * returns at.wea5.geocaching.webserviceproxy.ArrayOfCache */ @WebMethod(operationName = "GetFilteredCacheList", action = "http://GeoCaching.Services/GetFilteredCacheList") @WebResult(name = "GetFilteredCacheListResult", targetNamespace = "http://GeoCaching.Services/") @RequestWrapper(localName = "GetFilteredCacheList", targetNamespace = "http://GeoCaching.Services/", className = "at.wea5.geocaching.webserviceproxy.GetFilteredCacheList") @ResponseWrapper(localName = "GetFilteredCacheListResponse", targetNamespace = "http://GeoCaching.Services/", className = "at.wea5.geocaching.webserviceproxy.GetFilteredCacheListResponse") public ArrayOfCache getFilteredCacheList( @WebParam(name = "filter", targetNamespace = "http://GeoCaching.Services/") DataFilter filter); /** * * @return * returns at.wea5.geocaching.webserviceproxy.DataFilter */ @WebMethod(operationName = "ComputeDefaultFilter", action = "http://GeoCaching.Services/ComputeDefaultFilter") @WebResult(name = "ComputeDefaultFilterResult", targetNamespace = "http://GeoCaching.Services/") @RequestWrapper(localName = "ComputeDefaultFilter", targetNamespace = "http://GeoCaching.Services/", className = "at.wea5.geocaching.webserviceproxy.ComputeDefaultFilter") @ResponseWrapper(localName = "ComputeDefaultFilterResponse", targetNamespace = "http://GeoCaching.Services/", className = "at.wea5.geocaching.webserviceproxy.ComputeDefaultFilterResponse") public DataFilter computeDefaultFilter(); /** * * @return * returns at.wea5.geocaching.webserviceproxy.ArrayOfString */ @WebMethod(operationName = "GetCacheSizeList", action = "http://GeoCaching.Services/GetCacheSizeList") @WebResult(name = "GetCacheSizeListResult", targetNamespace = "http://GeoCaching.Services/") @RequestWrapper(localName = "GetCacheSizeList", targetNamespace = "http://GeoCaching.Services/", className = "at.wea5.geocaching.webserviceproxy.GetCacheSizeList") @ResponseWrapper(localName = "GetCacheSizeListResponse", targetNamespace = "http://GeoCaching.Services/", className = "at.wea5.geocaching.webserviceproxy.GetCacheSizeListResponse") public ArrayOfString getCacheSizeList(); /** * * @param cacheId * @return * returns at.wea5.geocaching.webserviceproxy.CacheDetails */ @WebMethod(operationName = "GetDetailedCache", action = "http://GeoCaching.Services/GetDetailedCache") @WebResult(name = "GetDetailedCacheResult", targetNamespace = "http://GeoCaching.Services/") @RequestWrapper(localName = "GetDetailedCache", targetNamespace = "http://GeoCaching.Services/", className = "at.wea5.geocaching.webserviceproxy.GetDetailedCache") @ResponseWrapper(localName = "GetDetailedCacheResponse", targetNamespace = "http://GeoCaching.Services/", className = "at.wea5.geocaching.webserviceproxy.GetDetailedCacheResponse") public CacheDetails getDetailedCache( @WebParam(name = "cacheId", targetNamespace = "http://GeoCaching.Services/") int cacheId); /** * * @param logEntry * @param requestingUser * @return * returns boolean */ @WebMethod(operationName = "AddLogEntryForCache", action = "http://GeoCaching.Services/AddLogEntryForCache") @WebResult(name = "AddLogEntryForCacheResult", targetNamespace = "http://GeoCaching.Services/") @RequestWrapper(localName = "AddLogEntryForCache", targetNamespace = "http://GeoCaching.Services/", className = "at.wea5.geocaching.webserviceproxy.AddLogEntryForCache") @ResponseWrapper(localName = "AddLogEntryForCacheResponse", targetNamespace = "http://GeoCaching.Services/", className = "at.wea5.geocaching.webserviceproxy.AddLogEntryForCacheResponse") public boolean addLogEntryForCache( @WebParam(name = "requestingUser", targetNamespace = "http://GeoCaching.Services/") User requestingUser, @WebParam(name = "logEntry", targetNamespace = "http://GeoCaching.Services/") LogEntry logEntry); /** * * @param requestingUser * @param rating * @return * returns boolean */ @WebMethod(operationName = "AddRatingForCache", action = "http://GeoCaching.Services/AddRatingForCache") @WebResult(name = "AddRatingForCacheResult", targetNamespace = "http://GeoCaching.Services/") @RequestWrapper(localName = "AddRatingForCache", targetNamespace = "http://GeoCaching.Services/", className = "at.wea5.geocaching.webserviceproxy.AddRatingForCache") @ResponseWrapper(localName = "AddRatingForCacheResponse", targetNamespace = "http://GeoCaching.Services/", className = "at.wea5.geocaching.webserviceproxy.AddRatingForCacheResponse") public boolean addRatingForCache( @WebParam(name = "requestingUser", targetNamespace = "http://GeoCaching.Services/") User requestingUser, @WebParam(name = "rating", targetNamespace = "http://GeoCaching.Services/") Rating rating); /** * * @param filter * @return * returns at.wea5.geocaching.webserviceproxy.StatisticDataset */ @WebMethod(operationName = "GetUserByFoundCaches", action = "http://GeoCaching.Services/GetUserByFoundCaches") @WebResult(name = "GetUserByFoundCachesResult", targetNamespace = "http://GeoCaching.Services/") @RequestWrapper(localName = "GetUserByFoundCaches", targetNamespace = "http://GeoCaching.Services/", className = "at.wea5.geocaching.webserviceproxy.GetUserByFoundCaches") @ResponseWrapper(localName = "GetUserByFoundCachesResponse", targetNamespace = "http://GeoCaching.Services/", className = "at.wea5.geocaching.webserviceproxy.GetUserByFoundCachesResponse") public StatisticDataset getUserByFoundCaches( @WebParam(name = "filter", targetNamespace = "http://GeoCaching.Services/") DataFilter filter); /** * * @param filter * @return * returns at.wea5.geocaching.webserviceproxy.StatisticDataset */ @WebMethod(operationName = "GetUserByHiddenCaches", action = "http://GeoCaching.Services/GetUserByHiddenCaches") @WebResult(name = "GetUserByHiddenCachesResult", targetNamespace = "http://GeoCaching.Services/") @RequestWrapper(localName = "GetUserByHiddenCaches", targetNamespace = "http://GeoCaching.Services/", className = "at.wea5.geocaching.webserviceproxy.GetUserByHiddenCaches") @ResponseWrapper(localName = "GetUserByHiddenCachesResponse", targetNamespace = "http://GeoCaching.Services/", className = "at.wea5.geocaching.webserviceproxy.GetUserByHiddenCachesResponse") public StatisticDataset getUserByHiddenCaches( @WebParam(name = "filter", targetNamespace = "http://GeoCaching.Services/") DataFilter filter); /** * * @param filter * @return * returns at.wea5.geocaching.webserviceproxy.StatisticDataset */ @WebMethod(operationName = "GetBestRatedCache", action = "http://GeoCaching.Services/GetBestRatedCache") @WebResult(name = "GetBestRatedCacheResult", targetNamespace = "http://GeoCaching.Services/") @RequestWrapper(localName = "GetBestRatedCache", targetNamespace = "http://GeoCaching.Services/", className = "at.wea5.geocaching.webserviceproxy.GetBestRatedCache") @ResponseWrapper(localName = "GetBestRatedCacheResponse", targetNamespace = "http://GeoCaching.Services/", className = "at.wea5.geocaching.webserviceproxy.GetBestRatedCacheResponse") public StatisticDataset getBestRatedCache( @WebParam(name = "filter", targetNamespace = "http://GeoCaching.Services/") DataFilter filter); /** * * @param filter * @return * returns at.wea5.geocaching.webserviceproxy.StatisticDataset */ @WebMethod(operationName = "GetMostLoggedCaches", action = "http://GeoCaching.Services/GetMostLoggedCaches") @WebResult(name = "GetMostLoggedCachesResult", targetNamespace = "http://GeoCaching.Services/") @RequestWrapper(localName = "GetMostLoggedCaches", targetNamespace = "http://GeoCaching.Services/", className = "at.wea5.geocaching.webserviceproxy.GetMostLoggedCaches") @ResponseWrapper(localName = "GetMostLoggedCachesResponse", targetNamespace = "http://GeoCaching.Services/", className = "at.wea5.geocaching.webserviceproxy.GetMostLoggedCachesResponse") public StatisticDataset getMostLoggedCaches( @WebParam(name = "filter", targetNamespace = "http://GeoCaching.Services/") DataFilter filter); /** * * @param filter * @return * returns at.wea5.geocaching.webserviceproxy.StatisticDataset */ @WebMethod(operationName = "GetCacheDistributionBySize", action = "http://GeoCaching.Services/GetCacheDistributionBySize") @WebResult(name = "GetCacheDistributionBySizeResult", targetNamespace = "http://GeoCaching.Services/") @RequestWrapper(localName = "GetCacheDistributionBySize", targetNamespace = "http://GeoCaching.Services/", className = "at.wea5.geocaching.webserviceproxy.GetCacheDistributionBySize") @ResponseWrapper(localName = "GetCacheDistributionBySizeResponse", targetNamespace = "http://GeoCaching.Services/", className = "at.wea5.geocaching.webserviceproxy.GetCacheDistributionBySizeResponse") public StatisticDataset getCacheDistributionBySize( @WebParam(name = "filter", targetNamespace = "http://GeoCaching.Services/") DataFilter filter); /** * * @param filter * @return * returns at.wea5.geocaching.webserviceproxy.StatisticDataset */ @WebMethod(operationName = "GetCacheDistributionByCacheDifficulty", action = "http://GeoCaching.Services/GetCacheDistributionByCacheDifficulty") @WebResult(name = "GetCacheDistributionByCacheDifficultyResult", targetNamespace = "http://GeoCaching.Services/") @RequestWrapper(localName = "GetCacheDistributionByCacheDifficulty", targetNamespace = "http://GeoCaching.Services/", className = "at.wea5.geocaching.webserviceproxy.GetCacheDistributionByCacheDifficulty") @ResponseWrapper(localName = "GetCacheDistributionByCacheDifficultyResponse", targetNamespace = "http://GeoCaching.Services/", className = "at.wea5.geocaching.webserviceproxy.GetCacheDistributionByCacheDifficultyResponse") public StatisticDataset getCacheDistributionByCacheDifficulty( @WebParam(name = "filter", targetNamespace = "http://GeoCaching.Services/") DataFilter filter); /** * * @param filter * @return * returns at.wea5.geocaching.webserviceproxy.StatisticDataset */ @WebMethod(operationName = "GetCacheDistributionByTerrainDifficulty", action = "http://GeoCaching.Services/GetCacheDistributionByTerrainDifficulty") @WebResult(name = "GetCacheDistributionByTerrainDifficultyResult", targetNamespace = "http://GeoCaching.Services/") @RequestWrapper(localName = "GetCacheDistributionByTerrainDifficulty", targetNamespace = "http://GeoCaching.Services/", className = "at.wea5.geocaching.webserviceproxy.GetCacheDistributionByTerrainDifficulty") @ResponseWrapper(localName = "GetCacheDistributionByTerrainDifficultyResponse", targetNamespace = "http://GeoCaching.Services/", className = "at.wea5.geocaching.webserviceproxy.GetCacheDistributionByTerrainDifficultyResponse") public StatisticDataset getCacheDistributionByTerrainDifficulty( @WebParam(name = "filter", targetNamespace = "http://GeoCaching.Services/") DataFilter filter); }
package Problem_1914; import java.math.BigInteger; import java.util.Scanner; public class Main { static StringBuilder sb = new StringBuilder(); public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); BigInteger answer = BigInteger.valueOf(2).pow(N).subtract(BigInteger.valueOf(1)); System.out.println(answer.toString()); if(N <= 20) { getRoute(N,"1","2","3"); System.out.print(sb.toString()); } sc.close(); } public static void getRoute(int N, String from, String temp, String to) { if(N == 1) { sb.append(from).append(" ").append(to).append("\n"); return; } getRoute(N-1, from, to, temp); sb.append(from).append(" ").append(to).append("\n"); getRoute(N-1, temp, from, to); } }
package vape.springmvc.dao; import java.util.List; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import vape.springmvc.entity.ProductosPrecio;; @Repository public class ProductosPrecioDAOImpl implements ProductosPrecioDAO { @Autowired private SessionFactory sessionFactory; @Override public List<ProductosPrecio> getProductosPrecio(){ Session session = sessionFactory.getCurrentSession(); CriteriaBuilder cb = session.getCriteriaBuilder(); CriteriaQuery < ProductosPrecio > cq = cb.createQuery(ProductosPrecio.class); Root < ProductosPrecio > root = cq.from(ProductosPrecio.class); CriteriaQuery<ProductosPrecio> all = cq.select(root); TypedQuery<ProductosPrecio> allQuery = session.createQuery(all); return allQuery.getResultList(); } }
package com.ahuo.personapp.base; /** * Created on 17-5-10 * * @author liuhuijie */ public interface IBaseView { }
package ivankar.parking.ui.console.actions; import ivankar.parking.facade.ParkingFacade; import ivankar.parking.domain.Invoice; import ivankar.parking.exceptions.NoSuchTicketException; import java.io.PrintStream; /** * Action to perform when client leaves parking. * <p> * Created by Ivan_Kar on 10/19/2016. */ public class CheckOutAction implements Action { private ParkingFacade parkingFacade; private PrintStream out; public CheckOutAction(PrintStream out, ParkingFacade parkingFacade) { this.out = out; this.parkingFacade = parkingFacade; } @Override public void handle(final String args) { try { Invoice invoice = parkingFacade.checkOut(args); out.println("Parking fee: '" + invoice.getAmount() + "'"); out.println("Parking duration: " + invoice.getDuration().toMinutes() + " minute(s)"); } catch (NoSuchTicketException e) { out.println("Can't find provided ticket"); } } @Override public String getDescription() { return "Performs checkout from parking, sample: checkout 7c89de2d-2693-4d09-9f81-814a417da427"; } }
package in.msmartpay.agent.busBooking.reportActivityExpand; import java.util.ArrayList; /** * Created by Smartkinda on 7/28/2017. */ public class GroupInfo { String TransactionId; String BookedDateTime; String TicketStatus; private ArrayList<ChildInfo> list = new ArrayList<ChildInfo>(); //========================================================================= public String getTransactionId() { return TransactionId; } public void setTransactionId(String transactionId) { TransactionId = transactionId; } public String getBookedDateTime() { return BookedDateTime; } public void setBookedDateTime(String bookedDateTime) { BookedDateTime = bookedDateTime; } public String getTicketStatus() { return TicketStatus; } public void setTicketStatus(String ticketStatus) { TicketStatus = ticketStatus; } public ArrayList<ChildInfo> getList() { return list; } public void setList(ArrayList<ChildInfo> list) { this.list = list; } }
package common.snake; import java.io.Serializable; import java.util.List; /** * @author korektur * 26/03/16 */ public class Board implements Serializable { private final int version; private final List<Snake> snakes; private final Apple apple; public Board(Apple apple, List<Snake> snakes, int version) { this.apple = apple; this.snakes = snakes; this.version = version; } public Apple getApple() { return apple; } public List<Snake> getSnakes() { return snakes; } @Override public String toString() { return "Board{" + "version=" + version + ", snakes=" + snakes + ", apple=" + apple + '}'; } }
package com.test.trejo.jesus.grabilitytest.View; /** * Created by jesus on 27/03/17. */ import android.content.Context; import android.os.Bundle; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.test.trejo.jesus.grabilitytest.Helper.OnFragmentSwap; import com.test.trejo.jesus.grabilitytest.Model.Movie; import com.test.trejo.jesus.grabilitytest.R; import java.util.List; import static com.test.trejo.jesus.grabilitytest.R.layout.list_item_movie; /** * Adapter para mostrar la lista de peliculas */ public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MovieViewHolder> { private List<Movie> movies; private int rowLayout; private Context context; private OnFragmentSwap mCallBack; public List<Movie> getMovies() { return movies; } /** * Clase MovieViewHolder, aca se declaran los elmentos que seran mostrados * en cada fila */ public static class MovieViewHolder extends RecyclerView.ViewHolder { LinearLayout moviesLayout; TextView movieTitle; TextView data; TextView movieDescription; TextView rating; /** * Se asignan a los campos de la vista sus valores reales * @param v recibe la Vista */ public MovieViewHolder(View v) { super(v); moviesLayout = (LinearLayout) v.findViewById(R.id.movies_layout); movieTitle = (TextView) v.findViewById(R.id.title); data = (TextView) v.findViewById(R.id.subtitle); movieDescription = (TextView) v.findViewById(R.id.description); rating = (TextView) v.findViewById(R.id.rating); } } /** * Constructor de la clase MoviesAdapter * @param movies Recibe la lista de peliculas que seran mostradas * @param rowLayout * @param context * @param mCallBack */ public MoviesAdapter(List<Movie> movies, int rowLayout, Context context, OnFragmentSwap mCallBack) { this.movies = movies; this.rowLayout = rowLayout; this.context = context; this.mCallBack = mCallBack; } @Override public MoviesAdapter.MovieViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(list_item_movie, parent, false); return new MovieViewHolder(view); } /** * Metodo Que se ejecuta Cada vez que es asignada una fila * Se utiliza para realizar el Listener del click en la fila * @param holder * @param position */ @Override public void onBindViewHolder(MovieViewHolder holder, final int position) { holder.movieTitle.setText(movies.get(position).getTitle()); holder.data.setText(movies.get(position).getReleaseDate()); holder.movieDescription.setText(movies.get(position).getOverview()); holder.rating.setText(movies.get(position).getVoteAverage().toString()); holder.moviesLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int id = movies.get(position).getId(); Bundle bundle = new Bundle(); bundle.putInt("movieId",id); mCallBack.onSwap("Detail",bundle); } }); } @Override public int getItemCount() { return movies.size(); } }
package com.esum.framework.util; import java.util.Timer; import java.util.TimerTask; public class TimeoutTaskTest extends TimerTask { private Thread task; private Timer timer; public TimeoutTaskTest() { } public void call(final Runnable t, long timeout) throws Exception { task = new Thread(t, "test"); task.setDaemon(true); task.start(); timer = new Timer(); timer.schedule(this, timeout, timeout); waitForFinish(); } private void waitForFinish() throws Exception { while(!Thread.interrupted()) { if(task!=null && task.isAlive()) { Thread.sleep(1000); System.out.println("Waiting task will be completed."); } else { break; } } timer.cancel(); } @Override public void run() { if(task!=null) task.interrupt(); timer.cancel(); System.out.println("Timeout."); task = null; } public static void main(String[] args) throws Exception { new TimeoutTaskTest().call(new Runnable() { @Override public void run() { System.out.println("hello."); // try { // Thread.sleep(10000); // } catch (InterruptedException e) { // } } }, 5000); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package pbo3.pkg10117089.latihan19.saldo; /** * * @author a * NAMA : Shendi Permana * Kelas : PBO3 * NIM : 10117089 * Deskripsi Program : Program ini berisi program untuk menampilkan * saldo tabungan selama 6 bulan */ public class PBO310117089Latihan19Saldo { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here int saldoAwal,bulan,bunga; saldoAwal = 2500000; for(bulan=0; bulan<=6; bulan++){ bunga = saldoAwal*15/100; if (bulan != 0) System.out.println("Saldo di bulan ke-" + bulan + " Rp. " + saldoAwal+"\n"); saldoAwal+=bunga; } System.out.println("Developed by : Shendi Permana"); System.out.println("===========A.Doyen==========="); } }
package demo.service; import demo.domain.ItemInfo; import java.util.List; public interface ItemService { List<ItemInfo> showMenu(String restaurantId); List<ItemInfo> saveMenu(List<ItemInfo> itemList); void deleteall(); }
package algorithms.sorting.heap; import algorithms.sorting.Sort; import algorithms.sorting.SortTest; /** * Created by Chen Li on 2018/2/6. */ public class HeapSortTest extends SortTest { @Override protected Sort newInstance() { return new HeapSortFactory().defaultHeapSort(); } }
/** * */ package com.PIM.persistence; import com.PIM.API.Product; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; /** * @author Henrik Lundin * */ public class ProductPersistenceService implements IProductPersistenceService { @Override public void CreateProduct(Product product) { HibernateUtils.saveAndCommit(product); } }
package com.bofsoft.laio.customerservice.DataClass.Order; import com.bofsoft.laio.data.BaseData; /** * 培训产品时间段Data * * @author yedong */ public class TrainProTimesData extends BaseData implements Comparable<TrainProTimesData> { /** * */ private static final long serialVersionUID = 1L; public int Id; // Integer 时间点ID,即产品Id public String GUID; // String // 投放批次GUID,在购买选择学时时,只有GUID相同的才能一起购买,且如果是多个学时学时必须连续。 public String Name; // String 时间点,如:7:00~8:00 public int SpecId; // Integer 培训产品规格ID,区分不同规格的产品,同一规格的产品价格体系一样,即可执行相同套餐价格。 public int TimeSpace; // 间隔时长,单位分钟,默认为0 @Override public int compareTo(TrainProTimesData another) { return Name.compareTo(another.Name); } }
package com.example.liuyafei.iforgettheumbrella.getweather; import android.content.Context; import android.database.Cursor; import android.util.Log; import com.example.liuyafei.iforgettheumbrella.TestVarables; import junit.framework.Test; import org.w3c.dom.Element; /** * Created by liuyafei on 9/7/15. */ public class WeatherOfToday { WeatherOpenHelper weatherOpenHelper; Cursor cursor; private String TAG = "WeatherOfToday"; private String city_id; private String city_name; private String city_coord_lon; private String city_coord_lat; private String city_country; private String city_sun_rise; private String city_sun_set; private String temperature_value; private String temperature_min; private String temperature_max; private String temperature_unit; private String humidity_value; private String humidity_unit; private String pressure_value; private String pressure_unit; private String wind_speed_value; public String getCity_id() { return city_id; } public String getCity_name() { return city_name; } public String getCity_coord_lon() { return city_coord_lon; } public String getCity_coord_lat() { return city_coord_lat; } public String getCity_country() { return city_country; } public String getCity_sun_rise() { return city_sun_rise; } public String getCity_sun_set() { return city_sun_set; } public String getTemperature_value() { return temperature_value; } public String getTemperature_min() { return temperature_min; } public String getTemperature_max() { return temperature_max; } public String getTemperature_unit() { return temperature_unit; } public String getHumidity_value() { return humidity_value; } public String getHumidity_unit() { return humidity_unit; } public String getPressure_value() { return pressure_value; } public String getPressure_unit() { return pressure_unit; } public String getWind_speed_value() { return wind_speed_value; } public String getWind_speed_name() { return wind_speed_name; } public String getWind_direction_value() { return wind_direction_value; } public String getWind_direction_code() { return wind_direction_code; } public String getWind_direction_name() { return wind_direction_name; } public String getClouds_value() { return clouds_value; } public String getClouds_name() { return clouds_name; } public String getVisibility_value() { return visibility_value; } public String getPrecipitation_value() { return precipitation_value; } public String getPrecipitation_mode() { return precipitation_mode; } public String getWeather_number() { return weather_number; } public String getWeather_value() { return weather_value; } public String getWeather_icon() { return weather_icon; } public String getLastupdate_value() { return lastupdate_value; } private String wind_speed_name; private String wind_direction_value; private String wind_direction_code; private String wind_direction_name; private String clouds_value; private String clouds_name; private String visibility_value; private String precipitation_value; private String precipitation_mode; private String weather_number; private String weather_value; private String weather_icon; private String lastupdate_value; public WeatherOfToday(Context context, int index){ weatherOpenHelper = new WeatherOpenHelper(context); cursor = weatherOpenHelper.getReadableDatabase().rawQuery("SELECT " + "CITY_ID," + "CITY_NAME," + "CITY_COORD_LON," + "CITY_COORD_LAT," + "CITY_COUNTRY," + "CITY_SUN_RISE," + "CITY_SUN_SET," + "TEMPERATURE_VALUE," + "TEMPERATURE_MIN," + "TEMPERATURE_MAX," + "TEMPERATURE_UNIT," + "HUMIDITY_VALUE," + "HUMIDITY_UNIT," + "PRESSURE_VALUE," + "PRESSURE_UNIT," + "WIND_SPEED_VALUE," + "WIND_SPEED_NAME," + "WIND_DIRECTION_VALUE," + "WIND_DIRECTION_CODE," + "WIND_DIRECTION_NAME," + "CLOUDS_VALUE," + "CLOUDS_NAME," + "VISIBILITY_VALUE," + "PRECIPITATION_VALUE," + "PRECIPITATION_MODE," + "WEATHER_NUMBER," + "WEATHER_VALUE," + "WEATHER_ICON," + "LASTUPDATE_VALUE" + " FROM TODAY WHERE _ID =" + "\"" + (index+1) + "\"", null); Log.i(TAG,""+index); cursor.moveToFirst(); city_id=cursor.getString(cursor.getColumnIndex("CITY_ID")); city_name=cursor.getString(cursor.getColumnIndex("CITY_NAME")); city_coord_lon=cursor.getString(cursor.getColumnIndex("CITY_COORD_LON")); city_coord_lat=cursor.getString(cursor.getColumnIndex("CITY_COORD_LAT")); city_country=cursor.getString(cursor.getColumnIndex("CITY_COUNTRY")); city_sun_rise=cursor.getString(cursor.getColumnIndex("CITY_SUN_RISE")); city_sun_set=cursor.getString(cursor.getColumnIndex("CITY_SUN_SET")); temperature_value=cursor.getString(cursor.getColumnIndex("TEMPERATURE_VALUE")); temperature_min=cursor.getString(cursor.getColumnIndex("TEMPERATURE_MIN")); temperature_max=cursor.getString(cursor.getColumnIndex("TEMPERATURE_MAX")); temperature_unit=cursor.getString(cursor.getColumnIndex("TEMPERATURE_UNIT")); humidity_value=cursor.getString(cursor.getColumnIndex("HUMIDITY_VALUE")); humidity_unit=cursor.getString(cursor.getColumnIndex("HUMIDITY_UNIT")); pressure_value=cursor.getString(cursor.getColumnIndex("PRESSURE_VALUE")); pressure_unit=cursor.getString(cursor.getColumnIndex("PRESSURE_UNIT")); wind_speed_value=cursor.getString(cursor.getColumnIndex("WIND_SPEED_VALUE")); wind_speed_name=cursor.getString(cursor.getColumnIndex("WIND_SPEED_NAME")); wind_direction_value=cursor.getString(cursor.getColumnIndex("WIND_DIRECTION_VALUE")); wind_direction_code=cursor.getString(cursor.getColumnIndex("WIND_DIRECTION_CODE")); wind_direction_name=cursor.getString(cursor.getColumnIndex("WIND_DIRECTION_NAME")); clouds_value=cursor.getString(cursor.getColumnIndex("CLOUDS_VALUE")); clouds_name=cursor.getString(cursor.getColumnIndex("CLOUDS_NAME")); visibility_value=cursor.getString(cursor.getColumnIndex("VISIBILITY_VALUE")); precipitation_value=cursor.getString(cursor.getColumnIndex("PRECIPITATION_VALUE")); precipitation_mode=cursor.getString(cursor.getColumnIndex("PRECIPITATION_MODE")); weather_number=cursor.getString(cursor.getColumnIndex("WEATHER_NUMBER")); weather_value=cursor.getString(cursor.getColumnIndex("WEATHER_VALUE")); weather_icon=cursor.getString(cursor.getColumnIndex("WEATHER_ICON")); lastupdate_value=cursor.getString(cursor.getColumnIndex("LASTUPDATE_VALUE")); } public WeatherOfToday(Context context, Element root){ weatherOpenHelper = new WeatherOpenHelper(context); city_id = getElementAttr(root,"city","id"); city_name = getElementAttr(root,"city","name"); city_coord_lon = getElementAttr(root,"coord","lon"); city_coord_lat = getElementAttr(root,"coord","lat"); Element temp = (Element)root.getElementsByTagName("country").item(0); city_country = temp.getFirstChild().getNodeValue(); city_sun_rise = getElementAttr(root,"sun","rise"); city_sun_set = getElementAttr(root,"sun","set"); temperature_value = getElementAttr(root,"temperature","value"); temperature_min = getElementAttr(root,"temperature","min"); temperature_max = getElementAttr(root,"temperature","max"); temperature_unit = getElementAttr(root,"temperature","unit"); humidity_value = getElementAttr(root,"humidity","value"); humidity_unit = getElementAttr(root,"humidity","unit"); pressure_value = getElementAttr(root,"pressure","value"); pressure_unit = getElementAttr(root,"pressure","unit"); wind_speed_value = getElementAttr(root,"speed","value"); wind_speed_name = getElementAttr(root,"speed","name"); wind_direction_value = getElementAttr(root,"direction","value"); wind_direction_code = getElementAttr(root,"direction","code"); wind_direction_name = getElementAttr(root,"direction","name"); clouds_value = getElementAttr(root,"clouds","value"); clouds_name = getElementAttr(root,"clouds","name"); visibility_value = getElementAttr(root,"visibility","value"); precipitation_value = getElementAttr(root,"precipitation","value"); precipitation_mode = getElementAttr(root,"precipitation","mode"); weather_number = getElementAttr(root,"weather","number"); weather_value = getElementAttr(root,"weather","value"); weather_icon = getElementAttr(root,"weather","icon"); lastupdate_value = getElementAttr(root,"lastupdate","value"); } String getElementAttr(Element root,String element,String attr){ if(root.getElementsByTagName(element).getLength()>1) Log.i(TAG,"bad"); Element temp = (Element)root.getElementsByTagName(element).item(0); return temp.getAttribute(attr); } public void print(){ Log.i(TAG,"city_id:"+city_id ); Log.i(TAG,"city_name:"+city_name ); Log.i(TAG,"city_coord_lon:"+city_coord_lon ); Log.i(TAG,"city_coord_lat:"+city_coord_lat ); Log.i(TAG,"city_country:"+city_country ); Log.i(TAG,"city_sun_rise:"+city_sun_rise ); Log.i(TAG,"city_sun_set:"+city_sun_set ); Log.i(TAG,"temperature_value:"+temperature_value ); Log.i(TAG,"temperature_min:"+temperature_min ); Log.i(TAG,"temperature_max:"+temperature_max ); Log.i(TAG,"temperature_unit:"+temperature_unit ); Log.i(TAG,"humidity_value:"+humidity_value ); Log.i(TAG,"humidity_unit:"+humidity_unit ); Log.i(TAG,"pressure_value:"+pressure_value ); Log.i(TAG,"pressure_unit:"+pressure_unit ); Log.i(TAG,"wind_speed_value:"+wind_speed_value ); Log.i(TAG,"wind_speed_name:"+wind_speed_name ); Log.i(TAG,"wind_direction_value:"+wind_direction_value ); Log.i(TAG,"wind_direction_code:"+wind_direction_code ); Log.i(TAG,"wind_direction_name:"+wind_direction_name ); Log.i(TAG,"clouds_value:"+clouds_value ); Log.i(TAG,"clouds_name:"+clouds_name ); Log.i(TAG,"visibility_value:"+visibility_value ); Log.i(TAG,"precipitation_value:"+precipitation_value ); Log.i(TAG,"precipitation_mode:"+precipitation_mode ); Log.i(TAG,"weather_number:"+weather_number ); Log.i(TAG,"weather_value:"+weather_value ); Log.i(TAG,"weather_icon:"+weather_icon ); Log.i(TAG,"lastupdate_value:"+lastupdate_value ); } public void writeToDB(int id){ Log.i(TAG,"writeToDB"); weatherOpenHelper.getWritableDatabase().execSQL("UPDATE TODAY SET " + "CITY_ID = \""+ city_id +"\","+ "CITY_NAME = \""+ city_name +"\","+ "CITY_COORD_LON = \""+ city_coord_lon +"\","+ "CITY_COORD_LAT = \""+ city_coord_lat +"\","+ "CITY_COUNTRY = \""+ city_country +"\","+ "CITY_SUN_RISE = \""+ city_sun_rise +"\","+ "CITY_SUN_SET = \""+ city_sun_set +"\","+ "TEMPERATURE_VALUE = \""+ temperature_value +"\","+ "TEMPERATURE_MIN = \""+ temperature_min +"\","+ "TEMPERATURE_MAX = \""+ temperature_max +"\","+ "TEMPERATURE_UNIT = \""+ temperature_unit +"\","+ "HUMIDITY_VALUE = \""+ humidity_value +"\","+ "HUMIDITY_UNIT = \""+ humidity_unit +"\","+ "PRESSURE_VALUE = \""+ pressure_value +"\","+ "PRESSURE_UNIT = \""+ pressure_unit +"\","+ "WIND_SPEED_VALUE = \""+ wind_speed_value +"\","+ "WIND_SPEED_NAME = \""+ wind_speed_name +"\","+ "WIND_DIRECTION_VALUE = \""+ wind_direction_value +"\","+ "WIND_DIRECTION_CODE = \""+ wind_direction_code +"\","+ "WIND_DIRECTION_NAME = \""+ wind_direction_name +"\","+ "CLOUDS_VALUE = \""+ clouds_value +"\","+ "CLOUDS_NAME = \""+ clouds_name +"\","+ "VISIBILITY_VALUE = \""+ visibility_value +"\","+ "PRECIPITATION_VALUE = \""+ precipitation_value +"\","+ "PRECIPITATION_MODE = \""+ precipitation_mode +"\","+ "WEATHER_NUMBER = \""+ weather_number +"\","+ "WEATHER_VALUE = \""+ weather_value +"\","+ "WEATHER_ICON = \""+ weather_icon +"\","+ "LASTUPDATE_VALUE = \""+ lastupdate_value +"\""+ " WHERE _ID ="+"\""+id+"\""); } }
import java.awt.Color; /** * Cette classe représente une couleur RVB * NB : les composantes sont des réels de 0.0 (noir) à 1.0 (blanc) * au cours des calculs, les valeurs peuvent dépasser ces limites * mais au moment de l'affichage sur écran, elles seront tronquées, * voir la méthode clamp. */ public class Couleur { // composantes de couleur protected float r,v,b; // 0.0 (noir) à 1.0 (valeur max) /** * constructeur par défaut */ public Couleur() { this(0.0f, 0.0f, 0.0f); } /** * constructeur * @param r * @param v * @param b */ public Couleur(float r, float v, float b) { this.r = r; this.v = v; this.b = b; } public Couleur(double r, double v, double b) { this.r = (float) r; this.v = (float) v; this.b = (float) b; } /** * constructeur à partir d'un vecteur * @param v */ public Couleur(Vecteur v) { this.r = (v.x+1.0f)/2.0f; this.v = (v.y+1.0f)/2.0f; this.b = (v.z+1.0f)/2.0f; } /** * constructeur à partir d'un seul float * @param v */ public Couleur(float g) { this.r = g; this.v = g; this.b = g; } /** * retourne une représentation affichable * @return */ public String toString() { return "Couleur("+r+","+v+","+b+")"; } /** * calcule c1+c2 * @param c1 * @param c2 * @return */ public static Couleur add(final Couleur c1, final Couleur c2) { return new Couleur(c1.r + c2.r, c1.v + c2.v, c1.b + c2.b); } /** * retourne this + c * @param c */ public Couleur add(final Couleur c) { return new Couleur(this.r + c.r, this.v + c.v, this.b + c.b); } /** * calcule c1*c2 * @param c1 * @param c2 * @return */ public static Couleur mul(final Couleur c1, final Couleur c2) { return new Couleur(c1.r * c2.r, c1.v * c2.v, c1.b * c2.b); } /** * calcule c*k * @param c * @param k * @return */ public static Couleur mul(final Couleur c, float k) { return new Couleur(c.r * k, c.v * k, c.b * k); } public static Couleur mul(float k, final Couleur c) { return new Couleur(c.r * k, c.v * k, c.b * k); } /** * retourne this * k * @param k */ public Couleur mul(float k) { return new Couleur(this.r * k, this.v * k, this.b * k); } /** * retourne this * c * @param c2 */ public Couleur mul(Couleur c) { return new Couleur(this.r * c.r, this.v * c.v, this.b * c.b); } /** * retourne this / k * @param k */ public Couleur div(float k) { return new Couleur(this.r / k, this.v / k, this.b / k); } /** * applique une correction pour améliorer le rendu des teintes sombres * @param gamma */ public Couleur correctionGamma(float gamma) { gamma = (float) Math.pow(gamma, 0.8); return mul(gamma); } /** * force val dans la plage [min,max] * @param val * @param min * @param max * @return */ private static float clamp(float val, float min, float max) { if (val < min) return min; if (val > max) return max; return val; } /** * retourne le code couleur pour l'affichage dans un BufferedImage * @return */ public int getCode() { return new Color(clamp(r, 0.0f, 1.0f), clamp(v, 0.0f, 1.0f), clamp(b, 0.0f, 1.0f)).getRGB(); } }
package com.hardcoded.plugin.tracer; import java.awt.Color; import java.util.*; import com.hardcoded.plugin.ScrapMechanicPlugin; import ghidra.program.model.address.Address; import ghidra.program.model.listing.*; /** * The bookmark system that ghidra provides can be used to label all the data * that we need to keep track of. * * <p>This class is a simplified implementation of the build in BookmarkManager * that will store important pointers. * * @author HardCoded */ public class ScrapMechanicBookmarkManager { private static final String BOOKMARK_TYPE = "ScrapMechanicTracerAnalysis"; private final ScrapMechanicPlugin plugin; public ScrapMechanicBookmarkManager(ScrapMechanicPlugin tool) { plugin = tool; } public List<Bookmark> getBookmarks(BookmarkCategory category) { Program program = plugin.getCurrentProgram(); if(program == null) return Collections.emptyList(); BookmarkManager manager = program.getBookmarkManager(); if(manager == null) return Collections.emptyList(); BookmarkType type = getBookmarkType(manager); List<Bookmark> list = new ArrayList<>(); Iterator<Bookmark> iter = manager.getBookmarksIterator(type.getTypeString()); while(iter.hasNext()) { Bookmark bookmark = iter.next(); if(bookmark.getCategory().equals(category.name)) { list.add(bookmark); } } return list; } public Bookmark getBookmarkFromAddress(Address address, BookmarkCategory category) { return getBookmarkFromAddress(address == null ? null:address.toString(), category); } public Bookmark getBookmarkFromAddress(String address, BookmarkCategory category) { List<Bookmark> list = getBookmarks(category); for(Bookmark bookmark : list) { String string = bookmark.getAddress().toString(); if(string.equals(address)) { return bookmark; } } return null; } public void addBookmark(Address address, BookmarkCategory category, String description) { Program program = plugin.getCurrentProgram(); if(program == null) return; BookmarkManager manager = program.getBookmarkManager(); if(manager == null) return; BookmarkType type = getBookmarkType(manager); manager.setBookmark(address, type.getTypeString(), category.name, description); } private BookmarkType getBookmarkType(BookmarkManager manager) { BookmarkType type = manager.getBookmarkType(BOOKMARK_TYPE); if(type == null || type.getIcon() == null) { type = manager.defineType(BOOKMARK_TYPE, plugin.icon_16, Color.CYAN, 0); } return type; } public boolean hasBookmarks() { Program program = plugin.getCurrentProgram(); if(program == null) return false; BookmarkManager manager = program.getBookmarkManager(); if(manager == null) return false; BookmarkType type = getBookmarkType(manager); return manager.hasBookmarks(type.getTypeString()); } public boolean clearBookmarks() { Program program = plugin.getCurrentProgram(); if(program == null) return false; BookmarkManager manager = program.getBookmarkManager(); if(manager == null) return false; int transactionId = program.startTransaction("ScrapMechanicPlugin - ResetScanData"); BookmarkType type = getBookmarkType(manager); manager.removeBookmarks(type.getTypeString()); program.endTransaction(transactionId, true); return true; } public static enum BookmarkCategory { DEFINING_FUNCTION("Defining Function"), STRING_POINTER("String Pointer"), TABLE_ELEMENT("Table Function"), LUA_TYPE("Lua Type"); public final String name; private BookmarkCategory(String name) { this.name = name; } } }
package excepciones; import java.io.FileNotFoundException; /* * Excepci�n lanzada cuando se pide cargar un nivel que no existe */ public class NivelNoEncontradoException extends FileNotFoundException { private static final long serialVersionUID = 1L; @SuppressWarnings("unused") private String mensaje; public NivelNoEncontradoException() { } public NivelNoEncontradoException(String mensaje) { this.mensaje = mensaje; } }
package com.mmc.design.load; /** * @packageName:com.mmc.design.load * @desrciption: * @author: gaowei * @date: 2018-10-24 15:17 * @history: (version) author date desc */ public class Driver { public static String param = "加载静态属性...."; static { System.out.println("加载静态代码块...."); } }
package pkgmain; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.ModuleLayer; import java.lang.Module; import java.util.Optional; import pkgb.BExportHelper; /** * This class cannot be compiled in Eclipse as compiler options --add-exports are needed. * See compile.sh for details. * * But if compilation has taken place outside Eclipse with the script, * the modular JARs can be found in .../mlib * * The Eclipse launch files takes the compiled code from there and can be run in Eclipse. */ public class Main { public static void main(String[] args) throws Exception { Main mymain = new Main(); Module modmain = Main.class.getModule(); // find module modb Optional<Module> optMod = ModuleLayer.boot().findModule("modb"); if (optMod.orElseGet(null) == null) { throw new RuntimeException("Main: Could not find modb"); } Module modb = optMod.get(); // ----------------------------------------------- // Implement the 'addReads modmain=modb' // note that this is caller-sensitive, needs to be done in modmain, i.e. here System.out.println("Main: add reads of " + modmain.getName() + " to " + modb.getName()); modmain.addReads(modb); // ----------------------------------------------- // Ask for the 'addExports modb/pkgb=modmain' // Note that this is caller-sensitive, so we need this to in a class which belongs to module modb // If we would call the addExports from here directly like with: // BExportHelper.class.getModule().addExports("pkgbinternal", modmain); // we would produce a java.lang.IllegalCallerException: module modmain != module modb // So instead we ask the BExportHelper to get access to the internal package pkgbinternal. // For that, Java Compiler and also Runtime option needed first: --add-exports modb/pkgb=modmain BExportHelper.addExports("pkgbinternal", modmain); // ----------------------------------------------- // get an instance of pkgb.B and call its doIt() method Class<?> myinternalBClass = Class.forName("pkgbinternal.InternalB"); Constructor<?> con = myinternalBClass.getDeclaredConstructor(); con.setAccessible(true); Object myInternalB = con.newInstance(); Method m = myInternalB.getClass().getMethod("doIt"); m.setAccessible(true); System.out.println("Main: " + mymain.toString() + ", InternalB: " + m.invoke(myInternalB)); } }
package in.msmartpay.agent.rechargeBillPay; import android.app.Activity; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.location.Location; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import in.msmartpay.agent.R; import in.msmartpay.agent.location.GPSTrackerPresenter; import in.msmartpay.agent.rechargeBillPay.plans.PlansActivity; import in.msmartpay.agent.utility.BaseActivity; import in.msmartpay.agent.utility.HttpURL; import in.msmartpay.agent.utility.Keys; import in.msmartpay.agent.utility.L; import in.msmartpay.agent.utility.Mysingleton; import in.msmartpay.agent.utility.RandomNumber; import in.msmartpay.agent.utility.Util; public class DthRechargeActivity extends BaseActivity implements GPSTrackerPresenter.LocationListener { public static final int REQ_LOCATION_CODE = 9001; private static final String TAG = DthRechargeActivity.class.getSimpleName(); private static final int REQUEST_PLAN = 0212; private LinearLayout linear_proceed_dth; private EditText edit_account_no_dth, edit_amount_dth; private TextView tv_view_plan, tv_view_offer, tv_cust_details, tv_details; private Spinner spinner_oprater_dth; private ProgressDialog pd; private Context context; private String dth_url = HttpURL.RECHARGE_URL; private SharedPreferences sharedPreferences; private String agentID, txn_key = ""; private String operator_code_url = HttpURL.OPERATOR_CODE_URL; private String cust_details_url = HttpURL.PLAN_VIEW; private ArrayList<OperatorListModel> OperatorList = null; private CustomOperatorClass operatorAdaptor; private OperatorListModel listModel = null; private String opcode = null; private GPSTrackerPresenter gpsTrackerPresenter = null; private boolean isTxnClick = false; private boolean isLocationGet = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.dth_recharge_activity); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle("DTH"); overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out); context = DthRechargeActivity.this; gpsTrackerPresenter = new GPSTrackerPresenter(this, this, GPSTrackerPresenter.GPS_IS_ON__OR_OFF_CODE); sharedPreferences = getSharedPreferences("myPrefs", MODE_PRIVATE); txn_key = sharedPreferences.getString("txn-key", null); agentID = sharedPreferences.getString("agentonlyid", null); edit_account_no_dth = findViewById(R.id.edit_account_no_dth); edit_amount_dth = findViewById(R.id.edit_amount_dth); spinner_oprater_dth = findViewById(R.id.spinner_oprater_dth); linear_proceed_dth = (LinearLayout) findViewById(R.id.linear_proceed_dth); tv_view_plan = findViewById(R.id.tv_view_plan); tv_view_offer = findViewById(R.id.tv_view_offer); tv_cust_details = findViewById(R.id.tv_cust_details); tv_details = findViewById(R.id.tv_details); //For OperatorList try { operatorsCodeRequest(); } catch (Exception e) { e.printStackTrace(); } tv_cust_details.setOnClickListener(v -> { if (isConnectionAvailable()) { customerDetailsRequest(); } else { Toast.makeText(context, "No Internet Connection !!!", Toast.LENGTH_SHORT).show(); } }); edit_account_no_dth.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (!TextUtils.isEmpty(s) && s.length() > 5) { if (spinner_oprater_dth.getSelectedItem() != null) tv_view_offer.setVisibility(View.VISIBLE); tv_cust_details.setVisibility(View.VISIBLE); } else { tv_view_offer.setVisibility(View.GONE); tv_cust_details.setVisibility(View.GONE); } } @Override public void afterTextChanged(Editable s) { } }); spinner_oprater_dth.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (position > -1) { listModel = OperatorList.get(position); opcode = listModel.getOpCode(); tv_view_plan.setVisibility(View.VISIBLE); if (!TextUtils.isEmpty(edit_account_no_dth.getText().toString()) && edit_account_no_dth.getText().toString().length() > 5) { tv_view_offer.setVisibility(View.VISIBLE); tv_cust_details.setVisibility(View.VISIBLE); } else { tv_view_offer.setVisibility(View.GONE); tv_cust_details.setVisibility(View.GONE); } } else { tv_view_plan.setVisibility(View.GONE); tv_view_offer.setVisibility(View.GONE); tv_cust_details.setVisibility(View.GONE); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); linear_proceed_dth.setOnClickListener(view -> { if (isConnectionAvailable()) { if (spinner_oprater_dth.getSelectedItem() == null) { Toast.makeText(context, "Select Operator !!!", Toast.LENGTH_SHORT).show(); } else if (TextUtils.isEmpty(edit_account_no_dth.getText().toString().trim()) && edit_account_no_dth.getText().toString().trim().length() < 5) { edit_account_no_dth.requestFocus(); Toast.makeText(context, "Enter Account Number !!!", Toast.LENGTH_SHORT).show(); } else if (TextUtils.isEmpty(edit_amount_dth.getText().toString().trim())) { edit_amount_dth.requestFocus(); Toast.makeText(context, "Enter Amount !!!", Toast.LENGTH_SHORT).show(); } else { startRechargeProcess(); } } else { Toast.makeText(context, "No Internet Connection !!!", Toast.LENGTH_SHORT).show(); } }); tv_view_plan.setOnClickListener(v -> { Intent intent = new Intent(context, PlansActivity.class); intent.putExtra("type", "dth"); intent.putExtra("operator", listModel.getDisplayName()); intent.putExtra("mobile", ""); startActivityForResult(intent, REQUEST_PLAN); }); tv_view_offer.setOnClickListener(v -> { Intent intent = new Intent(context, PlansActivity.class); intent.putExtra("type", "dth"); intent.putExtra("operator", listModel.getDisplayName()); intent.putExtra("mobile", edit_account_no_dth.getText().toString()); startActivityForResult(intent, REQUEST_PLAN); }); } private void startRechargeProcess() { /* if (Util.isPowerSaveMode(context)) { proceedConfirmationDialog(); } else {*/ if (isLocationGet) { proceedConfirmationDialog(); } else { if (!isTxnClick) { isTxnClick = true; gpsTrackerPresenter.checkGpsOnOrNot(GPSTrackerPresenter.GPS_IS_ON__OR_OFF_CODE); } } //} } //===========operatorCodeRequest============== private void operatorsCodeRequest() { pd = ProgressDialog.show(context, "", "Loading. Please wait...", true); pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); pd.setIndeterminate(true); pd.setCancelable(false); pd.show(); try { JSONObject jsonObjectReq = new JSONObject() .put("agent_id", agentID) .put("txn_key", txn_key) .put("service", "dth"); L.m2("url-operators", operator_code_url); L.m2("Request--operators", jsonObjectReq.toString()); JsonObjectRequest jsonrequest = new JsonObjectRequest(Request.Method.POST, operator_code_url, jsonObjectReq, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject data) { pd.dismiss(); L.m2("Response--operators", data.toString()); try { if (data.getString("response-code") != null && (data.getString("response-code").equals("0"))) { L.m2("Response--operators1", data.toString()); JSONArray operatorJsonArray = data.getJSONArray("data"); OperatorList = new ArrayList<>(); for (int i = 0; i < operatorJsonArray.length(); i++) { JSONObject obj = operatorJsonArray.getJSONObject(i); if (obj.getString("Service").equalsIgnoreCase("Dth")) { OperatorListModel operatorListModel = new OperatorListModel(); //operatorListModel.setSubService(obj.getString("SubService")); operatorListModel.setBillFetch(obj.getString("BillFetch")); operatorListModel.setService(obj.getString("Service")); operatorListModel.setOperatorName(obj.getString("OperatorName")); operatorListModel.setDisplayName(obj.getString("DisplayName")); operatorListModel.setOpCode(obj.getString("OpCode")); opcode = obj.getString("OpCode"); /*editor.putString("OpCode",obj.getString("OpCode")); editor.commit();*/ OperatorList.add(operatorListModel); } operatorAdaptor = new CustomOperatorClass(context, OperatorList); spinner_oprater_dth.setAdapter(operatorAdaptor); if (OperatorList.size() == 0) { Toast.makeText(context, "No Operator Available!", Toast.LENGTH_SHORT).show(); } } } else { Toast.makeText(context, data.getString("response-message"), Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { pd.dismiss(); Toast.makeText(context, "Server Error : " + error.toString(), Toast.LENGTH_SHORT).show(); } }); getSocketTimeOut(jsonrequest); Mysingleton.getInstance(context).addToRequsetque(jsonrequest); } catch (Exception exp) { pd.dismiss(); exp.printStackTrace(); } } private void proceedConfirmationDialog() { final Dialog d = new Dialog(context, R.style.Base_Theme_AppCompat_Light_Dialog_Alert); d.setCancelable(false); d.getWindow().requestFeature(Window.FEATURE_NO_TITLE); d.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN); d.setContentView(R.layout.confirmation_dialog); d.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); TextView confirm_mobile, confirm_operator, confirm_amount, tv_cancel, tv_recharge, tv_mobile_dth; confirm_mobile = (TextView) d.findViewById(R.id.confirm_mobile); confirm_operator = (TextView) d.findViewById(R.id.confirm_operator); confirm_amount = (TextView) d.findViewById(R.id.confirm_amount); tv_cancel = (TextView) d.findViewById(R.id.tv_cancel); tv_recharge = (TextView) d.findViewById(R.id.tv_recharge); tv_mobile_dth = (TextView) d.findViewById(R.id.tv_rename); tv_mobile_dth.setText("DTH Number"); confirm_mobile.setText(edit_account_no_dth.getText().toString()); confirm_operator.setText(listModel.getOperatorName()); confirm_amount.setText(edit_amount_dth.getText().toString()); tv_recharge.setOnClickListener(view -> { try { dthRechargeRequest(); d.dismiss(); } catch (Exception e) { e.printStackTrace(); } }); tv_cancel.setOnClickListener(v -> d.cancel()); d.show(); } //===========postpaidRechargeRequest============== private void dthRechargeRequest() { pd = ProgressDialog.show(context, "", "Loading. Please wait...", true); pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); pd.setIndeterminate(true); pd.setCancelable(false); pd.show(); try { JSONObject jsonObjectReq = new JSONObject(); jsonObjectReq.put("agent_id", agentID); jsonObjectReq.put("txn_key", txn_key); jsonObjectReq.put("service", "dth"); jsonObjectReq.put("operator", listModel.getCode()); jsonObjectReq.put("mobile_no", edit_account_no_dth.getText().toString().trim()); jsonObjectReq.put("amount", edit_amount_dth.getText().toString().trim()); jsonObjectReq.put("request_id", RandomNumber.getTranId_14()); jsonObjectReq.put("OpCode", opcode); jsonObjectReq.put("latitude", Util.LoadPrefData(context, getString(R.string.latitude))); jsonObjectReq.put("longitude", Util.LoadPrefData(context, getString(R.string.longitude))); jsonObjectReq.put("ip", Util.getIpAddress(context)); jsonObjectReq.put("power_mode", Util.LoadPrefBoolean(context, Keys.POWER_MODE)); L.m2("url-dth", dth_url); L.m2("Request--dth", jsonObjectReq.toString()); JsonObjectRequest jsonrequest = new JsonObjectRequest(Request.Method.POST, dth_url, jsonObjectReq, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject data) { pd.dismiss(); L.m2("Response--dth", data.toString()); try { if (data.get("response-code") != null && (data.get("response-code").equals("0") || data.get("response-code").equals("1"))) { Intent in = new Intent(context, SuccessDetailActivity.class); in.putExtra("responce", data.get("response-message").toString()); in.putExtra("mobileno", edit_account_no_dth.getText().toString().trim()); in.putExtra("requesttype", "dth"); in.putExtra("operator", listModel.getOperatorName()); in.putExtra("amount", edit_amount_dth.getText().toString().trim()); startActivity(in); finish(); } else if (data.get("Status") != null && data.get("Status").equals("2")) { Toast.makeText(context, data.getString("response-message").toString(), Toast.LENGTH_SHORT).show(); finish(); } else { Toast.makeText(context, "Unable To Process Your Request. Please try later.", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { pd.dismiss(); Toast.makeText(context, "Server Error : " + error.toString(), Toast.LENGTH_SHORT).show(); } }); getSocketTimeOut(jsonrequest); Mysingleton.getInstance(context).addToRequsetque(jsonrequest); } catch (Exception exp) { pd.dismiss(); exp.printStackTrace(); } } private void customerDetailsRequest() { pd = ProgressDialog.show(context, "", "Loading. Please wait...", true); pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); pd.setIndeterminate(true); pd.setCancelable(false); pd.show(); try { JSONObject jsonObjectReq = new JSONObject() .put("agent_id", agentID) .put("txn_key", txn_key) .put("type", "dthinfo") .put("client", HttpURL.CLIENT) .put("operator", listModel.getDisplayName()) .put("mobile", edit_account_no_dth.getText().toString().trim()); L.m2("url-cust", cust_details_url); L.m2("Request--cust", jsonObjectReq.toString()); JsonObjectRequest jsonrequest = new JsonObjectRequest(Request.Method.POST, cust_details_url, jsonObjectReq, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject data) { pd.dismiss(); try { L.m2("Response--cust", data.toString()); if (data.getString("status") != null && (data.getString("status").equals("1"))) { StringBuilder builder = new StringBuilder(); tv_details.setVisibility(View.VISIBLE); JSONArray array = data.getJSONArray("records"); for (int i = 0; i < array.length(); i++) { JSONObject object = array.getJSONObject(i); if (object.has("customerName")) builder.append("Name : " + object.getString("customerName")); if (object.has("status")) builder.append(", Status : " + object.getString("status")); if (object.has("MonthlyRecharge")) builder.append(", Monthly Recharge : " + object.getString("MonthlyRecharge")); if (object.has("lastrechargeamount")) builder.append(", Last Recharge Amount : " + object.getString("lastrechargeamount")); if (object.has("lastrechargedate")) builder.append(", Last Recharge Date : " + object.getString("lastrechargedate")); if (object.has("planname")) builder.append(", Plan Name : " + object.getString("planname")); } tv_details.setText(builder.toString()); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { pd.dismiss(); Toast.makeText(context, "Server Error : " + error.toString(), Toast.LENGTH_SHORT).show(); } }); getSocketTimeOut(jsonrequest); Mysingleton.getInstance(context).addToRequsetque(jsonrequest); } catch (Exception exp) { pd.dismiss(); exp.printStackTrace(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_PLAN && resultCode == RESULT_OK) { if (data != null) { if (data.getStringExtra("price") != null) edit_amount_dth.setText(data.getStringExtra("price")); } } if (requestCode == GPSTrackerPresenter.GPS_IS_ON__OR_OFF_CODE && resultCode == Activity.RESULT_OK) { gpsTrackerPresenter.onStart(); } } //==================================== //--------------------------------------------GPS Tracker-------------------------------------------------------------- @Override public void onLocationFound(Location location) { isLocationGet = true; gpsTrackerPresenter.stopLocationUpdates(); if (isTxnClick) { isTxnClick = false; startRechargeProcess(); } } @Override public void locationError(String msg) { } @Override protected void onStart() { super.onStart(); gpsTrackerPresenter.onStart(); } //--------------------------------------------End GPS Tracker-------------------------------------------------------------- @Override protected void onDestroy() { super.onDestroy(); gpsTrackerPresenter.onPause(); } @Override public void onBackPressed() { super.onBackPressed(); finish(); overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out); } @Override public boolean onSupportNavigateUp() { finish(); overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out); return true; } }
package cttd.database; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.Date; import java.sql.SQLException; public class CallableStatementExample { public static void main(String[] args) throws ClassNotFoundException, SQLException { // Lấy ra kết nối tới cơ sở dữ liệu. Connection connection = ConnectionUtils.getMyConnection(); // Câu lệnh gọi thủ tục (***) String sql = "{ CALL get_employee_info(?, ?, ?, ?, ?) }"; // Tạo một đối tượng CallableStatement. CallableStatement cstm = connection.prepareCall(sql); // Truyền tham số vào hàm (p_Emp_ID) // (Là dấu chấm hỏi thứ 1 trên câu lệnh sql ***) cstm.setInt(1, 10); // Đăng ký nhận giá trị trả về tại dấu hỏi thứ 2 // (v_Emp_No) cstm.registerOutParameter(2, java.sql.Types.VARCHAR); // Đăng ký nhận giá trị trả về tại dấu hỏi thứ 3 // (v_First_Name) cstm.registerOutParameter(3, java.sql.Types.VARCHAR); // Đăng ký nhận giá trị trả về tại dấu hỏi thứ 4 // (v_Last_Name) cstm.registerOutParameter(4, java.sql.Types.VARCHAR); // Đăng ký nhận giá trị trả về tại dấu hỏi thứ 5 // (v_Hire_Date) cstm.registerOutParameter(5, java.sql.Types.DATE); // Thực thi câu lệnh cstm.executeUpdate(); String empNo = cstm.getString(2); String firstName = cstm.getString(3); String lastName = cstm.getString(4); Date hireDate = cstm.getDate(5); System.out.println("Emp No: " + empNo); System.out.println("First Name: " + firstName); System.out.println("Last Name: " + lastName); System.out.println("Hire Date: " + hireDate); } }
package com.yedam.kunho; public class WideTire { public void showInfo() { System.out.println("금호타이어입니다."); } }
package com.trump.auction.back.activity.model; import lombok.Data; import java.io.Serializable; import java.util.Date; /** * 中奖记录 * @author wangbo 2018/1/23. */ @Data public class LotteryRecord implements Serializable { private static final long serialVersionUID = 6638253615104986636L; private Integer id; private String prizeNo; private String prizeName; private String prizePic; private Integer prizeType; private Integer prizeTypeSub; private Integer amount; private Integer userId; private String userName; private String userPhone; private String orderNo; private Date addTime; private Integer buyCoinType; private Integer productId; private String productName; private String productPic; }
package com.human.ex; public class quiz0228_06 { public static void main(String[] args) { //옷 사이즈 java.util.Scanner sc = new java.util.Scanner(System.in); System.out.print(" 나이 입력 : "); int age = Integer.parseInt(sc.nextLine()); System.out.print(" 가슴둘레 입력 : "); int ch = Integer.parseInt(sc.nextLine()); char size; if (age >= 20) { if (ch >= 100) { size = 'L'; } else if (ch < 100 && ch >= 90) { size = 'M'; } else { size = 'S'; } } else { if (ch >= 95) { size = 'L'; } else if (ch < 95 && ch >= 85) { size = 'M'; } else { size = 'S'; } } System.out.println("사이즈는 " + size + " 입니다."); sc.close(); } }
package com.shujie.myorm.core; /**java数据类型和数据库数据类型的转化 * Created by sun on 17-4-12. */ public interface TypeConvertor { /** * 数据库类型转化为java类型 * @param columnType 数据库字段的数据类型 * @return java数据类型 */ String databaseType2JavaType(String columnType); /** * java类型转化为数据库数据类型 * @param javaType java数据类型 * @return 数据库字段的数据类型 */ String JavaType2databaseType(String javaType); }
package com.example.chetanmuliya.studentpanel.activity; import android.content.Context; import android.content.Intent; import android.os.Build; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.example.chetanmuliya.studentpanel.R; import com.example.chetanmuliya.studentpanel.adapter.AttendanceMonthAdapter; import com.example.chetanmuliya.studentpanel.app.ApiClient; import com.example.chetanmuliya.studentpanel.app.ApiInterface; import com.example.chetanmuliya.studentpanel.helper.CustomOnCLickListener; import com.example.chetanmuliya.studentpanel.helper.CustomProgressDialog; import com.example.chetanmuliya.studentpanel.helper.SQLiteLoginHandler; import com.example.chetanmuliya.studentpanel.model.AttendanceMonth; import com.example.chetanmuliya.studentpanel.model.Student; import com.google.gson.Gson; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class AttendanceActivity extends AppCompatActivity { public CustomProgressDialog customProgressDialog; private CustomOnCLickListener customOnCLickListener; Context ctx; RecyclerView attendanceRVList; String username,batch,my; SQLiteLoginHandler db; List<AttendanceMonth> attendanceMonthList; private AttendanceMonthAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_attendance); Toolbar toolbar=(Toolbar)findViewById(R.id.toolbar); toolbar.setTitle("Attendance"); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); db=new SQLiteLoginHandler(getApplicationContext()); List<Student> studentList=db.getStudentdetails(); if(getIntent()!=null){ batch=getIntent().getExtras().getString("selectedBatch"); } username=studentList.get(0).getUsername(); //progress dialog customProgressDialog=new CustomProgressDialog(this); customProgressDialog.showProgressDialog(); customProgressDialog.addMessage("Please wait... loading attendance"); //adapter attendanceMonthList=new ArrayList<>(); attendanceRVList=(RecyclerView)findViewById(R.id.attendanceRV); attendanceRVList.setHasFixedSize(true); attendanceRVList.setLayoutManager(new LinearLayoutManager(this)); fetchAttendance(); } private void fetchAttendance() { ApiInterface services = ApiClient.getClient().create(ApiInterface.class); Log.e("(*****", "batch: "+batch +" username" +username ); Call<List<AttendanceMonth>> call = services.getAttendanceMonth(batch,username); call.enqueue(new Callback<List<AttendanceMonth>>() { @Override public void onResponse(Call<List<AttendanceMonth>> call, Response<List<AttendanceMonth>> response) { customProgressDialog.hideProgressDialog(); if(response == null){ Toast.makeText(getApplicationContext(),"No Attendance Record",Toast.LENGTH_LONG).show(); finish(); return; }else { attendanceMonthList = response.body(); adapter = new AttendanceMonthAdapter(attendanceMonthList, ctx, new CustomOnCLickListener() { @Override public void onCLick(View v, int position) { Intent intent = new Intent(v.getContext(), DetailAttendanceActivity.class); intent.putExtra("my", attendanceMonthList.get(position).getMonth()); intent.putExtra("username", username); intent.putExtra("batch", batch); startActivity(intent); } }); attendanceRVList.setAdapter(adapter); Log.e("****", "onResponse: " + new Gson().toJson(response)); } } @Override public void onFailure(Call<List<AttendanceMonth>> call, Throwable t) { CustomProgressDialog.hideProgressDialog(); Toast.makeText(getApplicationContext(),"FAILED ! to Load attendance",Toast.LENGTH_LONG).show(); t.printStackTrace(); } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case android.R.id.home : onBackPressed(); return true; default: return super.onOptionsItemSelected(item); } } }
package company; /** * Class Employee: abstracts a Company employee * @author Carolyn MacIsaac, with modifications by Dave Houtman - with modifications by Shuting Yang * student number: 040933020 * CST8284 lab Sec304 * Assignment 2: Company Management Tool prototype * March 30 2019 */ public abstract class Employee { // private fields to hold relevant Employee information private String name; // Employee's full name private int employeeNumber; // Employee's work number private OurDate startDate; // Employee's first day of work private double salary; // Employee's current salary // default constructor; uses values that clearly indicate default conditions; // chained to (String, int, OurDate, double) Employee constructor below public Employee() { this("unknown", -9, new OurDate(), -1); } // load constructor using Employee's full name, work number, start date and salary public Employee(String name, int employeeNumber, OurDate startDate, double salary) { setName(name); setEmployeeNumber(employeeNumber); setStartDate(startDate); setSalary(salary); } // return's the Employee's full name as a String public String getName() { return name; } // return's the Employee number, as an int public int getEmployeeNumber() { return employeeNumber; } // return's the Employee's starting date, as an OurDate object public OurDate getStartDate() { return startDate; } // return's the Employee's salary, as a double public double getSalary() { return salary; } // Note: all setters in this class are private; all Employee properties // must be set through the class constructor only public void setName(String name) { this.name = name; } public void setEmployeeNumber(int employeeNumber) { this.employeeNumber = employeeNumber; } public void setStartDate(OurDate startDate) { this.startDate = startDate; } public void setSalary(double salary) { this.salary = salary; } public abstract void loadExtraInfo(); // Display employee information to the console @Override public String toString() { return String.format("%-20s%-20d%-20s%-20.1f",name, employeeNumber,startDate, salary); } // Compare two employees for equality by comparing their relevant properties @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Employee other = (Employee) obj; return (this.getName().equals(other.getName()) && this.getEmployeeNumber() == other.getEmployeeNumber() && this.getStartDate().equals(other.getStartDate())); }//END EQUALS METHOD }//END CLASS EMPLOYEE
/* * Copyright 2002-2021 the original author or authors. * * 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 * * https://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.springframework.jdbc.core.metadata; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.jdbc.core.SqlInOutParameter; import org.springframework.jdbc.core.SqlOutParameter; import org.springframework.jdbc.core.SqlParameter; import org.springframework.lang.Nullable; import org.springframework.util.StringUtils; /** * A generic implementation of the {@link CallMetaDataProvider} interface. * This class can be extended to provide database specific behavior. * * @author Thomas Risberg * @author Juergen Hoeller * @author Sam Brannen * @since 2.5 */ public class GenericCallMetaDataProvider implements CallMetaDataProvider { /** Logger available to subclasses. */ protected static final Log logger = LogFactory.getLog(CallMetaDataProvider.class); private final String userName; private boolean supportsCatalogsInProcedureCalls = true; private boolean supportsSchemasInProcedureCalls = true; private boolean storesUpperCaseIdentifiers = true; private boolean storesLowerCaseIdentifiers = false; private boolean procedureColumnMetaDataUsed = false; private final List<CallParameterMetaData> callParameterMetaData = new ArrayList<>(); /** * Constructor used to initialize with provided database meta-data. * @param databaseMetaData meta-data to be used */ protected GenericCallMetaDataProvider(DatabaseMetaData databaseMetaData) throws SQLException { this.userName = databaseMetaData.getUserName(); } @Override public void initializeWithMetaData(DatabaseMetaData databaseMetaData) throws SQLException { try { setSupportsCatalogsInProcedureCalls(databaseMetaData.supportsCatalogsInProcedureCalls()); } catch (SQLException ex) { if (logger.isWarnEnabled()) { logger.warn("Error retrieving 'DatabaseMetaData.supportsCatalogsInProcedureCalls': " + ex.getMessage()); } } try { setSupportsSchemasInProcedureCalls(databaseMetaData.supportsSchemasInProcedureCalls()); } catch (SQLException ex) { if (logger.isWarnEnabled()) { logger.warn("Error retrieving 'DatabaseMetaData.supportsSchemasInProcedureCalls': " + ex.getMessage()); } } try { setStoresUpperCaseIdentifiers(databaseMetaData.storesUpperCaseIdentifiers()); } catch (SQLException ex) { if (logger.isWarnEnabled()) { logger.warn("Error retrieving 'DatabaseMetaData.storesUpperCaseIdentifiers': " + ex.getMessage()); } } try { setStoresLowerCaseIdentifiers(databaseMetaData.storesLowerCaseIdentifiers()); } catch (SQLException ex) { if (logger.isWarnEnabled()) { logger.warn("Error retrieving 'DatabaseMetaData.storesLowerCaseIdentifiers': " + ex.getMessage()); } } } @Override public void initializeWithProcedureColumnMetaData(DatabaseMetaData databaseMetaData, @Nullable String catalogName, @Nullable String schemaName, @Nullable String procedureName) throws SQLException { this.procedureColumnMetaDataUsed = true; processProcedureColumns(databaseMetaData, catalogName, schemaName, procedureName); } @Override public List<CallParameterMetaData> getCallParameterMetaData() { return this.callParameterMetaData; } @Override @Nullable public String procedureNameToUse(@Nullable String procedureName) { if (procedureName == null) { return null; } else if (isStoresUpperCaseIdentifiers()) { return procedureName.toUpperCase(); } else if (isStoresLowerCaseIdentifiers()) { return procedureName.toLowerCase(); } else { return procedureName; } } @Override @Nullable public String catalogNameToUse(@Nullable String catalogName) { if (catalogName == null) { return null; } else if (isStoresUpperCaseIdentifiers()) { return catalogName.toUpperCase(); } else if (isStoresLowerCaseIdentifiers()) { return catalogName.toLowerCase(); } else { return catalogName; } } @Override @Nullable public String schemaNameToUse(@Nullable String schemaName) { if (schemaName == null) { return null; } else if (isStoresUpperCaseIdentifiers()) { return schemaName.toUpperCase(); } else if (isStoresLowerCaseIdentifiers()) { return schemaName.toLowerCase(); } else { return schemaName; } } @Override @Nullable public String metaDataCatalogNameToUse(@Nullable String catalogName) { if (isSupportsCatalogsInProcedureCalls()) { return catalogNameToUse(catalogName); } else { return null; } } @Override @Nullable public String metaDataSchemaNameToUse(@Nullable String schemaName) { if (isSupportsSchemasInProcedureCalls()) { return schemaNameToUse(schemaName); } else { return null; } } @Override @Nullable public String parameterNameToUse(@Nullable String parameterName) { if (parameterName == null) { return null; } else if (isStoresUpperCaseIdentifiers()) { return parameterName.toUpperCase(); } else if (isStoresLowerCaseIdentifiers()) { return parameterName.toLowerCase(); } else { return parameterName; } } @Override public boolean byPassReturnParameter(String parameterName) { return false; } @Override public SqlParameter createDefaultOutParameter(String parameterName, CallParameterMetaData meta) { return new SqlOutParameter(parameterName, meta.getSqlType()); } @Override public SqlParameter createDefaultInOutParameter(String parameterName, CallParameterMetaData meta) { return new SqlInOutParameter(parameterName, meta.getSqlType()); } @Override public SqlParameter createDefaultInParameter(String parameterName, CallParameterMetaData meta) { return new SqlParameter(parameterName, meta.getSqlType()); } @Override public String getUserName() { return this.userName; } @Override public boolean isReturnResultSetSupported() { return true; } @Override public boolean isRefCursorSupported() { return false; } @Override public int getRefCursorSqlType() { return Types.OTHER; } @Override public boolean isProcedureColumnMetaDataUsed() { return this.procedureColumnMetaDataUsed; } /** * Specify whether the database supports the use of catalog name in procedure calls. */ protected void setSupportsCatalogsInProcedureCalls(boolean supportsCatalogsInProcedureCalls) { this.supportsCatalogsInProcedureCalls = supportsCatalogsInProcedureCalls; } /** * Does the database support the use of catalog name in procedure calls? */ @Override public boolean isSupportsCatalogsInProcedureCalls() { return this.supportsCatalogsInProcedureCalls; } /** * Specify whether the database supports the use of schema name in procedure calls. */ protected void setSupportsSchemasInProcedureCalls(boolean supportsSchemasInProcedureCalls) { this.supportsSchemasInProcedureCalls = supportsSchemasInProcedureCalls; } /** * Does the database support the use of schema name in procedure calls? */ @Override public boolean isSupportsSchemasInProcedureCalls() { return this.supportsSchemasInProcedureCalls; } /** * Specify whether the database uses upper case for identifiers. */ protected void setStoresUpperCaseIdentifiers(boolean storesUpperCaseIdentifiers) { this.storesUpperCaseIdentifiers = storesUpperCaseIdentifiers; } /** * Does the database use upper case for identifiers? */ protected boolean isStoresUpperCaseIdentifiers() { return this.storesUpperCaseIdentifiers; } /** * Specify whether the database uses lower case for identifiers. */ protected void setStoresLowerCaseIdentifiers(boolean storesLowerCaseIdentifiers) { this.storesLowerCaseIdentifiers = storesLowerCaseIdentifiers; } /** * Does the database use lower case for identifiers? */ protected boolean isStoresLowerCaseIdentifiers() { return this.storesLowerCaseIdentifiers; } /** * Process the procedure column meta-data. */ private void processProcedureColumns(DatabaseMetaData databaseMetaData, @Nullable String catalogName, @Nullable String schemaName, @Nullable String procedureName) { String metaDataCatalogName = metaDataCatalogNameToUse(catalogName); String metaDataSchemaName = metaDataSchemaNameToUse(schemaName); String metaDataProcedureName = procedureNameToUse(procedureName); if (logger.isDebugEnabled()) { logger.debug("Retrieving meta-data for " + metaDataCatalogName + '/' + metaDataSchemaName + '/' + metaDataProcedureName); } try { List<String> found = new ArrayList<>(); boolean function = false; try (ResultSet procedures = databaseMetaData.getProcedures( metaDataCatalogName, metaDataSchemaName, metaDataProcedureName)) { while (procedures.next()) { found.add(procedures.getString("PROCEDURE_CAT") + '.' + procedures.getString("PROCEDURE_SCHEM") + '.' + procedures.getString("PROCEDURE_NAME")); } } if (found.isEmpty()) { // Functions not exposed as procedures anymore on PostgreSQL driver 42.2.11 try (ResultSet functions = databaseMetaData.getFunctions( metaDataCatalogName, metaDataSchemaName, metaDataProcedureName)) { while (functions.next()) { found.add(functions.getString("FUNCTION_CAT") + '.' + functions.getString("FUNCTION_SCHEM") + '.' + functions.getString("FUNCTION_NAME")); function = true; } } } if (found.size() > 1) { throw new InvalidDataAccessApiUsageException( "Unable to determine the correct call signature - multiple signatures for '" + metaDataProcedureName + "': found " + found + " " + (function ? "functions" : "procedures")); } else if (found.isEmpty()) { if (metaDataProcedureName != null && metaDataProcedureName.contains(".") && !StringUtils.hasText(metaDataCatalogName)) { String packageName = metaDataProcedureName.substring(0, metaDataProcedureName.indexOf('.')); throw new InvalidDataAccessApiUsageException( "Unable to determine the correct call signature for '" + metaDataProcedureName + "' - package name should be specified separately using '.withCatalogName(\"" + packageName + "\")'"); } else if ("Oracle".equals(databaseMetaData.getDatabaseProductName())) { if (logger.isDebugEnabled()) { logger.debug("Oracle JDBC driver did not return procedure/function/signature for '" + metaDataProcedureName + "' - assuming a non-exposed synonym"); } } else { throw new InvalidDataAccessApiUsageException( "Unable to determine the correct call signature - no " + "procedure/function/signature for '" + metaDataProcedureName + "'"); } } if (logger.isDebugEnabled()) { logger.debug("Retrieving column meta-data for " + (function ? "function" : "procedure") + ' ' + metaDataCatalogName + '/' + metaDataSchemaName + '/' + metaDataProcedureName); } try (ResultSet columns = function ? databaseMetaData.getFunctionColumns(metaDataCatalogName, metaDataSchemaName, metaDataProcedureName, null) : databaseMetaData.getProcedureColumns(metaDataCatalogName, metaDataSchemaName, metaDataProcedureName, null)) { while (columns.next()) { String columnName = columns.getString("COLUMN_NAME"); int columnType = columns.getInt("COLUMN_TYPE"); if (columnName == null && isInOrOutColumn(columnType, function)) { if (logger.isDebugEnabled()) { logger.debug("Skipping meta-data for: " + columnType + " " + columns.getInt("DATA_TYPE") + " " + columns.getString("TYPE_NAME") + " " + columns.getInt("NULLABLE") + " (probably a member of a collection)"); } } else { int nullable = (function ? DatabaseMetaData.functionNullable : DatabaseMetaData.procedureNullable); CallParameterMetaData meta = new CallParameterMetaData(function, columnName, columnType, columns.getInt("DATA_TYPE"), columns.getString("TYPE_NAME"), columns.getInt("NULLABLE") == nullable); this.callParameterMetaData.add(meta); if (logger.isDebugEnabled()) { logger.debug("Retrieved meta-data: " + meta.getParameterName() + " " + meta.getParameterType() + " " + meta.getSqlType() + " " + meta.getTypeName() + " " + meta.isNullable()); } } } } } catch (SQLException ex) { if (logger.isWarnEnabled()) { logger.warn("Error while retrieving meta-data for procedure columns. " + "Consider declaring explicit parameters -- for example, via SimpleJdbcCall#addDeclaredParameter().", ex); } // Although we could invoke `this.callParameterMetaData.clear()` so that // we don't retain a partial list of column names (like we do in // GenericTableMetaDataProvider.processTableColumns(...)), we choose // not to do that here, since invocation of the stored procedure will // likely fail anyway with an incorrect argument list. } } private static boolean isInOrOutColumn(int columnType, boolean function) { if (function) { return (columnType == DatabaseMetaData.functionColumnIn || columnType == DatabaseMetaData.functionColumnInOut || columnType == DatabaseMetaData.functionColumnOut); } else { return (columnType == DatabaseMetaData.procedureColumnIn || columnType == DatabaseMetaData.procedureColumnInOut || columnType == DatabaseMetaData.procedureColumnOut); } } }
package com.tipster.tipster.Json; import android.util.Log; import com.tipster.tipster.Pojo.Rate; import com.tipster.tipster.Pojo.Tip; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; /** * Created by David_tepoche on 29/10/2016. */ public class JsonReader { public List<Tip> GetTipFromString(String param) { List<Tip> Tips = null; try { JSONObject jsonObj = new JSONObject(param); Tips = new ArrayList<>(); // Getting JSON Array node JSONArray jsontip = jsonObj.getJSONArray("Tip"); // looping through All Contacts for (int i = 0; i < jsontip.length(); i++) { JSONObject t = jsontip.getJSONObject(i); int ID = t.getInt("-ID"); String title = t.getString("title"); String author = t.getString("author"); String date = t.getString("date"); //on descend dans le noeud rate JSONObject r = t.getJSONObject("rate"); int good = r.getInt("good"); int bad = r.getInt("bad"); String message = t.getString("message"); Rate rate = new Rate(good, bad, good + bad); Tip tip = new Tip(ID, title, author, date, rate, message); Tips.add(tip); } } catch (JSONException e) { Log.e("Json/JsonReader", "erreur dans le parsing" + e.getMessage()); } return Tips; } }
package algo3.fiuba.modelo.cartas.nivel; import algo3.fiuba.modelo.cartas.Monstruo; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class UnaACuatroEstrellasTest { private UnaACuatroEstrellas unaACuatroEstrellas; private Monstruo monstruo1; private Monstruo monstruo2; @Before public void setUp() { unaACuatroEstrellas = UnaACuatroEstrellas.getInstancia(); } @Test public void requiere2Sacrificios() { Integer sacrificiosRequeridos = 0; Assert.assertEquals(sacrificiosRequeridos, unaACuatroEstrellas.sacrificiosRequeridos()); } @Test public void sacrificiosSuficientes_exactamente0SacrificiosDevuelveTrue() { Monstruo[] monstruos = {}; Assert.assertTrue(unaACuatroEstrellas.sacrificiosSuficientes(monstruos)); } @Test public void sacrificiosSuficientes_masDe0SacrificiosDevuelveFalse() { Monstruo[] monstruos1 = {monstruo1}; Monstruo[] monstruos2 = {monstruo1, monstruo2}; Assert.assertFalse(unaACuatroEstrellas.sacrificiosSuficientes(monstruos1)); Assert.assertFalse(unaACuatroEstrellas.sacrificiosSuficientes(monstruos2)); } }
package controller; import imageasgraph.GraphOfPixels; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import layeredimage.LayeredImage; import layeredimage.ViewModel; import scriptlanguage.LanguageSyntax; import scriptlanguage.LanguageSyntaxImpl; import scriptlanguage.ParsedCommand; import view.ErrorView.TextErrorView; import view.View; /** * Represents a controller object to execute scripts based on inputs. */ public class ProcessingController implements ImageProcessingController { private final View view; private final Readable input; private final Map<String, GraphOfPixels> singleImages; private final Map<String, LayeredImage> layeredImages; /** * Creates a controller instance using a readable input. * * @param input The Readable input for the program * @param output The Appendable where information is outputted * @throws IllegalArgumentException If any parameters are null */ public ProcessingController(Readable input, Appendable output) throws IllegalArgumentException { if (input == null || output == null) { throw new IllegalArgumentException("One or more inputs are null"); } this.view = new TextErrorView(output); this.input = input; this.singleImages = new HashMap<String, GraphOfPixels>(); this.layeredImages = new HashMap<String, LayeredImage>(); } /** * Creates a controller instance using a String file. * * @param fileInput The String input for the program representing a file * @param output The Appendable where information is outputted * @throws IllegalArgumentException If any parameters are null */ public ProcessingController(String fileInput, Appendable output) throws IllegalArgumentException { if (fileInput == null || output == null) { throw new IllegalArgumentException("One or more inputs are null"); } this.view = new TextErrorView(output); FileReader newScript; try { newScript = new FileReader(fileInput); } catch (FileNotFoundException e) { throw new IllegalArgumentException("File not found"); } this.input = newScript; this.singleImages = new HashMap<String, GraphOfPixels>(); this.layeredImages = new HashMap<String, LayeredImage>(); } /** * Creates a new constructor object. Throws an exception if this kind of controller is run. This * controller is simply acting as a script handler rather than an information medium. * * @param view The interactive or text view for the program * @throws IllegalArgumentException If view is null or if after construction this way, the * controller is run */ public ProcessingController(View view) throws IllegalArgumentException { if (view == null) { throw new IllegalArgumentException("Null view provided"); } this.view = view; this.input = null; this.singleImages = new HashMap<String, GraphOfPixels>(); this.layeredImages = new HashMap<String, LayeredImage>(); } /** * Creates a new constructor object. Throws an exception if this kind of controller is run. This * controller is simply acting as a script handler rather than an information medium. * * @param view The interactive or text view for the program * @throws IllegalArgumentException If view is null or if after construction this way, the * controller is run */ public ProcessingController(View view, Readable in) throws IllegalArgumentException { if (view == null) { throw new IllegalArgumentException("Null view provided"); } this.view = view; this.input = in; this.singleImages = new HashMap<String, GraphOfPixels>(); this.layeredImages = new HashMap<String, LayeredImage>(); } @Override public void run() { this.singleImages.clear(); this.layeredImages.clear(); if (this.input == null) { throw new IllegalArgumentException("Null input, cannot be run this way"); } Scanner scanner = new Scanner(this.input); this.runCommandsFromScanner(scanner); } @Override public ViewModel getReferenceToImage(String imageName) throws IllegalArgumentException { if (imageName == null) { throw new IllegalArgumentException("Null image name given"); } if (!layeredImages.containsKey(imageName)) { throw new IllegalArgumentException("Given image does not exist"); } return this.layeredImages.get(imageName); } @Override public void runCommands(String commands) { if (commands == null) { this.view.renderException("Null command given"); return; } Scanner scanner = new Scanner(commands); this.runCommandsFromScanner(scanner); } @Override public List<String> getLayeredImageNames() { return new ArrayList<String>(this.layeredImages.keySet()); } /** * Given a scanner over a set of input, runs every command contained in that input. * * @param scanner The scanner which is reading the input */ private void runCommandsFromScanner(Scanner scanner) { if (scanner == null) { this.view.renderException("Null scanner given for processing"); return; } LanguageSyntax parser = new LanguageSyntaxImpl(); int counter = 0; while (scanner.hasNext()) { String nextCommand = scanner.nextLine(); if (nextCommand.length() != 0 && nextCommand.charAt(0) != '#') { if (nextCommand.equals("quit")) { this.view.renderException("Image Processor Quit"); return; } try { ParsedCommand toExecute = parser.parseCommand(nextCommand); toExecute.execute(singleImages, layeredImages); toExecute.alterLanguageState(parser); } catch (IllegalArgumentException e) { this.view.renderException("Invalid line " + counter + ": " + e.getMessage() + "\n"); } } counter += 1; } } }
package com.zc.pivas.statistics.controller; import com.zc.base.common.controller.SdBaseController; import com.zc.base.sys.modules.user.entity.User; import com.zc.pivas.drugDamage.service.DrugDamageService; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.util.List; /** * 拆药使用统计 * * @author jagger * @version 1.0 */ @Controller @RequestMapping(value = "/statistics/drugOpenWorkload") public class DrugOpenWorkloadController extends SdBaseController { @Resource private DrugDamageService drugDamageService; @RequestMapping(value = "") public String init(Model model, HttpServletRequest request) throws Exception { // 获取药品标签 List<User> userList = drugDamageService.getAllUsers(); model.addAttribute("userList", userList); return "pivas/statistics/drugOpenWorkload"; } }
import java.util.Scanner; public class sorting { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int arr[]=new int[n]; for(int i=0;i<n;i++) { arr[i]=sc.nextInt(); } int brr[]=new int[n]; for(int i=0;i<n;i++) { brr[i]=count(arr[i]); } for(int i=0;i<n;i++) { for(int j=0;j<n-i-1;j++) { if(brr[j]<brr[j+1]) { int temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; int temp1=brr[j]; brr[j]=brr[j+1]; brr[j+1]=temp1; } } } for(int i=0;i<n;i++) { System.out.print(arr[i]+" "); } } public static int count(int n) { int c=0; while(n!=0&&n!=1) { int b=n%2; if(b==1) { c++; } n=n/2; } if(n==1) { c++; } return c; } }
package SchoolDomain.domain; /** * Created by student on 2015/04/15. */ public class SubjectTest { }
/* * Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.engine.authn; import pl.edu.icm.unity.exceptions.IllegalCredentialException; import pl.edu.icm.unity.server.authn.LocalCredentialVerificator; import pl.edu.icm.unity.server.authn.LocalCredentialVerificatorFactory; import pl.edu.icm.unity.server.registries.LocalCredentialsRegistry; import pl.edu.icm.unity.types.authn.CredentialDefinition; /** * Internal management of {@link CredentialDefinition} with Local credential verifier. Checks * if the local verificator is installed and allows to easily get it. * @author K. Benedyczak */ public class CredentialHolder { private CredentialDefinition credential; private LocalCredentialVerificator handler; public CredentialHolder(CredentialDefinition credDef, LocalCredentialsRegistry reg) throws IllegalCredentialException { checkCredentialDefinition(credDef, reg); credential = credDef; } private void checkCredentialDefinition(CredentialDefinition def, LocalCredentialsRegistry reg) throws IllegalCredentialException { LocalCredentialVerificatorFactory fact = reg.getLocalCredentialFactory(def.getTypeId()); if (fact == null) throw new IllegalCredentialException("The credential type " + def.getTypeId() + " is unknown"); LocalCredentialVerificator handler = fact.newInstance(); handler.setSerializedConfiguration(def.getJsonConfiguration()); this.handler = handler; } public CredentialDefinition getCredentialDefinition() { return credential; } public LocalCredentialVerificator getHandler() { return handler; } }
package kodlama.io.hrms.entities.dtos; import java.util.List; import kodlama.io.hrms.entities.concretes.Experience; import kodlama.io.hrms.entities.concretes.ForeignLanguage; import kodlama.io.hrms.entities.concretes.Image; import kodlama.io.hrms.entities.concretes.JobSeeker; import kodlama.io.hrms.entities.concretes.Link; import kodlama.io.hrms.entities.concretes.School; import kodlama.io.hrms.entities.concretes.Skill; public class CVDto { public JobSeeker jobSeeker; public Image image; public List<School> schools; public List<Link> links; public List<Skill> skills; public List<ForeignLanguage> languages; public List<Experience> experiences; }
package com.atgenghx.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; @Controller public class TestController { @ResponseBody @RequestMapping("/hello") public String hello(){ return "helloworld"; } /** * 2、通过HttpServletRequest接收 * @param request * @return */ @ResponseBody @RequestMapping("/addUser") public void addUser(HttpServletRequest request, HttpServletResponse response)throws IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); //获取请求行的相关信息 out.println("getMethod:" + request.getMethod() + "<br/>"); out.println("getQueryString:" + request.getQueryString() + "<br/>"); out.println("getProtocol:" + request.getProtocol() + "<br/>"); out.println("getContextPath" + request.getContextPath() + "<br/>"); out.println("getPathInfo:" + request.getPathInfo() + "<br/>"); out.println("getPathTranslated:" + request.getPathTranslated() + "<br/>"); out.println("getServletPath:" + request.getServletPath() + "<br/>"); out.println("getRemoteAddr:" + request.getRemoteAddr() + "<br/>"); out.println("getRemoteHost:" + request.getRemoteHost() + "<br/>"); out.println("getRemotePort:" + request.getRemotePort() + "<br/>"); out.println("getLocalAddr:" + request.getLocalAddr() + "<br/>"); out.println("getLocalName:" + request.getLocalName() + "<br/>"); out.println("getLocalPort:" + request.getLocalPort() + "<br/>"); out.println("getServerName:" + request.getServerName() + "<br/>"); out.println("getServerPort:" + request.getServerPort() + "<br/>"); out.println("getScheme:" + request.getScheme() + "<br/>"); out.println("getRequestURL:" + request.getRequestURL() + "<br/>"); } @ResponseBody @RequestMapping("/taskflux_source") public void report(HttpServletRequest request, HttpServletResponse response) throws IOException { StringBuffer url =request.getRequestURL(); System.out.println(url); String part=request.getQueryString(); String[] str=part.split("&"); System.out.println(Arrays.toString(str)); jdbc jd=new jdbc(); jd.report(part); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("return success"); } @ResponseBody @CrossOrigin @RequestMapping("/selecttaskflux_source") public void slereport(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException { jdbc jd=new jdbc(); ArrayList<String> arr= jd.douyinurl(); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println(arr.toString()); } }
package collection; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class HashSetDemo { public static void main(String[] args) { final int size = 1000; final int bound = 100; Set<Long> set = new HashSet(); for (int i = 0; i < size; i++) { set.add(Math.round(Math.random() * bound)); } Iterator<Long> iter = set.iterator(); for (int i = 0; i < 20 && iter.hasNext(); i++) { System.out.println(iter.next()); } System.out.println("...."); System.out.println(set.size() + " distinct numbers."); } }
package com.lenovohit.hcp.pharmacy.model; import java.math.BigDecimal; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Transient; import org.hibernate.annotations.NotFound; import org.hibernate.annotations.NotFoundAction; import com.lenovohit.hcp.base.annotation.RedisSequence; import com.lenovohit.hcp.base.model.Company; import com.lenovohit.hcp.base.model.HcpBaseModel; @Entity @Table(name = "PHA_DRUGINFO") // 药房药库 - 药品信息表 public class PhaDrugInfo extends HcpBaseModel { /** * @Author xlbd */ private static final long serialVersionUID = 1L; private String drugCode; // 药品编码 private String centerCode; // 中心药品编码 private String barcode; // 药品条码 private String approvedId; // 国标准字 private String commonName; // 通用名称 private String tradeName; // 商品名称 private String commonSpell; // 通用拼音 private String tradeSpell; // 商品拼音 private String commonWb; // 通用五笔 private String tradeWb; // 商品五笔 private String userCode; // 自定义码 private BigDecimal baseDose; // 基本剂量 private String doseUnit; // 剂量单位 private Integer packQty; // 包装数量 private String miniUnit; // 最小单位 private String packUnit; // 包装单位 private String drugSpecs; // 药品规格 private String drugType; // 药品分类 private String dosage; // 剂型编码 private String producer; // 生产厂家 private Boolean isskin; // 需要皮试 private Boolean isrecipe; // 处方药 private String priceCase; // 加价方案 private BigDecimal buyPrice; // 进价 private BigDecimal wholePrice; // 批发价 private BigDecimal salePrice; // 售价 private String drugQuality; // 药品性质 private String priceCode; // 物价编码 private String usage; // 用法编码 private String freqCode; // 频次编码 private String antCode; // 抗菌药编码 private Boolean stopFlag; // 停用标志 private Company companyInfo; @RedisSequence public String getDrugCode() { return drugCode; } public void setDrugCode(String drugCode) { this.drugCode = drugCode; } public String getCenterCode() { return centerCode; } public void setCenterCode(String centerCode) { this.centerCode = centerCode; } public String getBarcode() { return barcode; } public void setBarcode(String barcode) { this.barcode = barcode; } public String getApprovedId() { return approvedId; } public void setApprovedId(String approvedId) { this.approvedId = approvedId; } public String getCommonName() { return commonName; } public void setCommonName(String commonName) { this.commonName = commonName; } public String getTradeName() { return tradeName; } public void setTradeName(String tradeName) { this.tradeName = tradeName; } public String getCommonSpell() { return commonSpell; } public void setCommonSpell(String commonSpell) { this.commonSpell = commonSpell; } public String getTradeSpell() { return tradeSpell; } public void setTradeSpell(String tradeSpell) { this.tradeSpell = tradeSpell; } public String getCommonWb() { return commonWb; } public void setCommonWb(String commonWb) { this.commonWb = commonWb; } public String getTradeWb() { return tradeWb; } public void setTradeWb(String tradeWb) { this.tradeWb = tradeWb; } public String getUserCode() { return userCode; } public void setUserCode(String userCode) { this.userCode = userCode; } public BigDecimal getBaseDose() { return baseDose; } public void setBaseDose(BigDecimal baseDose) { this.baseDose = baseDose; } public String getDoseUnit() { return doseUnit; } public void setDoseUnit(String doseUnit) { this.doseUnit = doseUnit; } public Integer getPackQty() { return packQty; } public void setPackQty(Integer packQty) { this.packQty = packQty; } public String getMiniUnit() { return miniUnit; } public void setMiniUnit(String miniUnit) { this.miniUnit = miniUnit; } public String getPackUnit() { return packUnit; } public void setPackUnit(String packUnit) { this.packUnit = packUnit; } public String getDrugSpecs() { return drugSpecs; } public void setDrugSpecs(String drugSpecs) { this.drugSpecs = drugSpecs; } public String getDrugType() { return drugType; } public void setDrugType(String drugType) { this.drugType = drugType; } public String getDosage() { return dosage; } public void setDosage(String dosage) { this.dosage = dosage; } // public String getProducer() { // return producer; // } // public void setProducer(String producer) { // this.producer = producer; // } @ManyToOne//(cascade=(CascadeType.REFRESH)) 要把companyInfo.id传回来,就不会报级联相关错误 @JoinColumn(name = "PRODUCER", nullable = true) @NotFound(action=NotFoundAction.IGNORE) public Company getCompanyInfo() { return companyInfo; } public void setCompanyInfo(Company companyInfo) { this.companyInfo = companyInfo; } public Boolean getIsskin() { return isskin; } public void setIsskin(Boolean isskin) { this.isskin = isskin; } public Boolean getIsrecipe() { return isrecipe; } public void setIsrecipe(Boolean isrecipe) { this.isrecipe = isrecipe; } public String getPriceCase() { return priceCase; } public void setPriceCase(String priceCase) { this.priceCase = priceCase; } public BigDecimal getBuyPrice() { return buyPrice; } public void setBuyPrice(BigDecimal buyPrice) { this.buyPrice = buyPrice; } public BigDecimal getWholePrice() { return wholePrice; } public void setWholePrice(BigDecimal wholePrice) { this.wholePrice = wholePrice; } public BigDecimal getSalePrice() { return salePrice; } public void setSalePrice(BigDecimal salePrice) { this.salePrice = salePrice; } public String getDrugQuality() { return drugQuality; } public void setDrugQuality(String drugQuality) { this.drugQuality = drugQuality; } public String getPriceCode() { return priceCode; } public void setPriceCode(String priceCode) { this.priceCode = priceCode; } @Column(name = "USAGE_") public String getUsage() { return usage; } public void setUsage(String usage) { this.usage = usage; } public String getFreqCode() { return freqCode; } public void setFreqCode(String freqCode) { this.freqCode = freqCode; } public String getAntCode() { return antCode; } public void setAntCode(String antCode) { this.antCode = antCode; } public Boolean getStopFlag() { return stopFlag; } public void setStopFlag(Boolean stopFlag) { this.stopFlag = stopFlag; } @Transient public String getProducer() { return producer; } public void setProducer(String producer) { this.producer = producer; } }
package com.smartsampa.shapefileapi; import com.smartsampa.utils.SmartSampaDir; import org.opengis.feature.simple.SimpleFeature; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; /** * Created by ruan0408 on 22/03/2016. */ public class ShapefileAPI { private List<SimpleFeature> features; public ShapefileAPI(String relativePath) { String shapefilePath = SmartSampaDir.getPath()+"/"+relativePath; features = ShapefileHandler.handleShapefile(shapefilePath); } public List<SimpleFeature> getAllFeatures() {return features;} public Map<String, List<SimpleFeature>> groupBy(Function<SimpleFeature, String> function) { return features.stream().collect(Collectors.groupingBy(function)); } protected void printProperties() { for (SimpleFeature feature : features) System.out.println(feature.getProperties()); } protected void printPropertiesToFile() throws FileNotFoundException, UnsupportedEncodingException { PrintWriter writer = new PrintWriter("/Users/ruan0408/Downloads/output.txt", "UTF-8"); for (SimpleFeature feature : features) writer.println(feature.getProperties()); writer.close(); } }
package com.nextLevel.hero.mngBasicInformation.model.dto; import java.io.Serializable; import java.sql.Date; public class MngBasicInformationDTO implements Serializable{ private int companyNo; private String companyName; private String ceoName; private String address; private String addressDetail; private String phone; private String fax; private String companyRegistrationNo; private String companyRegistrationNo1; private String companyRegistrationNo2; private String companyRegistrationNo3; private String identificationNo; private String identificationNo1; private String identificationNo2; private String managerEmail; private String website; private Date foundingDate; private char firstCompanyYn; private int businessCode; private String businessName; private String businessDetail; public MngBasicInformationDTO() {} public MngBasicInformationDTO(int companyNo, String companyName, String ceoName, String address, String addressDetail, String phone, String fax, String companyRegistrationNo, String companyRegistrationNo1, String companyRegistrationNo2, String companyRegistrationNo3, String identificationNo, String identificationNo1, String identificationNo2, String managerEmail, String website, Date foundingDate, char firstCompanyYn, int businessCode, String businessName, String businessDetail) { super(); this.companyNo = companyNo; this.companyName = companyName; this.ceoName = ceoName; this.address = address; this.addressDetail = addressDetail; this.phone = phone; this.fax = fax; this.companyRegistrationNo = companyRegistrationNo; this.companyRegistrationNo1 = companyRegistrationNo1; this.companyRegistrationNo2 = companyRegistrationNo2; this.companyRegistrationNo3 = companyRegistrationNo3; this.identificationNo = identificationNo; this.identificationNo1 = identificationNo1; this.identificationNo2 = identificationNo2; this.managerEmail = managerEmail; this.website = website; this.foundingDate = foundingDate; this.firstCompanyYn = firstCompanyYn; this.businessCode = businessCode; this.businessName = businessName; this.businessDetail = businessDetail; } public int getCompanyNo() { return companyNo; } public void setCompanyNo(int companyNo) { this.companyNo = companyNo; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public String getCeoName() { return ceoName; } public void setCeoName(String ceoName) { this.ceoName = ceoName; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getAddressDetail() { return addressDetail; } public void setAddressDetail(String addressDetail) { this.addressDetail = addressDetail; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getFax() { return fax; } public void setFax(String fax) { this.fax = fax; } public String getCompanyRegistrationNo() { return companyRegistrationNo; } public void setCompanyRegistrationNo(String companyRegistrationNo) { this.companyRegistrationNo = companyRegistrationNo; } public String getCompanyRegistrationNo1() { return companyRegistrationNo1; } public void setCompanyRegistrationNo1(String companyRegistrationNo1) { this.companyRegistrationNo1 = companyRegistrationNo1; } public String getCompanyRegistrationNo2() { return companyRegistrationNo2; } public void setCompanyRegistrationNo2(String companyRegistrationNo2) { this.companyRegistrationNo2 = companyRegistrationNo2; } public String getCompanyRegistrationNo3() { return companyRegistrationNo3; } public void setCompanyRegistrationNo3(String companyRegistrationNo3) { this.companyRegistrationNo3 = companyRegistrationNo3; } public String getIdentificationNo() { return identificationNo; } public void setIdentificationNo(String identificationNo) { this.identificationNo = identificationNo; } public String getIdentificationNo1() { return identificationNo1; } public void setIdentificationNo1(String identificationNo1) { this.identificationNo1 = identificationNo1; } public String getIdentificationNo2() { return identificationNo2; } public void setIdentificationNo2(String identificationNo2) { this.identificationNo2 = identificationNo2; } public String getManagerEmail() { return managerEmail; } public void setManagerEmail(String managerEmail) { this.managerEmail = managerEmail; } public String getWebsite() { return website; } public void setWebsite(String website) { this.website = website; } public Date getFoundingDate() { return foundingDate; } public void setFoundingDate(Date foundingDate) { this.foundingDate = foundingDate; } public char getFirstCompanyYn() { return firstCompanyYn; } public void setFirstCompanyYn(char firstCompanyYn) { this.firstCompanyYn = firstCompanyYn; } public int getBusinessCode() { return businessCode; } public void setBusinessCode(int businessCode) { this.businessCode = businessCode; } public String getBusinessName() { return businessName; } public void setBusinessName(String businessName) { this.businessName = businessName; } public String getBusinessDetail() { return businessDetail; } public void setBusinessDetail(String businessDetail) { this.businessDetail = businessDetail; } @Override public String toString() { return "MngBasicInformationDTO [companyNo=" + companyNo + ", companyName=" + companyName + ", ceoName=" + ceoName + ", address=" + address + ", addressDetail=" + addressDetail + ", phone=" + phone + ", fax=" + fax + ", companyRegistrationNo=" + companyRegistrationNo + ", companyRegistrationNo1=" + companyRegistrationNo1 + ", companyRegistrationNo2=" + companyRegistrationNo2 + ", companyRegistrationNo3=" + companyRegistrationNo3 + ", identificationNo=" + identificationNo + ", identificationNo1=" + identificationNo1 + ", identificationNo2=" + identificationNo2 + ", managerEmail=" + managerEmail + ", website=" + website + ", foundingDate=" + foundingDate + ", firstCompanyYn=" + firstCompanyYn + ", businessCode=" + businessCode + ", businessName=" + businessName + ", businessDetail=" + businessDetail + "]"; } }
package com.lenovohit.ssm.base.model; import javax.persistence.Entity; import javax.persistence.Table; import com.lenovohit.core.model.BaseIdModel; @Entity @Table(name="SSM_MODEL") public class Model extends BaseIdModel { private static final long serialVersionUID = -2303540239972424841L; private String code; private String name; private String parent; private String supplier; private int sort; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getSort() { return sort; } public void setSort(int sort) { this.sort = sort; } public String getParent() { return parent; } public void setParent(String parent) { this.parent = parent; } public String getSupplier() { return supplier; } public void setSupplier(String supplier) { this.supplier = supplier; } }
package com.clinic.dentist.comparators.maintenances; import com.clinic.dentist.models.Maintenance; import java.util.Comparator; public class MaintenancePriceComparator implements Comparator<Maintenance> { @Override public int compare(Maintenance o1, Maintenance o2) { return new Double(o1.getPrice()).compareTo(new Double(o2.getPrice())); } }
package com.mastorindev.supmark; import android.graphics.drawable.AnimationDrawable; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.ImageView; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final ImageView image = (ImageView) findViewById(R.id.imageView); image.setBackgroundResource(R.drawable.loader); animation = (AnimationDrawable) image.getBackground(); if (animation != null) { animation.start(); } final Button connectButton = (Button) findViewById(R.id.connexion_button); connectButton.setOnClickListener(onClickListener); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } private AnimationDrawable animation; private View.OnClickListener onClickListener = new View.OnClickListener() { @Override public void onClick(View view) { switch (view.getId()) { case R.id.connexion_button: animation.start(); final ImageView image = (ImageView) findViewById(R.id.imageView); image.setVisibility(View.VISIBLE); break; } } }; }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author Cristey */ public class Edad { private int year=2016; public int edad; public int year2; public int getYear() { return year; } public void setYear(int year) { this.year=year; } public int getEdad() { edad=(this.year-this.year2); return edad; } public void setEdad(int edad) { this.edad=edad; } public int getYear2() { return year2; } public void setYear2(int year2) { this.year2 = year2; } }
package com.lenovohit.hwe.treat.service; import java.util.List; import java.util.Map; import com.lenovohit.hwe.treat.model.Charge; import com.lenovohit.hwe.treat.model.ChargeDetail; import com.lenovohit.hwe.treat.transfer.RestEntityResponse; import com.lenovohit.hwe.treat.transfer.RestListResponse; public interface HisChargeService { public RestEntityResponse<Charge> getInfo(Charge request, Map<String, ?> variables); public RestListResponse<Charge> findList(Charge request); public RestEntityResponse<Charge> prepay(List<ChargeDetail> chagerList); public RestEntityResponse<Charge> pay(Charge request, Map<String, ?> variables); public RestEntityResponse<Charge> hisCallBack(Charge charge); }
package nightgames.skills; import nightgames.characters.Character; import nightgames.combat.Combat; import nightgames.combat.Result; import nightgames.items.Item; import nightgames.status.Hypersensitive; import nightgames.status.Stsflag; public class Sensitize extends Skill { public Sensitize(Character self) { super("Sensitivity Potion", self); } @Override public boolean requirements(Combat c, Character user, Character target) { return true; } @Override public boolean usable(Combat c, Character target) { return c.getStance().mobile(getSelf()) && getSelf().canAct() && getSelf().has(Item.SPotion) && target.mostlyNude() && !c.getStance().prone(getSelf()) && !target.is(Stsflag.hypersensitive); } @Override public String describe(Combat c) { return "Makes your opponent hypersensitive"; } @Override public boolean resolve(Combat c, Character target) { getSelf().consume(Item.SPotion, 1); if (getSelf().has(Item.Aersolizer)) { if (getSelf().human()) { c.write(getSelf(), deal(c, 0, Result.special, target)); } else if (target.human()) { c.write(getSelf(), receive(c, 0, Result.special, getSelf())); } target.add(c, new Hypersensitive(target)); } else if (target.roll(this, c, accuracy(c))) { if (getSelf().human()) { c.write(getSelf(), deal(c, 0, Result.normal, target)); } else if (target.human()) { c.write(getSelf(), receive(c, 0, Result.normal, getSelf())); } target.add(c, new Hypersensitive(target)); } else { if (getSelf().human()) { c.write(getSelf(), deal(c, 0, Result.miss, target)); } else if (target.human()) { c.write(getSelf(), receive(c, 0, Result.miss, target)); } return false; } return true; } @Override public Skill copy(Character user) { return new Sensitize(user); } @Override public Tactics type(Combat c) { return Tactics.debuff; } @Override public String deal(Combat c, int damage, Result modifier, Character target) { if (modifier == Result.special) { return "You pop a sensitivity potion into your Aerosolizer and spray " + target.name() + " with a cloud of mist. She shivers as it takes hold and heightens her " + "sense of touch."; } else if (modifier == Result.miss) { return "You throw a bottle of sensitivity elixir at " + target.name() + ", but she ducks out of the way and it splashes harmlessly on the ground. What a waste."; } else { return "You throw a sensitivity potion at " + target.name() + ". You see her skin flush as it takes effect."; } } @Override public String receive(Combat c, int damage, Result modifier, Character target) { if (modifier == Result.special) { return getSelf().name() + " inserts a bottle into the attachment on her arm. You're suddenly surrounded by a cloud of minty gas. Your skin becomes hot, but goosebumps appear anyway. " + "Even the air touching your skin makes you shiver."; } else if (modifier == Result.miss) { return getSelf().name() + " splashes a bottle of liquid in your direction, but none of it hits you."; } else { return getSelf().name() + " throws a bottle of strange liquid at you. The skin it touches grows hot and oversensitive."; } } }
package se.ju.student.android_mjecipes; import android.Manifest; import android.app.SearchManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.os.Parcelable; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.NavigationView; import android.support.design.widget.Snackbar; import android.support.design.widget.TabLayout; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.view.ActionMode; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import java.util.Random; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.UUID; import se.ju.student.android_mjecipes.CacheHandlers.CacheHandler; import se.ju.student.android_mjecipes.MjepicesAPIHandler.Entities.JWToken; import se.ju.student.android_mjecipes.MjepicesAPIHandler.Entities.Recipe; import se.ju.student.android_mjecipes.MjepicesAPIHandler.Handler; import se.ju.student.android_mjecipes.UserAgent.UserAgent; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, RecipePageFragment.OnFragmentInteractionListener, View.OnClickListener { private static final int RECIPE_EDIT_REQUEST_CODE = 2; private static final String ACTION_MY_RECIPES = "Mjecipes.MyRecipes"; private static final String ACTION_MY_FAVORITES = "Mjecipes.MyFavorites"; private static final int CREATE_RECIPE_REQUEST = 0; private static final int IMAGE_REQUEST_CODE = 1; private static final int MY_RECIPES_PAGE_CODE = Integer.MAX_VALUE; private static final int MY_FAVORITES_PAGE_CODE = Integer.MAX_VALUE - 1; private DrawerLayout drawerLayout; private ActionBarDrawerToggle drawerToggle; private NavigationView navigationView; private ViewPager viewPager; private TabLayout tabDots; private View emptyScreen; private int currentRID; private ActionMode actionMode = null; private Uri outputFileUri; private boolean loaded = false; private boolean ordloaded = false; private boolean favloaded = false; int k = 0; int []rec; @Override public boolean onPrepareOptionsMenu(Menu menu) { String act = getIntent().getAction(); if(act != null && act.equals(Intent.ACTION_SEARCH)) { menu.findItem(R.id.search).setVisible(false); menu.findItem(R.id.refresh).setVisible(false); } return super.onPrepareOptionsMenu(menu); } @Override public boolean onCreateOptionsMenu(Menu menu){ getMenuInflater().inflate(R.menu.main_activity_menu,menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.search: onSearchRequested(); break; case R.id.refresh: refresh(); break; case android.R.id.home: drawerToggle.onOptionsItemSelected(item); break; default: return super.onOptionsItemSelected(item); } return true; } private void invalidateDrawerMenu() { if(UserAgent.getInstance(this).isLoggedIn()){ ((TextView)navigationView.getHeaderView(0).findViewById(R.id.uname)).setText(UserAgent.getInstance(this).getUsername()); navigationView.getMenu().removeItem(R.id.login); navigationView.getMenu().removeItem(R.id.signup); } else { ((TextView)navigationView.getHeaderView(0).findViewById(R.id.uname)).setText(getString(R.string.drawer_not_logged_in)); navigationView.getMenu().removeItem(R.id.favoriterecipes); navigationView.getMenu().removeItem(R.id.logout); } } @Override public void loaded() { View v = findViewById(R.id.loading_screen); if(v != null) v.setVisibility(View.GONE); } @Override public void onRecipeLongClick(final View v, final int recipeID, String creatorID) { if(actionMode != null) actionMode.finish(); final String cID = creatorID != null ? creatorID : UserAgent.getInstance(this).getUserID(); currentRID = recipeID; actionMode = startActionMode(new android.view.ActionMode.Callback() { @Override public boolean onCreateActionMode(android.view.ActionMode mode, Menu menu) { getMenuInflater().inflate(R.menu.main_activity_action_menu, menu); v.setBackgroundResource(R.color.colorPrimary); onPrepareActionMode(mode, menu); return true; } @Override public boolean onPrepareActionMode(android.view.ActionMode mode, Menu menu) { if(UserAgent.getInstance(MainActivity.this).isLoggedIn()) { if(UserAgent.getInstance(MainActivity.this).getUserID().equals(cID)) { menu.findItem(R.id.edit).setVisible(true); menu.findItem(R.id.upload_image).setVisible(true); menu.findItem(R.id.delete).setVisible(true); } menu.findItem(R.id.make_favorite).setVisible(true); if(UserAgent.getInstance(MainActivity.this).hasFavorite(recipeID)) menu.findItem(R.id.make_favorite).setIcon(R.drawable.ic_favorite_white_24dp); } return true; } @Override public boolean onActionItemClicked(android.view.ActionMode mode, MenuItem item) { switch(item.getItemId()) { case R.id.show_comments: Intent i = new Intent(MainActivity.this, ShowCommentActivity.class); i.putExtra("resid", Integer.toString(currentRID)); startActivity(i); break; case R.id.make_favorite: favorite(currentRID); break; case R.id.edit: edit(currentRID); break; case R.id.upload_image: openImageIntent(); break; case R.id.delete: deleteRecipe(currentRID); break; default: return false; } mode.finish(); return true; } @Override public void onDestroyActionMode(android.view.ActionMode mode) { actionMode = null; RecipePageFragment.actionMode = null; v.setBackgroundResource(R.color.colorAccent); } }); } private void favorite(int rID) { if(!isConnectionAvailable()) { Snackbar.make(navigationView, getString(R.string.no_connection), Snackbar.LENGTH_SHORT).show(); return; } UserAgent.getInstance(this).postFavorite(rID, new UserAgent.FavoriteListener() { @Override public void onFavoritePosted(boolean posted) { if(posted) { Snackbar.make(navigationView, getString(R.string.done), Snackbar.LENGTH_SHORT).show(); refresh(); } else Snackbar.make(navigationView, getString(R.string.error_favorite_recipe), Snackbar.LENGTH_SHORT).show(); } }); } private void deleteRecipe(final int rID) { if(!isConnectionAvailable()) { Snackbar.make(navigationView, getString(R.string.no_connection), Snackbar.LENGTH_SHORT).show(); return; } new AsyncTask<Void, Void, Boolean>() { @Override protected Boolean doInBackground(Void... params) { JWToken token = Handler.getTokenHandler().getToken( UserAgent.getInstance(getBaseContext()).getUsername(), UserAgent.getInstance(getBaseContext()).getPassword() ); return token != null && Handler.getRecipeHandler().deleteRecipe(rID, token); } @Override protected void onPostExecute(Boolean deleted) { if(deleted) { Snackbar.make(navigationView, getString(R.string.done), Snackbar.LENGTH_SHORT).show(); refresh(); } else Snackbar.make(navigationView, getString(R.string.error_delete_recipe), Snackbar.LENGTH_SHORT).show(); } }.execute(); } public ActionMode getActionMode() { return actionMode; } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent intent = getIntent(); final String action = intent.getAction(); drawerLayout = (DrawerLayout) findViewById(R.id.drawer); navigationView = (NavigationView) findViewById(R.id.navigation_view); viewPager = (ViewPager) findViewById(R.id.viewpager); tabDots = (TabLayout) findViewById(R.id.tabDots); emptyScreen = findViewById(R.id.empty_screen); FloatingActionButton createRecipeFab = (FloatingActionButton) findViewById(R.id.create_recipe_fab); rec= new int[50]; if(createRecipeFab != null) createRecipeFab.setOnClickListener(this); if(emptyScreen != null) ((TextView)emptyScreen.findViewById(R.id.empty_view_text)).setText(getString(R.string.main_activity_no_recipe)); ActionBar actionBar = getSupportActionBar(); if(actionBar != null) actionBar.setDisplayHomeAsUpEnabled(true); drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.open, R.string.close); drawerLayout.addDrawerListener(drawerToggle); drawerToggle.syncState(); navigationView.setNavigationItemSelectedListener(this); viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {} @Override public void onPageSelected(int position) { if(actionMode != null) actionMode.finish(); } @Override public void onPageScrollStateChanged(int state) {} }); if(action != null) { switch(action) { case Intent.ACTION_SEARCH: if(createRecipeFab != null) createRecipeFab.setVisibility(View.GONE); if(actionBar != null) actionBar.setDisplayHomeAsUpEnabled(false); loadSearchResults(intent); break; case ACTION_MY_RECIPES: loadMyRecipes(); break; case ACTION_MY_FAVORITES: loadMyFavorites(); break; default: loadLastPostedRecipes(); break; } return; } loadLastPostedRecipes(); } @Override public void onClick(View v) { startActivity(new Intent(this, CreateRecipeActivity.class)); } public void requestReadPermission() { if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0); } } private JWToken getToken() { return Handler.getTokenHandler().getToken( UserAgent.getInstance(this).getUsername(), UserAgent.getInstance(this).getPassword() ); } private void uploadImage(InputStream stream, final int rID) { new AsyncTask<InputStream, Void, Boolean>() { @Override protected Boolean doInBackground(InputStream... params) { JWToken token = getToken(); return token != null && Handler.getRecipeHandler().postImage(rID, params[0], token); } @Override protected void onPostExecute(Boolean result) { super.onPostExecute(result); if(result) { Snackbar.make(navigationView, getString(R.string.done), Snackbar.LENGTH_SHORT).show(); refresh(); } else Snackbar.make(navigationView, getString(R.string.error_image_upload), Snackbar.LENGTH_SHORT).show(); } }.execute(stream); } private void openImageIntent() { requestReadPermission(); final File root = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES) + File.separator + "Mjecipes"); if(root.mkdirs()) return; final String fname = "img-" + UUID.randomUUID().toString(); File sdImageMainDirectory; try { sdImageMainDirectory = File.createTempFile(fname, ".jpg", root); } catch(IOException e) { return; } outputFileUri = Uri.fromFile(sdImageMainDirectory); final List<Intent> cameraIntents = new ArrayList<>(); final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); final PackageManager packageManager = getPackageManager(); final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0); for(ResolveInfo res : listCam) { final String packageName = res.activityInfo.packageName; final Intent intent = new Intent(captureIntent); intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name)); intent.setPackage(packageName); intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); cameraIntents.add(intent); } final Intent galleryIntent = new Intent(); galleryIntent.setType("image/*"); galleryIntent.setAction(Intent.ACTION_GET_CONTENT); final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source"); chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[cameraIntents.size()])); startActivityForResult(chooserIntent, IMAGE_REQUEST_CODE); } @Override public boolean onNavigationItemSelected(MenuItem item) { Intent intent; switch (item.getItemId()) { case R.id.myaccount: if(UserAgent.getInstance(getBaseContext()).isLoggedIn()) { intent = new Intent(MainActivity.this, ShowAccountActivity.class); intent.setAction(Intent.ACTION_USER_PRESENT); } else intent = new Intent(MainActivity.this, LoginActivity.class); ordloaded = false; startActivity(intent); drawerLayout.closeDrawers(); break; case R.id.myrecipes: if(UserAgent.getInstance(getBaseContext()).isLoggedIn()) { intent = new Intent(MainActivity.this, MainActivity.class); intent.setAction(ACTION_MY_RECIPES); } else intent = new Intent(MainActivity.this, LoginActivity.class); ordloaded=false; startActivity(intent); drawerLayout.closeDrawers(); break; case R.id.createarecipe: if(UserAgent.getInstance(getBaseContext()).isLoggedIn()) { intent = new Intent(MainActivity.this, CreateRecipeActivity.class); ordloaded = false; startActivityForResult(intent, CREATE_RECIPE_REQUEST); } else { intent = new Intent(MainActivity.this, LoginActivity.class); ordloaded=false; startActivity(intent); } drawerLayout.closeDrawers(); break; case R.id.recipeofday: Random rand=new Random(); int randomNum = rand.nextInt(50); Intent i = new Intent(MainActivity.this, ShowRecipeActivity.class); i.putExtra("recipeId", Integer.toString(rec[randomNum])); i.setAction(""); startActivity(i); ordloaded = false; drawerLayout.closeDrawers(); break; case R.id.signup: intent = new Intent(MainActivity.this, SignupActivity.class); startActivity(intent); ordloaded = false; drawerLayout.closeDrawers(); break; case R.id.login: intent = new Intent(MainActivity.this, LoginActivity.class); ordloaded = false; startActivity(intent); drawerLayout.closeDrawers(); break; case R.id.logout: UserAgent.getInstance(getBaseContext()).logout(); intent = new Intent(MainActivity.this, MainActivity.class); ordloaded = false; startActivity(intent); finish(); break; case R.id.favoriterecipes: intent = new Intent(MainActivity.this, MainActivity.class); intent.setAction(ACTION_MY_FAVORITES); ordloaded = false; drawerLayout.closeDrawers(); startActivity(intent); break; default: return false; } return true; } private void refresh() { k = 0; View v = findViewById(R.id.loading_screen); if(v != null) v.setVisibility(View.VISIBLE); if(loaded) loadMyRecipes(); else if(favloaded) loadMyFavorites(); else if(ordloaded) loadLastPostedRecipes(); } private void loadSearchResults(Intent i) { setTitle("Search results"); new AsyncTask<String, Void, Recipe[]>() { @Override protected Recipe[] doInBackground(String... params) { return Handler.getRecipeHandler().search(params[0]); } @Override protected void onPostExecute(Recipe[] recipes) { if(recipes != null) { if(recipes.length == 0) { loaded(); emptyScreen.setVisibility(View.VISIBLE); return; } RecipePagerAdapter recipePagerAdapter = new RecipePagerAdapter(getSupportFragmentManager(), recipes, null); viewPager.setAdapter(recipePagerAdapter); tabDots.setupWithViewPager(viewPager); } } }.execute(i.getStringExtra(SearchManager.QUERY)); } private void loadLastPostedRecipes(){ invalidateDrawerMenu(); new AsyncTask<Void, Void, Recipe[]>() { @Override protected Recipe[] doInBackground(Void... p) { Recipe r[] = null; if(!isConnectionAvailable()) { if(!ordloaded) { for(int i = 0; i < 5; ++i) { Recipe[] re = CacheHandler.getJSONJsonCacheHandler(MainActivity.this).readRecipePage(i + 1); if(r == null) r = re; else r = concat(r, re); } if (r != null) { ordloaded = true; Snackbar.make(drawerLayout, getString(R.string.no_connection_cache_first), Snackbar.LENGTH_LONG).show(); } return r; } else { Snackbar.make(drawerLayout, getString(R.string.no_connection), Snackbar.LENGTH_LONG).show(); return null; } } for(int i = 0; i < 5; ++i) { Recipe[] re = Handler.getRecipeHandler().getRecipeByPage(i + 1); if(re != null){ handleCache(re, i + 1); for(int j=0;j<10;j++){ rec[k]= re[j].id; k++; } } if(r == null) r = re; else r = concat(r, re); } if(r != null) ordloaded = true; return r; } @Override protected void onPostExecute(Recipe[] recipes) { if(recipes != null) { if(recipes.length == 0) { loaded(); emptyScreen.setVisibility(View.VISIBLE); return; } RecipePagerAdapter recipePagerAdapter = new RecipePagerAdapter(getSupportFragmentManager(), recipes, null); viewPager.setAdapter(recipePagerAdapter); tabDots.setupWithViewPager(viewPager); } } }.execute(); } private void loadMyRecipes(){ invalidateDrawerMenu(); new AsyncTask<Void, Void, Recipe[]>() { @Override protected Recipe[] doInBackground(Void... p) { Recipe r[]; if(!isConnectionAvailable()) { if(!loaded) { r = CacheHandler.getJSONJsonCacheHandler(MainActivity.this).readRecipePage(MY_RECIPES_PAGE_CODE); if (r != null) { loaded = true; Snackbar.make(drawerLayout, getString(R.string.no_connection_cache_first), Snackbar.LENGTH_LONG).show(); } return r; } else { Snackbar.make(drawerLayout, getString(R.string.no_connection), Snackbar.LENGTH_LONG).show(); return null; } } r = Handler.getAccountHandler().getRecipes(UserAgent.getInstance(MainActivity.this).getUserID()); if(r != null) { handleCache(r, MY_RECIPES_PAGE_CODE); loaded = true; } return r; } @Override protected void onPostExecute(Recipe[] recipes) { if(recipes != null) { if(recipes.length == 0) { loaded(); emptyScreen.setVisibility(View.VISIBLE); return; } RecipePagerAdapter recipePagerAdapter = new RecipePagerAdapter( getSupportFragmentManager(), recipes, UserAgent.getInstance(MainActivity.this).getUsername()); viewPager.setAdapter(recipePagerAdapter); tabDots.setupWithViewPager(viewPager); } } }.execute(); } private void loadMyFavorites(){ invalidateDrawerMenu(); new AsyncTask<Void, Void, Recipe[]>() { @Override protected Recipe[] doInBackground(Void... p) { Recipe r[] = null; if(!isConnectionAvailable()) { if(!favloaded) { r = CacheHandler.getJSONJsonCacheHandler(MainActivity.this).readRecipePage(MY_FAVORITES_PAGE_CODE); if (r != null) { favloaded = true; Snackbar.make(drawerLayout, getString(R.string.no_connection_cache_first), Snackbar.LENGTH_LONG).show(); } return r; } else { Snackbar.make(drawerLayout, getString(R.string.no_connection), Snackbar.LENGTH_LONG).show(); return null; } } JWToken token = Handler.getTokenHandler().getToken( UserAgent.getInstance(MainActivity.this).getUsername(), UserAgent.getInstance(MainActivity.this).getPassword()); if(token != null) r = Handler.getAccountHandler().getFavorites(UserAgent.getInstance(MainActivity.this).getUserID(),token); if(r != null) { handleCache(r, MY_FAVORITES_PAGE_CODE); favloaded = true; } return r; } @Override protected void onPostExecute(Recipe[] recipes) { if(recipes != null){ if(recipes.length == 0) { loaded(); emptyScreen.setVisibility(View.VISIBLE); return; } RecipePagerAdapter recipePagerAdapter = new RecipePagerAdapter(getSupportFragmentManager(), recipes, null); viewPager.setAdapter(recipePagerAdapter); tabDots.setupWithViewPager(viewPager); } } }.execute(); } private void handleCache(Recipe r[], int page) { CacheHandler.getJSONJsonCacheHandler(this).clearRecipePage(page); CacheHandler.getJSONJsonCacheHandler(this).writeRecipePage(r, page); } private boolean isConnectionAvailable() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ni = cm.getActiveNetworkInfo(); return ni != null && ni.isConnected(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch(requestCode) { case CREATE_RECIPE_REQUEST: if(resultCode == RESULT_OK) { Snackbar.make(navigationView, getString(R.string.done), Snackbar.LENGTH_SHORT).show(); refresh(); } break; case IMAGE_REQUEST_CODE: if(resultCode == RESULT_OK) { final boolean isCamera; if (data == null) { isCamera = true; } else { final String action = data.getAction(); isCamera = action != null && action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); } try { uploadImage(getContentResolver().openInputStream(isCamera ? outputFileUri : data.getData()), currentRID); } catch(FileNotFoundException e) { Snackbar.make(navigationView, getString(R.string.error_image_upload), Snackbar.LENGTH_SHORT).show(); } } break; } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if(requestCode == 0) { if(grantResults.length > 0 && (grantResults[0] == PackageManager.PERMISSION_DENIED || grantResults[1] == PackageManager.PERMISSION_DENIED)) { Snackbar.make(navigationView, getString(R.string.error_permission_needed), Snackbar.LENGTH_SHORT).show(); } } } private static <T> T[] concat(T[] first, T[] second) { if(first == null || second == null) return null; T[] result = Arrays.copyOf(first, first.length + second.length); System.arraycopy(second, 0, result, first.length, second.length); return result; } private void edit(final int recipeid) { new AsyncTask<Void,Void,Recipe>() { @Override protected Recipe doInBackground(Void... params) { return Handler.getRecipeHandler().getRecipe(recipeid); } @Override protected void onPostExecute(Recipe recipe) { if(recipe == null) { Snackbar.make(navigationView, getString(R.string.something_went_wrong), Snackbar.LENGTH_SHORT).show(); return; } Intent intent = new Intent(MainActivity.this, CreateRecipeActivity.class); intent.putExtra("recipeID", Integer.toString(recipe.id)); intent.putExtra("recipeName",recipe.name); intent.putExtra("recipeDesc", recipe.description); String[] directions = new String[recipe.directions.length]; for(int i = 0; i < directions.length; ++i) directions[i] = recipe.directions[i].description; intent.putExtra("recipeDirecs", directions); startActivityForResult(intent, RECIPE_EDIT_REQUEST_CODE); } }.execute(); } }
/** * Sencha GXT 1.0.0-SNAPSHOT - Sencha for GWT * Copyright (c) 2006-2018, Sencha Inc. * * licensing@sencha.com * http://www.sencha.com/products/gxt/license/ * * ================================================================================ * Commercial License * ================================================================================ * This version of Sencha GXT is licensed commercially and is the appropriate * option for the vast majority of use cases. * * Please see the Sencha GXT Licensing page at: * http://www.sencha.com/products/gxt/license/ * * For clarification or additional options, please contact: * licensing@sencha.com * ================================================================================ * * * * * * * * * ================================================================================ * Disclaimer * ================================================================================ * THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND * REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE * IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, * FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE AND * THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. * ================================================================================ */ package com.sencha.gxt.explorer.client.layout; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.InlineHTML; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Widget; import com.sencha.gxt.examples.resources.client.Utils; import com.sencha.gxt.explorer.client.app.ui.ExampleContainer; import com.sencha.gxt.explorer.client.model.Example.Detail; import com.sencha.gxt.widget.core.client.ContentPanel; import com.sencha.gxt.widget.core.client.container.FlowLayoutContainer; import com.sencha.gxt.widget.core.client.container.MarginData; @Detail( name = "Flow Layout", category = "Layouts", icon = "verticallayout", minHeight = FlowLayoutExample.MIN_HEIGHT, minWidth = FlowLayoutExample.MIN_WIDTH, classes = { Utils.class }) public class FlowLayoutExample implements IsWidget, EntryPoint { protected static final int MIN_HEIGHT = 320; protected static final int MIN_WIDTH = 150; private ContentPanel panel; @Override public Widget asWidget() { if (panel == null) { FlowLayoutContainer flc = new FlowLayoutContainer(); flc.add(createRow("Stack 1"), new MarginData(10, 10, 10, 10)); flc.add(createRow("Stack 2"), new MarginData(10, 10, 10, 10)); flc.add(createRow("Stack 3"), new MarginData(10, 10, 10, 10)); flc.add(createColumn("Inline 1"), new MarginData(10, 10, 10, 10)); flc.add(createColumn("Inline 2"), new MarginData(10, 10, 10, 10)); flc.add(createColumn("Inline 3"), new MarginData(10, 10, 10, 10)); panel = new ContentPanel(); panel.setHeading("Flow Layout"); panel.add(flc); } return panel; } private Label createRow(String text) { HTML label = new HTML(text); label.getElement().getStyle().setProperty("whiteSpace", "nowrap"); label.addStyleName("pad-text gray-bg"); return label; } private Label createColumn(String text) { InlineHTML label = new InlineHTML(text); label.getElement().getStyle().setProperty("whiteSpace", "nowrap"); label.addStyleName("pad-text gray-bg"); return label; } @Override public void onModuleLoad() { new ExampleContainer(this).setMinHeight(MIN_HEIGHT).setMinWidth(MIN_WIDTH).doStandalone(); } }
package com.agamidev.newsfeedsapp.Activities; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.agamidev.newsfeedsapp.Adapters.NewsAdapter; import com.agamidev.newsfeedsapp.Activities.Main_Activity.MainContract; import com.agamidev.newsfeedsapp.Models.NewsModel; import com.agamidev.newsfeedsapp.R; import com.agamidev.newsfeedsapp.Interfaces.RecyclerItemClickListener; import com.agamidev.newsfeedsapp.Widget.Toaster; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; public class SearchActivity extends AppCompatActivity { //Search View @BindView(R.id.et_search) EditText et_search; //News Recycler @BindView(R.id.rv_news_list) RecyclerView rv_news_list; ArrayList<NewsModel> newsArrayList; NewsAdapter mNewsAdapter; public Toaster toaster; public static String TAG = SearchActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search); ButterKnife.bind(this); init(); et_search.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { Log.i("SearchString",s.toString()); mNewsAdapter.getFilter().filter(s.toString()); } @Override public void afterTextChanged(Editable s) { Log.e("afterTextChanged",s.toString()); if(s.toString().length() == 0){ } } }); } private void init(){ toaster = new Toaster(this); newsArrayList = new ArrayList<>(); //Get News Array if (getIntent().getExtras() != null){ newsArrayList = getIntent().getExtras().getParcelableArrayList("newsArray"); Log.e("newsArray in "+TAG,newsArrayList.toString()); fillRecycler(newsArrayList); }else { toaster.makeToast("Cannot Load News!"); } } private RecyclerItemClickListener recyclerItemClickListener = new RecyclerItemClickListener() { @Override public void onItemClick(NewsModel news) { Intent i = new Intent(SearchActivity.this, NewsDetailsActivity.class); i.putExtra("NewsModel",news); startActivity(i); } }; public void fillRecycler(ArrayList<NewsModel> arrayList){ mNewsAdapter = new NewsAdapter(SearchActivity.this,arrayList,recyclerItemClickListener); LinearLayoutManager newsLayoutManager = new LinearLayoutManager(SearchActivity.this); rv_news_list.setLayoutManager(newsLayoutManager); rv_news_list.setItemAnimator(new DefaultItemAnimator()); rv_news_list.setAdapter(mNewsAdapter); } public void btnCancelSearchListener(View view) { et_search.setText(""); mNewsAdapter.getFilter().filter(""); } public void goBack(View view) { onBackPressed(); } }
package com.sportyShoes.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.sportyShoes.model.Product; @Repository public interface ProductRepository extends JpaRepository<Product, Integer> { public Product findByProductName(String productName); public List<Product> findByProductPrice(int productPrice); public List<Product> findByProductCategory(String productCategory); }
package com.socialmeeting.domain.product; public class ProductFactory { public static IProductEdition create(Editions edition) { IProductEdition productEdition = null; if(edition == Editions.DEMONSTRATION) { productEdition = new DemonstrationEdition(); } else if(edition == Editions.ENTERPRISE) { productEdition = new EnterpriseEdition(); } else if(edition == Editions.PERSONAL) { productEdition = new PersonalEdition(); } return productEdition; } }
package com.mattcramblett.primenumbergenerator; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.stream.Stream; import org.junit.Ignore; import org.junit.Test; public class PrimeNumberGeneratorTest extends AbstractTest { private final PrimeNumberGeneratorImpl classUnderTest = new PrimeNumberGeneratorImpl(); @Test public void testIsPrimeFalseWithNonNaturalNumbers() { Stream.of(-1, -2, -4, -13, -29, -7901, -100000, Integer.MIN_VALUE) .forEach(nonNaturalNum -> assertFalse(this.classUnderTest.isPrime(nonNaturalNum))); } @Test public void testIsPrimeFalseWith0() { assertFalse(this.classUnderTest.isPrime(0)); } @Test public void testIsPrimeFalseWith1() { assertFalse(this.classUnderTest.isPrime(1)); } @Test public void testIsPrimeTrueWithSmallPrimes() { SMALL_PRIMES.forEach(smallPrime -> assertTrue(this.classUnderTest.isPrime(smallPrime))); } @Test public void testIsPrimeFalseWithSmallComposites() { Stream.of(4, 6, 12, 20, 24, 30, 42, 56, 64, 78, 82, 100) .forEach(smallComp -> assertFalse(this.classUnderTest.isPrime(smallComp))); } @Test public void testIsPrimeTrueWithLargePrime() { assertTrue(this.classUnderTest.isPrime(Integer.MAX_VALUE)); } @Test public void testIsPrimeFalseWithLargeComposite() { assertFalse(this.classUnderTest.isPrime(Integer.MAX_VALUE - 1)); } @Test public void testGeneratePrimesEmptyWithOutOfBoundsRange() { assertEquals(Arrays.asList(), this.classUnderTest.generate(Integer.MIN_VALUE, -1)); } @Test public void testGenerateSmallPrimes() { assertEquals(SMALL_PRIMES, this.classUnderTest.generate(0, 102)); } @Test public void testGenerateSmallPrimesWithInverseRange() { assertEquals(SMALL_PRIMES, this.classUnderTest.generate(102, -102)); } @Ignore("Covers edge case but is too slow for unit test") @Test public void testGenerateMaxPrimes() { assertEquals(Arrays.asList(2147483549, 2147483563, 2147483579, 2147483587, 2147483629, Integer.MAX_VALUE), this.classUnderTest.generate(Integer.MAX_VALUE - 100, Integer.MAX_VALUE)); } @Test public void testGenerateLargePrimes() { assertEquals(Arrays.asList(99999931, 99999941, 99999959, 99999971, 99999989), this.classUnderTest.generate(99999900, 100000001)); } @Test public void testGeneratePrimesWithNarrowRange() { assertEquals(Arrays.asList(7901, 7907, 7919), this.classUnderTest.generate(7900, 7920)); } @Test public void testGeneratePrimesWhereTwoIsOnlyResult() { assertEquals(Arrays.asList(2), this.classUnderTest.generate(-1, 2)); } @Test public void testGeneratePrimesWherePrimeIsUpperBound() { assertEquals(Arrays.asList(2, 3, 5, 7, 11), this.classUnderTest.generate(0, 11)); } }
package com.ecjtu.hotel.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ecjtu.hotel.dao.ExpendMapper; import com.ecjtu.hotel.pojo.Expend; import com.ecjtu.hotel.service.IExpendService; @Service public class ExpendService implements IExpendService { @Autowired ExpendMapper expendMapper; @Override public Expend getExpendById(Integer id) { // TODO Auto-generated method stub return expendMapper.getExpendById(id); } @Override public int deleteExpendById(Integer id) { // TODO Auto-generated method stub return expendMapper.deleteExpendById(id); } @Override public int addExpend(Expend expend) { // TODO Auto-generated method stub return expendMapper.addExpend(expend); } @Override public List<Expend> getExpends() { // TODO Auto-generated method stub return expendMapper.getExpends(); } @Override public int updateExpend(Expend expend) { // TODO Auto-generated method stub return expendMapper.updateExpend(expend); } }
package com.rankytank.server; import java.util.*; /** * */ public class PlayerGenerator { private Map<Integer, String> players = new HashMap<Integer, String>(); private Random random; private static PlayerGenerator instance; public static PlayerGenerator get() { if (instance == null) { instance = new PlayerGenerator(); } return instance; } private PlayerGenerator() { } public void setup(int numberOfPlayers) { String PRE_NAME = "Player Name "; players = new HashMap<Integer, String>(); int i = 0; while (i < numberOfPlayers){ players.put(i++, PRE_NAME + i); } random = new Random(numberOfPlayers); } public int[] getTwoDistinctPlayerIds(){ return getDistinctPlayers(2, new int[]{}); } public int[] getTwoDistinctPlayerIds(int[] usedPlayers){ return getDistinctPlayers(2, usedPlayers); } private int[] getDistinctPlayers(int numberOfPlayers, int[] alreadyUsedIds){ int[] playerIds = new int[numberOfPlayers]; Set<Integer> usedPlayerIds = new HashSet<Integer>(); for (int usedId : alreadyUsedIds) { usedPlayerIds.add(usedId); } int i = 0; while (i < numberOfPlayers){ int next = random.nextInt(players.size()); if(!usedPlayerIds.contains(next)){ usedPlayerIds.add(next); playerIds[i++] = next; } } return playerIds; } }
package com.logicbig.example; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @EnableWebSecurity public class AppConfig extends WebSecurityConfigurerAdapter { @Override public void configure(AuthenticationManagerBuilder builder) throws Exception { builder.inMemoryAuthentication() .withUser("joe") .password("123") .roles("ADMIN"); } }
package com.kh.jd.lecture; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; @Service("LService") public class LectureServiceImpl implements LectureService{ @Autowired private LectureDao Ldao; @Override public int addLecture(Lecture lecture) { int result = 0; try { System.out.println("오류1"); result = Ldao.addLecture(lecture); } catch (Exception e) { System.out.println("오류2"); e.printStackTrace(); } return result; } @Override public List<Lecture> listLecture(int teacher_number) { return Ldao.listLecture(teacher_number); } @Override public int removeLecture(String lecture_no) { int result = 0; result = Ldao.removeLecture(lecture_no); return result; } @Override public Lecture viewLecture(String lecture_no) { return Ldao.viewLecture(lecture_no); } @Override public int editLecture(Lecture lecture) { return Ldao.editLecture(lecture); } @Override public List<Lecture> listLectureClass() { return Ldao.listLectureClass(); } @Override public Lecture viewLectureClass(Lecture lecture) { return Ldao.viewLectureClass(lecture); } @Override public int checkLectureClass(int lecture_no) { return Ldao.checkLectureClass(lecture_no); } @Override // @Scheduled(cron = "0 * * * * *") // 1분 주기 @Scheduled(cron = "0 0 0 * * *") // 매일 자정 public void scheduleState() { // System.out.println("1분마다 나와@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); System.out.println("@@@@@@자정에 확인@@@@@@"); try { Ldao.scheduleState(); } catch (Exception e) { e.printStackTrace(); System.out.println("---------스케줄러 에러-----------"); } } @Override public Lecture addLecturePlan(Lecture lecture) { return Ldao.addLecturePlan(lecture); } @Override public List<Lecture> listTeacherVideo(int teacher_number) { return Ldao.listTeacherVideo(teacher_number); } @Override public List<Lecture> listStudentVideo(int student_number) { return Ldao.listStudentVideo(student_number); } }
package com.vinodborole.portal.persistence.model.token; public interface IPortalJwtToken { String getToken(); }
package com.wrathOfLoD.Controllers.InputStates.Action.AvatarActions; import com.wrathOfLoD.Controllers.InputStates.Action.Action; import com.wrathOfLoD.Models.Commands.ActionCommand; /** * Created by luluding on 4/17/16. */ public class CastAbilityAction extends Action { public CastAbilityAction(int currKeyCode, ActionCommand myAction) { super(currKeyCode, myAction); } }
package global.coda.hospitalmanagement.helper; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.ResourceBundle; import org.apache.log4j.Logger; import global.coda.hospitalmanagement.constant.BundleKey; import global.coda.hospitalmanagement.daoImpl.DoctorDbDaoImpl; import global.coda.hospitalmanagement.daoImpl.PatientDbDaoImpl; import global.coda.hospitalmanagement.model.Doctor; import global.coda.hospitalmanagement.model.Patient; // TODO: Auto-generated Javadoc /** * The Class DoctorHelper. */ public class DoctorHelper { /** The Constant LOCAL_MESSAGES_BUNDLE. */ private static final ResourceBundle LOCAL_MESSAGES_BUNDLE = ResourceBundle.getBundle("messages", Locale.getDefault()); /** The doctor db. */ DoctorDbDaoImpl doctorDb = new DoctorDbDaoImpl(); /** The logger. */ private Logger LOGGER = Logger.getLogger(DoctorHelper.class); /** * Creates the doctor. * * @param doctor the doctor * @return the boolean * @throws ClassNotFoundException the class not found exception * @throws SQLException the SQL exception */ public Boolean createDoctor(Doctor doctor) throws ClassNotFoundException, SQLException ,Exception{ try { if (doctorDb.insert(doctor)) { LOGGER.info(LOCAL_MESSAGES_BUNDLE.getString(BundleKey.DS7)); } } catch (SQLException e) { throw new SQLException(e); } return true; } /** * Read particular doctor. * * @param doctor the doctor * @return the doctor * @throws ClassNotFoundException the class not found exception * @throws SQLException the SQL exception */ public Doctor readParticularDoctor(Doctor doctor) throws ClassNotFoundException, SQLException ,Exception{ try { doctor = doctorDb.read(doctor); } catch (SQLException e) { throw new SQLException(e); } return doctor; } /** * Update doctor. * * @param doctor the doctor * @return the boolean * @throws ClassNotFoundException the class not found exception * @throws SQLException the SQL exception */ public Boolean updateDoctor(Doctor doctor) throws ClassNotFoundException, SQLException ,Exception{ try { if (doctorDb.update(doctor)) { LOGGER.info(LOCAL_MESSAGES_BUNDLE.getString(BundleKey.DS7)); } } catch (SQLException e) { throw new SQLException(e); } return true; } /** * Read all doctor. * * @return the list * @throws Exception */ public List<Doctor> readAllDoctor() throws ClassNotFoundException, SQLException , Exception{ List<Doctor> doctorList = new ArrayList<>(); try { doctorList = doctorDb.readAll(); } catch (SQLException e) { throw new SQLException(e); } return doctorList; } /** * Delete doctor. * * @param doctor the doctor * @return the boolean * @throws Exception */ public Boolean deleteDoctor(Doctor doctor) throws ClassNotFoundException, SQLException ,Exception{ try { doctorDb.delete(doctor); } catch (SQLException e) { throw new SQLException(e); } return true; } /** * Read all patients. * * @return the list * @throws Exception */ public List<Patient> readAllPatients() throws ClassNotFoundException, SQLException ,Exception{ List<Patient> patientList = new ArrayList<>(); try { PatientDbDaoImpl patientDbDao = new PatientDbDaoImpl(); patientList = patientDbDao.readAllWithMaskedDetails(); } catch (SQLException e) { throw new SQLException(e); } return patientList; } /** * Read patient keys particular doctor. * * @param doctor the doctor * @return the list * @throws Exception */ public List<Integer> readPatientKeysParticularDoctor(Doctor doctor) throws ClassNotFoundException, SQLException,Exception{ List<Integer> patientKeys = new ArrayList<>(); try { DoctorDbDaoImpl doctorDbDao = new DoctorDbDaoImpl(); patientKeys = doctorDbDao.readAllPatientsParticularDoctor(doctor); } catch (SQLException e) { throw new SQLException(e); } return patientKeys; } }
package ru.aggregator.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * Created by user on 08.04.2015. */ @Entity @Table(name="COIN") public class Coin { @Id @Column(name = "COIN_ID") private Long id; @Column(name="CODE") private String code; @Column(name="WEIGHT") private Double weight; @Column(name="DSC") private String dsc; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public Double getWeight() { return weight; } public void setWeight(Double weight) { this.weight = weight; } public String getDsc() { return dsc; } public void setDsc(String dsc) { this.dsc = dsc; } }
package com.qiyewan.crm_joint.service; import com.qiyewan.crm_joint.domain.ContractServiceDetail; import java.util.List; public interface ContractServiceDetailService { List<ContractServiceDetail> getContractServiceDetails(String contractServiceId); }
package com.lesports.albatross.listener.community; /** * 社区动态评论长按监听 * Created by jiangjianxiong on 16/6/8. */ public interface OnCommentLongClickListener { /** * @param parentPosition 位于父类list中得位置 * @param childPosition 所处list中的位置 * @param comment 评论内容 * @param comment_id 评论ID */ void onCommentLongClickEvent(int parentPosition, int childPosition, String comment, String comment_id); }
package com.seeker.datedialog.widget.wheel; import android.content.Context; import android.util.AttributeSet; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.seeker.datedialog.widget.util.DeviceUtils; import com.seeker.datedialog.widget.wheel.abs.WheelAdapterView; import com.seeker.datedialog.widget.wheel.abs.WheelGallery; /** * 纯文字,WheelTextView。。 选中的文字,会高亮,中部有实现分割线 * @author zhengxiaobin <gybin02@Gmail.com> * @since 2016/4/13 */ public class WheelTextView extends WheelView{ private WheelTextAdapter wheelTextAdapter; Context context; private String[] mData; private OnWheelItemSelectedListener listener; private int textColor=0xffff5073; private int textColorUnselect=0xff999999; public WheelTextView(Context context) { super(context); init(context); } /** * 换肤 需要这个构造函数 * @param context * @param attrs */ public WheelTextView(Context context, AttributeSet attrs) { super(context,attrs); init(context); } public WheelTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context); } public void init(Context context){ this.context=context; this.wheelTextAdapter = new WheelTextAdapter(context); this.setAdapter(wheelTextAdapter); this.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(WheelAdapterView<?> parent, View view, int position, long id) { wheelTextAdapter.setSelectItem(position); if(listener!=null){ listener.onItemSelected(parent,view,position,id); } } @Override public void onNothingSelected(WheelAdapterView<?> parent) { } }); } public void setData(String[] data) { mData = data; wheelTextAdapter.setData(mData); wheelTextAdapter.notifyDataSetChanged(); } public void setSelect(int select){ this.setSelection(select); wheelTextAdapter.setSelectItem(select); } public void setColor(int color){ // super.setPaintColor(color); textColor=color; } public void setOnWheelItemSelectListener(OnWheelItemSelectedListener listener){ this.listener=listener; } /** * Adapter数据源 TextVIew实现 * @author zhengxiaobin <gybin02@Gmail.com> * @since 2016/4/13 21:39 */ protected class WheelTextAdapter extends BaseAdapter { String[] mData = {}; int mWidth = ViewGroup.LayoutParams.MATCH_PARENT; int mHeight = 60; private int selectItem; Context mContext = null; public WheelTextAdapter(Context context) { mContext = context; mHeight = (int) DeviceUtils.dip2px(context, mHeight); } public void setData(String[] data) { mData = data; this.notifyDataSetChanged(); } // // public void setItemSize(int width, int height) { // mWidth = width; // mHeight = (int) Utils.pixelToDp(mContext, height); // } public void setSelectItem(int selectItem) { if (this.selectItem != selectItem) { this.selectItem = selectItem; notifyDataSetChanged(); } } @Override public int getCount() { return mData.length; } @Override public String getItem(int position) { return mData[position]; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { TextView textView = null; if (null == convertView) { convertView = new TextView(mContext); convertView.setLayoutParams(new WheelGallery.LayoutParams(mWidth, mHeight)); textView = (TextView) convertView; textView.setGravity(Gravity.CENTER); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20); } if (null == textView) { textView = (TextView) convertView; } String text = mData[position]; textView.setText(text); if(selectItem==position){ textView.setTextColor(textColor); }else{ textView.setTextColor(textColorUnselect); } return convertView; } } public interface OnWheelItemSelectedListener { public void onItemSelected(WheelAdapterView<?> parent, View view, int position, long id); } }
package String_Level1.Programming_Questions; import java.util.Scanner; public class P23 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String S[] =new String[6]; int[] rollNos = new int[6]; for(int i=1;i<=5;i++) { rollNos[i]=sc.nextInt(); S[i]=sc.next(); } System.out.println("R.N"+" "+"Name"); for(int i=1;i<=5;i++) { System.out.println(rollNos[i]+" "+S[i]); } } }
/* * Copyright 2002-2012 the original author or authors. * * 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 * * https://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.springframework.jmx.export.naming; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; /** * Interface that allows infrastructure components to provide their own * {@code ObjectName}s to the {@code MBeanExporter}. * * <p><b>Note:</b> This interface is mainly intended for internal usage. * * @author Rob Harrop * @since 1.2.2 * @see org.springframework.jmx.export.MBeanExporter */ public interface SelfNaming { /** * Return the {@code ObjectName} for the implementing object. * @throws MalformedObjectNameException if thrown by the ObjectName constructor * @see javax.management.ObjectName#ObjectName(String) * @see javax.management.ObjectName#getInstance(String) * @see org.springframework.jmx.support.ObjectNameManager#getInstance(String) */ ObjectName getObjectName() throws MalformedObjectNameException; }
@javax.xml.bind.annotation.XmlSchema(namespace = "http://demo.bottomup.com/") package com.bottomup.demo;
package br.com.facisa.bd2.projeto.agendadecompromissos; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "compromissoProfissional") public class CompromissoProfissional{ private int id; private String dataCompromisso; private String horaCompromisso; private String Descrišao; private String local; private String qtdTempo; private String Periodicidade; @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) @Column(name = "compromisso_id") public int getId() { return id; } public void setId(int id) { this.id = id; } public String getDataCompromisso() { return dataCompromisso; } public void setDataCompromisso(String dataCompromisso) { this.dataCompromisso = dataCompromisso; } public String getHoraCompromisso() { return horaCompromisso; } public void setHoraCompromisso(String horaCompromisso) { this.horaCompromisso = horaCompromisso; } public String getDescrišao() { return Descrišao; } public void setDescrišao(String descrišao) { Descrišao = descrišao; } public String getLocal() { return local; } public void setLocal(String local) { this.local = local; } public String getQtdTempo() { return qtdTempo; } public void setQtdTempo(String qtdTempo) { this.qtdTempo = qtdTempo; } public String getPeriodicidade() { return Periodicidade; } public void setPeriodicidade(String periodicidade) { Periodicidade = periodicidade; } }
/* * $Id$ * * ### Copyright (C) 2005 Michael Fuchs ### * ### All Rights Reserved. ### * * Author: Michael Fuchs * E-Mail: michael.fuchs@unico-group.com * URL: http://www.michael-a-fuchs.de * * RCS Information * Author..........: $Author$ * Date............: $Date$ * Revision........: $Revision$ * State...........: $State$ */ package org.dbdoclet.test.sample; import junit.framework.TestCase; public class SampleTestCase extends TestCase { protected String sourcePath = "java"; protected String tmpPath = "sampleTmp"; public void setUp() { } public void tearDown() { } } /* * $Log$ */
package JV2_assement6; import javax.jws.soap.SOAPBinding; import java.sql.Connection; import java.util.ArrayList; public class DAOUser { public DAOUser() { super(); } @Override public int ArrayLi<User> getUsers() { String sql = "SELECT * FROM user"; Connector connector = Connector.getQuery(sql); ArrayList<User> users = new ArrayList<>(); while (rs.next()){ Integer id = rs.getInt("id"); String username = rs.getString("username"); String email = rs.getString ("email"); String password = rs.getSring("passwdrd"); Integer status = rs.getString("status"); User u = new User(id,username,email,password,status); users.add(u); } return users; }catch (Exception){} return null; @Override public boolean equals(Object obj) { return super.equals(obj); } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } @Override public String toString() { return super.toString(); } @Override protected void finalize() throws Throwable { super.finalize(); } }
/* * (c) 2009 Thomas Smits */ package de.smits_net.tpe.callback; public class Berechnung { public static int[] berechne(int[][] input, Funktion funktion) { int[] ergebnis = new int[input.length]; for (int i = 0; i < input.length; i++) { ergebnis[i] = funktion.apply(input[i][0], input[i][1]); } return ergebnis; } }
package com.ql.util.express; /** * 数据类型定义 * @author qhlhl2010@gmail.com * */ public class OperateData { // extends ExpressTreeNodeImple { protected Object dataObject; public Class<?> type; public OperateData(Object obj, Class<?> aType) { this.type = aType; this.dataObject = obj; } public Class<?> getDefineType(){ throw new RuntimeException(this.getClass().getName() + "必须实现方法:getDefineType"); } public Class<?> getType(InstructionSetContext<String,Object> parent) throws Exception { if (type != null) return type; Object obj = this.getObject(parent); if (obj == null) return null; else return obj.getClass(); } public final Object getObject(InstructionSetContext<String,Object> context) throws Exception { return getObjectInner(context); } public Object getObjectInner(InstructionSetContext<String,Object> context){ return this.dataObject; } public void setObject(InstructionSetContext<String,Object> parent, Object object) { throw new RuntimeException("必须在子类中实现此方法"); } public String toString() { if( this.dataObject == null) return this.type + ":null"; else{ if(this.dataObject instanceof Class){ return ExpressUtil.getClassName((Class<?>)this.dataObject); }else{ return this.dataObject.toString(); } } } public void toResource(StringBuilder builder,int level){ if(this.dataObject != null){ builder.append(this.dataObject.toString()); }else{ builder.append("null"); } } }
package jianzhioffer; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.stream.Collectors; /** * @ClassName : Solution45 * @Description : 把数组排成最小的数 * 例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。 * * 思路:定义一个比较大小的规则 * @Date : 2019/9/19 20:20 */ public class Solution45 { public String PrintMinNumber(int [] numbers) { ArrayList<String> list=new ArrayList<>(); if (numbers==null|| numbers.length==0) return ""; for (int x:numbers) list.add(String.valueOf(x)); Collections.sort(list, new Comparator<String>() { @Override public int compare(String o1, String o2) { String s1=o1+o2; String s2=o2+o1; return s1.compareTo(s2); } }); return list.stream().collect(Collectors.joining()); } }
package com.jdnew.library.hotfix.andfix; import android.app.Service; import android.content.Intent; import android.os.Handler; import android.os.IBinder; import android.os.Message; import androidx.annotation.Nullable; import java.io.File; /** * AndFix 服务 */ public class AndFixService extends Service { private String mPatchFileDir; private String mPatchFile; private static final int UPDATE_PATCH = 0x02; private static final int DOWNLOAD_PATCH = 0x01; private static final String FILE_END = ".apatch"; private Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); } }; @Override public void onCreate() { super.onCreate(); init(); } private void init() { mPatchFileDir = getExternalCacheDir().getAbsolutePath() + "/apatch/"; File patchDir = new File(mPatchFileDir); try{ if (patchDir == null || !patchDir.exists()) { patchDir.mkdir(); } }catch (Exception e){ e.printStackTrace(); stopSelf(); } } @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { mHandler.sendEmptyMessage() return START_NOT_STICKY; } }
package com.example.sheduleorganizer; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.Adapter; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.Spinner; import android.widget.Toast; import com.google.gson.Gson; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import static com.example.sheduleorganizer.MainActivity.EXTRA_MESSAGE; public class DisciplinesActivity<course_id> extends AppCompatActivity{ private static UserManager userManager; private ArrayList<String> textStrings = new ArrayList<String>(); private List<Subjects> recyclerViewStrings = new ArrayList<>(); private ImageView add; private Spinner dropdown; private Adapter dropdownAdapter; private Long course_id ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_disciplines); userManager = userManager.getInstance(); add = findViewById(R.id.add); dropdown = findViewById(R.id.selectCourse); dropdownAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, textStrings); dropdown.setAdapter((ArrayAdapter)dropdownAdapter); SharedPreferences shared = getSharedPreferences("info", MODE_PRIVATE); final String userId = shared.getString("id", "DEFAULT"); Log.d("userId", userId); userManager.getCoursesByIdUser(Long.parseLong(userId), new Callback<List<Courses>>() { @Override public void onResponse(Call<List<Courses>> call, Response<List<Courses>> response) { Log.w(" => ", new Gson().toJson(response)); if (response.code() == 200) { Log.d("status", "200"); for (int i = 0; i < response.body().size(); i++) { textStrings.add(response.body().get(i).getTitle()); } ((ArrayAdapter) dropdownAdapter).notifyDataSetChanged(); } else { Log.d("status", "Failed"); } } @Override public void onFailure(Call<List<Courses>> call, Throwable t) { Log.d("eroos", t.getMessage()); Toast.makeText(DisciplinesActivity.this, "Error is " + t.getMessage() , Toast.LENGTH_LONG).show(); } }); // Recycler view Call RecyclerView subjectsList = (RecyclerView) findViewById(R.id.subjectsList); final ListAdapterSubjects adpater = new ListAdapterSubjects((ArrayList<Subjects>) recyclerViewStrings, DisciplinesActivity.this); subjectsList.setAdapter(adpater); subjectsList.setLayoutManager(new LinearLayoutManager(DisciplinesActivity.this)); dropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){ @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { recyclerViewStrings.clear(); userManager.getCourseByTitle(Long.parseLong(userId),String.valueOf(parent.getItemAtPosition(position)), new Callback<List<Courses>>() { @Override public void onResponse(Call<List<Courses>> call, Response<List<Courses>> response) { Log.w(" => ", new Gson().toJson(response)); if (response.code() == 200) { Log.d("status", "200"); course_id= response.body().get(0).getId(); userManager.getSubjectsByCourse(response.body().get(0).getId(), new Callback<List<Subjects>>() { @Override public void onResponse(Call<List<Subjects>> call, Response<List<Subjects>> response) { Log.w(" => ", new Gson().toJson(response)); if (response.code() == 200) { Log.d("statusSubjects", "200"); for (int i = 0; i < response.body().size(); i++) { recyclerViewStrings.add(response.body().get(i)); } adpater.notifyDataSetChanged(); } else { Log.d("status", "Failed"); } } @Override public void onFailure(Call<List<Subjects>> call, Throwable t) { Log.d("eroos", t.getMessage()); Toast.makeText(DisciplinesActivity.this, "Error is " + t.getMessage() , Toast.LENGTH_LONG).show(); } }); } else { Log.d("status", "Failed"); } } @Override public void onFailure(Call<List<Courses>> call, Throwable t) { Log.d("eroos", t.getMessage()); Toast.makeText(DisciplinesActivity.this, "Error is " + t.getMessage() , Toast.LENGTH_LONG).show(); } }); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); add.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if(course_id!=0){ Intent i = new Intent(DisciplinesActivity.this, CreateSubjectForm.class); i.putExtra("course_id",Long.toString(course_id)); startActivity(i); } } }); BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation); navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.signOut: SharedPreferences loginPreferences = getSharedPreferences("info", MODE_PRIVATE); SharedPreferences.Editor editor = loginPreferences.edit(); editor.putString("id",null); editor.putString("username",null); editor.commit(); Intent i = new Intent(DisciplinesActivity.this, Login.class); i.putExtra(EXTRA_MESSAGE, "1"); startActivity(i); return true; case R.id.menu: Intent is = new Intent(DisciplinesActivity.this, Menu.class); startActivity(is); return true; } return false; } }); } }
package com.ravi.travel.budget_travel.domain; import com.fasterxml.jackson.annotation.JsonBackReference; import com.ravi.travel.budget_travel.utilities.SocialMedia; public class LetsConnect { private long id; @JsonBackReference private Author author; private SocialMedia socialMedia; private String socialMediaUrl; public long getId() { return id; } public void setId(long id) { this.id = id; } public SocialMedia getSocialMedia() { return socialMedia; } public void setSocialMedia(SocialMedia socialMedia) { this.socialMedia = socialMedia; } public String getSocialMediaUrl() { return socialMediaUrl; } public void setSocialMediaUrl(String socialMediaUrl) { this.socialMediaUrl = socialMediaUrl; } @Override public String toString() { return "LetsConnect{" + "id=" + id + ", author=" + author + ", socialMedia=" + socialMedia + ", socialMediaUrl='" + socialMediaUrl + '\'' + '}'; } public Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; } }
package AStarSearch; import javax.swing.*; import java.awt.*; import java.io.IOException; import java.util.*; import java.util.List; public class Window extends JFrame { Board board; public Window(List<WorldState> states) { super(); JFrame window = new JFrame("ZeldAStar"); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.board = new Board(states); window.setContentPane(board); window.setResizable(false); window.setVisible(true); window.setSize(1024, 720); //this.update(g); } // public void setStateOfBoard(WorldState state) { // this.board.setState(state); // } }
package org.yxm.modules.wan.repo.network; import java.util.List; import org.yxm.modules.wan.entity.WanArticleEntity; import org.yxm.modules.wan.entity.WanArticleWithTag; import org.yxm.modules.wan.entity.WanBaseEntity; import org.yxm.modules.wan.entity.WanPageEntity; import org.yxm.modules.wan.entity.WanTabEntity; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; /** * Wan 的所有网络请求api接口 */ public interface IWanApi { String BASE_URL = "http://wanandroid.com"; @GET(value = "/wxarticle/chapters/json") Call<WanBaseEntity<List<WanTabEntity>>> listWanTabs(); @GET(value = "/wxarticle/list/{authorId}/{page}/json") Call<WanBaseEntity<WanPageEntity<WanArticleEntity>>> listAuthorArticles( @Path("authorId") int authorId, @Path("page") int page ); @GET(value = "/wxarticle/list/{authorId}/{page}/json") Call<WanBaseEntity<WanPageEntity<WanArticleWithTag>>> listAuthorArticleWithTag( @Path("authorId") int authorId, @Path("page") int page ); }
package br.com.drem.entity; /** * @author AndreMart * @contacts: andremartins@outlook.com.br;andre.drem@gmail.com * @tel: 63 8412 1921 * @site: drem.com.br */ import javax.persistence.Entity; import javax.persistence.Table; @Entity @Table(name = "pessoa_juridica") public class PessoaJuridica extends Pessoa { private String cnpj; private String razaoSocial; private String inscricaoEstadual; private String matricula; public String getCnpj() { return cnpj; } public void setCnpj(String cnpj) { this.cnpj = cnpj; } public String getRazaoSocial() { return razaoSocial; } public void setRazaoSocial(String razaoSocial) { this.razaoSocial = razaoSocial; } public String getInscricaoEstadual() { return inscricaoEstadual; } public void setInscricaoEstadual(String inscricaoEstadual) { this.inscricaoEstadual = inscricaoEstadual; } public String getMatricula() { return matricula; } public void setMatricula(String matricula) { this.matricula = matricula; } }
package com.foxshooter.servlet; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.solr.client.solrj.SolrServerException; import com.foxshooter.bean.Log; import com.foxshooter.solr.SolrSeacher; public class SearchLogServlet extends HttpServlet { protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String queryString = request.getParameter("queryString"); System.out.println(queryString); SolrSeacher search = new SolrSeacher(); List<Log> logs = new ArrayList<Log>(); // Log log = new Log(); // log.logId = "swwwwwwwwwwww"; // log.operateTime = new Date(); // log.personName = "egawe"; // logs.add(log); try { logs = search.searchLogs(queryString); } catch (SolrServerException e) { e.printStackTrace(); } request.setAttribute("logs", logs); request.getRequestDispatcher("search.jsp").forward(request, response); } }
/////////////////////////////////////////////////////////////////////////////// //FILE: PanelUtils.java //PROJECT: Micro-Manager //SUBSYSTEM: ASIdiSPIM plugin //----------------------------------------------------------------------------- // // AUTHOR: Nico Stuurman, Jon Daniels // // COPYRIGHT: University of California, San Francisco, & ASI, 2013 // // LICENSE: This file is distributed under the BSD license. // License text is included with the source distribution. // // This file 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. // // IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES. package org.micromanager.asidispim.Utils; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.Hashtable; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFormattedTextField; import javax.swing.JLabel; import javax.swing.JSlider; import javax.swing.JSpinner; import javax.swing.SpinnerModel; import javax.swing.SpinnerNumberModel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.micromanager.asidispim.Data.Devices; import org.micromanager.asidispim.Data.Joystick; import org.micromanager.asidispim.Data.Positions; import org.micromanager.asidispim.Data.Properties; import org.micromanager.utils.ReportingUtils; /** * * @author nico * @author Jon */ public class PanelUtils { /** * makes JSlider for double values where the values are multiplied by a scale factor * before internal representation as integer (as JSlider requires) * @return */ public JSlider makeSlider(double min, double max, int scalefactor, Properties props, Devices devs, Devices.Keys devKey, Properties.Keys propKey) { class sliderListener implements ChangeListener, UpdateFromPropertyListenerInterface, DevicesListenerInterface { JSlider js_; int scalefactor_; Properties props_; Devices.Keys devKey_; Properties.Keys propKey_; public sliderListener(JSlider js, int scalefactor, Properties props, Devices.Keys devKey, Properties.Keys propKey) { js_ = js; scalefactor_ = scalefactor; props_ = props; devKey_ = devKey; propKey_ = propKey; } public void stateChanged(ChangeEvent ce) { if (!((JSlider)ce.getSource()).getValueIsAdjusting()) { // only change when user releases props_.setPropValue(devKey_, propKey_, (float)js_.getValue()/(float)scalefactor_, true); } } public void updateFromProperty() { js_.setValue((int)(scalefactor_*props_.getPropValueFloat(devKey_, propKey_, true))); } public void devicesChangedAlert() { // TODO refresh limits updateFromProperty(); } } int intmin = (int)(min*scalefactor); int intmax = (int)(max*scalefactor); JSlider js = new JSlider(JSlider.HORIZONTAL, intmin, intmax, intmin); // initialize with min value, will set to current value shortly ChangeListener l = new sliderListener(js, scalefactor, props, devKey, propKey); ((UpdateFromPropertyListenerInterface) l).updateFromProperty(); // set to value of property at present js.addChangeListener(l); devs.addListener((DevicesListenerInterface) l); props.addListener((UpdateFromPropertyListenerInterface) l); js.setMajorTickSpacing(intmax-intmin); js.setMinorTickSpacing(scalefactor); //Create the label table Hashtable<Integer, JLabel> labelTable = new Hashtable<Integer, JLabel>(); labelTable.put( new Integer(intmax), new JLabel(Double.toString(max)) ); labelTable.put( new Integer(intmin), new JLabel(Double.toString(min)) ); js.setLabelTable( labelTable ); js.setPaintTicks(true); js.setPaintLabels(true); return js; } /** * Constructs JCheckBox appropriately set up * @param label the GUI label * @param offValue the value of the property when not checked * @param onValue the value of the property when checked * @param props * @param devs * @param devKey * @param propKey * @return constructed JCheckBox */ public JCheckBox makeCheckBox(String label, String offValue, String onValue, Properties props, Devices devs, Devices.Keys devKey, Properties.Keys propKey) { /** * nested inner class * @author Jon */ class checkBoxListener implements ItemListener, UpdateFromPropertyListenerInterface, DevicesListenerInterface { JCheckBox jc_; String offValue_; String onValue_; Properties props_; Devices.Keys devKey_; Properties.Keys propKey_; public checkBoxListener(JCheckBox jc, String offValue, String onValue, Properties props, Devices.Keys devKey, Properties.Keys propKey) { jc_ = jc; offValue_ = offValue; onValue_ = onValue; props_ = props; devKey_ = devKey; propKey_ = propKey; } public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { props_.setPropValue(devKey_, propKey_, onValue_, true); } else { props_.setPropValue(devKey_, propKey_, offValue_, true); } } public void updateFromProperty() { jc_.setSelected(props_.getPropValueString(devKey_, propKey_, true).equals(onValue_)); } public void devicesChangedAlert() { updateFromProperty(); } } JCheckBox jc = new JCheckBox(label); ItemListener l = new checkBoxListener(jc, offValue, onValue, props, devKey, propKey); jc.addItemListener(l); devs.addListener((DevicesListenerInterface) l); props.addListener((UpdateFromPropertyListenerInterface) l); ((UpdateFromPropertyListenerInterface) l).updateFromProperty(); // set to value of property at present return jc; } /** * Creates spinner for integers in the GUI * Implements UpdateFromPropertyListenerInterface, causing updates in the model * that were generated by changes in the device to be propagated back to the UI */ public JSpinner makeSpinnerInteger(int min, int max, Properties props, Devices devs, Devices.Keys devKey, Properties.Keys propKey) { class SpinnerListenerInt implements ChangeListener, UpdateFromPropertyListenerInterface, DevicesListenerInterface { JSpinner sp_; Properties props_; Devices.Keys devKey_; Properties.Keys propKey_; public SpinnerListenerInt(JSpinner sp, Properties props, Devices.Keys devKey, Properties.Keys propKey) { sp_ = sp; props_ = props; devKey_ = devKey; propKey_ = propKey; } public void stateChanged(ChangeEvent ce) { props_.setPropValue(devKey_, propKey_, ((Integer)sp_.getValue()).intValue(), true); } public void updateFromProperty() { sp_.setValue(props_.getPropValueInteger(devKey_, propKey_, true)); } public void devicesChangedAlert() { updateFromProperty(); } } // read the existing value from property and make sure it is within our min/max limits int origVal = props.getPropValueInteger(devKey, propKey, true); if (origVal < min) { origVal = min; } if (origVal > max) { origVal = max; } SpinnerModel jspm = new SpinnerNumberModel(origVal, min, max, 1); JSpinner jsp = new JSpinner(jspm); SpinnerListenerInt ispl = new SpinnerListenerInt(jsp, props, devKey, propKey); jsp.addChangeListener(ispl); devs.addListener(ispl); props.addListener(ispl); return jsp; } /** * Creates spinner for floats in the GUI * Implements UpdateFromPropertyListenerInterface, causing updates in the model * that were generated by changes in the device to be propagated back to the UI */ public JSpinner makeSpinnerFloat(double min, double max, double step, Properties props, Devices devs, Devices.Keys devKey, Properties.Keys propKey) { // same as IntSpinnerListener except // - cast to Float object in stateChanged() // - getPropValueFloat in spimParamsChangedAlert() class SpinnerListenerFloat implements ChangeListener, UpdateFromPropertyListenerInterface, DevicesListenerInterface { JSpinner sp_; Properties props_; Devices.Keys devKey_; Properties.Keys propKey_; public SpinnerListenerFloat(JSpinner sp, Properties props, Devices.Keys devKey, Properties.Keys propKey) { sp_ = sp; props_ = props; devKey_ = devKey; propKey_ = propKey; } public void stateChanged(ChangeEvent ce) { // TODO figure out why the type of value in the numbermodel is changing type to float which necessitates this code float f; try { f = (float)((Double)sp_.getValue()).doubleValue(); } catch (Exception ex) { f = ((Float)sp_.getValue()).floatValue(); } props_.setPropValue(devKey_, propKey_, f, true); } public void updateFromProperty() { sp_.setValue(props_.getPropValueFloat(devKey_, propKey_, true)); } public void devicesChangedAlert() { updateFromProperty(); } } // read the existing value from property and make sure it is within our min/max limits double origVal = (double)props.getPropValueFloat(devKey, propKey, true); if (origVal < min) { origVal = min; } if (origVal > max) { origVal = max; } SpinnerModel jspm = new SpinnerNumberModel(origVal, min, max, step); JSpinner jsp = new JSpinner(jspm); SpinnerListenerFloat ispl = new SpinnerListenerFloat(jsp, props, devKey, propKey); jsp.addChangeListener(ispl); devs.addListener(ispl); props.addListener(ispl); return jsp; } /** * Constructs a DropDown box selecting between multiple strings * Sets selection based on property value and attaches a Listener * * @param key property key as known in the params * @param vals array of strings, each one is a different option in the dropdown * @return constructed JComboBox */ public JComboBox makeDropDownBox(String[] vals, Properties props, Devices devs, Devices.Keys devKey, Properties.Keys propKey) { /** * Listener for the string-based dropdown boxes * Updates the model in the params class with any GUI changes */ class StringBoxListener implements ActionListener, UpdateFromPropertyListenerInterface, DevicesListenerInterface { JComboBox box_; Properties props_; Devices.Keys devKey_; Properties.Keys propKey_; public StringBoxListener(JComboBox box, Properties props, Devices.Keys devKey, Properties.Keys propKey) { box_ = box; props_ = props; devKey_ = devKey; propKey_ = propKey; } public void actionPerformed(ActionEvent ae) { props_.setPropValue(devKey_, propKey_, (String) box_.getSelectedItem(), true); } public void updateFromProperty() { box_.setSelectedItem(props_.getPropValueString(devKey_, propKey_, true)); } public void devicesChangedAlert() { updateFromProperty(); } } JComboBox jcb = new JComboBox(vals); jcb.setSelectedItem(props.getPropValueString(devKey, propKey, true)); StringBoxListener l = new StringBoxListener(jcb, props, devKey, propKey); jcb.addActionListener(l); devs.addListener(l); props.addListener(l); return jcb; } /** * Creates field for user to type in new position for an axis, with default value of 0 * @param key * @param dir * @return */ public JFormattedTextField makeSetPositionField(Devices.Keys key, Joystick.Directions dir, Positions positions) { class setPositionListener implements PropertyChangeListener { private final Devices.Keys key_; private final Joystick.Directions dir_; private final Positions positions_; public void propertyChange(PropertyChangeEvent evt) { try { positions_.setPosition(key_, dir_, ((Number)evt.getNewValue()).doubleValue()); } catch (Exception e) { ReportingUtils.showError(e); } } setPositionListener(Devices.Keys key, Joystick.Directions dir, Positions positions) { key_ = key; dir_ = dir; positions_ = positions; } } JFormattedTextField tf = new JFormattedTextField(); tf.setValue(new Double(0.0)); tf.setColumns(4); PropertyChangeListener pc = new setPositionListener(key, dir, positions); tf.addPropertyChangeListener("value", pc); return tf; } }
package ExceptionsLecture; class FixedExample2 { static void assign(int [] arr, int index, int a, int b) // The following line is optional because we are dealing // with RuntimeExceptions { // "ducking all Exceptions and passing it off to the caller arr[index] = a/b; } public static void main(String[] args) { int [] arr = new int[10]; int index; try { index = Integer.parseInt(args[0]); int i = Integer.parseInt(args[1]); assign(arr, index, 10, i); } // The following will catch all Exceptions derived from RuntimeException that // haven't already been matched (i.e. NumberFormatException) catch (RuntimeException e) { System.out.println(" Some Runtime Exception: " +e); e.printStackTrace(); } System.out.println(" Finished Simple Example"); } }
package pro2e.teamX.userinterface; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Observable; import java.util.Observer; import java.util.StringTokenizer; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.KeyStroke; import pro2e.teamX.model.DataImport; import pro2e.teamX.model.Model; public class MenuBar extends JMenuBar implements Observer, ActionListener { JMenu menu, submenu; JMenuItem menuItemOnTop, submenuItem; JFrame frame; Controller controller; private JMenuItem openItem, saveItem, exportItem, quitItem; private JFileChooser jfchooser = new JFileChooser(new File(".//")); private SchrittantwortPlot schrittantwortPlot = new SchrittantwortPlot(); private String[] zeilen; private double[] y1; public MenuBar(Controller controller, JFrame frame) { this.frame = frame; this.controller = controller; menu = new JMenu("Datei"); menu.setMnemonic(KeyEvent.VK_D); menu.addSeparator(); // submenu = new JMenu("A submenu"); // submenu.setMnemonic(KeyEvent.VK_S); // submenuItem = new JMenuItem("SubmenuItem"); // submenu.add(submenuItem); // menu.add(submenu); menuItemOnTop = new JMenuItem("Immer im Vordergrund", KeyEvent.VK_T); menuItemOnTop.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, ActionEvent.ALT_MASK)); menuItemOnTop.setActionCommand("OnTop"); menuItemOnTop.addActionListener(this); menu.add(menuItemOnTop); JMenuItem menuItemResizable = new JMenuItem("Resizable", KeyEvent.VK_R); menuItemResizable.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, ActionEvent.ALT_MASK)); menuItemResizable.setActionCommand("Resizable"); menuItemResizable.addActionListener(this); menu.add(menuItemResizable); JMenuItem menuItemNotResizable = new JMenuItem("Not Resizable", KeyEvent.VK_N); menuItemNotResizable.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.ALT_MASK)); menuItemNotResizable.setActionCommand("NotResizable"); menuItemNotResizable.addActionListener(this); menu.add(menuItemNotResizable); add(menu); openItem = new JMenuItem("Oeffnen", KeyEvent.VK_O); menu.add(openItem); openItem.addActionListener(this); } public void update(Observable o, Object obj) {} public void actionPerformed(ActionEvent e) { if (e.getSource() == openItem) { int returnVal = jfchooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = jfchooser.getSelectedFile(); System.out.println(file.getAbsolutePath()); this.zeilen = leseDatei1(file.getAbsolutePath()); for (int i = 0; i < zeilen.length; i++) { System.out.println("" + zeilen[i]); } System.out.println("" + zeilen.length); } if (e.getActionCommand().equals("Resizable")) { frame.setResizable(true); Dimension dim = frame.getSize(); dim.width -= 100; frame.setSize(dim); } if (e.getActionCommand().equals("NotResizable")) { frame.setResizable(false); Dimension dim = frame.getSize(); dim.width += 100; frame.setSize(dim); } if (e.getActionCommand().equals("OnTop")) { StatusBar.showStatus(this, e, e.getActionCommand()); if (((JFrame) this.getTopLevelAncestor()).isAlwaysOnTop()) { ((JFrame) this.getTopLevelAncestor()).setAlwaysOnTop(false); menuItemOnTop.setText("Allwas on Top"); } else { ((JFrame) this.getTopLevelAncestor()).setAlwaysOnTop(true); menuItemOnTop.setText("Not allwas on Top"); } } } } private String[] leseDatei1(String absolutePath) { String[] str = null; try { // Anzahl Zeilen zählen: BufferedReader eingabeDatei = new BufferedReader(new FileReader(absolutePath)); int cnt = 0; while (eingabeDatei.readLine() != null) { cnt++; } eingabeDatei.close(); // Gezählte Anzahle Zeilen lesen: eingabeDatei = new BufferedReader(new FileReader(absolutePath)); str = new String[cnt]; for (int i = 0; i < str.length; i++) { str[i] = eingabeDatei.readLine(); } eingabeDatei.close(); } catch (IOException exc) { System.err.println("Dateifehler: " + exc.toString()); } return str; } }
package com.random.randomizeit.exceptions; import com.random.randomizeit.models.ErrorDTO; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; @ControllerAdvice public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { @ExceptionHandler(AnswerNotFoundException.class) public ResponseEntity<Object> AnswerNotFound(AnswerNotFoundException e) { return new ResponseEntity<>(new ErrorDTO(e.getMessage()), HttpStatus.NOT_FOUND); } @ExceptionHandler(QuestionIsRequiredException.class) public ResponseEntity<Object> QuestionRequired(QuestionIsRequiredException e){ return new ResponseEntity<>(new ErrorDTO(e.getMessage()),HttpStatus.BAD_REQUEST); } }
package com.hello.ourcookies.download; /** * 下载任务回调 */ public interface DownLoadListener { /** * 下载进度 * * @param progress 进度值 */ void onProgress(int progress); /** * 下载成功 */ void onSuccess(); /** * 下载失败 */ void onFailed(); /** * 暂停下载 */ void onPaused(); /** * 取消下载 */ void onCanceled(); }
// Langauage: Java // Author: Ishita Chourasia // Github: https://github.com/ishitach import java.util.*; import java.lang.*; import java.io.*; class Ideone { public static void main (String[] args) throws java.lang.Exception { System.out.println("Hello, World!") } }
package com.ads.similator.generator; import java.util.ArrayList; import com.ads.similator.entity.User; public class UserGenerator implements Generator<User>{ @Override public ArrayList<User> generate() { // TODO Auto-generated method stub return null; } public UserGenerator(){}; public UserGenerator(String filename){}; }
package com.mycompany.ghhrkapp1.service; import org.springframework.data.domain.Page; import com.mycompany.ghhrkapp1.entity.Employees; public interface EmployeeService { Iterable<Employees> listAll(); Page<Employees> listAllPaged(int page); }
package com.ledungcobra.databoostrap; import com.ledungcobra.applicationcontext.AppContext; import com.ledungcobra.entites.EducationType; import com.ledungcobra.entites.StudentAccount; import com.ledungcobra.entites.StudentInfo; import com.ledungcobra.entites.TeachingManager; import lombok.val; import java.util.Date; public class DataBoostrap { public void run() { } }
package me.jcomo.slimtwitter.fragments; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.widget.SwipeRefreshLayout; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import android.widget.ProgressBar; import com.codepath.apps.slimtwitter.R; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import me.jcomo.slimtwitter.TwitterApplication; import me.jcomo.slimtwitter.activities.ProfileActivity; import me.jcomo.slimtwitter.activities.TweetDetailActivity; import me.jcomo.slimtwitter.adapters.TweetsArrayAdapter; import me.jcomo.slimtwitter.listeners.EndlessScrollListener; import me.jcomo.slimtwitter.models.Tweet; import me.jcomo.slimtwitter.models.User; import me.jcomo.slimtwitter.net.TwitterClient; import me.jcomo.slimtwitter.net.TwitterResponseHandler; public abstract class TweetsListFragment extends Fragment { private static final int VISIBILITY_THRESHOLD = 2; private ProgressBar progressBarFooter; private SwipeRefreshLayout swipeContainer; private long oldestTweetId; private List<Tweet> tweets; private TweetsArrayAdapter aTweets; private ListView lvTweets; private TwitterClient client; public abstract void getInitialTweets(OnCompleteHandler handler); public abstract void getMoreTweets(OnCompleteHandler handler); interface OnCompleteHandler { void onComplete(); } public void setTweets(List<Tweet> tweets) { aTweets.clear(); addTweets(tweets); } public void setTweets(List<Tweet> tweets, long oldestTweetId) { setTweets(tweets); setOldestTweetId(oldestTweetId); } public void addTweets(List<Tweet> tweets) { aTweets.addAll(tweets); updateOldestTweetId(); } public void addTweets(List<Tweet> tweets, long oldestTweetId) { addTweets(tweets); setOldestTweetId(oldestTweetId); } public void insertTweet(int position, Tweet tweet) { tweets.add(position, tweet); aTweets.notifyDataSetChanged(); } /** * Returns the tweet id that is one before the last one currently being displayed in the view. * The reason it returns the one prior is because this is used to get more tweets but the Twitter * API uses the id that is less than or equal to the max id, so this would result in an off * by one error if the current id was returned. */ public long getOldestTweetId() { return oldestTweetId - 1; } private void setOldestTweetId(long oldestTweetId) { this.oldestTweetId = oldestTweetId; } public TwitterClient getClient() { return client; } public void loadProfile(User user) { Intent i = new Intent(getActivity(), ProfileActivity.class); i.putExtra(ProfileActivity.USER, user); startActivity(i); } public void replyToTweet(Tweet tweet) { FragmentManager fm = getActivity().getSupportFragmentManager(); TweetReplyFragment fragment = TweetReplyFragment.newInstance(tweet); fragment.show(fm, "tweet_reply_fragment"); } public void retweet(Tweet tweet) { client.postRetweet(tweet.getUid(), new TwitterResponseHandler() { @Override public void onFailure(Throwable t, JSONObject errorResponse) { if (errorResponse != null) { Log.w("DEBUG", errorResponse.toString()); } } }); } public void updateFavoriteStatus(Tweet tweet) { client.postFavoriteStatus(tweet.getUid(), tweet.isFavorited(), new TwitterResponseHandler() { @Override public void onFailure(Throwable t, JSONObject errorResponse) { if (errorResponse != null) { Log.w("DEBUG", errorResponse.toString()); } } }); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_tweets_list, container, false); setupViews(view, savedInstanceState); showProgressBar(); getInitialTweets(new OnCompleteHandler() { @Override public void onComplete() { hideProgressBar(); } }); return view; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); client = TwitterApplication.getRestClient(); setupDataSource(); } private void setupDataSource() { tweets = new ArrayList<>(); aTweets = new TweetsArrayAdapter(getActivity(), tweets); aTweets.setOnTweetClickedListener(new TweetsArrayAdapter.OnTweetClickedListener() { @Override public void onTweetClicked(int position) { displayTweet(aTweets.getItem(position)); } }); aTweets.setOnProfileClickedListener(new TweetsArrayAdapter.OnProfileClickedListener() { @Override public void onProfileClicked(int position) { Tweet tweet = aTweets.getItem(position); loadProfile(tweet.getUser()); } }); aTweets.setOnReplyClickedListener(new TweetsArrayAdapter.OnReplyClickedListener() { @Override public void onReplyClicked(int position) { replyToTweet(aTweets.getItem(position)); } }); aTweets.setOnRetweetListener(new TweetsArrayAdapter.OnRetweetListener() { @Override public void onRetweet(Tweet tweet) { retweet(tweet); } }); aTweets.setOnFavoriteListener(new TweetsArrayAdapter.OnFavoriteListener() { @Override public void onFavorite(Tweet tweet) { updateFavoriteStatus(tweet); } }); } private void setupViews(View view, Bundle savedInstanceState) { setupSwipeToRefresh(view); setupTimelineView(view, savedInstanceState); } public void setupSwipeToRefresh(View view) { swipeContainer = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container); swipeContainer.setColorSchemeResources( R.color.primary, R.color.primary_dark, R.color.primary_light); swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { getInitialTweets(new OnCompleteHandler() { @Override public void onComplete() { swipeContainer.setRefreshing(false); } }); } }); } public void setupTimelineView(View view, Bundle savedInstanceState) { lvTweets = (ListView) view.findViewById(R.id.lv_tweets); View footer = getLayoutInflater(savedInstanceState).inflate(R.layout.footer_progress, null); progressBarFooter = (ProgressBar) footer.findViewById(R.id.pb_loading); lvTweets.addFooterView(footer); lvTweets.setAdapter(aTweets); lvTweets.setOnScrollListener(new EndlessScrollListener(VISIBILITY_THRESHOLD) { @Override public void onLoadMore(int page, int totalItemCount) { if (totalItemCount > 1) { // Total item includes the footer view showProgressBar(); getMoreTweets(new OnCompleteHandler() { @Override public void onComplete() { hideProgressBar(); } }); } } }); } private void updateOldestTweetId() { if (tweets.size() > 0) { Tweet oldestTweet = tweets.get(tweets.size() - 1); setOldestTweetId(oldestTweet.getUid()); } } private void displayTweet(Tweet tweet) { Intent i = new Intent(getActivity(), TweetDetailActivity.class); i.putExtra(TweetDetailActivity.TWEET, tweet); startActivity(i); } private void showProgressBar() { progressBarFooter.setVisibility(View.VISIBLE); } private void hideProgressBar() { progressBarFooter.setVisibility(View.GONE); } }
package com.example.appretrofitwithrecyclerviewandmvvm.ui; import androidx.appcompat.app.AppCompatActivity; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProviders; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import com.example.appretrofitwithrecyclerviewandmvvm.R; import com.example.appretrofitwithrecyclerviewandmvvm.pojo.Post; import java.util.List; public class MainActivity extends AppCompatActivity { RecyclerView recyclerView; PostViewModel postViewModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView=findViewById(R.id.recycler_id); postViewModel= ViewModelProviders.of(this).get(PostViewModel.class); postViewModel.listMutableLiveData.observe(this, new Observer<List<Post>>() { @Override public void onChanged(List<Post> posts) { PostAdabter adabter=new PostAdabter(posts); RecyclerView.LayoutManager manager=new LinearLayoutManager(getApplication()); recyclerView.setLayoutManager(manager); recyclerView.setAdapter(adabter); } }); postViewModel.getData(); } }
package com.GestiondesClub.entities; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQuery; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonBackReference; @Entity @Table(name="sponsarisation_materiel") @NamedQuery(name="SponsarisationMateriel.findAll", query="SELECT sm FROM SponsarisationMateriel sm") public class SponsarisationMateriel { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", updatable = false, nullable = false) private Long id; @JsonBackReference(value="Sponsarisation-Materiel") @ManyToOne @JoinColumn(name = "evenementsponseur_id") EvenementSponseur evenementSpon; @ManyToOne @JoinColumn(name = "materielexterne_id") MaterielExterne materielExterne; @Column(name="quantite") private int quantite; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public EvenementSponseur getEvenementSpon() { return evenementSpon; } public void setEvenementSpon(EvenementSponseur evenementSpon) { this.evenementSpon = evenementSpon; } public MaterielExterne getMaterielExterne() { return materielExterne; } public void setMaterielExterne(MaterielExterne materielExterne) { this.materielExterne = materielExterne; } public int getQuantite() { return quantite; } public void setQuantite(int quantite) { this.quantite = quantite; } @Override public String toString() { return "SponsarisationMateriel [id=" + id + ", evenementSpon=" + evenementSpon + ", materielExterne=" + materielExterne + ", quantite=" + quantite + "]"; } }