text stringlengths 10 2.72M |
|---|
package com.huailai.club.huailaiclub.view;
import android.content.Context;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;
/**
* Created by lenovo on 2017/3/22.
*/
public class RectangleView extends View{
private Context context;
public RectangleView(Context context) {
super(context);
this.context=context;
}
public RectangleView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context=context;
}
public RectangleView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.context=context;
}
public void setHeightRate(float rate){
int width = getScreenWidth(context);
int height =(int)(width*rate) ;
getLayoutParams().height=height;
}
/**
* 获取屏幕宽度
* @return the int
*/
public int getScreenWidth(Context activity) {
// 获取屏幕密度(方法2)
DisplayMetrics dm = new DisplayMetrics();
dm = activity.getResources().getDisplayMetrics();
return dm.widthPixels; // 屏幕宽(像素,如:480px)
}
}
|
package com.irozon.sneaker;
import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.GradientDrawable;
import android.view.View;
import android.view.Window;
/**
* Created by hammad.akram on 2/27/18.
*/
class Utils {
/**
* Returns status bar height.
*
* @return
*/
static int getStatusBarHeight(Activity activity) {
Rect rectangle = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rectangle);
return Math.max(rectangle.top, 0);
}
static int convertToDp(Context context, float sizeInDp) {
float scale = context.getResources().getDisplayMetrics().density;
return (int) (sizeInDp * scale + 0.5f);
}
static void customView(Context context, View v, int backgroundColor, int cornerRadius) {
int radiusInDP = convertToDp(context, cornerRadius);
GradientDrawable shape = new GradientDrawable();
shape.setShape(GradientDrawable.RECTANGLE);
shape.setCornerRadii(
new float[]{radiusInDP, radiusInDP, radiusInDP, radiusInDP, radiusInDP, radiusInDP, radiusInDP,
radiusInDP});
shape.setColor(backgroundColor);
v.setBackground(shape);
}
}
|
package com.netcracker.DTO;
public class UserModerDto {
private Long userId;
private String fio;
private String email;
private String phoneNumber;
private Long numberOfComplaints;
public Long getIsBan() {
return isBan;
}
public void setIsBan(Long isBan) {
this.isBan = isBan;
}
private Long isBan;
public UserModerDto(Long userId, String fio, String email, String phoneNumber, Long numberOfComplaints, Long isBan) {
this.userId = userId;
this.fio = fio;
this.email = email;
this.phoneNumber = phoneNumber;
this.numberOfComplaints = numberOfComplaints;
this.isBan = isBan;
}
public UserModerDto() {
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getFio() {
return fio;
}
public void setFio(String fio) {
this.fio = fio;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public Long getNumberOfComplaints() {
return numberOfComplaints;
}
public void setNumberOfComplaints(Long numberOfComplaints) {
this.numberOfComplaints = numberOfComplaints;
}
}
|
/*
* Copyright (c) 2017-2020 Peter G. Horvath, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.blausql.ui;
import com.github.blausql.core.connection.ConnectionDefinition;
import com.github.blausql.ui.components.CloseOnEscapeKeyPressWindow;
import com.googlecode.lanterna.gui.Action;
import com.googlecode.lanterna.gui.Border;
import com.googlecode.lanterna.gui.component.Button;
import com.googlecode.lanterna.gui.component.EmptySpace;
import com.googlecode.lanterna.gui.component.Label;
import com.googlecode.lanterna.gui.component.Panel;
import com.googlecode.lanterna.gui.component.PasswordBox;
import com.googlecode.lanterna.gui.component.TextBox;
import com.googlecode.lanterna.gui.dialog.DialogResult;
final class CredentialsDialog extends CloseOnEscapeKeyPressWindow {
private static final int USERNAME_BOX_LEN = 20;
private static final int PASSWORD_BOX_LEN = 20;
private final TextBox userNameTextBox;
private final PasswordBox passwordPasswordBox;
private DialogResult dialogResult = DialogResult.CANCEL;
CredentialsDialog(ConnectionDefinition cd) {
super("Enter credentials for " + cd.getConnectionName());
addComponent(new Label("User name:"));
userNameTextBox = new TextBox(cd.getUserName(), USERNAME_BOX_LEN);
addComponent(userNameTextBox);
addComponent(new Label("Password:"));
passwordPasswordBox = new PasswordBox(cd.getPassword(), PASSWORD_BOX_LEN);
addComponent(passwordPasswordBox);
Button okButton = new Button("OK", new Action() {
public void doAction() {
dialogResult = DialogResult.OK;
close();
}
});
Button cancelButton = new Button("Cancel", new Action() {
public void doAction() {
dialogResult = DialogResult.CANCEL;
close();
}
});
int labelWidth = userNameTextBox.getPreferredSize().getColumns();
Panel buttonPanel = new Panel(new Border.Invisible(), Panel.Orientation.HORISONTAL);
int leftPadding = 0;
int buttonsWidth = okButton.getPreferredSize().getColumns()
+ cancelButton.getPreferredSize().getColumns() + 1;
if (buttonsWidth < labelWidth) {
leftPadding = (labelWidth - buttonsWidth) / 2;
}
if (leftPadding > 0) {
buttonPanel.addComponent(new EmptySpace(leftPadding, 1));
}
buttonPanel.addComponent(okButton);
buttonPanel.addComponent(cancelButton);
addComponent(new EmptySpace());
addComponent(buttonPanel);
setFocus(okButton);
}
public DialogResult getDialogResult() {
return dialogResult;
}
public String getUserName() {
return userNameTextBox.getText();
}
public String getPassword() {
return passwordPasswordBox.getText();
}
}
|
package com.housesline.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
/**
* 数据库链接工具类
* @author cdh
*
*/
public class JDBCUtils {
//创建数据库使用的默认数据源
public static final String DEFAULT_DRIVER = PropertiesUtil.DEFAULT_DRIVER;
public static final String DEFAULT_URL = PropertiesUtil.DEFAULT_URL;
public static final String DEFAULT_USERNAME = PropertiesUtil.DEFAULT_USERNAME;
public static final String DEFAULT_PASSWORD = PropertiesUtil.DEFAULT_PASSWORD;
/**
* 获取连接
*/
public static Connection getMyConnection(String driver, String userName, String password, String url){
Connection conn = null;
try {
//加载驱动
Class.forName(driver);
//获取连接
conn = DriverManager.getConnection(url, userName, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
//返回连接对象
return conn;
}
}
|
package com.yang.Admin;
/**
* Created by GY on 12/1/2016.
*/
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import com.yang.*;
import com.yang.Beans.Dish;
import com.yang.Dao.DishDao;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;
public class loadMenuAction extends ActionSupport implements SessionAware {
public Map<String, Object> getSession() {
return session;
}
@Override
public void setSession(Map<String, Object> map) {
}
private Map<String,Object> session;
public ArrayList<Dish> getDishMenu() {
return dishMenu;
}
public void setDishMenu(ArrayList<Dish> dishMenu) {
this.dishMenu = dishMenu;
}
private ArrayList<Dish> dishMenu;
public String execute(){
DishDao allDish = new DishDao();
dishMenu = allDish.AllDishs();
return "success";
}
} |
package DataStorageLayer;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
public class DAOEpisode {
ResultSet resultSet;
// String matching the Database Query's
private static final String TABLE = "Episode";
public static final String TITLE = "Title";
public static final String DURATION = "Duration";
public static final String SERIE_ID = "SerieID";
public static final String EPIDODE_ID = "EpisodeID";
// Returns all Episodes as a String
public static String getEpisodes() {
return "SELECT * FROM " + TABLE;
}
// Returns Episode with the Serie - ID as a String
public static String getEpisodeSerieId(int serieId) {
return "SELECT * FROM " + TABLE + " WHERE " + serieId + " = " + serieId;
}
// Getting the Episodes with the database Connection
public HashMap<Integer, HashMap<String, String>> hashMapforAllEpisodes() {
HashMap<Integer, HashMap<String, String>> hashMapHashMap = new HashMap<>();
try {
resultSet = DatabaseConnection.getStatementResult(getEpisodes());
int episodeId;
while (resultSet.next()) {
episodeId = resultSet.getInt(EPIDODE_ID);
HashMap<String, String> stringStringHashMap = new HashMap<>();
stringStringHashMap.put(TITLE, resultSet.getString(TITLE));
stringStringHashMap.put(SERIE_ID, resultSet.getString(SERIE_ID));
stringStringHashMap.put(DURATION, resultSet.getString(DURATION));
hashMapHashMap.put(episodeId, stringStringHashMap);
}
} catch (SQLException e) {
e.printStackTrace();
return new HashMap<>();
}
return hashMapHashMap;
}
// Updating the Episode
public boolean update_Episode(String query) {
boolean isSaved = false;
try {
DatabaseConnection.executeSQLCreateStatement(query);
isSaved = true;
} catch (Exception ignored) {
}
return isSaved;
}
} |
package com.example.myaccountmechanism;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
/**
* This is used if the user invokes the "Add Account" dialog.
* Instantiate the Authenticator and return the corresponding IBinder.
* @author Ian Darwin
*
*/
public class MyAccountService extends Service {
private static final String TAG = MainActivity.TAG;
MyAuthenticator mAuthenticator;
public MyAccountService() {
Log.d(TAG, "MyAccountService()");
}
@Override
public void onCreate() {
Log.d(TAG, "MyAccountService.onCreate()");
mAuthenticator = new MyAuthenticator(this);
}
@Override
public IBinder onBind(Intent intent) {
Log.d(TAG, "MyAccountService.onBind()");
return mAuthenticator.getIBinder();
}
}
|
package io.github.ihongs.normal.serv;
import io.github.ihongs.action.ActionDriver;
import io.github.ihongs.action.serv.AuthAction;
import io.github.ihongs.action.serv.ConfAction;
import io.github.ihongs.action.serv.LangAction;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 综合配置接口
* 将 AuthAction,ConfAction,LangAction 集合到一起
* @author Hongs
*/
public class SaclAction extends ActionDriver {
ConfAction conf = new ConfAction();
LangAction lang = new LangAction();
AuthAction auth = new AuthAction();
@Override
public void service(HttpServletRequest req, HttpServletResponse rsp)
throws ServletException, IOException
{
String name = req.getServletPath();
name = name.substring(name.lastIndexOf("/"));
if ("/conf".equals( name )) {
conf.service(req, rsp);
} else
if ("/lang".equals( name )) {
lang.service(req, rsp);
} else
if ("/auth".equals( name )) {
auth.service(req, rsp);
} else
{
rsp.setStatus(HttpServletResponse.SC_NOT_FOUND);
rsp.getWriter().print("Unsupported name "+name);
}
}
@Override
public void destroy()
{
conf.destroy();
lang.destroy();
}
}
|
package lesson7.classfiles;
import java.util.LinkedList;
//Класс обхода графа в глубину
public class DepthFirstPaths {
private boolean[] marked;//маркер посещен(visited)
private int[] edgeTo;//массив откуда пришли к этой вершине
private int source;//начальная вершина обхода графа
public DepthFirstPaths(Graph g, int source) {
this.source = source;
edgeTo = new int[g.getVertexCount()];//инициируем пустой массив "откуда" по количеству вершин
marked = new boolean[g.getVertexCount()];//инициируем пустой массив "посещен" по количеству вершин
dfs(g, source);
}
/**
* Рекурсивный метод обхода графа в глубину
* @param g - граф
* @param v - текущая вершина
*/
private void dfs(Graph g, int v) {
marked[v] = true;//сразу помечаем "посещен" текущую вершину
//проверяем последовательно все элементы в ссылочном списке связей вершин-соседей w
for (int w : g.getAdjList(v)) {
if (!marked[w]) {
//если вершина еще не посещена, добавляем в ее ячейку массива вершину,
// откуда к ней пришли
edgeTo[w] = v;
dfs(g, w);//и запускаем рекурсию
}
}
}
/**
* Метод из массива самой вершины возвращает значение в ячейке проверяемой вершины,
* полученное в результате обхода графа
* @param v - проверяемая вершина
* @return true - да, путь к этой вершине есть, false - не дошли, значит пути нет.
*/
public boolean hasPathTo(int v){
return marked[v];
}
/**
* Метод возвращает путь от самой вершины до требуемой
* @param v - проверяемая вершина
* @return стек
*/
public LinkedList<Integer> pathTo(int v){
if (!hasPathTo(v)){//проверяем дошли ли
return null;
}
LinkedList<Integer> stack = new LinkedList<>();//создаем стек, куда будем складывать вершины
int vertex = v;
//наполняем стэк пока не вернемся к начальной вершине, то есть путем,
// который прошли во время обхода
while(vertex != source){
stack.push(vertex);
vertex = edgeTo[vertex];
}
return stack;
}
}
|
package cn.itcast.core.controller.order;
import cn.itcast.core.entity.PageResult;
import cn.itcast.core.pojo.order.Order;
import cn.itcast.core.pojo.order.OrderItem;
import cn.itcast.core.service.order.OrderItemService;
import cn.itcast.core.service.order.OrderService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/orderitem")
public class OrderItemController {
@Reference
private OrderItemService orderItemService;
@Reference
private OrderService orderService;
/**
* 提交订单
*/
//@RequestMapping("/findAll.do")
//public List<Order> findAll() {
//
//
// List<Order> orders = orderService.findAll();
// System.out.println(orders);
// return orders;
////
// }
// @RequestMapping("/findpage.do")
// public PageResult findPage(Integer pageNum, Integer pageSize){
// return orderService.findPage(pageNum, pageSize);
// }
// @RequestMapping("/search.do")
// public PageResult search(Integer page, Integer rows, @RequestBody Order order){
// String name = SecurityContextHolder.getContext().getAuthentication().getName();
// return orderService.searchForShop(page, rows, order,name);
// }
// @RequestMapping("/findPage.do")
// public PageResult findPage(Integer pageNum, Integer pageSize){
// return orderService.findPage(pageNum, pageSize);
// }
// }
@RequestMapping("/search.do")
public PageResult search(Integer page, Integer rows, @RequestBody OrderItem orderItem){
String name = SecurityContextHolder.getContext().getAuthentication().getName();
return orderItemService.searchitem(page, rows, orderItem);
}
}
|
package pp;
import hlp.MyHttpClient;
import pp.model.HippoHorse;
import pp.model.HippoTour;
import pp.service.GlRuService;
import pp.service.GlRuServiceImpl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author alexander.sokolovsky.a@gmail.com
*/
public class HippoAnalyze {
public static final String domain = "s2.gladiators.ru";
public static void main(String[] args) {
MyHttpClient client = new MyHttpClient();
client.appendInitialCookie("cookie_lang_3", "rus", domain);
try {
int granularity = 1700;
GlRuService service = new GlRuServiceImpl(client, new GlRuParser(), "s2.gladiators.ru");
service.loadHippoTours();
double pot = 0;
int cnty = 0;
int totcnty = 0;
List<HippoTour> hippoTours = new ArrayList<HippoTour>(service.getHippoTours().values());
for (HippoTour hippoTour : hippoTours) {
for (HippoHorse hippoHorse : hippoTour.getHorses()) {
if (hippoHorse.getFactor() > 17d) {
totcnty++;
}
}
Double factor = hippoTour.getHorses()[hippoTour.getWinner()].getFactor();
if (factor > 17d) {
pot += factor;
cnty++;
}
}
System.out.println(pot);
System.out.println(cnty);
System.out.println(totcnty);
Collections.sort(hippoTours, new Comparator<HippoTour>() {
@Override
public int compare(final HippoTour o1, final HippoTour o2) {
return Long.valueOf(o1.getTimestamp()).compareTo(o2.getTimestamp());
}
});
sortFactorsAscending(hippoTours);
double [] pots = new double[4];
int [] wins = new int[4];
int counter = 0;
pot = 0;
for (HippoTour hippoTour : hippoTours) {
//System.out.println(Arrays.toString(hippoTour.simpleform()));
counter++;
pots[hippoTour.getWinner()] += hippoTour.getHorses()[hippoTour.getWinner()].getFactor();
wins[hippoTour.getWinner()] += 1;
if (counter == granularity) {
//System.out.println(counter + " tours.");
System.out.println(Arrays.toString(pots));
//System.out.println(Arrays.toString(wins));
pots[0] = pots[1] = pots[2] = pots[3] = 0d;
counter = 0;
}
pot+= (hippoTour.getWinner() == randomWinner()) ? hippoTour.getHorses()[hippoTour.getWinner()].getFactor() : 0d;
}
if (counter > 0) {
System.out.println(counter + " tours.");
System.out.println(Arrays.toString(pots));
//System.out.println(Arrays.toString(wins));
pots[0] = pots[1] = pots[2] = pots[3] = 0d;
wins[0] = wins[1] = wins[2] = wins[3] = 0;
counter = 0;
}
double balance = 0d;
for (HippoTour hippoTour : hippoTours) {
HippoHorse[] horses = hippoTour.getHorses();
//System.out.println(horses[0].getFactor() + " - " + horses[1].getFactor() + " - " + horses[2].getFactor() + " - " + horses[3].getFactor() + " - " + hippoTour.getWinner());
//balance += horses[hippoTour.getWinner()].getFactor() - 4;
//System.out.println(horses[hippoTour.getWinner()].getFactor() - 4);
}
Map<HippoTour, Integer> density = new HashMap<HippoTour, Integer>(hippoTours.size());
for (HippoTour hippoTour : hippoTours) {
Integer dens = density.get(hippoTour);
if (dens == null) {
dens = 0;
}
dens = dens + 1;
density.put(hippoTour, dens);
}
for (HippoTour hippoTour : density.keySet()) {
System.out.print(hippoTour);
System.out.println(" " + density.get(hippoTour));
}
//System.out.println("Balance:" + balance);
System.out.println("Random pot:" + pot);
System.out.println("Tours: " + hippoTours.size());
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
private static void sortFactorsAscending(final List<HippoTour> hippoTours) {
for (HippoTour hippoTour : hippoTours) {
hippoTour.getHorses()[hippoTour.getWinner()].setWinner(true);
Arrays.sort(hippoTour.getHorses(), new Comparator() {
@Override
public int compare(final Object o1, final Object o2) {
HippoHorse h1 = (HippoHorse) o1;
HippoHorse h2 = (HippoHorse) o2;
return Double.valueOf(h1.getFactor()).compareTo(h2.getFactor());
}
});
for(int i = 0; i < 4; ++i) {
if (hippoTour.getHorses()[i].getWinner()) {
hippoTour.setWinner(i);
}
}
}
}
private static int randomWinner(double ... k) {
double r = Math.random();
if (r < 0.25) return 0;
if (r < 0.5) return 1;
if (r < 0.75) return 2;
return 3;
}
}
|
package com.metoo.modul.app.game.view.tree;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.nutz.json.Json;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSONObject;
import com.metoo.core.constant.Globals;
import com.metoo.core.domain.virtual.SysMap;
import com.metoo.core.mv.JModelAndView;
import com.metoo.core.query.support.IPageList;
import com.metoo.core.tools.CommUtil;
import com.metoo.core.tools.ResponseUtils;
import com.metoo.core.tools.database.DatabaseTools;
import com.metoo.foundation.domain.Accessory;
import com.metoo.foundation.domain.Friend;
import com.metoo.foundation.domain.Game;
import com.metoo.foundation.domain.GameAward;
import com.metoo.foundation.domain.GameGoods;
import com.metoo.foundation.domain.GameTreeLog;
import com.metoo.foundation.domain.GoodsVoucher;
import com.metoo.foundation.domain.GoodsVoucherLog;
import com.metoo.foundation.domain.PlantingTrees;
import com.metoo.foundation.domain.SubTrees;
import com.metoo.foundation.domain.Tree;
import com.metoo.foundation.domain.User;
import com.metoo.foundation.domain.query.FriendQueryObject;
import com.metoo.foundation.service.IFriendService;
import com.metoo.foundation.service.IGameService;
import com.metoo.foundation.service.IGameTreeLogService;
import com.metoo.foundation.service.IPlantingtreesService;
import com.metoo.foundation.service.ISubTreesService;
import com.metoo.foundation.service.ISysConfigService;
import com.metoo.foundation.service.IUserConfigService;
import com.metoo.foundation.service.IUserService;
import com.metoo.modul.app.game.tree.tools.AppFriendBuyerTools;
import com.metoo.modul.app.game.tree.tools.AppGameAwardTools;
import com.metoo.modul.app.game.tree.tools.AppGameTreeTools;
import com.metoo.module.app.buyer.domain.Result;
import com.metoo.module.app.manage.buyer.tool.AppUserTools;
import com.metoo.module.app.view.web.tool.AppRegisterViewTools;
import com.metoo.module.app.view.web.tool.AppobileTools;
import net.sf.json.JSONArray;
/**
* <p>
* Title: AppFriendBuyerAction.java
* </p>
*
* <p>
* Description: 种树小游戏,邀请好友;(邀请好友免费得300水滴); # 抢好友水滴 # 帮好友浇水
* </p>
*
*
*
* @author 46075
*
*/
@Controller
@RequestMapping("/app/v1/game/tree/friend")
public class AppGameTreeFriendBuyerAction {
@Autowired
private IUserService userService;
@Autowired
private AppobileTools mobileTools;
@Autowired
private AppRegisterViewTools appRegisterViewTools;
@Autowired
private AppUserTools appUserTools;
@Autowired
private IFriendService friendService;
@Autowired
private ISysConfigService configService;
@Autowired
private IGameService gameService;
@Autowired
private IGameTreeLogService gameTreeLogService;
@Autowired
private ISubTreesService subTreesService;
@Autowired
private IPlantingtreesService plantingtreesService;
@Autowired
private AppGameAwardTools appGameAwardTools;
@Autowired
private AppFriendBuyerTools appFriendBuyerTools;
@Autowired
private DatabaseTools databaseTools;
@Autowired
private IUserConfigService userConfigService;
/**
* 用户好友列表
*
* @param request
* @param response
* @param token
* @return
*/
@RequestMapping(value = "/list.json", produces = "application/json;charset=utf-8")
@ResponseBody
public String list(HttpServletRequest request, HttpServletResponse response, String token) {
String msg = "Success";
int code = 4200;
User user = null;
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
if (!CommUtil.null2String(token).equals("")) {
user = this.userService.getObjByProperty(null, "app_login_token", token);
if (user != null) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("deleteStatus", 0);
params.put("user_id", user.getId());
params.put("status", 1);
List<Friend> friends = this.friendService
.query("SELECT obj FROM " + "Friend obj " + "WHERE obj.deleteStatus=:deleteStatus "
+ "AND obj.user.id=:user_id " + "AND obj.status=:status", params, -1, -1);
for (Friend friend : friends) {
Map<String, Object> map = this.appUserTools.get(friend.getFriend());
map.put("friend_id", friend.getFriend().getId());
list.add(map);
}
} else {
code = 4220;
msg = "The user does not exist";
}
} else {
msg = "token Invalidation";
code = -100;
}
return JSONObject.toJSONString(new Result(code, msg, list));
}
/**
* 添加好友:通过好友账号,用户名,邮箱,查找用户
*
* @param request
* @param response
*/
@RequestMapping(value = "/get.json", produces = "application/json;charset=utf-8")
@ResponseBody
public String get(HttpServletRequest request, HttpServletResponse response, String account, String token) {
int code = 4200;
String msg = "Success";
List<User> list = null;
if (!CommUtil.null2String(account).equals("")) {
Map params = new HashMap();
boolean flag = this.mobileTools.verify(account);
StringBuffer sb = new StringBuffer("select obj from ");
sb.append(User.class.getName()).append(" obj").append(" where ");
sb.append("obj.userName=:userName");
String sql = null;
if (flag) {
Map map = this.mobileTools.mobile(account);
String areaMobile = (String) map.get("userMobile");
params.put("mobile", areaMobile);
sb.append(" or obj.mobile=:mobile");
account = areaMobile;
}
boolean verify = this.appRegisterViewTools.verify_email(account);
if (verify) {
params.put("email", account);
sb.append(" or obj.email=:email");
}
params.put("userName", account);
List<User> users = this.userService.query(sb.toString(), params, -1, -1);
list = this.appUserTools.get(users);
if (list == null) {
code = 4220;
msg = "The user does not exist";
}
} else {
code = 4403;
msg = "Parameter is null";
}
return JSONObject.toJSONString(new Result(code, msg, list));
}
/**
* 发送添加好友申请
*
* @param request
* @param response
* @param id
* @param token
* 用户身份令牌
* @param message
* 发送申请信息
* @return
*/
@RequestMapping("apply.json")
@ResponseBody
public String apply(HttpServletRequest request, HttpServletResponse response, String id, String token,
String message) {
String msg = "Success";
int code = 4200;
if (!CommUtil.null2String(token).equals("")) {
User user = this.userService.getObjByProperty(null, "app_login_token", token);
if (user != null) {
User friend = this.userService.getObjById(CommUtil.null2Long(id));
if (friend != null) {
if (!friend.getId().equals(user.getId())) {
List<Friend> friendList = null;
Map params = new HashMap();
// 查询A=B(A=B:双方互为好友、 A->B: A申请添加B为好友、A<-B: B申请添加A为好友)
params.clear();
params.put("deleteStatus", 0);
params.put("user_id", user.getId());
params.put("friend_id", friend.getId());
params.put("status", 1);
friendList = this.friendService.query(
"SELECT obj FROM Friend obj WHERE obj.deleteStatus=:deleteStatus AND obj.user.id=:user_id AND obj.friend.id=:friend_id AND obj.status=:status",
params, -1, -1);
if (friendList.size() < 1) {// 判断 user <==> friend
// 是否互为好友
// 查询A->B
params.clear();
params.put("deleteStatus", 0);
params.put("user_id", friend.getId());
params.put("friend_id", user.getId());
params.put("status", 0);
friendList = this.friendService.query(
"SELECT obj FROM Friend obj WHERE obj.deleteStatus=:deleteStatus AND obj.user.id=:user_id AND obj.friend.id=:friend_id AND obj.status=:status",
params, -1, -1);
if (friendList.size() < 1) {// 判断 A <== B
// 好友是否已添加我为好友、已添加自动设置双方为好友
// 查询是否已生成添加好友请求
params.clear();
params.put("deleteStatus", 0);
params.put("user_id", user.getId());
params.put("friend_id", friend.getId());
friendList = this.friendService.query(
"SELECT obj FROM Friend obj WHERE obj.deleteStatus=:deleteStatus AND obj.user.id=:user_id AND obj.friend.id=:friend_id",
params, -1, -1);
// 查询今天是否已提交申请 to_days
params.clear();
// 查询今日是否已生成添加好友请求
String sql = "SELECT COUNT(*) FROM metoo_game_treelog obj WHERE obj.user_id="
+ user.getId() + " AND " + " obj.friend_id=" + friend.getId() + " AND "
+ "type=5" + " AND " + "status=1" + " AND "
+ " TO_DAYS(obj.addTime)=TO_DAYS(now())";
int number = this.databaseTools.queryNum(sql);
boolean flag = false;
if (number < 1) {
flag = true;
}
Friend obj = null;
if (friendList.size() == 0) {
obj = new Friend();
obj.setAddTime(new Date());
obj.setStatus(0);
// obj.setUser_id(user.getId());
obj.setUser(user);
obj.setUserName(user.getUserName());
obj.setFriend(friend);
obj.setMobile(friend.getMobile());
obj.setSex(friend.getSex());
obj.setFriendName(friend.getUsername());
obj.setVerification_information(message);
this.friendService.save(obj);
if (flag)
// 发送好友申请、记录好友申日志
this.appFriendBuyerTools.apply(user, friend);
} else {
obj = friendList.get(0);
int status = obj.getStatus();
if (status == 0) {
code = 4200;
msg = "Success";
if (flag)
this.appFriendBuyerTools.apply(user, friend);
/*
* AppGameFactory factory = new
* AppGameFactory();
* AppGameTreeLogInterface interfaces =
* factory.creatLog("ADD"); // 创建申请日志
* interfaces.add(user, friend);
*/
} else if (status == 1) {
code = 4223;
msg = "Have become friends";
} else if (status == 2) {
code = 4222;
msg = "Added, pending reply";
obj.setStatus(0);
this.friendService.update(obj);
}
}
} else {
code = 4200;
msg = "Success";
Friend obj = friendList.get(0);
obj.setStatus(1);
this.friendService.update(obj);
Friend newFriend = new Friend();
newFriend.setAddTime(new Date());
newFriend.setStatus(1);
// newFriend.setUser_id(user.getId());
newFriend.setUser(user);
newFriend.setUserName(user.getUserName());
newFriend.setFriendName(friend.getUserName());
newFriend.setMobile(friend.getMobile());
newFriend.setSex(friend.getSex());
newFriend.setFriend(friend);
this.friendService.save(newFriend);
// 调整申请记录 A->B
params.clear();
params.put("user_id", friend.getId());
params.put("friend_id", user.getId());
params.put("type", 5);
this.appFriendBuyerTools.verifyFriend(params, 2);
// A->B (被)
params.clear();
params.put("user_id", user.getId());
params.put("friend_id", friend.getId());
params.put("type", 5);
this.appFriendBuyerTools.verifyFriend(params, -2);
}
} else {
code = 4223;
msg = "Have become friends";
}
} else {
code = 4225;
msg = "You cannot add yourself as a friend";
}
} else {
code = 4221;
msg = "Friends don't exist";
}
} else {
code = 4220;
msg = "The user does not exist";
}
} else {
msg = "token Invalidation";
code = -100;
}
return JSONObject.toJSONString(new Result(code, msg));
}
/**
* 好友验证
*
* @param request
* @param response
* @param id
* @param token
* @return
*/
@RequestMapping("verify.json")
@ResponseBody
public String verify(HttpServletRequest request, HttpServletResponse response, String id, String token,
Integer status) {
String msg = "Success";
int code = 4200;
if (!CommUtil.null2String(token).equals("")) {
User user = this.userService.getObjByProperty(null, "app_login_token", token);
if (user != null) {
User friend = this.userService.getObjById(CommUtil.null2Long(id));
if (friend != null) {
Map params = new HashMap();
List<Friend> friends = null;
// 判断双方是否已是好友
params.put("deleteStatus", 0);
params.put("user_id", user.getId());
params.put("friend_id", friend.getId());
params.put("status", 1);
friends = this.friendService.query(
"SELECT obj FROM Friend obj WHERE obj.deleteStatus=:deleteStatus AND obj.friend.id=:friend_id AND obj.user.id=:user_id AND obj.status=:status",
params, -1, -1);
if (friends.size() < 1) {
// 查询是否有此好友申请
params.clear();
params.put("deleteStatus", 0);
params.put("user_id", friend.getId());
params.put("friend_id", user.getId());
params.put("status", 0);
friends = this.friendService.query(
"SELECT obj FROM Friend obj WHERE obj.deleteStatus=:deleteStatus AND obj.friend.id=:friend_id AND obj.user.id=:user_id AND obj.status=:status",
params, -1, -1);
if (friends.size() > 0) {
for (Friend obj : friends) {
obj.setStatus(status);
this.friendService.update(obj);
Friend newFriend = new Friend();
newFriend.setAddTime(new Date());
newFriend.setStatus(status == 1 ? 1 : status == 2 ? 2 : 0);
// newFriend.setUser_id(user.getId());
newFriend.setUser(user);
newFriend.setUserName(user.getUserName());
newFriend.setFriendName(friend.getUserName());
newFriend.setMobile(friend.getMobile());
newFriend.setSex(friend.getSex());
newFriend.setFriend(friend);
this.friendService.save(newFriend);
// 修改添加好友日志
params.clear();
params.put("user_id", user.getId());
params.put("friend_id", friend.getId());
params.put("type", 5);
this.appFriendBuyerTools.verifyFriend(params, status == 1 ? -2 : -3);
params.clear();
params.put("user_id", friend.getId());
params.put("friend_id", user.getId());
params.put("type", 5);
this.appFriendBuyerTools.verifyFriend(params, status == 1 ? 2 : 3);
// break;
}
} else {
code = 5440;
msg = "Parameter error";
}
} else {
code = 4223;
msg = "Have become friends";
// 此处不存在双方互相添加记录;做了互相添加好友验证
/*
* params.clear(); params.put("deleteStatus", 0);
* params.put("friend_id", user.getId());
* params.put("user_id", friend.getId());
* params.put("status", 0); friends =
* this.friendService.query(
* "SELECT obj FROM Friend obj WHERE obj.deleteStatus=:deleteStatus AND obj.friend.id=:friend_id AND obj.user_id=:user_id AND obj.status=:status"
* , params, -1, -1);
* this.friendService.delete(friends.get(0).getId());
*/
}
} else {
code = 4221;
msg = "The user does not exist";
}
} else {
code = 4220;
msg = "The user does not exist";
}
} else {
msg = "token Invalidation";
code = -100;
}
return JSONObject.toJSONString(new Result(code, msg));
}
/**
* 删除好友
*
* @param request
* @param response
* @param id
* @return
*/
@RequestMapping("remove.json")
@ResponseBody
public String refuse(HttpServletRequest request, HttpServletResponse response, String id, String token) {
String msg = "Success";
int code = 4200;
if (!CommUtil.null2String(token).equals("")) {
User user = this.userService.getObjByProperty(null, "app_login_token", token);
if (user != null) {
User friend = this.userService.getObjById(CommUtil.null2Long(id));
if (friend != null) {
Map params = new HashMap();
params.put("deleteStatus", 0);
params.put("user_id", user.getId());
params.put("friend_id", friend.getId());
params.put("status", 1);
List<Friend> friendList = this.friendService.query(
"SELECT obj FROM Friend obj WHERE obj.deleteStatus=:deleteStatus AND obj.user.id=:user_id AND obj.friend.id=:friend_id AND obj.status=:status",
params, -1, -1);
if (friendList.size() > 0) {
for (Friend f : friendList) {
f.setDeleteStatus(-1);
f.setStatus(-1);
this.friendService.update(f);
}
params.clear();
params.put("deleteStatus", 0);
params.put("user_id", friend.getId());
params.put("friend_id", user.getId());
params.put("status", 1);
List<Friend> friends = this.friendService.query(
"SELECT obj FROM Friend obj WHERE obj.deleteStatus=:deleteStatus AND obj.user.id=:user_id AND obj.friend.id=:friend_id AND obj.status=:status",
params, -1, -1);
if (friends.size() > 0) {
Friend obj = friends.get(0);
obj.setDeleteStatus(-1);
obj.setStatus(-1);
this.friendService.update(obj);
// 创建日志
this.appFriendBuyerTools.remove(user, friend);
/*
* List<GameTreeLog> gameTreeLogs =
* this.gameTreeLogService.query(
* "SELECT obj FROM GameTreeLog obj WHERE obj.user_id=:user_id AND obj.friend_id=:friend_id AND obj.type=:type"
* , params, -1, -1); if(gameTreeLogs.size() > 0){
* GameTreeLog gameTreeLog = gameTreeLogs.get(0);
* gameTreeLog.setStatus(4);
* this.gameTreeLogService.update(gameTreeLog); }
*/
}
} else {
code = 4224;
msg = "Non-friend relationship";
}
} else {
code = 4221;
msg = "The user does not exist";
}
} else {
code = 4220;
msg = "The user does not exist";
}
} else {
msg = "token Invalidation";
code = -100;
}
return JSONObject.toJSONString(new Result(code, msg));
}
/**
* 树
*
* @param request
* @param response
* @param token
* 用户身份令牌 TOKEN
*
* @param id
* 好友ID
* @return
*/
@RequestMapping(value = "/planting.json", produces = "application/json;charset=utf-8")
@ResponseBody
public Object getFrinendTree(HttpServletRequest request, HttpServletResponse response, String token, String id) {
String msg = "Success";
int code = 4200;
Map map = new HashMap();
if (!CommUtil.null2String(token).equals("")) {
User user = this.userService.getObjByProperty(null, "app_login_token", token);
System.out.println(user.getUsername());
if (user != null) {
User friend = this.userService.getObjById(CommUtil.null2Long(id));
map.put("user_name", friend.getUsername());
Map params = new HashMap();
params.put("user", user.getId());
params.put("friend", friend.getId());
params.put("status", 1);
List<Friend> objs = this.friendService.query(
"SELECT obj FROM Friend obj WHERE obj.user.id=:user AND obj.friend.id=:friend AND obj.status=:status",
params, -1, -1);
if (objs.size() > 0) {
map.put("unused_water", friend.getWater_drops_unused());
PlantingTrees plantingTree = friend.getPlanting_trees();
if (plantingTree != null) {
SubTrees subTree = plantingTree.getSubTree();
if (subTree != null) {
map.put("name", plantingTree.getName());
map.put("watering", plantingTree.getWatering());
map.put("accessory",
plantingTree.getAccessory() != null
? this.configService.getSysConfig().getImageWebServer() + "/"
+ plantingTree.getAccessory().getPath() + "/"
+ plantingTree.getAccessory().getName()
: "");
Tree trees = plantingTree.getTree();
int watering = subTree.getWatering();
map.put("schedule",
Math.round(CommUtil.div(plantingTree.getGrade_watering(), watering) * 100));
SubTrees sub = this.subTreesService.getObjById(plantingTree.getSub_trees());
// 判断是否已完成种植
if (subTree.getStatus() == 12 && plantingTree.getGrade_watering() >= sub.getWatering()) {
map.put("fill_level", true);
}
// 添加访问日志
// 设置互为好友 日志
// this.appFriendBuyerTools.visit(user, friend);
} else {
code = 4500;
msg = "System error, please contact customer service";
}
} else {
code = 4603;
msg = "The user has not yet selected a tree to grow";
}
} else {
code = 4224;
msg = "It's not your best friend";
}
} else {
msg = "token Invalidation";
code = -100;
}
} else {
msg = "token Invalidation";
code = -100;
}
return new Result(code, msg, map);
}
/**
* 浇水
*
* @param request
* @param response
* @param token
* @param user_id
* @return
*/
@RequestMapping("/share_water.json")
@ResponseBody
public Object share_water(HttpServletRequest request, HttpServletResponse response, String token, String user_id) {
// 1,判断游戏状态
// 2,判断水滴数是否大于可用水滴数
// 3,判断是否互为好友
String msg = "";
int code = -1;
Map map = new HashMap();
if (!CommUtil.null2String(token).equals("")) {
User user = this.userService.getObjByProperty(null, "app_login_token", token);
int unused = user.getWater_drops_unused();
Map params = new HashMap();
params.put("type", 0);
List<Game> games = this.gameService.query("SELECT obj FROM Game obj WHERE obj.type=:type", params, -1, -1);
Game gameTree = null;
if (games.size() > 0) {
gameTree = games.get(0);
}
if (gameTree != null && gameTree.getStatus() == 0) {
int water = gameTree.getShar_water();
map.put("water", water);
if (unused > 0 && unused >= water) {
params.clear();
params.put("deleteStatus", 0);
params.put("user_id", user.getId());
params.put("friend_id", Long.parseLong(user_id));
params.put("status", 1);
List<Friend> friends = this.friendService.query(
"SELECT obj FROM Friend obj WHERE obj.deleteStatus=:deleteStatus AND obj.user_id=:user_id AND friend.id=:friend_id AND obj.status=:status",
params, -1, -1);
if (friends.size() > 0) {
User friend = this.userService.getObjById(CommUtil.null2Long(user_id));
if (friend != null) {
PlantingTrees plantingTree = friend.getPlanting_trees();
if (plantingTree != null) {
Tree tree = plantingTree.getTree();
if (plantingTree.getStatus() <= 12 && plantingTree.getStatus() == 0) {
SubTrees subTree = plantingTree.getSubTree();
if (subTree.getStatus() <= 12) {
map.put("flag", Boolean.FALSE);
if (plantingTree.getGrade_watering() + water >= subTree.getWatering()) {// 升级
params.clear();
params.put("tree_id", plantingTree.getTree().getId());
params.put("status", subTree.getStatus() + 1);
List<SubTrees> subTrees = this.subTreesService.query(
"select obj from SubTrees obj where obj.tree.id=:tree_id and obj.status=:status order by obj.watering desc",
params, -1, -1);
if (subTrees.size() > 0) {
SubTrees next_subtree = subTrees.get(0);
plantingTree.setAccessory(next_subtree.getAccessory());
plantingTree.setGrade_watering(new Double(
CommUtil.subtract(plantingTree.getGrade_watering() + water,
subTree.getWatering())).intValue());
plantingTree.setSub_trees(next_subtree.getId());
plantingTree.setSubTree(next_subtree);
}
if (subTree.getGameAward() != null) {
List gameAward = appGameAwardTools.createUpgradeAward(friend,
subTree.getGameAward(), 0); // 阶段奖品
// 记录升级日志
// 好友记录谁帮他浇了水
GameTreeLog ltg = new GameTreeLog();
ltg.setAddTime(new Date());
ltg.setUser_id(friend.getId());
ltg.setUser_name(friend.getUsername());
ltg.setFriend_id(user.getId());
ltg.setFriend_name(user.getUserName());
ltg.setWater(water);
ltg.setTree_id(gameTree.getId());
ltg.setType(10);
ltg.setStatus(-10);
ltg.setGameAward(JSONArray.fromObject(gameAward).toString());
this.gameTreeLogService.save(ltg);
}
if (subTree.getStatus() == 12) {
plantingTree.setStatus(1);
map.put("schedule", 100);
map.put("progress", 100);
// 满级奖品
GameGoods gameGoods = plantingTree.getGameGoods();
if (gameGoods != null) {
GameAward gameAward = gameGoods.getGameAward();
if (gameAward != null) {
List accomplishAward = appGameAwardTools
.createUpgradeAward(user, gameAward);
map.put("accomplishAward", accomplishAward);
// 记录满级日志
// 好友记录谁帮他浇了水
GameTreeLog ltg = new GameTreeLog();
ltg.setAddTime(new Date());
ltg.setUser_id(friend.getId());
ltg.setUser_name(friend.getUsername());
ltg.setFriend_id(user.getId());
ltg.setFriend_name(user.getUserName());
ltg.setWater(CommUtil.null2Int(Math.floor(water)));
ltg.setTree_id(gameTree.getId());
ltg.setType(12);
ltg.setStatus(-12);
ltg.setGameAward(
JSONArray.fromObject(accomplishAward).toString());
this.gameTreeLogService.save(ltg);
}
}
}
map.put("flag", Boolean.TRUE);
}
plantingTree.setGrade_watering(plantingTree.getGrade_watering() + water);
plantingTree.setWatering(plantingTree.getWatering() + water);
user.setWater_drops_unused(user.getWater_drops_unused() - water);
user.setWater_drop_used(user.getWater_drop_used() + water);
this.plantingtreesService.update(plantingTree);
this.userService.update(user);
}
map.put("schedule", Math.floor(CommUtil.div02(plantingTree.getGrade_watering(),
plantingTree.getSubTree().getWatering()) * 100));
map.put("progress", Math
.floor(CommUtil.div02(plantingTree.getWatering(), tree.getWaters()) * 100));
map.put("remaining_water",
CommUtil.subtract(subTree.getWatering(), plantingTree.getGrade_watering()));
// 记录浇水日志
GameTreeLog gtl = new GameTreeLog();
gtl.setAddTime(new Date());
gtl.setUser_id(user.getId());
gtl.setUser_name(user.getUsername());
gtl.setFriend_id(friend.getId());
gtl.setFriend_name(friend.getUserName());
gtl.setWater(CommUtil.null2Int(Math.floor(water)));
gtl.setTree_id(gameTree.getId());
gtl.setType(6);
gtl.setStatus(6);
String message = "You watered " + Globals.PREFIXHTML + friend.getUserName() + Globals.SUFFIXHTML + "'s tree with " + water
+ " water-drops";
gtl.setMessage(message);
this.gameTreeLogService.save(gtl);
// 好友记录谁帮他浇了水
GameTreeLog ltg = new GameTreeLog();
ltg.setAddTime(new Date());
ltg.setUser_id(friend.getId());
ltg.setUser_name(friend.getUsername());
ltg.setFriend_id(user.getId());
ltg.setFriend_name(user.getUserName());
ltg.setWater(CommUtil.null2Int(Math.floor(water)));
ltg.setTree_id(gameTree.getId());
ltg.setType(6);
ltg.setStatus(-6);
String message1 = Globals.PREFIXHTML + user.getUserName() + Globals.SUFFIXHTML + " watered your tree with " + water
+ " water-drops";
ltg.setMessage(message1);
this.gameTreeLogService.save(ltg);
code = 4200;
msg = "Success";
} else {
code = 4610;
msg = "The current game is over";
}
} else {
code = 4603;
msg = "The user has not yet selected a tree to grow";
}
} else {
msg = "Is not a friend";
code = 4611;
}
} else {
msg = "Is not a friend";
code = 4611;
}
} else {
msg = "Lack of water droplets";
code = 4602;
}
} else {
msg = "The current game is over";
code = 4610;
}
} else {
msg = "token Invalidation";
code = -100;
}
return new Result(code, msg, map);
}
/**
* 浇水日志
*
* @param request
* @param response
* @param token
* @return
*/
@RequestMapping("/getLog.json")
@ResponseBody
public Object water_log(HttpServletRequest request, HttpServletResponse response, String token) {
User user = null;
Result result = null;
if (!"".equals(CommUtil.null2String(token))) {
user = this.userService.getObjByProperty(null, "app_login_token", token);
}
if (user != null) {
Map<String, Object> params = new HashMap<String, Object>();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Date dayStart = calendar.getTime();
System.out.println(calendar.getTime());
// 一天的结束时间 yyyy:MM:dd 23:59:59
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
Date dayEnd = calendar.getTime();
params.put("dayStart", dayStart);
params.put("dayEnd", dayEnd);
params.put("friend_id", user.getId());
params.put("type", 0);
List<GameTreeLog> log = this.gameTreeLogService.query(
"SELECT obj FROM GameTreeLog obj WHERE obj.addTime>=:dayStart AND obj.addTime<=:dayEnd AND obj.friend_id=:friend_id AND obj.type=:type",
params, -1, -1);
result = new Result(4200, "Success", log);
} else {
result = new Result(-100, "token Invalidation");
}
return result;
}
/*
* public static void main(String[] args) { Calendar calendar =
* Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY,0);
* calendar.set(Calendar.MINUTE,0); calendar.set(Calendar.SECOND,0);
* calendar.set(Calendar.MILLISECOND,0); Date dayStart = calendar.getTime();
*
* System.out.println(calendar.getTime());
*
* //一天的结束时间 yyyy:MM:dd 23:59:59 calendar.set(Calendar.HOUR_OF_DAY,23);
* calendar.set(Calendar.MINUTE,59); calendar.set(Calendar.SECOND,59);
* calendar.set(Calendar.MILLISECOND,999);
* System.out.println(calendar.getTime()); }
*/
/**
* 收取好友水滴
*
* @param request
* @param response
* @param token
* @param user_id
* @return
*/
@RequestMapping("steal.json")
@ResponseBody
public Object steal(HttpServletRequest request, HttpServletResponse response, String token, String user_id) {
String msg = "";
int code = -1;
Result result = null;
if (!CommUtil.null2String(token).equals("")) {
User user = this.userService.getObjByProperty(null, "app_login_token", token);
int unused = user.getWater_drops_unused();
Map params = new HashMap();
params.put("type", 0);
List<Game> games = this.gameService.query("SELECT obj FROM Game obj WHERE obj.type=:type", params, -1, -1);
Game game = null;
if (games.size() > 0) {
game = games.get(0);
}
if (game != null && game.getStatus() == 0) {
// this.userService.getObjById(user_id);
// 查询是否超过每日水滴上限以及收取次数
int upper_limit = game.getUpper_limit();
int frequency_limit = game.getFrequency_limit();
// 查询好友被收取水滴上限 1,查询日志 2,每次收取水滴在用户当前树种记录
User friend = this.userService.getObjById(CommUtil.null2Long(user_id));
params.put("user_id", user.getId());
params.put("friend_id", friend.getId());
params.put("type", 9);
params.put("dayStart", CommUtil.dayStart());
List<GameTreeLog> logs = this.gameTreeLogService.query(
"SELECT obj from GameTreeLog obj "
+ "WHERE "
+ "obj.addTime>=:dayStart "
+ "AND obj.friend_id=:friend_id "
+ "AND obj.type=:type "
+ "AND obj.user_id=:user_id",
params, -1, -1);
int sum = 0;
for (GameTreeLog log : logs) {
sum += log.getWater();
}
int drops_unused = friend.getWater_drops_unused();
if (sum <= upper_limit && logs.size() <= frequency_limit) { // 未超过收取次数
if (drops_unused > 0) {
int gather = game.getGather();
double water = Math.floor(CommUtil.mul(drops_unused, gather * 0.01));
if (drops_unused >= water) {
user.setWater_drops_unused(
new Double(CommUtil.add(user.getWater_drops_unused(), water)).intValue());
friend.setWater_drop_used(
new Double(CommUtil.add(friend.getWater_drop_used(), water)).intValue());
friend.setWater_drops_unused(
new Double(CommUtil.subtract(friend.getWater_drops_unused(), water)).intValue());
this.userService.update(user);
this.userService.update(friend);
// 记录收取日志
GameTreeLog gtl = new GameTreeLog();
gtl.setAddTime(new Date());
gtl.setUser_id(user.getId());
gtl.setUser_name(user.getUsername());
gtl.setFriend_id(friend.getId());
gtl.setFriend_name(friend.getUserName());
gtl.setWater(new Double(water).intValue());
gtl.setTree_id(game.getId());
gtl.setType(9);
gtl.setStatus(9);
String message = "You got " + new Double(water).intValue() + " water-drops from " + Globals.PREFIXHTML + friend.getUserName() + Globals.SUFFIXHTML;
gtl.setMessage(message);
this.gameTreeLogService.save(gtl);
// 记录好友被收取多少水滴
GameTreeLog ltg = new GameTreeLog();
ltg.setAddTime(new Date());
ltg.setUser_id(friend.getId());
ltg.setUser_name(friend.getUsername());
ltg.setFriend_id(user.getId());
ltg.setFriend_name(user.getUserName());
ltg.setWater(new Double(water).intValue());
ltg.setTree_id(game.getId());
ltg.setType(9);
ltg.setStatus(-9);
ltg.setMessage(Globals.PREFIXHTML + user.getUserName() + Globals.SUFFIXHTML + " got " + new Double(water).intValue() + " water-drops from you");
this.gameTreeLogService.save(ltg);
return new Result(4200, "Success", water);
} else {
// 用户水滴不足
return new Result(4602, "Lack of water droplets");
}
} else {
// 用户水滴不足
return new Result(4602, "Lack of water droplets");
}
} else {
// 今日超过被收取上限
return new Result(4612, "Has reached its limit");
}
} else {
return new Result(4601, "The game is not opened");
}
}
return result = new Result(-100, "token Invalidation");
}
// 好友排行榜
@RequestMapping("/ranking.json")
@ResponseBody
public Object ranking(HttpServletRequest request, HttpServletResponse response,
String currentPage, String orderBy, String orderType, String token){
if (!CommUtil.null2String(token).equals("")) {
User user = userService.getObjByProperty(null, "app_login_token", token);
if(user != null){
/*if(orderBy == null || orderBy.equals("")){
orderBy = "friend.planting_trees.watering";
}
if(orderType == null || orderType.equals("")){
orderType = "DESC";
}*/
/*Map params = new HashMap();
params.put("friend_id", user.getId());
params.put("deleteStatus", 0);
params.put("status", 1);
List<Friend> friends = this.friendService
.query("SELECT new Friend(user_id, userName, nickName, sex) "
+ "FROM Friend obj WHERE obj.friend.id=:friend_id "
+ "AND obj.deleteStatus=:deleteStatus "
+ "AND obj.status=:status "
+ "ORDER BY obj.friend.planting_trees.watering DESC", params, -1, -1);*/
ModelAndView mv = new JModelAndView("",
configService.getSysConfig(),this.userConfigService.getUserConfig(), 0, request, response);
FriendQueryObject qo = new FriendQueryObject(currentPage, mv, orderBy,
orderType);
qo.addQuery("obj.friend.id", new SysMap("friend_id",
user.getId()), "=");
qo.addQuery("obj.deleteStatus", new SysMap("deleteStatus",
0), "=");
qo.addQuery("obj.status", new SysMap("status",
1), "=");
IPageList pList = this.friendService.list(qo);
List<Map> maps = new ArrayList<Map>();
if(pList.getResult().size() > 0 ){
List<Friend> friends = pList.getResult();
compareToFriend(friends);
for(Friend friend : friends){
Map map = new HashMap();
map.put("user_id", friend.getUser().getId());
map.put("userName", friend.getUserName());
map.put("sex", friend.getSex());
if (friend.getSex() == -1) {
map.put("photo", this.configService.getSysConfig().getImageWebServer() + "/"
+ "resources" + "/" + "style" + "/" + "common" + "/" + "images" + "/" + "member.png");
}
if (friend.getSex() == 0) {
map.put("photo", this.configService.getSysConfig().getImageWebServer() + "/"
+ "resources" + "/" + "style" + "/" + "common" + "/" + "images" + "/" + "member0.png");
}
if (friend.getSex() == 1) {
map.put("photo", this.configService.getSysConfig().getImageWebServer() + "/"
+ "resources" + "/" + "style" + "/" + "common" + "/" + "images" + "/" + "member1.png");
}
User obj = this.userService.getObjById(friend.getUser().getId());
if(obj.getPlanting_trees() != null){
map.put("progress",
Math.floor(CommUtil.div02(obj.getPlanting_trees().getWatering(), obj.getPlanting_trees().getTree().getWaters()) * 100));
}else{
map.put("progress", 0);
}
map.put("tree", user.getTrees().size());
map.put("water", obj.getPlanting_trees() != null ? obj.getPlanting_trees().getWatering() : 0);
maps.add(map);
}
}
return ResponseUtils.ok(maps);
}
}
return ResponseUtils.unlogin();
}
public static void compareToFriend(List<Friend> list){
Collections.sort(list, new Comparator<Friend>() {
@Override
public int compare(Friend o1, Friend o2) {
User obj1 = o1.getUser();
Integer water1 = obj1.getPlanting_trees() != null ? obj1.getPlanting_trees().getWatering() : 0;
User obj2 = o2.getUser();
Integer water2 = obj2.getPlanting_trees() != null ? obj2.getPlanting_trees().getWatering() : 0;
return water2.compareTo(water1);
}
});
}
}
|
package com.crmiguez.aixinainventory.service.location;
import com.crmiguez.aixinainventory.entities.Location;
import com.crmiguez.aixinainventory.repository.LocationRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service("locationService")
public class LocationService implements ILocationService {
@Autowired
@Qualifier("locationRepository")
private LocationRepository locationRepository;
@Override
public List<Location> findAllLocations() {
return (List<Location>) locationRepository.findAll();
}
@Override
public Optional<Location> findLocationById(Long locationId){
return locationRepository.findById(locationId);
}
@Override
public Location addLocation(Location location){
return locationRepository.save(location);
}
@Override
public void deleteLocation (Location location){
locationRepository.delete(location);
}
@Override
public Location updateLocation(Location LocationDetails, Location Location){
Location.setDepartment(LocationDetails.getDepartment());
Location.setLocationAbbreviation(LocationDetails.getLocationAbbreviation());
Location.setLocationDescription(LocationDetails.getLocationDescription());
return locationRepository.save(Location);
}
}
|
package com.example.datatocursor;
import android.database.AbstractCursor;
import android.database.Cursor;
/**
* Provide a Cursor from a fixed list of data
* column 1 - _id
* column 2 - filename
* column 3 - file type
*/
public class DataToCursor extends AbstractCursor {
private static final String[] COLUMN_NAMES = {"_id", "filename", "type"};
private static final String[] DATA_ROWS = {
"one.mpg",
"two.jpg",
"tre.dat",
"fou.git",
};
@Override
public int getCount() {
return DATA_ROWS.length;
}
@Override
public int getColumnCount() {
return COLUMN_NAMES.length;
}
@Override
public String[] getColumnNames() {
return COLUMN_NAMES;
}
@Override
public int getType(int column) {
switch(column) {
case 0:
return Cursor.FIELD_TYPE_INTEGER;
case 1:
case 2:
return Cursor.FIELD_TYPE_STRING;
default: throw new IllegalArgumentException(Integer.toString(column));
}
}
/**
* Return the _id value (the only integer-valued column).
* Conveniently, rows and array indices are both 0-based.
*/
@Override
public int getInt(int column) {
int row = getPosition();
switch(column) {
case 0: return row;
default: throw new IllegalArgumentException(Integer.toString(column));
}
}
/** SQLite _ids are actually long, so make this work as well.
* This direct equivalence is usually not applicable; do not blindly copy.
*/
@Override
public long getLong(int column) {
return getInt(column);
}
@Override
public String getString(int column) {
int row = getPosition();
switch(column) {
case 1: return DATA_ROWS[row];
case 2: return extension(DATA_ROWS[row]);
default: throw new IllegalArgumentException(Integer.toString(column));
}
}
/** Stub version, works for sample filenames like only */
private String extension(String path) {
return path.substring(4);
}
// Remaining get*() methods call this as there are no other column types
private char dieBadColumn() {
throw new IllegalArgumentException("No columns of this type");
}
@Override
public short getShort(int column) {
return (short) dieBadColumn();
}
@Override
public float getFloat(int column) {
return dieBadColumn();
}
@Override
public double getDouble(int column) {
return dieBadColumn();
}
@Override
public boolean isNull(int column) {
return false;
}
}
|
import java.util.ArrayList;
import java.util.List;
/*
* 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 listya
*/
public class Pipe<T> {
private List<T> lists;
public Pipe() {
this.lists = new ArrayList<>();
}
public void putIntoPipe(T value) {
this.lists.add(value);
}
public T takeFromPipe() {
T taken;
int index;
if (this.lists.size() > 0) {
index = this.lists.size()-1;
taken = this.lists.get(index);
this.lists.remove(this.lists.get(index));
return taken;
}
return null;
}
public boolean isInPipe() {
if (this.lists.size() > 0) {
return true;
}
return false;
}
}
|
package model;
import java.sql.Statement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.DriverManager;
public class ProjectDAO {
// Connection 객체를 생성해줌. -> 추후 dao 모두 만들고 나면 connection pool로 교체하자.
private Connection connectDB() {
Connection conn = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "moviein", "moviein");
} catch (Exception e) {
System.out.println("ConnectDB() : " + e);
}
return conn;
}
// sort로 입력 가능한 값 : "cnt desc"(큰거에서 작은거), "enddate", "writedate", "m_collected desc", "pna desc nulls last"
// 조회수 많은 순 마감임박 신작순 모아진 돈 많은 순. 예상관객수
public ArrayList<ProjectVO> listAll(String sorting) {
ArrayList<ProjectVO> projectList = null;
Connection conn = connectDB();
Statement st = null;
ResultSet rs = null;
try {
st = conn.createStatement();
// seq_PID(프로젝트 id), 사용자 id, 프로젝트명, imgurl명을 받음
// level_ 과 status가 3인 것만 받고 매개변수에 따라 정렬 기준을 달리하여 ArrayList에 순서대로 담아서 출력함.
rs = st.executeQuery("select seq_PID, id, proj, imgurl, inv_type, purpose, to_char(enddate,'yyyy-mm-dd'), to_char(writedate, 'yyyy-mm-dd'), cnt, pna, m_collected from project where level_ = 3 and status = 3 order by " + sorting);
ProjectVO vo = null;
projectList = new ArrayList<ProjectVO>();
while (rs.next()) {
vo = new ProjectVO();
vo.setSeq_PID(rs.getInt(1));
vo.setId(rs.getString(2));
vo.setProj(rs.getString(3));
vo.setImgurl(rs.getString(4));
vo.setInv_type(rs.getString(5));
vo.setPurpose(rs.getString(6));
vo.setEnddate(rs.getString(7));
vo.setWritedate(rs.getString(8));
vo.setCnt(rs.getInt(9));
vo.setPna(rs.getInt(10));
vo.setM_collected(rs.getInt(11));
projectList.add(vo);
}
} catch (Exception e) {
System.out.println("listAll : " + e);
} finally {
try {
rs.close();
st.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return projectList;
}
// FilterVO의 값을 가져옴. 프로젝트 둘러보기 시에 FilterVO의 값을 이용하여 프로젝트 list를 출력함.
public ArrayList<FilterVO> listFilter(String sorting) {
ArrayList<FilterVO> filterList = null;
Connection conn = connectDB();
Statement st = null;
ResultSet rs = null;
try {
st = conn.createStatement();
// seq_PID(프로젝트 id), 사용자 id, 프로젝트명, imgurl명을 받음
// level_ 과 status가 3인 것만 받고 매개변수에 따라 정렬 기준을 달리하여 ArrayList에 순서대로 담아서 출력함.
rs = st.executeQuery("select movie.seq_PID, id, proj, imgurl, inv_type, purpose, genre1, genre2, genre3 from project, movie where project.seq_pid = movie.seq_pid and level_ = 3 and status = 3 order by " + sorting);
FilterVO vo = null;
filterList = new ArrayList<FilterVO>();
while (rs.next()) {
vo = new FilterVO();
vo.setSeq_PID(rs.getInt(1));
vo.setId(rs.getString(2));
vo.setProj(rs.getString(3));
vo.setImgurl(rs.getString(4));
vo.setInv_type(rs.getString(5));
vo.setPurpose(rs.getString(6));
vo.setGenre1(rs.getString(7));
vo.setGenre2(rs.getString(8));
vo.setGenre3(rs.getString(9));
filterList.add(vo);
}
} catch (Exception e) {
System.out.println("listAll : " + e);
} finally {
try {
rs.close();
st.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return filterList;
}
// 검색기능 dao. 검색어를 입력하면 프로젝트 이름 중 그 keyword가 들어간 글자를 찾아줌.
public ArrayList<ProjectVO> search(String keyword) {
ArrayList<ProjectVO> projectList = null;
Connection conn = connectDB();
String query = "select seq_PID, id, proj, imgurl, inv_type, purpose from project where level_ = 3 and status = 3 and proj like '%" + keyword + "%'";
Statement st = null;
ResultSet rs = null;
try {
st = conn.createStatement();
rs = st.executeQuery(query);
ProjectVO vo = null;
projectList = new ArrayList<ProjectVO>();
while (rs.next()) {
vo = new ProjectVO();
vo.setSeq_PID(rs.getInt(1));
vo.setId(rs.getString(2));
vo.setProj(rs.getString(3));
vo.setImgurl(rs.getString(4));
vo.setInv_type(rs.getString(5));
vo.setPurpose(rs.getString(6));
projectList.add(vo);
}
} catch (Exception e) {
System.out.println("search : " + e);
} finally {
try {
rs.close();
st.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return projectList;
}
// project에 대한 상세 페이지에서 처음으로 나오는 위의 정보를 출력하기 위해 projectDB의 모든 정보를 담음.
public ProjectVO listOneProject(int seq_PID) {
ProjectVO vo = null;
Connection conn = connectDB();
Statement st = null;
ResultSet rs = null;
try {
st = conn.createStatement();
rs = st.executeQuery("select seq_PID, id, proj, m_target, m_collected, enddate, cnt, writedate, m_min, m_max, inv_type, pna, level_, purpose, status, imgurl from project where level_ = 3 and status = 3 and seq_pid = " + seq_PID);
vo = new ProjectVO();
if (rs.next()) {
vo.setSeq_PID(rs.getInt(1));
vo.setId(rs.getString(2));
vo.setProj(rs.getString(3));
vo.setM_target(rs.getInt(4));
vo.setM_collected(rs.getInt(5));
vo.setEnddate(rs.getString(6));
vo.setCnt(rs.getInt(7));
vo.setWritedate(rs.getString(8));
vo.setM_min(rs.getInt(9));
vo.setM_max(rs.getInt(10));
vo.setInv_type(rs.getString(11));
vo.setPna(rs.getInt(12));
vo.setLevel_(rs.getInt(13));
vo.setPurpose(rs.getString(14));
vo.setStatus(rs.getInt(15));
vo.setImgurl(rs.getString(16));
}
} catch (Exception e) {
System.out.println("listOne : " + e);
} finally {
try {
rs.close();
st.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return vo;
}
// 메서드 종료 시점에서 찜한 프로젝트가 있을 경우 True, 없을 경우 False
public boolean likeProjectChange(int seq_PID, String id) {
boolean result = false;
Connection conn = connectDB();
Statement st = null;
ResultSet rs = null;
try {
st = conn.createStatement();
rs = st.executeQuery("select seq_pid, id from likeproject where seq_PID = " + seq_PID + " and id = '" + id +"'");
System.out.println("11");
if (rs.next()) {
System.out.println("12");
st.executeUpdate("delete from likeproject where seq_pid = " + rs.getInt(1) + " and id = '" + rs.getString(2) + "'");
} else {
System.out.println("13");
st.executeUpdate("insert into likeproject(seq_pid, id) values (" + seq_PID + ", '" + id + "')");
result = true;
}
} catch (Exception e) {
System.out.println("likeProjectChange : " + e);
} finally {
try {
rs.close();
st.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
// 찜한 프로젝트가 있는지 없는지만 확인함.
public boolean likeProjectCheck(int seq_PID, String id) {
boolean result = false;
Connection conn = connectDB();
Statement st = null;
ResultSet rs = null;
try {
st = conn.createStatement();
System.out.println(111);
rs = st.executeQuery("select seq_pid, id from likeproject where seq_PID = " + seq_PID + " and id = '" + id + "'");
System.out.println(112);
if (rs.next()) {
System.out.println(113);
result = true;
}
} catch (Exception e) {
System.out.println("likeProjectCheck : " + e);
} finally {
try {
rs.close();
st.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
// boolean insertPrice(seq_PID, id, m_invest) 투자하기 누를 때 구현.
// price의 최소 최대값은 input 에서 min, max 속성? 같은 걸로?
public boolean insertInvest(int seq_PID, String id, int m_invest) {
boolean result = false;
Connection conn = connectDB();
PreparedStatement st = null;
PreparedStatement st1 = null;
try {
st = conn.prepareStatement("insert into investProject(seq_pid, id, m_invest) values (?, ?, ?)");
st.setInt(1, seq_PID);
st.setString(2, id);
st.setInt(3, m_invest);
st.executeUpdate();
st1 = conn.prepareStatement("update project set m_collected = m_collected + ? where seq_pid = ?");
st1.setInt(1, m_invest);
st1.setInt(2, seq_PID);
st1.executeUpdate();
result = true;
} catch (Exception e) {
System.out.println("insertPrice : " + e);
} finally {
try {
st.close();
st1.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
// 전에 투자를 했었는지 확인하는 DAO
public boolean investCheck(int seq_PID, String id) {
boolean result = false;
Connection conn = connectDB();
Statement st = null;
ResultSet rs = null;
// String query = "select * from investProject where seq_pid = " + seq_PID + " and id = " + id;
// System.out.println(query);
try {
st = conn.createStatement();
// rs = st.executeQuery(query);
rs = st.executeQuery("select * from investProject where seq_pid = " + seq_PID + " and id = '" + id + "'");
if (rs.next()) {
result = true;
}
} catch (Exception e) {
System.out.println("investCheck : " + e);
} finally {
try {
rs.close();
st.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
// CompanyVO companyInfo(seq_PID) - 기업정보 불러오기
public CompanyVO companyInfo(int seq_PID) {
CompanyVO vo = null;
Connection conn = connectDB();
Statement st = null;
ResultSet rs = null;
try {
st = conn.createStatement();
rs = st.executeQuery("select seq_CID, seq_pid, id, c_name, c_location, to_char(c_date,'yyyy\"년\" mm\"월\" dd\"일\"'), c_eoname, c_emp, c_crime, c_site, c_mail from company where seq_pid = " + seq_PID);
vo = new CompanyVO();
if (rs.next()) {
vo.setSeq_CID(rs.getInt(1));
vo.setSeq_PID(rs.getInt(2));
vo.setId(rs.getString(3));
vo.setC_name(rs.getString(4));
vo.setC_location(rs.getString(5));
vo.setC_date(rs.getString(6));
vo.setC_eoname(rs.getString(7));
vo.setC_emp(rs.getInt(8));
vo.setC_crime(rs.getString(9));
vo.setC_site(rs.getString(10));
vo.setC_mail(rs.getString(11));
}
} catch (Exception e) {
System.out.println("companyInfo : " + e);
} finally {
try {
rs.close();
st.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return vo;
}
// MovieVO movieInfo(seq_PID) - 영화정보 불러오기
public MovieVO movieInfo(int seq_PID) {
MovieVO vo = null;
Connection conn = connectDB();
Statement st = null;
ResultSet rs = null;
try {
st = conn.createStatement();
rs = st.executeQuery("select seq_pid, title, genre1, genre2, genre3, director, actor1, actor2, actor3, actor4, production, distributor, to_char(releasedate,'yyyy\"년\" mm\"월\" dd\"일\"'), origin_title, importer from movie where seq_pid = " + seq_PID);
vo = new MovieVO();
if (rs.next()) {
vo.setSeq_PID(rs.getInt(1));
vo.setTitle(rs.getString(2));
vo.setGenre1(rs.getString(3));
vo.setGenre2(rs.getString(4));
vo.setGenre3(rs.getString(5));
vo.setDirector(rs.getString(6));
vo.setActor1(rs.getString(7));
vo.setActor2(rs.getString(8));
vo.setActor3(rs.getString(9));
vo.setActor4(rs.getString(10));
vo.setProduction(rs.getString(11));
vo.setDistributor(rs.getString(12));
vo.setReleasedate(rs.getString(13));
vo.setOrigin_title(rs.getString(14));
vo.setImporter(rs.getString(15));
}
} catch (Exception e) {
System.out.println("movieInfo : " + e);
} finally {
try {
rs.close();
st.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return vo;
}
// ProjectVO에서 inv_type에 따라서
// ArrayList<InterestVO> interestInfo(seq_PID) or ArrayList<RewardVO> rewardInfo(seq_PID) 를 호출하여 정보를 얻음.
public ArrayList<InterestVO> interestInfo(int seq_PID) {
ArrayList<InterestVO> list = null;
InterestVO vo = null;
Connection conn = connectDB();
Statement st = null;
ResultSet rs = null;
try {
st = conn.createStatement();
rs = st.executeQuery("select seq_pid, audience, interest from interest where seq_pid = " + seq_PID + " order by audience");
list = new ArrayList<InterestVO>();
while (rs.next()) {
vo = new InterestVO();
vo.setSeq_PID(rs.getInt(1));
vo.setAudience(rs.getInt(2));
vo.setInterest(rs.getInt(3));
list.add(vo);
}
} catch (Exception e) {
System.out.println("interestInfo : " + e);
} finally {
try {
rs.close();
st.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return list;
}
public ArrayList<RewardVO> rewardInfo(int seq_PID) {
ArrayList<RewardVO> list = null;
RewardVO vo = null;
Connection conn = connectDB();
Statement st = null;
ResultSet rs = null;
try {
st = conn.createStatement();
rs = st.executeQuery("select seq_pid, std_invest, reward from reward where seq_pid = " + seq_PID + " order by std_invest");
list = new ArrayList<RewardVO>();
while (rs.next()) {
vo = new RewardVO();
vo.setSeq_PID(rs.getInt(1));
vo.setStd_invest(rs.getInt(2));
vo.setReward(rs.getString(3));
list.add(vo);
}
} catch (Exception e) {
System.out.println("rewardInfo : " + e);
} finally {
try {
rs.close();
st.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return list;
}
// ArrayList<NewsVO> listNews(int seq_PID) : 새소식 글들 출력
// group이 높은 순서(새소식이 최근에 작성된 순서로 우선 정렬)
// 그 다음 depth 순서로 정리해서 댓글보다 작성글이 먼저 올 수 있게 정렬
// 그 다음 n_date 로 정렬해서 먼저 적은 댓글이 위로 올 수 있게 함.
public ArrayList<NewsVO> listNews(int seq_PID) {
ArrayList<NewsVO> list = null;
NewsVO vo = null;
Connection conn = connectDB();
Statement st = null;
ResultSet rs = null;
try {
st = conn.createStatement();
rs = st.executeQuery("select seq_NNO, seq_PID, id, n_contents, n_date, n_depth, n_group, n_imgurl, n_videourl from news where seq_pid = " + seq_PID + " order by n_group desc, depth, n_date");
list = new ArrayList<NewsVO>();
while (rs.next()) {
vo = new NewsVO();
vo.setSeq_NNO(rs.getInt(1));
vo.setSeq_PID(rs.getInt(2));
vo.setId(rs.getString(3));
vo.setN_contents(rs.getString(4));
vo.setN_date(rs.getString(5));
vo.setN_depth(rs.getInt(6));
vo.setN_group(rs.getInt(7));
vo.setN_imgurl(rs.getString(8));
vo.setN_videourl(rs.getString(9));
list.add(vo);
}
} catch (Exception e) {
System.out.println("listNews : " + e);
} finally {
try {
rs.close();
st.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return list;
}
// boolean insertNewsReply(NewsVO vo) : 새소식에 댓글 달기
public boolean insertNewsReply(NewsVO vo) {
boolean result = false;
Connection conn = connectDB();
PreparedStatement st = null;
try {
st = conn.prepareStatement("insert into news(seq_NNO, seq_pid, id, n_contents, n_date, n_depth, n_group) values(?,?,?,?,?,?,?)");
st.setInt(1, vo.getSeq_NNO());
st.setInt(2, vo.getSeq_PID());
st.setString(3, vo.getId());
st.setString(4, vo.getN_contents());
st.setString(5, vo.getN_date());
st.setInt(6, vo.getN_depth());
st.setInt(7, vo.getN_group());
int num = st.executeUpdate();
if (num != 0) {
result = true;
}
} catch (Exception e) {
System.out.println("insertNewsReply : " + e);
} finally {
try {
st.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
public boolean deleteNewsReply(int seq_NNO) {
boolean result = false;
Connection conn = connectDB();
Statement st = null;
try {
st = conn.createStatement();
int num = st.executeUpdate("delete from news where seq_nno = " + seq_NNO);
if (num != 0) {
result = true;
}
} catch (Exception e) {
System.out.println("deleteNews : " + e);
} finally {
try {
st.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
public boolean updateNewsReply(NewsVO vo) {
boolean result = false;
Connection conn = connectDB();
PreparedStatement st = null;
try {
st = conn.prepareStatement("update news set n_contents=? where seq_NNO = ?");
st.setString(1, vo.getN_contents());
st.setInt(2, vo.getSeq_NNO());
int num = st.executeUpdate();
if (num != 0) {
result = true;
}
} catch (Exception e) {
System.out.println("updateNewsReply : " + e);
} finally {
try {
st.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
// 관리자 - 새소식 쓰기
public boolean insertNews(NewsVO vo) {
boolean result = false;
Connection conn = connectDB();
PreparedStatement st = null;
try {
st = conn.prepareStatement("insert into news(seq_NNO, seq_pid, id, n_contents, n_date, n_depth, n_group, n_imgurl, n_videourl) values(?,?,?,?,?,?,?,?,?)");
st.setInt(1, vo.getSeq_NNO());
st.setInt(2, vo.getSeq_PID());
st.setString(3, vo.getId());
st.setString(4, vo.getN_contents());
st.setString(5, vo.getN_date());
st.setInt(6, vo.getN_depth());
st.setInt(7, vo.getN_group());
st.setString(8, vo.getN_imgurl());
st.setString(9, vo.getN_videourl());
int num = st.executeUpdate();
if (num != 0) {
result = true;
}
} catch (Exception e) {
System.out.println("insertNews : " + e);
} finally {
try {
st.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
// 관리자 - 새소식 삭제
public boolean deleteNews(int seq_NNO) {
boolean result = false;
Connection conn = connectDB();
Statement st = null;
try {
st = conn.createStatement();
int num = st.executeUpdate("delete from news where n_group = " + seq_NNO);
if (num != 0) {
result = true;
}
} catch (Exception e) {
System.out.println("deleteNews : " + e);
} finally {
try {
st.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
// 관리자 - 새소식 수정
public boolean updateNews(NewsVO vo) {
boolean result = false;
Connection conn = connectDB();
PreparedStatement st = null;
try {
st = conn.prepareStatement("update news set n_contents=?, n_date=?, n_imgurl=?, n_videourl=? where seq_NNO = ?");
st.setString(1, vo.getN_contents());
st.setString(2, vo.getN_date());
st.setString(3, vo.getN_imgurl());
st.setString(4, vo.getN_videourl());
st.setInt(5, vo.getSeq_NNO());
int num = st.executeUpdate();
if (num != 0) {
result = true;
}
} catch (Exception e) {
System.out.println("updateNews : " + e);
} finally {
try {
st.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
// 피드백 내용 보이기
public ArrayList<FeedbackVO> listFeedback(int seq_PID) {
ArrayList<FeedbackVO> list = null;
FeedbackVO vo = null;
Connection conn = connectDB();
Statement st = null;
ResultSet rs = null;
try {
st = conn.createStatement();
rs = st.executeQuery("select seq_FNO, seq_PID, f_contents, f_date, depth, f_group, id from feedback where seq_pid = " + seq_PID + " order by f_group, depth");
list = new ArrayList<FeedbackVO>();
while (rs.next()) {
vo = new FeedbackVO();
vo.setSeq_FNO(rs.getInt(1));
vo.setSeq_PID(rs.getInt(2));
vo.setF_contents(rs.getString(3));
vo.setF_date(rs.getString(4));
vo.setDepth(rs.getInt(5));
vo.setF_group(rs.getInt(6));
vo.setId(rs.getString(7));
list.add(vo);
}
} catch (Exception e) {
System.out.println("listFeedback : " + e);
} finally {
try {
rs.close();
st.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return list;
}
// 피드백 올리기
public boolean insertFeedback(FeedbackVO vo) {
boolean result = false;
Connection conn = connectDB();
PreparedStatement st = null;
try {
st = conn.prepareStatement("insert into feedback(seq_FNO, seq_PID, f_contents, f_date, depth, f_group, id) values(?,?,?,?,?,?,?)");
st.setInt(1, vo.getSeq_FNO());
st.setInt(2, vo.getSeq_PID());
st.setString(3, vo.getF_contents());
st.setString(4, vo.getF_date());
st.setInt(5, vo.getDepth());
st.setInt(6, vo.getF_group());
st.setString(7, vo.getId());
int num = st.executeUpdate();
if (num != 0) {
result = true;
}
} catch (Exception e) {
System.out.println("insertFeedback : " + e);
} finally {
try {
st.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
//피드백 삭제
public boolean deleteFeedback(int seq_FNO) {
boolean result = false;
Connection conn = connectDB();
Statement st = null;
try {
st = conn.createStatement();
int num = st.executeUpdate("delete from feedback where seq_fno = " + seq_FNO);
if (num != 0) {
result = true;
}
} catch (Exception e) {
System.out.println("deleteFeedback : " + e);
} finally {
try {
st.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
// feedback 수정
public boolean updateFeedback(FeedbackVO vo) {
boolean result = false;
Connection conn = connectDB();
PreparedStatement st = null;
try {
st = conn.prepareStatement("update Feedback set f_contents=? where seq_FNO = ?");
st.setString(1, vo.getF_contents());
st.setInt(2, vo.getSeq_FNO());
int num = st.executeUpdate();
if (num != 0) {
result = true;
}
} catch (Exception e) {
System.out.println("updateNews : " + e);
} finally {
try {
st.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
//프로젝트 진행중인지 확인
public ProjectVO checkProject(String id) {
ProjectVO vo = null;
Connection conn = connectDB();
PreparedStatement st = null;
ResultSet rs = null;
try {
st = conn.prepareStatement("select seq_PID, level_, inv_type from project where id = ? and status = 0");
st.setString(1, id);
rs = st.executeQuery();
if (rs.next()) {
vo = new ProjectVO();
vo.setSeq_PID(rs.getInt(1));
vo.setLevel_(rs.getInt(2));
vo.setInv_type(rs.getString(3));
}
} catch (Exception e) {
System.out.println("checkProject : " + e);
} finally {
try {
rs.close();
st.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return vo;
}
// 프로젝트정보(project DB)에 자료 올리기
public int insertProject(ProjectVO vo) {
int result = -1;
Connection conn = connectDB();
PreparedStatement st = null;
PreparedStatement st1 = null;
ResultSet rs = null;
// vo에 있는 값을 DB의 insert 명령어를 통해 넣기.
try {
st = conn.prepareStatement("insert into project values(seq_PID.nextval,?,?,?,0,?,0,sysdate,?,?,?,-1,0,?,0,?)");
st.setString(1, vo.getId());
st.setString(2, vo.getProj());
st.setInt(3, vo.getM_target());
st.setString(4, vo.getEnddate());
st.setInt(5, vo.getM_min());
st.setInt(6, vo.getM_max());
st.setString(7, vo.getInv_type());
st.setString(8, vo.getPurpose());
st.setString(9, vo.getImgurl());
st.executeQuery();
st1 = conn.prepareStatement("select seq_PID from project where proj = ?");
st1.setString(1, vo.getProj());
rs = st1.executeQuery();
if (rs.next()) {
result = rs.getInt(1);
}
} catch (Exception e) {
System.out.println("insertProject : " + e);
} finally {
try {
rs.close();
st1.close();
st.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
// 프로젝트에 inv_type 'R'일때, reward DB에 자료 올리기
public boolean insertReward(ArrayList<RewardVO> list) {
boolean result = true;
Connection conn = connectDB();
PreparedStatement st = null;
PreparedStatement st1 = null;
try {
for (int i = 0; i < list.size(); ++i) {
st = conn.prepareStatement("insert into reward values(?, ?, ?)");
st.setInt(1, list.get(i).getSeq_PID());
st.setInt(2, list.get(i).getStd_invest());
st.setString(3, list.get(i).getReward());
st.executeUpdate();
}
st1 = conn.prepareStatement("update project set level_ = 1 where seq_PID = ?");
st1.setInt(1,list.get(0).getSeq_PID());
st1.executeUpdate();
result = true;
} catch (Exception e) {
System.out.println("insertReward : " + e);
} finally {
try {
st.close();
st1.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
// 프로젝트에 inv_type 'I'일때, interest DB에 자료 올리기
public boolean insertInterest(ArrayList<InterestVO> list) {
boolean result = true;
Connection conn = connectDB();
PreparedStatement st = null;
PreparedStatement st1 = null;
try {
for (int i = 0; i < list.size(); ++i) {
st = conn.prepareStatement("insert into interest values(?, ?, ?)");
st.setInt(1, list.get(i).getSeq_PID());
st.setInt(2, list.get(i).getAudience());
st.setInt(3, list.get(i).getInterest());
st.executeUpdate();
}
st1 = conn.prepareStatement("update project set level_ = 1 where seq_PID = ?");
st1.setInt(1,list.get(0).getSeq_PID());
st1.executeUpdate();
result = true;
result = true;
} catch (Exception e) {
System.out.println("insertInterest : " + e);
} finally {
try {
st.close();
st1.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
// 영화정보(movie DB)에 자료 올리기
public boolean insertMovie(MovieVO vo) {
boolean result = false;
Connection conn = connectDB();
PreparedStatement st = null;
PreparedStatement st1 = null;
// vo에 있는 값을 DB의 insert 명령어를 통해 넣기.
try {
st = conn.prepareStatement("insert into movie values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
st.setInt(1, vo.getSeq_PID());
st.setString(2, vo.getTitle());
st.setString(3, vo.getGenre1());
st.setString(4, vo.getGenre2());
st.setString(5, vo.getGenre3());
st.setString(6, vo.getDirector());
st.setString(7, vo.getActor1());
st.setString(8, vo.getActor2());
st.setString(9, vo.getActor3());
st.setString(10, vo.getActor4());
st.setString(11, vo.getProduction());
st.setString(12, vo.getDistributor());
st.setString(13, vo.getReleasedate());
st.setString(14, vo.getOrigin_title());
st.setString(15, vo.getImporter());
st.executeQuery();
st1 = conn.prepareStatement("update project set level_ = 3, status = 1 where seq_PID = ?");
st1.setInt(1,vo.getSeq_PID());
st1.executeUpdate();
result = true;
} catch (Exception e) {
System.out.println("insertMovie : " + e);
} finally {
try {
st.close();
st1.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
// 기업정보(company DB)에 자료 올리기
public boolean insertCompany(CompanyVO vo) {
boolean result = false;
Connection conn = connectDB();
PreparedStatement st = null;
PreparedStatement st1 = null;
// vo에 있는 값을 DB의 insert 명령어를 통해 넣기.
try {
st = conn.prepareStatement("insert into company values(seq_CID.nextval,?,?,?,?,?,?,?,?,?,?)");
st.setInt(1, vo.getSeq_PID());
st.setString(2, vo.getId());
st.setString(3, vo.getC_name());
st.setString(4, vo.getC_location());
st.setString(5, vo.getC_date());
st.setString(6, vo.getC_eoname());
st.setInt(7, vo.getC_emp());
st.setString(8, vo.getC_crime());
st.setString(9, vo.getC_site());
st.setString(10, vo.getC_mail());
st.executeQuery();
st1 = conn.prepareStatement("update project set level_ = 2 where seq_PID = ?");
st1.setInt(1,vo.getSeq_PID());
st1.executeUpdate();
result = true;
} catch (Exception e) {
System.out.println("insertCompany : " + e);
} finally {
try {
st.close();
st1.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
public int investorNumber(int seq_PID) {
int result = 0;
Connection conn = connectDB();
Statement st = null;
ResultSet rs = null;
try {
st = conn.createStatement();
rs = st.executeQuery("select count(id) from investProject where seq_pid = " + seq_PID);
if (rs.next()) {
result = rs.getInt(1);
}
} catch (Exception e) {
System.out.println("investorNumber : " + e);
} finally {
try {
rs.close();
st.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
public int remainingDay(int seq_PID) {
int result = 0;
Connection conn = connectDB();
Statement st = null;
ResultSet rs = null;
try {
st = conn.createStatement();
rs = st.executeQuery("select enddate - sysdate from project where seq_pid = " + seq_PID);
if (rs.next()) {
result = rs.getInt(1);
}
} catch (Exception e) {
System.out.println("investorNumber : " + e);
} finally {
try {
rs.close();
st.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
}
|
package L4_June19.OOPS_Story1;
public class Person {
String name = "xyz";
int age = 45;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void setAge(int age) throws Exception {
if (age < 0) {
throw new Exception("Invalid age.");
}
this.age = age;
}
public void introduceYourself() {
System.out.println(this.name + " is " + this.age + " years old.");
}
public void sayHi(String name) {
System.out.println(this.name + " says hi to " + name);
}
}
|
package kr.co.magiclms.domain;
public class Transaction {
}
|
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class form4 extends JFrame implements ActionListener
{
JLabel l1,l2;
JTextField t1,t2;
JButton b1,b2;
String dep;
double ecode;
public void de()
{
l1=new JLabel("Emp-code");
l2=new JLabel("Department");
t1=new JTextField();
t2=new JTextField();
b1=new JButton("Accept");
b2=new JButton("Close");
setLayout(null);
setBounds(10,10,300,300);
show();
setTitle("Department Entry");
l1.setBounds(20,20,100,30);
t1.setBounds(140,20,100,30);
l2.setBounds(20,70,100,30);
t2.setBounds(140,70,100,30);
b1.setBounds(20,140,80,20);
b2.setBounds(120,140,80,20);
add(l1);
add(l2);
add(t1);
add(t2);
add(b1);
add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
}//close of de
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b1)
{
dep=(t1.getText());
ecode=Double.parseDouble(t2.getText());
}
if(ae.getSource()==b2)
{
form2 f2=new form2();
f2.setVisible(true);
f2.de();
setVisible(false);
}
}
} |
package com.neu.spring.pojo;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.AssociationOverride;
import javax.persistence.AssociationOverrides;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.SecondaryTable;
import javax.persistence.Table;
import javax.persistence.Transient;
//@Entity
//@Table(name="traderstock")
//@AssociationOverrides({
//
// @AssociationOverride(name = "traderstock",
// joinColumns = @JoinColumn(name = "trader_ID")),
// @AssociationOverride(name = "pk_stock",
// joinColumns = @JoinColumn(name = "STOCK_ID"))
//
//
//
//})
public class TraderStock {
// private StockTraderId pk = new StockTraderId();
//
//
// @EmbeddedId
// public StockTraderId getPk() {
// return pk;
// }
//
// public void setPk(StockTraderId pk) {
// this.pk = pk;
// }
//
// @Transient
// public StockInfo getStockInfo() {
// return getPk().getStock();
// }
//
// public void setStock(StockInfo stock) {
// getPk().setStock(stock);
// }
//
// @Transient
// public Trader getCategory() {
// return getPk().getTrader();
// }
//
// public void setTrader(Trader trader) {
// getPk().setTrader(trader);
// }
//
//
// @Column(name="qtyOwned")
// private int qtyOwned;
//
// @Column(name="activeQty")
// private int activeQty;
//
//
// public TraderStock()
// {
//
// }
//
//
//
//
//
// public int getQtyOwned() {
// return qtyOwned;
// }
// public void setQtyOwned(int qtyOwned) {
// this.qtyOwned = qtyOwned;
// }
// public int getActiveQty() {
// return activeQty;
// }
// public void setActiveQty(int activeQty) {
// this.activeQty = activeQty;
// }
//
// public boolean equals(Object o) {
// if (this == o)
// return true;
// if (o == null || getClass() != o.getClass())
// return false;
//
// TraderStock that = (TraderStock) o;
//
// if (getPk() != null ? !getPk().equals(that.getPk())
// : that.getPk() != null)
// return false;
//
// return true;
// }
//
// public int hashCode() {
// return (getPk() != null ? getPk().hashCode() : 0);
// }
//
}
|
package com.allmsi.sys.service;
/**
* 系统登录和退出操作
* @author sunnannan
*
*/
public interface WebLoginService {
Object login(String loginName,String password);
Object logout(String token);
}
|
/**
* Copyright (C) 2008 Atlassian
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.atlassian.theplugin.idea.autoupdate;
import com.atlassian.connector.cfg.ProjectCfgManager;
import com.atlassian.theplugin.commons.SchedulableChecker;
import com.atlassian.theplugin.commons.configuration.GeneralConfigurationBean;
import com.atlassian.theplugin.commons.configuration.PluginConfiguration;
import com.atlassian.theplugin.commons.exception.IncorrectVersionException;
import com.atlassian.theplugin.commons.exception.ThePluginException;
import com.atlassian.theplugin.commons.remoteapi.ServerData;
import com.atlassian.theplugin.commons.util.Version;
import com.atlassian.theplugin.exception.VersionServiceException;
import com.atlassian.theplugin.idea.IdeaHelper;
import com.atlassian.theplugin.util.InfoServer;
import com.atlassian.theplugin.util.PluginUtil;
import com.atlassian.theplugin.util.UsageStatisticsGeneratorImpl;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import java.util.Collection;
import java.util.HashSet;
import java.util.TimerTask;
/**
* Provides functionality to check for new version and update plugin
*/
public final class NewVersionChecker implements SchedulableChecker {
private static final long PLUGIN_UPDATE_ATTEMPT_DELAY = 60 * 60 * 1000; // every hour
// private static final long PLUGIN_UPDATE_ATTEMPT_DELAY = 10000; // every hour
private transient PluginConfiguration pluginConfiguration;
private static final String NAME = "New Version checker";
private boolean alreadyRunOnce = false;
public NewVersionChecker(final PluginConfiguration pluginConfiguration) {
this.pluginConfiguration = pluginConfiguration;
}
public static NewVersionChecker getInstance() {
return (NewVersionChecker) ApplicationManager.getApplication()
.getPicoContainer().getComponentInstanceOfType(NewVersionChecker.class);
}
/**
* Connects to the server, checks for new version and updates if necessary
*
* @return new TimerTask to be scheduled
*/
public TimerTask newTimerTask() {
return new TimerTask() {
@Override
public void run() {
try {
doRun(new ForwardToIconHandler(pluginConfiguration.getGeneralConfigurationData()), true);
} catch (ThePluginException e) {
PluginUtil.getLogger().info("Error checking new version: " + e.getMessage());
}
}
};
}
public boolean canSchedule() {
return true; // NewVersionChecker is always enabled
}
public long getInterval() {
return PLUGIN_UPDATE_ATTEMPT_DELAY;
}
public void resetListenersState() {
// do nothing
}
public String getName() {
return NAME;
}
private void doRun(UpdateActionHandler action, boolean showConfigPath) throws ThePluginException {
doRun(action, showConfigPath, pluginConfiguration.getGeneralConfigurationData(), false);
}
protected void doRun(UpdateActionHandler action, boolean showConfigPath, GeneralConfigurationBean configuration, boolean force)
throws ThePluginException {
if (!configuration.isAutoUpdateEnabled()) {
alreadyRunOnce = false;
return;
}
if (!force && alreadyRunOnce) {
return;
}
alreadyRunOnce = true;
if (action == null) {
throw new IllegalArgumentException("UpdateAction handler not provided.");
}
// get latest version
InfoServer.VersionInfo versionInfo = getLatestVersion(configuration);
Version newVersion = versionInfo.getVersion();
// get current version
Version thisVersion = new Version(PluginUtil.getInstance().getVersion());
if (newVersion.greater(thisVersion)) {
//
action.doAction(versionInfo, showConfigPath);
}
}
private InfoServer.VersionInfo getLatestVersion(GeneralConfigurationBean configuration)
throws VersionServiceException, IncorrectVersionException {
final Boolean anonymousFeedbackEnabled = configuration.getAnonymousEnhancedFeedbackEnabled();
// I was asked for all counters to always be present, so adding them here with zero values
pluginConfiguration.getGeneralConfigurationData().addCounterIfNotPresent("a");
pluginConfiguration.getGeneralConfigurationData().addCounterIfNotPresent("i");
pluginConfiguration.getGeneralConfigurationData().addCounterIfNotPresent("r");
pluginConfiguration.getGeneralConfigurationData().addCounterIfNotPresent("b");
Collection<ServerData> servers = new HashSet<ServerData>();
for (Project project : ProjectManager.getInstance().getOpenProjects()) {
ProjectCfgManager cfg = IdeaHelper.getProjectCfgManager(project);
if (cfg != null) {
servers.addAll(cfg.getAllServerss());
}
}
InfoServer.VersionInfo info = InfoServer.getLatestPluginVersion(
new UsageStatisticsGeneratorImpl(anonymousFeedbackEnabled != null ? anonymousFeedbackEnabled : true,
configuration.getUid(), pluginConfiguration.getGeneralConfigurationData(), servers),
configuration.isCheckUnstableVersionsEnabled());
// reset counters only after successful version info poll
for (String counter : pluginConfiguration.getGeneralConfigurationData().getStatsCountersMap().keySet()) {
pluginConfiguration.getGeneralConfigurationData().resetCounter(counter);
}
return info;
}
}
|
package com.shan.tech.javlib.consts;
public class ErrorMessage {
public static final String NO_FOUND = "There is no %s found by %s.";
}
|
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.neuron.mytelkom.model;
import java.io.Serializable;
public class MyTicketItem
implements Serializable
{
private static final long serialVersionUID = 0x8472bf1bde5baf01L;
String date;
String no;
String status;
public MyTicketItem()
{
}
public String getDate()
{
return date;
}
public String getNo()
{
return no;
}
public String getStatus()
{
return status;
}
public void setDate(String s)
{
date = s;
}
public void setNo(String s)
{
no = s;
}
public void setStatus(String s)
{
status = s;
}
}
|
package Sorters;
public class BogoSort extends Sorter{
public BogoSort(int[] array){
super(array);
}
@Override
protected void sort(int start, int finish) {
while(!isSorted()) {
randomize();
}
}
private void randomize(){
int[] temp = array.clone();
for(int i = array.length - 1; i >= 0; i--){
int randomNum = (int) Math.floor(Math.random() * i);
array[i] = temp[randomNum];
temp[randomNum] = temp[i];
}
}
}
|
package com.beike.wap.service;
import java.util.List;
import com.beike.wap.entity.MMerchant;
/**
* <p>
* Title:品牌或分店Service
* </p>
* <p>
* Description:
* </p>
* <p>
* Copyright: Copyright (c) 2011
* </p>
* <p>
* Company: qianpin.com
* </p>
*
* @date 2011-09-23
* @author k.w
* @version 1.0
*/
public interface MMerchantService {
/**
* 获取品牌
*/
public MMerchant getBrandById(long brandId);
/**
* 获取分店
*/
public List<MMerchant> getBranchByBrandId(long brandId);
/**
* 获得商家
*
* @param merchantId
* 商家ID
* @return
*/
public String getGoodsMerchantLogo(Long merchantId);
/**
* 获得商家评价平均分数
*
* @param merchantId
* 商家ID
* @return
*/
public String getAvgEvationScores(Long merchantId);
/**
* 根据brandId列表获取品牌列表
* @param brandIds
* @return
*/
public List<MMerchant> getBrandByIds(String brandIds);
/**
* Desceription : 根据商品ID去查询商品所属品牌
* @param goodsId
* @return
*/
public MMerchant getBrandByGoodId(String goodsId);
}
|
package com.trump.auction.cust.domain;
import lombok.Data;
import lombok.ToString;
import java.util.Date;
/**
* 用户实体
* @author wangbo
*/
@Data
@ToString
public class UserInfo {
private Integer id;
private String userType;
private String userPhone;
private String realName;
private String idNumber;
private String loginPassword;
private String payPassword;
private String wxNickName;
private String wxOpenId;
private String wxHeadImg;
private String qqNickName;
private String qqOpenId;
private String qqHeadImg;
private Date addTime;
private String addIp;
private Date updateTime;
private String status;
private String userFrom;
private Integer rechargeType;
private Integer rechargeMoney;
private String loginType;
private String provinceName;
private String cityName;
private String appInfo;
/**
* 昵称
*/
private String nickName;
/**
* 头像
*/
private String headImg;
}
|
package com.legaoyi.storer.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.legaoyi.storer.dao.GeneralDao;
import com.legaoyi.storer.service.GeneralService;
@Transactional
@Service("deviceUpMessageService")
public class DeviceUpMessageServiceImpl implements GeneralService {
@Autowired
@Qualifier("deviceUpMessageDao")
private GeneralDao deviceUpMessageDao;
public void batchSave(List<?> list) throws Exception {
deviceUpMessageDao.batchSave(list);
}
}
|
/**
* This class, the driver class, contains the main method of the program. In an attempt to make the program
* more modular and the main method simpler, the main method makes use of the "InputProcessor" class to
* process the input in the text file, rather than processing it solely in the main method itself.
*
* Having the input processing loop take place in InputProcessor adds more modularity to the program, and
* makes the main method more flexible, allowing it to be more easily modified, if desired, in the future.
*
* As for the program itself, this is a driver class of a program that will insert values into, and remove
* values from a binary tree. This program will also print a binary tree out, with the root node on the left
* and its children subtrees to the top-right and bottom-right of it. Finally, this program will print the
* values of the binary tree in the inOrder format.
*
* These processes are all carried out in the Binary Search Tree class, and the decision of which process
* to execute takes place in the InputProcessor class.
*
* @author Steven Wojsnis
* Binary Search Tree Project
* CS313, Dr.Svitak
*/
public class Project2 {
public static void main(String[] args){
BinarySearchTree<Integer> tree = new BinarySearchTree<>(); //creates new instance of BinarySearchTree
new InputProcessor(tree); //calls constructor of InputProcessor to read input of text file
}
}
|
package com.catCake.cakeonline.admin.entity;
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="cakeSize")
public class CakeSize {
private int sizeId ;
private int cakeSize ;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="sizeId")
public int getSizeId() {
return sizeId;
}
public void setSizeId(int sizeId) {
this.sizeId = sizeId;
}
@Column(name="cakeSize")
public int getCakeSize() {
return cakeSize;
}
public void setCakeSize(int cakeSize) {
this.cakeSize = cakeSize;
}
}
|
package Strategy;
public class AccountPremiumStrategy extends CableTVStrategy{
private static double serviceCharge = 0.2;
private static double valueAdditionalChannel = 2;
@Override
public double invoice(double numbersChannels, double valueChannels) {
return (numbersChannels * valueChannels * this.valueAdditionalChannel)*this.serviceCharge+numbersChannels * valueChannels;
}
}
|
/*
* Copyright 2002-2023 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.context.annotation.configuration;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.function.Supplier;
import jakarta.annotation.Resource;
import jakarta.inject.Provider;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InjectionPoint;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.DependencyDescriptor;
import org.springframework.beans.factory.config.ListFactoryBean;
import org.springframework.beans.factory.parsing.BeanDefinitionParsingException;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.testfixture.beans.ITestBean;
import org.springframework.beans.testfixture.beans.NestedTestBean;
import org.springframework.beans.testfixture.beans.TestBean;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.AnnotationConfigUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ConfigurationClassPostProcessor;
import org.springframework.context.annotation.Scope;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.support.GenericApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Miscellaneous system tests covering {@link Bean} naming, aliases, scoping and
* error handling within {@link Configuration} class definitions.
*
* @author Chris Beams
* @author Juergen Hoeller
* @author Sam Brannen
*/
class ConfigurationClassProcessingTests {
@Test
void customBeanNameIsRespectedWhenConfiguredViaNameAttribute() {
customBeanNameIsRespected(ConfigWithBeanWithCustomName.class,
() -> ConfigWithBeanWithCustomName.testBean, "customName");
}
@Test
void customBeanNameIsRespectedWhenConfiguredViaValueAttribute() {
customBeanNameIsRespected(ConfigWithBeanWithCustomNameConfiguredViaValueAttribute.class,
() -> ConfigWithBeanWithCustomNameConfiguredViaValueAttribute.testBean, "enigma");
}
private void customBeanNameIsRespected(Class<?> testClass, Supplier<TestBean> testBeanSupplier, String beanName) {
GenericApplicationContext ac = new GenericApplicationContext();
AnnotationConfigUtils.registerAnnotationConfigProcessors(ac);
ac.registerBeanDefinition("config", new RootBeanDefinition(testClass));
ac.refresh();
assertThat(ac.getBean(beanName)).isSameAs(testBeanSupplier.get());
// method name should not be registered
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() ->
ac.getBean("methodName"));
}
@Test
void aliasesAreRespectedWhenConfiguredViaNameAttribute() {
aliasesAreRespected(ConfigWithBeanWithAliases.class,
() -> ConfigWithBeanWithAliases.testBean, "name1");
}
@Test
void aliasesAreRespectedWhenConfiguredViaValueAttribute() {
aliasesAreRespected(ConfigWithBeanWithAliasesConfiguredViaValueAttribute.class,
() -> ConfigWithBeanWithAliasesConfiguredViaValueAttribute.testBean, "enigma");
}
private void aliasesAreRespected(Class<?> testClass, Supplier<TestBean> testBeanSupplier, String beanName) {
TestBean testBean = testBeanSupplier.get();
BeanFactory factory = initBeanFactory(testClass);
assertThat(factory.getBean(beanName)).isSameAs(testBean);
Arrays.stream(factory.getAliases(beanName)).map(factory::getBean).forEach(alias -> assertThat(alias).isSameAs(testBean));
// method name should not be registered
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() ->
factory.getBean("methodName"));
}
@Test // SPR-11830
void configWithBeanWithProviderImplementation() {
GenericApplicationContext ac = new GenericApplicationContext();
AnnotationConfigUtils.registerAnnotationConfigProcessors(ac);
ac.registerBeanDefinition("config", new RootBeanDefinition(ConfigWithBeanWithProviderImplementation.class));
ac.refresh();
assertThat(ConfigWithBeanWithProviderImplementation.testBean).isSameAs(ac.getBean("customName"));
}
@Test // SPR-11830
void configWithSetWithProviderImplementation() {
GenericApplicationContext ac = new GenericApplicationContext();
AnnotationConfigUtils.registerAnnotationConfigProcessors(ac);
ac.registerBeanDefinition("config", new RootBeanDefinition(ConfigWithSetWithProviderImplementation.class));
ac.refresh();
assertThat(ConfigWithSetWithProviderImplementation.set).isSameAs(ac.getBean("customName"));
}
@Test
void finalBeanMethod() {
assertThatExceptionOfType(BeanDefinitionParsingException.class).isThrownBy(() ->
initBeanFactory(ConfigWithFinalBean.class));
}
@Test // gh-31007
void voidBeanMethod() {
assertThatExceptionOfType(BeanDefinitionParsingException.class).isThrownBy(() ->
initBeanFactory(ConfigWithVoidBean.class));
}
@Test
void simplestPossibleConfig() {
BeanFactory factory = initBeanFactory(SimplestPossibleConfig.class);
String stringBean = factory.getBean("stringBean", String.class);
assertThat(stringBean).isEqualTo("foo");
}
@Test
void configWithObjectReturnType() {
BeanFactory factory = initBeanFactory(ConfigWithNonSpecificReturnTypes.class);
assertThat(factory.getType("stringBean")).isEqualTo(Object.class);
assertThat(factory.isTypeMatch("stringBean", String.class)).isFalse();
String stringBean = factory.getBean("stringBean", String.class);
assertThat(stringBean).isEqualTo("foo");
}
@Test
void configWithFactoryBeanReturnType() {
ListableBeanFactory factory = initBeanFactory(ConfigWithNonSpecificReturnTypes.class);
assertThat(factory.getType("factoryBean")).isEqualTo(List.class);
assertThat(factory.isTypeMatch("factoryBean", List.class)).isTrue();
assertThat(factory.getType("&factoryBean")).isEqualTo(FactoryBean.class);
assertThat(factory.isTypeMatch("&factoryBean", FactoryBean.class)).isTrue();
assertThat(factory.isTypeMatch("&factoryBean", BeanClassLoaderAware.class)).isFalse();
assertThat(factory.isTypeMatch("&factoryBean", ListFactoryBean.class)).isFalse();
boolean condition = factory.getBean("factoryBean") instanceof List;
assertThat(condition).isTrue();
String[] beanNames = factory.getBeanNamesForType(FactoryBean.class);
assertThat(beanNames).hasSize(1);
assertThat(beanNames[0]).isEqualTo("&factoryBean");
beanNames = factory.getBeanNamesForType(BeanClassLoaderAware.class);
assertThat(beanNames).hasSize(1);
assertThat(beanNames[0]).isEqualTo("&factoryBean");
beanNames = factory.getBeanNamesForType(ListFactoryBean.class);
assertThat(beanNames).hasSize(1);
assertThat(beanNames[0]).isEqualTo("&factoryBean");
beanNames = factory.getBeanNamesForType(List.class);
assertThat(beanNames[0]).isEqualTo("factoryBean");
}
@Test
void configurationWithPrototypeScopedBeans() {
BeanFactory factory = initBeanFactory(ConfigWithPrototypeBean.class);
TestBean foo = factory.getBean("foo", TestBean.class);
ITestBean bar = factory.getBean("bar", ITestBean.class);
ITestBean baz = factory.getBean("baz", ITestBean.class);
assertThat(bar).isSameAs(foo.getSpouse());
assertThat(baz).isNotSameAs(bar.getSpouse());
}
@Test
void configurationWithNullReference() {
BeanFactory factory = initBeanFactory(ConfigWithNullReference.class);
TestBean foo = factory.getBean("foo", TestBean.class);
assertThat(factory.getBean("bar").equals(null)).isTrue();
assertThat(foo.getSpouse()).isNull();
}
@Test
void configurationWithAdaptivePrototypes() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(ConfigWithPrototypeBean.class, AdaptiveInjectionPoints.class);
ctx.refresh();
AdaptiveInjectionPoints adaptive = ctx.getBean(AdaptiveInjectionPoints.class);
assertThat(adaptive.adaptiveInjectionPoint1.getName()).isEqualTo("adaptiveInjectionPoint1");
assertThat(adaptive.adaptiveInjectionPoint2.getName()).isEqualTo("setAdaptiveInjectionPoint2");
adaptive = ctx.getBean(AdaptiveInjectionPoints.class);
assertThat(adaptive.adaptiveInjectionPoint1.getName()).isEqualTo("adaptiveInjectionPoint1");
assertThat(adaptive.adaptiveInjectionPoint2.getName()).isEqualTo("setAdaptiveInjectionPoint2");
ctx.close();
}
@Test
void configurationWithAdaptiveResourcePrototypes() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(ConfigWithPrototypeBean.class, AdaptiveResourceInjectionPoints.class);
ctx.refresh();
AdaptiveResourceInjectionPoints adaptive = ctx.getBean(AdaptiveResourceInjectionPoints.class);
assertThat(adaptive.adaptiveInjectionPoint1.getName()).isEqualTo("adaptiveInjectionPoint1");
assertThat(adaptive.adaptiveInjectionPoint2.getName()).isEqualTo("setAdaptiveInjectionPoint2");
adaptive = ctx.getBean(AdaptiveResourceInjectionPoints.class);
assertThat(adaptive.adaptiveInjectionPoint1.getName()).isEqualTo("adaptiveInjectionPoint1");
assertThat(adaptive.adaptiveInjectionPoint2.getName()).isEqualTo("setAdaptiveInjectionPoint2");
ctx.close();
}
@Test
void configurationWithPostProcessor() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(ConfigWithPostProcessor.class);
@SuppressWarnings("deprecation")
RootBeanDefinition placeholderConfigurer = new RootBeanDefinition(
org.springframework.beans.factory.config.PropertyPlaceholderConfigurer.class);
placeholderConfigurer.getPropertyValues().add("properties", "myProp=myValue");
ctx.registerBeanDefinition("placeholderConfigurer", placeholderConfigurer);
ctx.refresh();
TestBean foo = ctx.getBean("foo", TestBean.class);
ITestBean bar = ctx.getBean("bar", ITestBean.class);
ITestBean baz = ctx.getBean("baz", ITestBean.class);
assertThat(foo.getName()).isEqualTo("foo-processed-myValue");
assertThat(bar.getName()).isEqualTo("bar-processed-myValue");
assertThat(baz.getName()).isEqualTo("baz-processed-myValue");
SpousyTestBean listener = ctx.getBean("listenerTestBean", SpousyTestBean.class);
assertThat(listener.refreshed).isTrue();
ctx.close();
}
@Test
void configurationWithFunctionalRegistration() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(ConfigWithFunctionalRegistration.class);
ctx.refresh();
assertThat(ctx.getBean(TestBean.class).getSpouse()).isSameAs(ctx.getBean("spouse"));
assertThat(ctx.getBean(NestedTestBean.class).getCompany()).isEqualTo("functional");
ctx.close();
}
@Test
void configurationWithApplicationListener() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(ConfigWithApplicationListener.class);
ctx.refresh();
ConfigWithApplicationListener config = ctx.getBean(ConfigWithApplicationListener.class);
assertThat(config.closed).isFalse();
ctx.close();
assertThat(config.closed).isTrue();
}
@Test
void configurationWithOverloadedBeanMismatch() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.registerBeanDefinition("config", new RootBeanDefinition(OverloadedBeanMismatch.class));
ctx.refresh();
TestBean tb = ctx.getBean(TestBean.class);
assertThat(tb.getLawyer()).isEqualTo(ctx.getBean(NestedTestBean.class));
ctx.close();
}
@Test
void configurationWithOverloadedBeanMismatchWithAsm() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.registerBeanDefinition("config", new RootBeanDefinition(OverloadedBeanMismatch.class.getName()));
ctx.refresh();
TestBean tb = ctx.getBean(TestBean.class);
assertThat(tb.getLawyer()).isEqualTo(ctx.getBean(NestedTestBean.class));
ctx.close();
}
@Test // gh-26019
void autowiringWithDynamicPrototypeBeanClass() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(
ConfigWithDynamicPrototype.class, PrototypeDependency.class);
PrototypeInterface p1 = ctx.getBean(PrototypeInterface.class, 1);
assertThat(p1).isInstanceOf(PrototypeOne.class);
assertThat(((PrototypeOne) p1).prototypeDependency).isNotNull();
PrototypeInterface p2 = ctx.getBean(PrototypeInterface.class, 2);
assertThat(p2).isInstanceOf(PrototypeTwo.class);
PrototypeInterface p3 = ctx.getBean(PrototypeInterface.class, 1);
assertThat(p3).isInstanceOf(PrototypeOne.class);
assertThat(((PrototypeOne) p3).prototypeDependency).isNotNull();
ctx.close();
}
/**
* Creates a new {@link BeanFactory}, populates it with a {@link BeanDefinition}
* for each of the given {@link Configuration} {@code configClasses}, and then
* post-processes the factory using JavaConfig's {@link ConfigurationClassPostProcessor}.
* When complete, the factory is ready to service requests for any {@link Bean} methods
* declared by {@code configClasses}.
*/
private DefaultListableBeanFactory initBeanFactory(Class<?>... configClasses) {
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
for (Class<?> configClass : configClasses) {
String configBeanName = configClass.getName();
factory.registerBeanDefinition(configBeanName, new RootBeanDefinition(configClass));
}
ConfigurationClassPostProcessor ccpp = new ConfigurationClassPostProcessor();
ccpp.postProcessBeanDefinitionRegistry(factory);
ccpp.postProcessBeanFactory(factory);
factory.freezeConfiguration();
return factory;
}
@Configuration
static class ConfigWithBeanWithCustomName {
static TestBean testBean = new TestBean(ConfigWithBeanWithCustomName.class.getSimpleName());
@Bean(name = "customName")
public TestBean methodName() {
return testBean;
}
}
@Configuration
static class ConfigWithBeanWithCustomNameConfiguredViaValueAttribute {
static TestBean testBean = new TestBean(ConfigWithBeanWithCustomNameConfiguredViaValueAttribute.class.getSimpleName());
@Bean("enigma")
public TestBean methodName() {
return testBean;
}
}
@Configuration
static class ConfigWithBeanWithAliases {
static TestBean testBean = new TestBean(ConfigWithBeanWithAliases.class.getSimpleName());
@Bean(name = {"name1", "alias1", "alias2", "alias3"})
public TestBean methodName() {
return testBean;
}
}
@Configuration
static class ConfigWithBeanWithAliasesConfiguredViaValueAttribute {
static TestBean testBean = new TestBean(ConfigWithBeanWithAliasesConfiguredViaValueAttribute.class.getSimpleName());
@Bean({"enigma", "alias1", "alias2", "alias3"})
public TestBean methodName() {
return testBean;
}
}
@Configuration
static class ConfigWithBeanWithProviderImplementation implements Provider<TestBean> {
static TestBean testBean = new TestBean(ConfigWithBeanWithProviderImplementation.class.getSimpleName());
@Override
@Bean(name = "customName")
public TestBean get() {
return testBean;
}
}
@Configuration
static class ConfigWithSetWithProviderImplementation implements Provider<Set<String>> {
static Set<String> set = Collections.singleton("value");
@Override
@Bean(name = "customName")
public Set<String> get() {
return set;
}
}
@Configuration
static class ConfigWithFinalBean {
public final @Bean TestBean testBean() {
return new TestBean();
}
}
@Configuration
static class ConfigWithVoidBean {
public @Bean void testBean() {
}
}
@Configuration
static class SimplestPossibleConfig {
public @Bean String stringBean() {
return "foo";
}
}
@Configuration
static class ConfigWithNonSpecificReturnTypes {
public @Bean Object stringBean() {
return "foo";
}
public @Bean FactoryBean<?> factoryBean() {
ListFactoryBean fb = new ListFactoryBean();
fb.setSourceList(Arrays.asList("element1", "element2"));
return fb;
}
}
@Configuration
static class ConfigWithPrototypeBean {
public @Bean TestBean foo() {
TestBean foo = new SpousyTestBean("foo");
foo.setSpouse(bar());
return foo;
}
public @Bean TestBean bar() {
TestBean bar = new SpousyTestBean("bar");
bar.setSpouse(baz());
return bar;
}
@Bean @Scope("prototype")
public TestBean baz() {
return new TestBean("baz");
}
@Bean @Scope("prototype")
public TestBean adaptive1(InjectionPoint ip) {
return new TestBean(ip.getMember().getName());
}
@Bean @Scope("prototype")
public TestBean adaptive2(DependencyDescriptor dd) {
return new TestBean(dd.getMember().getName());
}
}
@Configuration
static class ConfigWithNullReference extends ConfigWithPrototypeBean {
@Override
public TestBean bar() {
return null;
}
}
@Scope("prototype")
static class AdaptiveInjectionPoints {
@Autowired @Qualifier("adaptive1")
public TestBean adaptiveInjectionPoint1;
public TestBean adaptiveInjectionPoint2;
@Autowired @Qualifier("adaptive2")
public void setAdaptiveInjectionPoint2(TestBean adaptiveInjectionPoint2) {
this.adaptiveInjectionPoint2 = adaptiveInjectionPoint2;
}
}
@Scope("prototype")
static class AdaptiveResourceInjectionPoints {
@Resource(name = "adaptive1")
public TestBean adaptiveInjectionPoint1;
public TestBean adaptiveInjectionPoint2;
@Resource(name = "adaptive2")
public void setAdaptiveInjectionPoint2(TestBean adaptiveInjectionPoint2) {
this.adaptiveInjectionPoint2 = adaptiveInjectionPoint2;
}
}
static class ConfigWithPostProcessor extends ConfigWithPrototypeBean {
@Value("${myProp}")
private String myProp;
@Bean
public POBPP beanPostProcessor() {
return new POBPP() {
String nameSuffix = "-processed-" + myProp;
@SuppressWarnings("unused")
public void setNameSuffix(String nameSuffix) {
this.nameSuffix = nameSuffix;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) {
if (bean instanceof ITestBean) {
((ITestBean) bean).setName(((ITestBean) bean).getName() + nameSuffix);
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
return bean;
}
};
}
// @Bean
public BeanFactoryPostProcessor beanFactoryPostProcessor() {
return beanFactory -> {
BeanDefinition bd = beanFactory.getBeanDefinition("beanPostProcessor");
bd.getPropertyValues().addPropertyValue("nameSuffix", "-processed-" + myProp);
};
}
@Bean
public ITestBean listenerTestBean() {
return new SpousyTestBean("listener");
}
}
public interface POBPP extends BeanPostProcessor {
}
private static class SpousyTestBean extends TestBean implements ApplicationListener<ContextRefreshedEvent> {
public boolean refreshed = false;
public SpousyTestBean(String name) {
super(name);
}
@Override
public void setSpouse(ITestBean spouse) {
super.setSpouse(spouse);
}
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
this.refreshed = true;
}
}
@Configuration
static class ConfigWithFunctionalRegistration {
@Autowired
void register(GenericApplicationContext ctx) {
ctx.registerBean("spouse", TestBean.class,
() -> new TestBean("functional"));
Supplier<TestBean> testBeanSupplier = () -> new TestBean(ctx.getBean("spouse", TestBean.class));
ctx.registerBean(TestBean.class,
testBeanSupplier,
bd -> bd.setPrimary(true));
}
@Bean
public NestedTestBean nestedTestBean(TestBean testBean) {
return new NestedTestBean(testBean.getSpouse().getName());
}
}
@Configuration
static class ConfigWithApplicationListener {
boolean closed = false;
@Bean
public ApplicationListener<ContextClosedEvent> listener() {
return (event -> this.closed = true);
}
}
@Configuration(enforceUniqueMethods = false)
public static class OverloadedBeanMismatch {
@Bean(name = "other")
public NestedTestBean foo() {
return new NestedTestBean();
}
@Bean(name = "foo")
public TestBean foo(@Qualifier("other") NestedTestBean other) {
TestBean tb = new TestBean();
tb.setLawyer(other);
return tb;
}
}
static class PrototypeDependency {
}
interface PrototypeInterface {
}
static class PrototypeOne extends AbstractPrototype {
@Autowired
PrototypeDependency prototypeDependency;
}
static class PrototypeTwo extends AbstractPrototype {
// no autowired dependency here, in contrast to above
}
static class AbstractPrototype implements PrototypeInterface {
}
@Configuration
static class ConfigWithDynamicPrototype {
@Bean
@Scope(value = "prototype")
public PrototypeInterface getDemoBean(int i) {
return switch (i) {
case 1 -> new PrototypeOne();
default -> new PrototypeTwo();
};
}
}
}
|
package com.app.AdminUI.ControlsUI;
import com.app.DBConnection;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class DeleteScreen extends JFrame {
private JPanel deletePanel;
private JTextField IDTextField;
private JButton deleteButton;
public DeleteScreen(int choice) {
add(deletePanel);
setSize(400, 200);
setTitle("Music App / Admin Delete Data");
deleteButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String ID = IDTextField.getText();
deleteRecord(choice, ID);
}
});
}
public void deleteRecord(int choice, String ID) {
try {
Connection connection = DBConnection.getConnection();
String sqlQuery = null;
if (choice == 1) {
sqlQuery = "DELETE FROM songs WHERE id = '" + ID + "'";
PreparedStatement songStatement = connection.prepareStatement(sqlQuery);
int resultSet = songStatement.executeUpdate();
if (resultSet != 0) {
songStatement.execute();
}
} else if (choice == 2) {
sqlQuery = "DELETE FROM artists WHERE id= '" + ID + "'";
PreparedStatement artistStatement = connection.prepareStatement(sqlQuery);
int resultSet = artistStatement.executeUpdate();
if (resultSet != 0) {
artistStatement.execute();
}
} else if (choice == 3) {
sqlQuery = "DELETE FROM albums WHERE id= '" + ID + "'";
PreparedStatement albumStatement = connection.prepareStatement(sqlQuery);
int resultSet = albumStatement.executeUpdate();
if (resultSet != 0) {
albumStatement.execute();
}
}
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
|
package com.xld.timer.test;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* @descript 定时器测试
* @author xld
* @date 2019-09-29 4:01 PM
*/
@Component
public class TestTimer {
@Scheduled(cron = "0/5 * * * * ?")
public void test(){
System.out.println("----定时器测试----");
}
}
|
package by.htp.carparking.web.action.impl;
//import static by.htp.carparking.web.util.WebConstantDeclaration.*;
//import static by.htp.carparking.web.util.HttpRequestParamValidator.*;
//import static by.htp.carparking.web.util.HttpRequestParamFormatter.*;
import javax.servlet.http.HttpServletRequest;
import by.htp.carparking.service.OrderService;
import by.htp.carparking.service.impl.OrderServiceImpl;
import by.htp.carparking.web.action.BaseAction;
public class OrderCarAction implements BaseAction {
//TODO to IoC
private OrderService orderService = new OrderServiceImpl();
@Override
public String executeAction(HttpServletRequest request) {
//
// String carId = request.getParameter(REQUEST_PARAM_CAR_ID);
// String userId = request.getParameter(REQUEST_PARAM_USER_ID);
//
// validateRequestParamNotNull(carId, userId);
// orderService.orderCar(formatString(userId), formatString(carId));
//
// request.setAttribute(REQUEST_MSG_SUCCESS, "The car was ordered succesfully");
// return PAGE_USER_MAIN;
return "";
}
}
|
package com.ecej.nove.autoconfigure.redis;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import com.ecej.nove.redis.core.RedisAutoConfiguration;
import com.ecej.nove.redis.utils.JedisClusterUtils;
import org.springframework.core.annotation.Order;
@Configuration
@ConditionalOnClass(JedisClusterUtils.class)
@Import(RedisAutoConfiguration.class)
@Order(0)
public class RedisAutoConfig {
}
|
package reportExtends;
import java.io.IOException;
import com.aventstack.extentreports.ExtentReporter;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.MediaEntityBuilder;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
public class Report_Extends {
public static void main(String[] args) throws IOException {
ExtentHtmlReporter html=new ExtentHtmlReporter("./Reports/result.html");
//Maintaining history
html.setAppendExisting(true);
ExtentReports extents=new ExtentReports();
//Making as Editable from non-editable
extents.attachReporter(html);
//Adding Description
ExtentTest test = extents.createTest("TC002_EditLead","Edit an existing lead" );
test.assignCategory("sanity");
test.assignAuthor("Ramki");
test.pass("Login is successfull",MediaEntityBuilder.createScreenCaptureFromPath("./../snaps/img.png").build());
test.pass("An existing lead is successfully edited",MediaEntityBuilder.createScreenCaptureFromPath("./../snaps/img.png").build());
test.assignAuthor("Antony");
test.fail("The Edit lead is success");
extents.flush();
}
}
|
package com.jgchk.haven.data.model.db;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.Ignore;
import android.arch.persistence.room.PrimaryKey;
import android.location.Location;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jgchk.haven.data.model.others.Restriction;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
@Entity(tableName = "shelters")
public class Shelter implements Serializable {
private static final double METERS_TO_MILES_CONVERSION_FACTOR = 0.000621371192;
@PrimaryKey
public Long id;
public String name;
public int capacity;
public Location location;
public String address;
public String notes;
public String phone;
public Set<Restriction> restrictions;
@Ignore
public double distance;
@Ignore
public int vacancies;
public Shelter(String name, int capacity, Location location,
String address, String notes, String phone, Set<Restriction> restrictions) {
this.name = name;
this.capacity = capacity;
this.location = location;
this.address = address;
this.notes = notes;
this.phone = phone;
this.restrictions = restrictions;
// this.reservations = new HashMap<>();
}
// public int getTotalReservations() {
// int totalReservations = 0;
// for (Integer reservations : reservations.values()) {
// if (reservations != null) {
// totalReservations += reservations;
// }
// }
// return totalReservations;
// }
// public int getVacancies() {
// return capacity - getTotalReservations();
// }
public double getDistanceInMiles(Location currentLocation) {
return convertMetersToMiles(location.distanceTo(currentLocation));
}
private double convertMetersToMiles(double meters) {
return meters * METERS_TO_MILES_CONVERSION_FACTOR;
}
public String getRestrictionsString() {
return restrictions.stream().map(Restriction::toString).collect(Collectors.joining(", "));
}
// public boolean reserve(User user, int numReservations) {
// if (reservations.containsKey(user)) {
// return false;
// }
//
// reservations.put(user, numReservations);
// return true;
// }
// public boolean release(User user) {
// if (!reservations.containsKey(user)) {
// return false;
// }
//
// reservations.remove(user);
// return true;
// }
@Override
public String toString() {
return "Shelter{" +
"id=" + id +
", name='" + name + '\'' +
", capacity=" + capacity +
", location=" + location +
", address='" + address + '\'' +
", notes='" + notes + '\'' +
", phone='" + phone + '\'' +
", restrictions=" + restrictions +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Shelter shelter = (Shelter) o;
return capacity == shelter.capacity &&
Objects.equals(name, shelter.name) &&
Objects.equals(location, shelter.location) &&
Objects.equals(address, shelter.address) &&
Objects.equals(notes, shelter.notes) &&
Objects.equals(phone, shelter.phone) &&
Objects.equals(restrictions, shelter.restrictions);
}
@Override
public int hashCode() {
return Objects.hash(name, capacity, location, address, notes, phone, restrictions);
}
private void writeObject(ObjectOutputStream oos) throws IOException {
oos.writeLong(id);
oos.writeObject(name);
oos.writeInt(capacity);
oos.writeObject(new Gson().toJson(location));
oos.writeObject(address);
oos.writeObject(notes);
oos.writeObject(phone);
oos.writeObject(restrictions);
oos.writeDouble(distance);
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
id = ois.readLong();
name = (String) ois.readObject();
capacity = ois.readInt();
location = new Gson().fromJson((String) ois.readObject(), new TypeToken<Location>() {
}.getType());
address = (String) ois.readObject();
notes = (String) ois.readObject();
phone = (String) ois.readObject();
restrictions = (Set<Restriction>) ois.readObject();
distance = ois.readDouble();
}
}
|
package com.universidadeafit.appeafit.Views;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import com.universidadeafit.appeafit.Adapters.MyRecyclerViewAdapterSolicitudes;
import com.universidadeafit.appeafit.Model.Solicitud;
import com.universidadeafit.appeafit.R;
import java.util.ArrayList;
public class DetalleSolicitud extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;
private RecyclerView.Adapter mAdapter;
private static String LOG_TAG = "CardViewActivity";
String placa = "";
String usuario;
String ip = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detalle_vehiculos);
verToolbar("Detalle",true);
placa = getIntent().getExtras().getString("placa");
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MyRecyclerViewAdapterSolicitudes(getDataSet());
mRecyclerView.setAdapter(mAdapter);
}
public void verToolbar(String titulo,Boolean UpButton){
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(titulo);
getSupportActionBar().setDisplayHomeAsUpEnabled(UpButton);
}
@Override
protected void onResume() {
super.onResume();
((MyRecyclerViewAdapterSolicitudes) mAdapter).setOnItemClickListener(new MyRecyclerViewAdapterSolicitudes
.MyClickListener() {
@Override
public void onItemClick(int position, View v) {
}
});
}
private ArrayList<Solicitud> getDataSet() {
ArrayList<Solicitud> persons = new ArrayList<>();
persons.add(new Solicitud(placa, "23 years old", R.drawable.im_logo_eafit_55,"Descripcion","Material is the metaphor.\n\n"+
"A material metaphor is the unifying theory of a rationalized space and a system of motion."+
"The material is grounded in tactile reality, inspired by the study of paper and ink, yet "+
"technologically advanced and open to imagination and magic.\n"+
"Surfaces and edges of the material provide visual cues that are grounded in reality. The "+
"use of familiar tactile attributes helps users quickly understand affordances. Yet the "+
"flexibility of the material creates new affordances that supercede those in the physical "+
"world, without breaking the rules of physics.\n" +
"The fundamentals of light, surface, and movement are key to conveying how objects move, "+
"interact, and exist in space and in relation to each other. Realistic lighting shows "+
"seams, divides space, and indicates moving parts.\n\n",""));
persons.add(new Solicitud("Lavery Maiss", "25 years old", R.drawable.im_logo_eafit_55, "Vendo", "Vendo paisaje",""));
persons.add(new Solicitud("Lillie Watts", "35 years old", R.drawable.im_logo_eafit_55, "Vendo", "Vendo paisaje",""));
return persons;
}
}
|
/*
* 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 services;
import javax.swing.JOptionPane;
/**
*
* @author boc
*/
public class Alerts {
public static void infoBox(String infoMsg , String Title){
JOptionPane.showMessageDialog(null,infoMsg, Title,JOptionPane.INFORMATION_MESSAGE);
}
}
|
package Problem1;
public class ArrayDictionary implements Dictionary {
private KVEntry[] entries;
public ArrayDictionary(int capacity) {
entries = new KVEntry[capacity];
}
@Override
public boolean isEmpty() {
// NOT IMPLEMENTED YET
return false;
}
private int hashFunction(String key) {
// not ideal
return key.length();
}
@Override
public void put(String key, String value) {
int hashedKey = hashFunction(key);
// when there's no entry yet
if (entries[hashedKey] == null) {
entries[hashedKey] = new KVEntry(key, value);
return;
}
KVEntry ptr = entries[hashedKey];
while (ptr.next != null) {
// update value if key already exists
if (ptr.key.equals(key)) {
ptr.value = value;
return;
}
ptr = ptr.next;
}
// add an entry to the end of the chain
ptr.next = new KVEntry(key, value);
}
@Override
public void remove(String key) {
// homework
for (int i = 0; i < entries.length; i++) {
if (!(entries[i] == null)) {
if (entries[i].key.equals(key)) {
entries[i] = entries[i].next;
}
}
}
}
@Override
public String get(String key) {
int hashedKey = hashFunction(key);
if (entries[hashedKey] == null) {
return null;
}
KVEntry ptr = entries[hashedKey];
while (ptr != null) {
if (ptr.key.equals(key)) {
return ptr.value;
}
ptr = ptr.next;
}
return null;
}
@Override
public boolean contains(String key) {
int hashedKey = hashFunction(key);
if (hashedKey >= entries.length) {
return false;
}
if (entries[hashedKey] == null) {
return false;
}
KVEntry ptr = entries[hashedKey];
while (ptr != null) {
if (ptr.key.equals(key)) {
return true;
}
ptr = ptr.next;
}
return false;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < entries.length; i++) {
if (entries[i] == null) {
builder.append("dictionary[" + i + "] = null\n");
continue;
}
KVEntry ptr = entries[i];
builder.append("dictionary[" + i + "] = {");
while (ptr != null) {
builder.append("(" + ptr.key + ", " + ptr.value + ")");
ptr = ptr.next;
}
builder.append("}\n");
}
return builder.toString();
}
}
|
package com.example.coolcloudweather;
public class Hour {
private String degree;
private String time;
private String text;
public String getDegree() {
return degree;
}
public void setDegree(String degree) {
this.degree = degree;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
|
package Problem_2156;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
int[] cup = new int[N + 1];
int[] dp = new int[N + 1];
for (int i = 1; i <= N; i++) {
cup[i] = Integer.parseInt(br.readLine());
}
if (N == 1) {
System.out.println(cup[N]);
return;
} else if (N == 2) {
System.out.println((cup[N] + cup[N - 1]));
return;
}
dp[1] = cup[1];
dp[2] = cup[1]+cup[2];
for (int i = 3; i <= N; i++) {
dp[i] = Math.max(dp[i-3] + cup[i-1] + cup[i], Math.max(dp[i - 2] + cup[i], dp[i - 1]));
}
System.out.println(dp[N]);
}
}
|
package com.karya.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="unitofmeasure001mb")
public class UnitofMeasures001MB implements Serializable{
private static final long serialVersionUID = -723583058586873479L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "unitId")
private int unitId;
@Column(name="unitName")
private String unitName;
public int getUnitId() {
return unitId;
}
public void setUnitId(int unitId) {
this.unitId = unitId;
}
public String getUnitName() {
return unitName;
}
public void setUnitName(String unitName) {
this.unitName = unitName;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
|
package com.agamidev.newsfeedsapp.Interfaces;
import com.agamidev.newsfeedsapp.Models.NewsModel;
public interface RecyclerItemClickListener {
void onItemClick(NewsModel news);
}
|
package com.vicutu.batchdownload.dao;
import com.vicutu.batchdownload.domain.DownloadDetail;
public interface DownloadDetailDao {
void saveOrUpdateAccessDetail(DownloadDetail downloadDetail);
}
|
package com.example.administrator.competition.fragment.my;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.administrator.competition.R;
import com.yidao.module_lib.base.BaseView;
import com.yidao.module_lib.manager.ViewManager;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MySettingActivity extends BaseView {
@BindView(R.id.tv_title)
TextView tvTitle;
@BindView(R.id.tv_right)
TextView tvRight;
@BindView(R.id.iv_head)
ImageView ivHead;
@BindView(R.id.tv_name)
TextView tvName;
@Override
protected int getView() {
return R.layout.activity_my_setting;
}
@Override
public void init() {
tvTitle.setText("设置");
tvRight.setText("确定");
}
@OnClick({R.id.iv_back, R.id.tv_right, R.id.rl_clear, R.id.rl_about_us, R.id.tv_logout})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.iv_back:
ViewManager.getInstance().finishView();
break;
case R.id.tv_right:
break;
case R.id.rl_clear:
break;
case R.id.rl_about_us:
skipActivity(MyAboutUsActivity.class);
break;
case R.id.tv_logout:
break;
}
}
}
|
package quiz03;
public class MainClass {
public static void main(String[] args) {
// 월급쟁이
SalaryMan staff1 = new SalaryMan("james" , 300);
SalaryMan staff4 = new SalaryMan("brown" , 300);
//System.out.println(staff1.getName());
//System.out.println(staff1.getPay());
// 판매직
SalesMan staff2 = new SalesMan("alice" , 100);
staff2.setSalesAmount(2000);
//System.out.println(staff2.getName());
//System.out.println(staff2.getPay());
// 알바
Alba staff3 = new Alba("david");
staff3.setPayPerHour(10000);
staff3.setTimes(200);
//System.out.println(staff3.getName());
//System.out.println(staff3.getPay());
// 회사
Company company = new Company(10);
company.hireStaff(staff1);
company.hireStaff(staff2);
company.hireStaff(staff3);
company.hireStaff(staff4);
company.staffInfo();
}
}
|
class Perulangan
{
public static void main(String[] args)
{
for(int i = 1; i <= 10; i++) {
System.out.println(i);
}
int a=1;
while(a <= 10) {
System.out.println(a);
a = a +1; // a++;
}
int b = 1;
do {
System.out.println(b);
b = b +1; // b++;
}while(b <=10);
}
} |
package Models;
public class EmployeeRole
{
private String SSN;
private String title;
private double salary;
public EmployeeRole(String SSN, String title, double salary)
{
this.SSN = SSN;
this.title = title;
this.salary = salary;
}
public String getSSN() {
return SSN;
}
public void setSSN(String SSN) {
this.SSN = SSN;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
|
import gtfs.GtfsData;
import network.datasource.CategoryAPI;
import network.datasource.EventAPI;
import network.datasource.impl.CategoryAPIImpl;
import network.datasource.impl.EventAPIImpl;
import network.model.response.CategoryResponse;
import network.model.response.EventResponse;
import org.onebusaway.csv_entities.schema.DefaultEntitySchemaFactory;
import org.onebusaway.gtfs.serialization.GtfsEntitySchemaFactory;
import org.onebusaway.gtfs.serialization.GtfsWriter;
import utils.Const;
import xplanner.model.PoiData;
import java.io.File;
import java.io.IOException;
import java.util.List;
public class Main {
public static void main(String[] args) {
GtfsData gtfs = new GtfsData();
try {
/*
Process p = Runtime.getRuntime().exec("python " +
"/Users/qiaoruixiang/development/workspace/python/transitfeed/feedvalidator.py " +
// "-p -d " +
args[0]);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String s = null;
System.out.println("Feed Validator:");
while ((s = stdInput.readLine()) != null) {
System.out.println("\t" + s);
}
System.out.println("Error msg:");
while ((s = stdError.readLine()) != null) {
System.out.println("\t" + s);
}
*/
ProgressIndicator.getInstance().init();
ProgressIndicator.getInstance().setText("creating GTFS objects");
gtfs.readGtfsFile(new File(args[0]));
ProgressIndicator.getInstance().setText("rebuilding GTFS");
//Assume the gtfs is clean and correct
gtfs.rebuild();
//gtfs.fillTransfer();
ProgressIndicator.getInstance().setText("reading POIs");
EventAPI eventAPI = new EventAPIImpl();
List<EventResponse> events = eventAPI.getAllEventByLastDate(Const.FESTIVAL_TOKEN, 0, null);
System.out.println("Retrieved pois: " + events.size());
PoiData poiData = new PoiData();
poiData.readFromData(events);
//poiData.readDataFromWeb("http://xplanner-cigo.herokuapp.com/api/pois");
ProgressIndicator.getInstance().setText("initializing sparksee");
SparkseeWriter sparkseeWriter = new SparkseeWriter();
sparkseeWriter.init();
ProgressIndicator.getInstance().setText("creating sparksee schema");
sparkseeWriter.createSchema(Const.SPARKSEE_DB_FILE, Const.SPARKSEE_DB);
ProgressIndicator.getInstance().setText("Sparksee: building POIs data");
sparkseeWriter.buildData(poiData.getPois(), poiData.getPlaces());
ProgressIndicator.getInstance().setText("Sparksee: building GTFS data");
sparkseeWriter.writeGTFS(gtfs);
ProgressIndicator.getInstance().setText("Sparksee: building auxiliary point");
sparkseeWriter.setUpAuxiliaryPoints();
ProgressIndicator.getInstance().setText("Sparksee: precalculating routes");
sparkseeWriter.precalculateRoutes();
sparkseeWriter.close();
sparkseeWriter.testData();
//for (StopTime stopTime : store.getAllStopTimes()) {
// System.out.println(stopTime);
//}
/*
for (Transfer transfer : store.getAllTransfers()) {
System.out.println("from " + transfer.getFromStop().getId() + " to " + transfer.getToStop().getId() +
" using " + transfer.getMinTransferTime());
}
*/
/*
// Access entities through the store
Map<AgencyAndId, Route> routesById = store.getEntitiesByIdForEntityType(
AgencyAndId.class, Route.class);
System.out.println("agencyID:" + Arrays.asList(routesById.keySet()));
for (Route route : routesById.values()) {
System.out.println("route: " + route.getShortName());
}
gtfs.removeUnusedStops();
File outputDir = new File("output");
if (!outputDir.exists()) outputDir.mkdirs();
GtfsWriter writer = new GtfsWriter();
writer.setOutputLocation(outputDir);
DefaultEntitySchemaFactory schemaFactory = new DefaultEntitySchemaFactory();
schemaFactory.addFactory(GtfsEntitySchemaFactory.createEntitySchemaFactory());
writer.setEntitySchemaFactory(schemaFactory);
try {
writer.run(gtfs.getStore());
} catch (Exception e) {
e.printStackTrace();
}
*/
ProgressIndicator.getInstance().close();
} catch (IOException e) {
e.printStackTrace();
}
System.exit(0);
}
}
|
package com.jgw.supercodeplatform.project.hainanrunda.dto.batchinfo;
import io.swagger.annotations.ApiModelProperty;
public class PlantingBatchDto {
@ApiModelProperty(value = "种植批次")
private String traceBatchName;
private String traceBatchInfoId;//唯一id
@ApiModelProperty(value = "种植产品")
private String productName;//产品名称
@ApiModelProperty(value = "开始时间")
private String startDate;
@ApiModelProperty(value = "种植大棚")
private String massIfName;
@ApiModelProperty(value = "种植面积")
private String massArea;
@ApiModelProperty(value = "结束时间")
private String endDate;
@ApiModelProperty(value = "共计(天)")
private Integer totalDays;
public String getMassId() {
return massId;
}
public void setMassId(String massId) {
this.massId = massId;
}
@ApiModelProperty(value = "地块id")
private String massId;
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
@ApiModelProperty(value = "产品id")
private String productId;
public PlantingBatchDto(String traceBatchName, String traceBatchInfoId, String productName){
this.traceBatchName=traceBatchName;
this.traceBatchInfoId=traceBatchInfoId;
this.productName=productName;
}
public PlantingBatchDto(String traceBatchName, String traceBatchInfoId, String productName,String pickingBatchId){
this(traceBatchName,traceBatchInfoId,productName);
this.pickingBatchId=pickingBatchId;
}
public String getPickingBatchId() {
return pickingBatchId;
}
public void setPickingBatchId(String pickingBatchId) {
this.pickingBatchId = pickingBatchId;
}
private String pickingBatchId;
public PlantingBatchDto(){ }
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getMassIfName() {
return massIfName;
}
public void setMassIfName(String massIfName) {
this.massIfName = massIfName;
}
public String getMassArea() {
return massArea;
}
public void setMassArea(String massArea) {
this.massArea = massArea;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public Integer getTotalDays() {
return totalDays;
}
public void setTotalDays(Integer totalDays) {
this.totalDays = totalDays;
}
public String getTraceBatchName() {
return traceBatchName;
}
public void setTraceBatchName(String traceBatchName) {
this.traceBatchName = traceBatchName;
}
public String getTraceBatchInfoId() {
return traceBatchInfoId;
}
public void setTraceBatchInfoId(String traceBatchInfoId) {
this.traceBatchInfoId = traceBatchInfoId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
}
|
package com.sunny.model;
/**
* Created by Sunny on 8/2/2019.
*/
import lombok.Data;
import javax.persistence.*;
import java.sql.Date;
@Data//a Lombok annotation to create all the getters, setters, equals, hash, and toString methods, based on the fields
@Entity
@Table(name = "BOOKING")
public class Booking {//the relationship table => no merging because the cardinality is m:n
//specifies how the manyToMany association is formed between the two entities
//has a many to one to each entitty
//and the entities have a one to many to the relation
@Id
@GeneratedValue
@Column(name = "booking_id")
private Long booking_id;//using a separate key instead of composite key (embeddable composite key class)
//private Integer customer_id;//via object see below @manyToOne
//private Integer car_id;//via object see below @manyToOne
private Date start_date;
private Date end_date;
private Date return_date;
private Integer total_price;
public Long getBooking_id() {
return booking_id;
}
public void setBooking_id(Long booking_id) {
this.booking_id = booking_id;
}
public Date getStart_date() {
return start_date;
}
public void setStart_date(Date start_date) {
this.start_date = start_date;
}
public Date getEnd_date() {
return end_date;
}
public void setEnd_date(Date end_date) {
this.end_date = end_date;
}
public Date getReturn_date() {
return return_date;
}
public void setReturn_date(Date return_date) {
this.return_date = return_date;
}
public Integer getTotal_price() {
return total_price;
}
public void setTotal_price(Integer total_price) {
this.total_price = total_price;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
@ManyToOne (cascade = CascadeType.ALL)
@JoinColumn(name="customer_id")
private Customer customer;
@ManyToOne (cascade = CascadeType.ALL)
@JoinColumn(name="car_id")
private Car car;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
Booking booking = (Booking) o;
if (!booking_id.equals(booking.booking_id)) return false;
if (start_date != null ? !start_date.equals(booking.start_date) : booking.start_date != null) return false;
if (end_date != null ? !end_date.equals(booking.end_date) : booking.end_date != null) return false;
if (return_date != null ? !return_date.equals(booking.return_date) : booking.return_date != null) return false;
if (total_price != null ? !total_price.equals(booking.total_price) : booking.total_price != null) return false;
if (customer != null ? !customer.equals(booking.customer) : booking.customer != null) return false;
return car != null ? car.equals(booking.car) : booking.car == null;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + booking_id.hashCode();
result = 31 * result + (start_date != null ? start_date.hashCode() : 0);
result = 31 * result + (end_date != null ? end_date.hashCode() : 0);
result = 31 * result + (return_date != null ? return_date.hashCode() : 0);
result = 31 * result + (total_price != null ? total_price.hashCode() : 0);
result = 31 * result + (customer != null ? customer.hashCode() : 0);
result = 31 * result + (car != null ? car.hashCode() : 0);
return result;
}
//getters and setters via Lombok
}
|
/*
* Copyright 2002-2023 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.web.server.handler;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import reactor.core.publisher.Mono;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebExceptionHandler;
import org.springframework.web.server.WebHandler;
/**
* WebHandler decorator that invokes one or more {@link WebExceptionHandler WebExceptionHandlers}
* after the delegate {@link WebHandler}.
*
* @author Rossen Stoyanchev
* @since 5.0
*/
public class ExceptionHandlingWebHandler extends WebHandlerDecorator {
/**
* Name of the {@link ServerWebExchange#getAttributes() attribute} that
* contains the exception handled by {@link WebExceptionHandler WebExceptionHandlers}.
* @since 6.1
*/
public static final String HANDLED_WEB_EXCEPTION = ExceptionHandlingWebHandler.class.getSimpleName() + ".handledException";
private final List<WebExceptionHandler> exceptionHandlers;
/**
* Create an {@code ExceptionHandlingWebHandler} for the given delegate.
* @param delegate the WebHandler delegate
* @param handlers the WebExceptionHandlers to apply
*/
public ExceptionHandlingWebHandler(WebHandler delegate, List<WebExceptionHandler> handlers) {
super(delegate);
List<WebExceptionHandler> handlersToUse = new ArrayList<>();
handlersToUse.add(new CheckpointInsertingHandler());
handlersToUse.addAll(handlers);
this.exceptionHandlers = Collections.unmodifiableList(handlersToUse);
}
/**
* Return a read-only list of the configured exception handlers.
*/
public List<WebExceptionHandler> getExceptionHandlers() {
return this.exceptionHandlers;
}
@Override
public Mono<Void> handle(ServerWebExchange exchange) {
Mono<Void> completion;
try {
completion = super.handle(exchange);
}
catch (Throwable ex) {
completion = Mono.error(ex);
}
for (WebExceptionHandler handler : this.exceptionHandlers) {
completion = completion.doOnError(error -> exchange.getAttributes().put(HANDLED_WEB_EXCEPTION, error))
.onErrorResume(ex -> handler.handle(exchange, ex));
}
return completion;
}
/**
* WebExceptionHandler to insert a checkpoint with current URL information.
* Must be the first in order to ensure we catch the error signal before
* the exception is handled and e.g. turned into an error response.
* @since 5.2
*/
private static class CheckpointInsertingHandler implements WebExceptionHandler {
@Override
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
ServerHttpRequest request = exchange.getRequest();
String rawQuery = request.getURI().getRawQuery();
String query = StringUtils.hasText(rawQuery) ? "?" + rawQuery : "";
HttpMethod httpMethod = request.getMethod();
String description = "HTTP " + httpMethod + " \"" + request.getPath() + query + "\"";
return Mono.<Void>error(ex).checkpoint(description + " [ExceptionHandlingWebHandler]");
}
}
}
|
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.PriorityQueue;
public class FriendSuggestion {
private static class Impl {
// Number of nodes
int n;
// adj[0] and cost[0] store the initial graph, adj[1] and cost[1] store the reversed graph.
// Each graph is stored as array of adjacency lists for each node. adj stores the edges,
// and cost stores their costs.
ArrayList<Integer>[][] adj;
ArrayList<Integer>[][] cost;
// distance[0] and distance[1] correspond to distance estimates in the forward and backward searches.
Long[][] distance;
// Two priority queues, one for forward and one for backward search.
ArrayList<PriorityQueue<Entry>> queue;
// visited[v] == true iff v was visited either by forward or backward search.
boolean[] visited;
// List of all the nodes which were visited either by forward or backward search.
ArrayList<Integer> workset;
final Long INFINITY = Long.MAX_VALUE / 4;
Impl(int n) {
this.n = n;
visited = new boolean[n];
Arrays.fill(visited, false);
workset = new ArrayList<Integer>();
distance = new Long[][] {new Long[n], new Long[n]};
for (int i = 0; i < n; ++i) {
distance[0][i] = distance[1][i] = INFINITY;
}
queue = new ArrayList<PriorityQueue<Entry>>();
queue.add(new PriorityQueue<Entry>(n));
queue.add(new PriorityQueue<Entry>(n));
}
// Reinitialize the data structures before new query after the previous query
void clear() {
for (int v : workset) {
distance[0][v] = distance[1][v] = INFINITY;
visited[v] = false;
}
workset.clear();
queue.get(0).clear();
queue.get(1).clear();
}
// Try to relax the distance from direction side to node v using value dist.
void visit(int side, int v, Long dist) {
// Implement this method yourself
}
// Returns the distance from s to t in the graph.
Long query(int s, int t) {
clear();
visit(0, s, 0L);
visit(1, t, 0L);
// Implement the rest of the algorithm yourself
return -1L;
}
class Entry implements Comparable<Entry>
{
Long cost;
int node;
public Entry(Long cost, int node)
{
this.cost = cost;
this.node = node;
}
public int compareTo(Entry other)
{
return cost < other.cost ? -1 : cost > other.cost ? 1 : 0;
}
}
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
Impl bidij = new Impl(n);
bidij.adj = (ArrayList<Integer>[][])new ArrayList[2][];
bidij.cost = (ArrayList<Integer>[][])new ArrayList[2][];
for (int side = 0; side < 2; ++side) {
bidij.adj[side] = (ArrayList<Integer>[])new ArrayList[n];
bidij.cost[side] = (ArrayList<Integer>[])new ArrayList[n];
for (int i = 0; i < n; i++) {
bidij.adj[side][i] = new ArrayList<Integer>();
bidij.cost[side][i] = new ArrayList<Integer>();
}
}
for (int i = 0; i < m; i++) {
int x, y, c;
x = in.nextInt();
y = in.nextInt();
c = in.nextInt();
bidij.adj[0][x - 1].add(y - 1);
bidij.cost[0][x - 1].add(c);
bidij.adj[1][y - 1].add(x - 1);
bidij.cost[1][y - 1].add(c);
}
int t = in.nextInt();
for (int i = 0; i < t; i++) {
int u, v;
u = in.nextInt();
v = in.nextInt();
System.out.println(bidij.query(u-1, v-1));
}
}
}
|
package com.cosplay.demo.mvp.presenter;
import android.os.Handler;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.cosplay.demo.mvp.bean.FHnews;
import com.cosplay.demo.mvp.view.IView.IFHnewsView;
import com.google.gson.Gson;
import static com.cosplay.demo.mvp.app.DdemoApplication.getApp;
/**
* Created by zhiwei.wang on 2017/3/23.
*/
public class FHnewsProsenter {
private IFHnewsView ifHnewsView;
public String FHNEWS_URL = "http://api.irecommend.ifeng.com/irecommendList.php?userId=359908051392059&count=15&gv=5.5.3" +
"&av=5.5.3&uid=359908051392059&deviceid=359908051392059&proid=ifengnews&os=android_22&df=" +
"androidphone&vt=5&screen=1600x2560&publishid=2024&nw=wifi&city=%E5%8C%97%E4%BA%AC%E5%B8%82&province=%E5%8C%97%E4%BA%AC%E5%B8%82&lastDoc=,,,";
public FHnewsProsenter(IFHnewsView ifHnewsView) {
this.ifHnewsView = ifHnewsView;
}
public void lodingFHnews(){
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
StringRequest stringRequest = new StringRequest(FHNEWS_URL, new Response.Listener<String>() {
@Override
public void onResponse(String s) {
Gson gson = new Gson();
FHnews fHnews = gson.fromJson(s, FHnews.class);
ifHnewsView.Success(fHnews);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
ifHnewsView.Failed(1);
}
});
getApp().getRequestQueue().add(stringRequest);
}
},0);
}
}
|
package yinq.situation.fragments;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.yinq.cherrydialyrecord.R;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import yinq.Request.HttpRequestObservice;
import yinq.situation.ListAdapter.SleepSituationListAdapter;
import yinq.situation.dataModel.SleepSituationModel;
import yinq.situation.util.SleepSituationUtil;
/**
* A simple {@link Fragment} subclass.
*/
public class SituationSleepFragment extends Fragment {
ListView listView;
ArrayList<SleepSituationModel> sleepSituationModels;
public SituationSleepFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_situation_sleep, container, false);
initListView(view);
return view;
}
@Override
public void onStart() {
super.onStart();
startLoadTodaySituations();
}
protected void initListView(View view){
listView = view.findViewById(R.id.sleep_situation_listview);
listView.setAdapter(new SleepSituationListAdapter(getContext()));
}
protected void startLoadTodaySituations(){
SleepSituationUtil util = new SleepSituationUtil();
HttpRequestObservice observice = new HttpRequestObservice() {
@Override
public void onRequestSuccess(Object result) {
List<SleepSituationModel> models = (List<SleepSituationModel>) result;
sleepSituationModels = new ArrayList<SleepSituationModel>(models);
Gson gson = new Gson();
String modelsJson = gson.toJson(sleepSituationModels);
System.out.println("today sleep situaitons ");
System.out.println(modelsJson);
}
@Override
public void onRequestFail(int errCode, String errMsg) {
Toast.makeText(getContext(), errMsg, Toast.LENGTH_SHORT).show();
}
@Override
public void onRequestComplete(int errCode) throws InvocationTargetException, NoSuchMethodException, java.lang.InstantiationException, IllegalAccessException {
if (errCode == 0){
SleepSituationListAdapter adapter = (SleepSituationListAdapter) listView.getAdapter();
adapter.setModels(sleepSituationModels);
}
}
};
util.startLoadTodaySleepSituations(observice);
}
}
|
package liu.java.util.stream.classes;
public class Test {
}
|
package com.aof.core.persistence.hibernate;
public class LookupException extends Exception {
public LookupException(String message, Throwable cause) {
super(message, cause);
}
public LookupException(String message) {
super(message);
}
}
|
package com.dhc.openglbasic;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;
import java.util.ArrayList;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.opengl.GLSurfaceView;
import android.opengl.GLUtils;
import android.opengl.Matrix;
import android.opengl.GLES20;
import android.os.SystemClock;
import android.util.Log;
public class MyGL20Renderer implements GLSurfaceView.Renderer{
private Triangle myTriangle;
private static final String TAG = "MyGL20Renderer";
private Square leftFG, leftBG ;
private Triangle leftForward, leftBackard;
private Triangle leftBalanceBG, leftBalanceFG;
private Square rightFG, rightBG;
private Triangle rightForward, rightBackard;
private Triangle rightBalanceBG, rightBalanceFG;
private final float[] mMVPMatrix = new float[16];
private final float[] mProjMatrix = new float[16];
private final float[] mVMatrix = new float[16];
private final float[] mRotationMatrix = new float[16];
public static float leftSquare[] = {
1.25f, 0.7f, 0.0f, //top left
1.25f, -0.7f, 0.0f, //bottom left
0.75f,-0.7f, 0.0f, //bottom right
0.75f, 0.7f, 0.0f }; //top right
static float leftForwardTriangleCoords[] = { //in counterclockwise order:
1.26f, 0.61f, 0.0f, //top
1.40f, 0.01f, 0.0f, //bottom left
1.26f, 0.01f, 0.0f //bottom right
};
static float leftBackwardTriangleCoords[] = { //in counterclockwise order:
1.26f, -0.61f, 0.0f, //top
1.40f, -0.01f, 0.0f, //bottom left
1.26f, -0.01f, 0.0f //bottom right
};
static float leftBalanceTriangleCoords[] = { //in counterclockwise order:
0.74f, 0.50f, 0.0f, //top
0.74f, -0.50f, 0.0f, //bottom left
0.0f, 0.0f, 0.0f //bottom right
};
public static float rightSquare[] = {
-1.25f, 0.7f, 0.0f, //top left
-1.25f, -0.7f, 0.0f, //bottom left
-0.75f,-0.7f, 0.0f, //bottom right
-0.75f, 0.7f, 0.0f //top right
};
static float rightForwardTriangleCoords[] = { //in counterclockwise order:
-1.26f, 0.61f, 0.0f, //top
-1.40f, 0.01f, 0.0f, //bottom left
-1.26f, 0.01f, 0.0f //bottom right
};
static float rightBackwardTriangleCoords[] = { //in counterclockwise order:
-1.26f, -0.61f, 0.0f, //top
-1.40f, -0.01f, 0.0f, //bottom left
-1.26f, -0.01f, 0.0f //bottom right
};
static float rightBalanceTriangleCoords[] = { //in counterclockwise order:
-0.74f, 0.50f, 0.0f, //top
-0.74f, -0.50f, 0.0f, //bottom left
0.0f, 0.0f, 0.0f //bottom right
};
public static float upperRightButtonTouch[] = {.85f, 0f, 1.0f, 0.27f};
public static float upperRightButton[] = {
-2.10f, 0.98f, 0.0f, //top left
-2.10f, 0.38f, 0.0f, //bottom left
-1.50f, 0.38f, 0.0f, //bottom right
-1.50f, 0.98f, 0.0f //top right
};
public static float midRightButtonTouch[] = {.85f, .33f, 1.0f, 0.6f};
public static float midRightButton[] = {
-2.10f, 0.3f, 0.0f, //top left
-2.10f, -0.3f, 0.0f, //bottom left
-1.50f, -0.3f, 0.0f, //bottom right
-1.50f, 0.3f, 0.0f //top right
};
public static float lowRightButtonTouch[] = {.85f, .33f, 1.0f, 0.6f};
public static float lowRightButton[] = {
-2.10f, -0.98f, 0.0f, //top left
-2.10f, -0.38f, 0.0f, //bottom left
-1.50f, -0.38f, 0.0f, //bottom right
-1.50f, -0.98f, 0.0f //top right
};
public static float upperLeftButtonTouch[] = {.0f, 0f, 0.15f, 0.27f};
public static float upperLeftButton[] = {
2.10f, 0.98f, 0.0f, //top left
2.10f, 0.38f, 0.0f, //bottom left
1.50f, 0.38f, 0.0f, //bottom right
1.50f, 0.98f, 0.0f //top right
};
public static float midLeftButtonTouch[] = {.0f, .33f, 0.15f, 0.6f};
public static float midLeftButton[] = {
2.10f, 0.3f, 0.0f, //top left
2.10f, -0.3f, 0.0f, //bottom left
1.50f, -0.3f, 0.0f, //bottom right
1.50f, 0.3f, 0.0f //top right
};
public static float lowLeftButtonTouch[] = {.0f, .33f, 0.15f, 0.6f};
public static float lowLeftButton[] = {
2.10f, -0.98f, 0.0f, //top left
2.10f, -0.38f, 0.0f, //bottom left
1.50f, -0.38f, 0.0f, //bottom right
1.50f, -0.98f, 0.0f //top right
};
public static float infoTemplate[] = {
-0.25f, -0.25f, 0.0f, //top left
-0.25f, 0.25f, 0.0f, //bottom left
0.25f, 0.25f, 0.0f, //bottom right
0.25f, -0.25f, 0.0f //top right
};
// float bgSquareColor [] = { 0.2f, 0.709803922f, 0.898039216f, 1.0f };
public static float bgSquareColor [] = { 0.2f, 0.2f, 0.2f, 1.0f };
public static float fgSquareColor [] = { 0.6f, 0f, 0f, 1.0f };
public static float blueColor [] = { 0.2f, 0.2f, 1.0f, 1.0f };
public static float lightBlueColor [] = { 0.5f, 0.6f, .8f, 1.0f };
public static float whiteColor [] = { 1f, 1f, 1f, 1.0f };
public static float greyColor [] = { 0.7f, 0.7f, 0.7f, 1.0f };
//Declare as volatile because we are updated it from another thread
public volatile float mAngle;
public volatile float leftPower = 0.0f;
public volatile float rightPower = 0.0f;
public volatile float leftPowerBalance = 0.0f;
public volatile float rightPowerBalance = 0.0f;
private volatile ArrayList<Button> buttons = new ArrayList<Button>();
public static final int BUTTON_POWER = 0;
public static final int BUTTON_STOP = 1;
public static final int BUTTON_SPEAK = 2;
public static final int BUTTON_CONNECT = 3;
public static final int BUTTON_PLACEHOLDER1 = 4;
public static final int BUTTON_PLACEHOLDER2 = 5;
public static final float BUTTON_WIDTH = 0.6f;
private volatile ArrayList<Info> infos = new ArrayList<Info>();
public static final int INFO_CONNECTED = 0;
public static final int INFO_ENABLED = 1;
public static final int INFO_PLACEHOLDER1 = 2;
public static final int INFO_PLACEHOLDER2 = 3;
public static final int INFO_INVERT = 4;
public static final int INFO_REBALANCE = 5;
public static final float INFO_WIDTH = .5f;
public void onSurfaceCreated(GL10 unused, EGLConfig config){
//set the frame bg color
GLES20.glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
//set up the buttons
buttons.add(new Button(-2.10f, 0.98f, BUTTON_WIDTH, R.drawable.button_transparent, "Power", BUTTON_POWER));
buttons.add(new Button(-2.10f, 0.3f, BUTTON_WIDTH, R.drawable.button_transparent, "Stop", BUTTON_STOP));
buttons.add(new Button(-2.10f, -0.98f, BUTTON_WIDTH, R.drawable.button_transparent, "P1", BUTTON_PLACEHOLDER1));
buttons.add(new Button(2.10f, 0.98f, BUTTON_WIDTH, R.drawable.button_transparent, "Speak", BUTTON_SPEAK));
buttons.add(new Button(2.10f, 0.3f, BUTTON_WIDTH, R.drawable.button_transparent, "Connect", BUTTON_CONNECT));
buttons.add(new Button(2.10f, -0.98f, BUTTON_WIDTH, R.drawable.button_transparent, "P2", BUTTON_PLACEHOLDER2));
//set up the info displays
// (squareCoords[0], squareCoords[1], squareCoords[1] - squareCoords[4]);
infos.add(new Info(-0.25f, -0.25f, INFO_WIDTH, R.drawable.info, "Connected", INFO_CONNECTED));
infos.add(new Info(-0.25f, -0.25f, INFO_WIDTH, R.drawable.info, "Enabled", INFO_ENABLED));
infos.add(new Info(-0.25f, -0.25f, INFO_WIDTH, R.drawable.info, "1", INFO_PLACEHOLDER1));
infos.add(new Info(-0.25f, -0.25f, INFO_WIDTH, R.drawable.info, "2", INFO_PLACEHOLDER2));
infos.add(new Info(-0.25f, -0.25f, INFO_WIDTH, R.drawable.info, "3", INFO_INVERT));
infos.add(new Info(-0.25f, -0.25f, INFO_WIDTH, R.drawable.info, "4", INFO_REBALANCE));
myTriangle = new Triangle(null);
//mySquare = new Square();
leftFG = new Square(leftSquare);
leftBG = new Square(leftSquare);
leftForward = new Triangle(leftForwardTriangleCoords);
leftBackard= new Triangle(leftBackwardTriangleCoords);
leftBalanceFG = new Triangle(leftBalanceTriangleCoords);
leftBalanceBG = new Triangle(leftBalanceTriangleCoords);
rightFG = new Square(rightSquare);
rightBG = new Square(rightSquare);
rightForward = new Triangle(rightForwardTriangleCoords);
rightBackard= new Triangle(rightBackwardTriangleCoords);
rightBalanceFG = new Triangle(rightBalanceTriangleCoords);
rightBalanceBG = new Triangle(rightBalanceTriangleCoords);
}
public void onDrawFrame(GL10 unused){
//redraw bg color
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
//set up camera position (View matrix)
Matrix.setLookAtM(mVMatrix, 0, 0, 0, -3, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
//calc the projection and view transformation
Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mVMatrix, 0);
float[] leftBarMatrix = new float[16];
System.arraycopy( mMVPMatrix, 0, leftBarMatrix, 0, mMVPMatrix.length );
float[] leftBalanceMatrix = new float[16];
System.arraycopy( mMVPMatrix, 0, leftBalanceMatrix, 0, mMVPMatrix.length );
float[] rightBarMatrix = new float[16];
System.arraycopy( mMVPMatrix, 0, rightBarMatrix, 0, mMVPMatrix.length );
float[] rightBalanceMatrix = new float[16];
System.arraycopy( mMVPMatrix, 0, rightBalanceMatrix, 0, mMVPMatrix.length );
float[] pointerMatrix = new float[16];
System.arraycopy( mMVPMatrix, 0, pointerMatrix, 0, mMVPMatrix.length );
float[] infoMatrix = new float[16];
System.arraycopy( mMVPMatrix, 0, infoMatrix, 0, mMVPMatrix.length );
for( Button b : getButtons())
b.draw(mMVPMatrix);
int max = getInfos().size();
for( Info i : getInfos())
i.draw(infoMatrix.clone(), i.getId(), max);
leftBG.draw(mMVPMatrix, bgSquareColor);
leftForward.draw(mMVPMatrix, leftPower>0?fgSquareColor:bgSquareColor);
leftBackard.draw(mMVPMatrix, leftPower<0?blueColor:bgSquareColor);
leftBalanceBG.draw(mMVPMatrix, bgSquareColor);
rightBG.draw(mMVPMatrix, bgSquareColor);
rightForward.draw(mMVPMatrix, rightPower>0?fgSquareColor:bgSquareColor);
rightBackard.draw(mMVPMatrix, rightPower<0?blueColor:bgSquareColor);
rightBalanceBG.draw(mMVPMatrix, bgSquareColor);
Matrix.scaleM(leftBarMatrix, 0, 1.0f, leftPower, 1.0f); //width, height, ?
leftFG.draw(leftBarMatrix, leftPower>=0?fgSquareColor:blueColor);
Matrix.scaleM(rightBarMatrix, 0, 1.0f, rightPower, 1.0f); //width, height, ?
rightFG.draw(rightBarMatrix, rightPower>=0?fgSquareColor:blueColor);
// float leftScale = leftPowerBalance>0?leftPowerBalance:0.0f;
Matrix.scaleM(leftBalanceMatrix, 0, Math.abs(leftPowerBalance), Math.abs(leftPowerBalance), 1.0f); //width, height, ?
leftBalanceFG.draw(leftBalanceMatrix, leftPowerBalance>=0?fgSquareColor:blueColor);
Matrix.scaleM(rightBalanceMatrix, 0, Math.abs(rightPowerBalance), Math.abs(rightPowerBalance), 1.0f); //width, height, ?
rightBalanceFG.draw(rightBalanceMatrix, rightPowerBalance>=0?fgSquareColor:blueColor);
//create a rotation transformation for the triangle
//long time = SystemClock.uptimeMillis() % 4000L;
//float angle = 0.090f * ((int) time);
Matrix.setRotateM(mRotationMatrix, 0, mAngle, 0, 0, -1.0f);
//combine the rotation matrix with the projection and camera view
Matrix.multiplyMM(pointerMatrix, 0, mRotationMatrix, 0, pointerMatrix, 0);
myTriangle.draw(pointerMatrix, null);
}
public ArrayList<Button> getButtons(){
return buttons;
}
public Button getButton(int index){
for( Button b : getButtons())
if(b.getId() == index)
return b;
return null;
}
public ArrayList<Info> getInfos(){
return infos;
}
public Info getInfo(int index){
for( Info i : getInfos())
if(i.getId() == index)
return i;
return null;
}
public void onSurfaceChanged(GL10 unused, int width, int height){
GLES20.glViewport(0, 0, width, height);
float ratio = (float) width / height;
//this porjection amtrix is applied to object coords
// in the onDrawFrame() method
Matrix.frustumM(mProjMatrix, 0, -ratio, ratio, -1, 1, 3, 7);
}
public static int loadShader(int type, String shaderCode){
//create a vertex shader type
//or a fragment shader type
int shader = GLES20.glCreateShader(type);
//add the code to the shader and compile
GLES20.glShaderSource(shader, shaderCode);
GLES20.glCompileShader(shader);
return shader;
}
}
class Triangle{
public final static String vertexShaderCode =
"uniform mat4 uMVPMatrix;" +
"attribute vec4 vPosition;" +
"void main() {" +
"gl_Position = vPosition * uMVPMatrix;" +
"}";
public final static String fragmentShaderCode =
"precision mediump float;" +
"uniform vec4 vColor;" +
"void main() {" +
"gl_FragColor = vColor;" +
"}";
private FloatBuffer vertexBuffer;
//number of coordinates per vertex in this array
static final int COORDS_PER_VERTEX = 3;
//By default, OpenGL ES assumes a coordinate system where [0,0,0] (X,Y,Z)
//specifies the center of the GLSurfaceView frame, [1,1,0] is the top right
//corner of the frame and [-1,-1,0] is bottom left corner of the frame.
static float triangleCoords[] = { //in counterclockwise order:
0.0f, 0.25f, 0.0f, //top
-0.15f, -0.15f, 0.0f, //bottom left
0.15f, -0.15f, 0.0f //bottom right
};
private final int vertexCount = triangleCoords.length / COORDS_PER_VERTEX;
private final int vertexStride = COORDS_PER_VERTEX * 4; //4 bytes per vertex
//set the color with r,g,b,a values
float defaultColor[] = { 0.63671875f, 0.76953125f, 0.22265625f, 0.6f };
private final int mProgram;
private int mPositionHandle;
private int mColorHandle;
private int mMVPMatrixHandle;
public Triangle(float[] coords){
if(coords==null)
coords = triangleCoords;
//initialize vertex by buffer for shape coordinates
ByteBuffer bb = ByteBuffer.allocateDirect(
// (number of coordinate values * 4 bytes per float)
triangleCoords.length * 4);
//use the device hardware's native byte order
bb.order(ByteOrder.nativeOrder());
//create a floating point buffer from the ByteBuffer
vertexBuffer = bb.asFloatBuffer();
//add the coords
vertexBuffer.put(coords);
//set the buffer to read the first coord
vertexBuffer.position(0);
int vertexShader = MyGL20Renderer.loadShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode);
int fragmentShader = MyGL20Renderer.loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode);
mProgram = GLES20.glCreateProgram(); //create an empty OpenGL ES Program
GLES20.glAttachShader(mProgram, vertexShader); //add the vertex shader
GLES20.glAttachShader(mProgram, fragmentShader); //add the fragment shader
GLES20.glLinkProgram(mProgram); //create OpenGL ES program execs
}
public void draw(float[] mvpMatrix, float color[]){ //pass in the calc'd transofrmation matrix
if(color==null)
color = defaultColor;
//add program to OpenGL ES env
GLES20.glUseProgram(mProgram);
//get handle to vertex shader's vPosition member
mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition");
//enable a hangle to the triangle vertices
GLES20.glEnableVertexAttribArray(mPositionHandle);
//prep the triangle coord data
GLES20.glVertexAttribPointer(mPositionHandle, COORDS_PER_VERTEX, GLES20.GL_FLOAT, false, vertexStride, vertexBuffer);
//get handle to grament's shader vColor member
mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor");
//set color for drawing
GLES20.glUniform4fv(mColorHandle, 1, color, 0);
//get handle to shape's transofrmation matrix
mMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
//Apply the projection and view transormation
GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mvpMatrix, 0);
//Draw it!
GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vertexCount);
//disable the vertex array
GLES20.glDisableVertexAttribArray(mPositionHandle);
}
}
class Square {
private FloatBuffer vertexBuffer;
private ShortBuffer drawListBuffer;
private final int mProgram;
private int mPositionHandle;
private int mColorHandle;
private int mMVPMatrixHandle;
//numer of coords per vertex
static final int COORDS_PER_VERTEX = 3;
public static float defaultCoords[] = { -0.5f, 0.5f, 0.0f, //top left
-0.5f, -0.5f, 0.0f, //bottom left
0.5f, -0.5f, 0.0f, //bottom right
0.5f, 0.5f, 0.0f }; //top right
private short drawOrder[] = { 0, 1, 2, 0, 2, 3 }; //order to draw vertices
//private final int vertexCount = squareCoords.length / COORDS_PER_VERTEX;
private final int vertexStride = COORDS_PER_VERTEX * 4; //4 bytes per vertex
//set the color with r,g,b,a values
float defaultColor[] = { 0.2f, 0.709803922f, 0.898039216f, 1.0f };
public Square(float[] squareCoords){
//init vertex bb for shape coords
ByteBuffer bb = ByteBuffer.allocateDirect( squareCoords.length * 4 ); //4 byte per float
bb.order(ByteOrder.nativeOrder());
vertexBuffer = bb.asFloatBuffer();
vertexBuffer.put(squareCoords);
vertexBuffer.position(0);
//iit bb for draw list
ByteBuffer dlb = ByteBuffer.allocateDirect(
//(# of coord values * 2 bytes per short)
drawOrder.length *2 );
dlb.order(ByteOrder.nativeOrder());
drawListBuffer = dlb.asShortBuffer();
drawListBuffer.put(drawOrder);
drawListBuffer.position(0);
int vertexShader = MyGL20Renderer.loadShader(GLES20.GL_VERTEX_SHADER, Triangle.vertexShaderCode);
int fragmentShader = MyGL20Renderer.loadShader(GLES20.GL_FRAGMENT_SHADER, Triangle.fragmentShaderCode);
mProgram = GLES20.glCreateProgram(); //create an empty OpenGL ES Program
GLES20.glAttachShader(mProgram, vertexShader); //add the vertex shader
GLES20.glAttachShader(mProgram, fragmentShader); //add the fragment shader
GLES20.glLinkProgram(mProgram); //create OpenGL ES program execs
}
public void draw(float[] mvpMatrix, float color[]){ //pass in the calc'd transofrmation matrix
//add program to OpenGL ES env
GLES20.glUseProgram(mProgram);
//get handle to vertex shader's vPosition member
mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition");
//enable a hangle to the triangle vertices
GLES20.glEnableVertexAttribArray(mPositionHandle);
//prep the trianle coord data
GLES20.glVertexAttribPointer(mPositionHandle, COORDS_PER_VERTEX,
GLES20.GL_FLOAT, false, vertexStride, vertexBuffer);
//get handle to grament's shader vColor member
mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor");
//set color for drawing
GLES20.glUniform4fv(mColorHandle, 1, color, 0);
//get handle to shape's transformation matrix
mMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
//Apply the projection and view transformation
GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mvpMatrix, 0);
//Draw it!
//GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vertexCount);
GLES20.glDrawElements(GLES20.GL_TRIANGLES, drawOrder.length, GLES20.GL_UNSIGNED_SHORT, drawListBuffer);
//disable the vertex array
GLES20.glDisableVertexAttribArray(mPositionHandle);
}
}
class Info extends Button{
private final float[] mTranslationMatrix = new float[16];
private static final String TAG = "Info";
public Info(float upperLeftX, float upperLeftY, float width, int background, String messageText, int id){
super(upperLeftX, upperLeftY, width, background, messageText, id);
setColor(MyGL20Renderer.greyColor);
}
public static final int NUMBER_OF_ROWS = 2;
public static final float ROW_OFFSET = 1.45f;
public static final float SPACING_OFFSET = 0.22f;
public void draw(float[] mvpMatrix, int index, int max){
// Matrix.translateM(mTranslationMatrix, 0, mvpMatrix, 0, 0.0f, 0.0f, 0.0f);
int itemsPerRow = max / NUMBER_OF_ROWS;
int rowNumber = (int) Math.floor( (float)index / itemsPerRow);
int rowIndex = index - (rowNumber * itemsPerRow);
Matrix.setIdentityM(mTranslationMatrix, 0);
Matrix.translateM(mTranslationMatrix, 0,
(-(SPACING_OFFSET) + (rowIndex * SPACING_OFFSET)), // x axis
(-(ROW_OFFSET/NUMBER_OF_ROWS) + (rowNumber * ROW_OFFSET)) // y axis
, 0.0f);
// Log.e(TAG,itemsPerRow + ", " + rowNumber + ", " + rowIndex + ", " + index + ", " + max);
Matrix.multiplyMM(mvpMatrix, 0, mTranslationMatrix, 0, mvpMatrix, 0);
super.draw(mvpMatrix);
}
public void updateMessage(String message){
this.updateMessage(message);
}
}
class Button {
private FloatBuffer vertexBuffer;
private ShortBuffer drawListBuffer;
private final int mProgram;
private int mPositionHandle;
private int mColorHandle;
private int mMVPMatrixHandle;
private static final String TAG = "Button";
protected String messageText;
protected int background;
protected int mTextureDataHandle;
private FloatBuffer textureBuffer;
private float texture[] = {
// Mapping coordinates for the vertices
0.0f, 1.0f, // top left (V2)
0.0f, 0.0f, // bottom left (V1)
1.0f, 0.0f, // bottom right (V3)
1.0f, 1.0f, // top right (V4)
};
//numer of coords per vertex
static final int COORDS_PER_VERTEX = 3;
public static float defaultCoords[] = {
-0.5f, 0.5f, 0.0f, //top left
-0.5f, -0.5f, 0.0f, //bottom left
0.5f, -0.5f, 0.0f, //bottom right
0.5f, 0.5f, 0.0f }; //top right
private short drawOrder[] = { 0, 1, 2, 0, 2, 3 }; //order to draw vertices
//private final int vertexCount = squareCoords.length / COORDS_PER_VERTEX;
private final int vertexStride = COORDS_PER_VERTEX * 4; //4 bytes per vertex
//set the color with r,g,b,a values
private float defaultColor[] = { 0.2f, 0.709803922f, 0.898039216f, 1.0f };
private int buttonId = -1;
public int getId(){
return buttonId;
}
protected void updateMessage(String message){
if(message != null && !message.equals(this.messageText)){
this.messageText = message;
this.updateText = true;
Log.e(TAG, "Updating Message: " + message);
}
}
public static final float MAX_MAP_WIDTH_OBSERVABLE = 4.34f;
// public static final float MAX_MAP_WIDTH = 4.55f;
public static final float MAX_MAP_WIDTH_SLOPE_LEFT = 4.34f;// for left
// public static final float MAX_MAP_WIDTH_SLOPE_RIGHT = 6.05f;// for right
public static final float MAX_MAP_WIDTH_SLOPE_RIGHT = 6.1f;// for right
//this is wonky. The projection along the x-axis is not linear, so this function is required
//to determine the relative max width, based on the current position of the touch.
public static float getMaxMapWidth(float currentPosition){
return (((currentPosition+(MAX_MAP_WIDTH_OBSERVABLE/2))/MAX_MAP_WIDTH_OBSERVABLE) * (MAX_MAP_WIDTH_SLOPE_RIGHT-MAX_MAP_WIDTH_SLOPE_LEFT) )+MAX_MAP_WIDTH_SLOPE_LEFT;
}
public static final float MAX_MAP_HEIGHT = 2.0f;
public boolean wasTouched(float xP, float yP){
/*
//full screen coverage
2.17f, 1.0f, 0.0f, //top left
2.17f, -1.0f, 0.0f, //bottom left
-2.17f, -1.0f, 0.0f, //bottom right
-2.17f, 1.0f, 0.0f //top right
Full Width = 4.34
Full Height = 2
*/
/*
this.upperLeftX = squareCoords[0];
this.upperLeftY = squareCoords[1];
this.widthPercentage = widthPercentage;
*/
// square[4] = upperLeftY<0?upperLeftY + width:upperLeftY - width;
//convert these values to percentages that will match the touch percentages
//invert this value
float tmpUpperLeftX = -this.upperLeftX;
float maxWidth = getMaxMapWidth(tmpUpperLeftX);
tmpUpperLeftX += maxWidth/2;
tmpUpperLeftX /= maxWidth;
float tmpUpperLeftY = this.upperLeftY;
tmpUpperLeftY += MAX_MAP_HEIGHT/2;
tmpUpperLeftY /= MAX_MAP_HEIGHT;
tmpUpperLeftY = 1 - tmpUpperLeftY;
float tmpLowerRightX = tmpUpperLeftX + this.widthPercentage;
float tmpLowerRightY = tmpUpperLeftY + this.widthPercentage;
Log.e(TAG + "-" + this.messageText, this.messageText + " (" + xP + "," + yP + ") | (" + tmpUpperLeftX + "," + tmpUpperLeftY + ") (" + tmpLowerRightX + "," +tmpLowerRightY + ")");
return (
xP > tmpUpperLeftX && xP < tmpLowerRightX &&
yP > tmpUpperLeftY && yP < tmpLowerRightY
);
// return false;
}
private float upperLeftX, upperLeftY, widthPercentage;
public Button(float upperLeftX, float upperLeftY, float width, int background, String buttonText , int id){
// if(touches!=null)
// this.touchDetection = touches;
this.buttonId = id;
this.messageText = buttonText;
this.background = background;
// 2.10f, 0.98f, 0.0f, //top left
// 2.10f, 0.38f, 0.0f, //bottom left
float[] squareCoords = getSquare(upperLeftX, upperLeftY, width);
widthPercentage = width / 4.34f;
// float[] touches
//init vertex bb for shape coords
ByteBuffer bb = ByteBuffer.allocateDirect( squareCoords.length * 4 ); //4 byte per float
bb.order(ByteOrder.nativeOrder());
vertexBuffer = bb.asFloatBuffer();
vertexBuffer.put(squareCoords);
vertexBuffer.position(0);
//iit bb for draw list
ByteBuffer dlb = ByteBuffer.allocateDirect(
//(# of coord values * 2 bytes per short)
drawOrder.length *2 );
dlb.order(ByteOrder.nativeOrder());
drawListBuffer = dlb.asShortBuffer();
drawListBuffer.put(drawOrder);
drawListBuffer.position(0);
//adding texture buffer
bb = ByteBuffer.allocateDirect(texture.length * 4);
bb.order(ByteOrder.nativeOrder());
textureBuffer = bb.asFloatBuffer();
textureBuffer.put(texture);
textureBuffer.position(0);
int vertexShader = MyGL20Renderer.loadShader(GLES20.GL_VERTEX_SHADER, getVertexShader());
int fragmentShader = MyGL20Renderer.loadShader(GLES20.GL_FRAGMENT_SHADER, getFragmentShader());
mProgram = GLES20.glCreateProgram(); //create an empty OpenGL ES Program
GLES20.glAttachShader(mProgram, vertexShader); //add the vertex shader
GLES20.glAttachShader(mProgram, fragmentShader); //add the fragment shader
GLES20.glLinkProgram(mProgram); //create OpenGL ES program execs
this.upperLeftX = upperLeftX;
this.upperLeftY = upperLeftY;
this.widthPercentage = widthPercentage;
mTextureDataHandle = loadTransparentTextureWithText(OpenGLES20Basic.getContext(), background, buttonText, this.upperLeftX, this.upperLeftY, -1);
}
private int maTextureHandle;
private int msTextureHandle;
private float[] color;
public void setColor(float[] c){
color = c;
}
private boolean updateText = false;
public void draw(float[] mvpMatrix){ //pass in the calc'd transformation matrix
if(color == null)
color = MyGL20Renderer.lightBlueColor;
//add program to OpenGL ES env
GLES20.glUseProgram(mProgram);
if(this.updateText){
this.updateText = false;
this.mTextureDataHandle = loadTransparentTextureWithText(OpenGLES20Basic.getContext(), this.background, this.messageText, this.upperLeftX, this.upperLeftY, this.mTextureDataHandle);
}
//get handle to vertex shader's vPosition member
mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition");
//enable a hangle to the triangle vertices//prep the triangle coord data
GLES20.glEnableVertexAttribArray(mPositionHandle);
GLES20.glVertexAttribPointer(mPositionHandle, COORDS_PER_VERTEX, GLES20.GL_FLOAT, false, vertexStride, vertexBuffer);
//get handle to grament's shader vColor member//set color for drawing
mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor");
GLES20.glUniform4fv(mColorHandle, 1, color, 0);
//get handle to shape's transformation matrix//Apply the projection and view transformation
mMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mvpMatrix, 0);
//TEXTURE STUFF
maTextureHandle = GLES20.glGetAttribLocation(mProgram, "aTextureCoord");
msTextureHandle = GLES20.glGetUniformLocation(mProgram, "sTexture");
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mTextureDataHandle);
GLES20.glUniform1i(msTextureHandle, 0);
GLES20.glEnableVertexAttribArray(maTextureHandle);
GLES20.glVertexAttribPointer(maTextureHandle, 2, GLES20.GL_FLOAT, false, 0, textureBuffer);
GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA);
//Draw it!
GLES20.glEnable(GLES20.GL_BLEND);
GLES20.glDrawElements(GLES20.GL_TRIANGLES, drawOrder.length, GLES20.GL_UNSIGNED_SHORT, drawListBuffer);
GLES20.glDisable(GLES20.GL_BLEND);
//disable the vertex array
GLES20.glDisableVertexAttribArray(mPositionHandle);
GLES20.glDisableVertexAttribArray(maTextureHandle);
}
public static int loadTransparentTextureWithText(final Context context, final int resourceId, String text, float x, float y, int existingHandle) {
Log.e(TAG, "Loading texture: " + resourceId + ": " + text);
final int[] textureHandle = new int[1];
if(existingHandle != -1)
textureHandle[0] = existingHandle;
else
GLES20.glGenTextures(1, textureHandle, 0);
Log.e(TAG, "New texture: " + textureHandle[0]);
if (textureHandle[0] != 0)
{
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false; // No pre-scaling
// Read in the resource
//Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resourceId, options);
Bitmap bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888 );
Canvas canvas = new Canvas(bitmap);
bitmap.eraseColor(0);
Drawable background = context.getResources().getDrawable(resourceId);
background.setBounds(0, 0, 100, 100);
background.draw(canvas);
if(text!=null){
// Draw the text
Paint textPaint = new Paint();
textPaint.setTextAlign(Paint.Align.CENTER);
textPaint.setAntiAlias(true);
int fontSize = 16;
textPaint.setTextSize(fontSize);
textPaint.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
textPaint.setARGB(0xff, 0xff, 0xff, 0xff);
canvas.drawText(text, 50,50+(fontSize/3), textPaint);
textPaint.setTextSize(fontSize);
textPaint.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
textPaint.setARGB(0xff, 0x00, 0x00, 0x00);
canvas.drawText(text, 50,50+(fontSize/3), textPaint);
}
/*
byte[] buffer = new byte[bitmap.getWidth() * bitmap.getHeight() * 4];
for ( int y = 0; y < bitmap.getHeight(); y++ )
for ( int x = 0; x < bitmap.getWidth(); x++ ){
int pixel = bitmap.getPixel(x, y);
buffer[(y * bitmap.getWidth() + x) * 4 + 0] = (byte)((pixel >> 16) & 0xFF);
buffer[(y * bitmap.getWidth() + x) * 4 + 1] = (byte)((pixel >> 8) & 0xFF);
buffer[(y * bitmap.getWidth() + x) * 4 + 2] = (byte)((pixel >> 0) & 0xFF);
buffer[(y * bitmap.getWidth() + x) * 4 + 3] = (byte)((pixel >> 24) & 0xFF);
}
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(bitmap.getWidth() * bitmap.getHeight() * 4);
byteBuffer.put(buffer).position(0);
*/
//flip it
android.graphics.Matrix flip = new android.graphics.Matrix();
flip.postScale(x>=0?1f:-1f, y>=0?-1f:1f);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(),flip, true);
// Bind to the texture in OpenGL
Log.e(TAG, "Binding texture" + textureHandle[0]);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureHandle[0]);
if(existingHandle != -1){
GLUtils.texSubImage2D(GLES20.GL_TEXTURE_2D, 0, 0, 0, bitmap);
} else {
// Set filtering
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_NEAREST);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
// Load the bitmap into the bound texture.
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);
//GLES20.glTexImage2D ( GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, bitmap.getWidth(), bitmap.getHeight(), 0, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, byteBuffer );
}
// Recycle the bitmap, since its data has been loaded into OpenGL.
bitmap.recycle();
}
if (textureHandle[0] == 0)
{
throw new RuntimeException("Error loading texture.");
}
return textureHandle[0];
}
public static int loadTransparentTexture(final Context context, final int resourceId) {
final int[] textureHandle = new int[1];
GLES20.glGenTextures(1, textureHandle, 0);
if (textureHandle[0] != 0)
{
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false; // No pre-scaling
// Read in the resource
final Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resourceId, options);
byte[] buffer = new byte[bitmap.getWidth() * bitmap.getHeight() * 4];
for ( int y = 0; y < bitmap.getHeight(); y++ )
for ( int x = 0; x < bitmap.getWidth(); x++ ){
int pixel = bitmap.getPixel(x, y);
buffer[(y * bitmap.getWidth() + x) * 4 + 0] = (byte)((pixel >> 16) & 0xFF);
buffer[(y * bitmap.getWidth() + x) * 4 + 1] = (byte)((pixel >> 8) & 0xFF);
buffer[(y * bitmap.getWidth() + x) * 4 + 2] = (byte)((pixel >> 0) & 0xFF);
buffer[(y * bitmap.getWidth() + x) * 4 + 3] = (byte)((pixel >> 24) & 0xFF);
}
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(bitmap.getWidth() * bitmap.getHeight() * 4);
byteBuffer.put(buffer).position(0);
// Bind to the texture in OpenGL
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureHandle[0]);
// Load the bitmap into the bound texture.
//GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);
GLES20.glTexImage2D ( GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, bitmap.getWidth(), bitmap.getHeight(), 0, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, byteBuffer );
// Set filtering
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_NEAREST);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
// Recycle the bitmap, since its data has been loaded into OpenGL.
bitmap.recycle();
}
if (textureHandle[0] == 0)
{
throw new RuntimeException("Error loading texture.");
}
return textureHandle[0];
}
public static int loadTexture(final Context context, final int resourceId) {
final int[] textureHandle = new int[1];
GLES20.glGenTextures(1, textureHandle, 0);
if (textureHandle[0] != 0)
{
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false; // No pre-scaling
// Read in the resource
final Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resourceId, options);
// Bind to the texture in OpenGL
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureHandle[0]);
// Set filtering
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_NEAREST);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
// Load the bitmap into the bound texture.
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);
// Recycle the bitmap, since its data has been loaded into OpenGL.
bitmap.recycle();
}
if (textureHandle[0] == 0)
{
throw new RuntimeException("Error loading texture.");
}
return textureHandle[0];
}
protected String getVertexShader(){
return readTextFileFromRawResource(OpenGLES20Basic.getContext(), R.raw.button_vertex_shader);
}
protected String getFragmentShader(){
return readTextFileFromRawResource(OpenGLES20Basic.getContext(), R.raw.button_fragment_shader);
}
public static String readTextFileFromRawResource(final Context context, final int resourceId){
final InputStream inputStream = context.getResources().openRawResource(resourceId);
final InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
final BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String nextLine;
final StringBuilder body = new StringBuilder();
try{
while ((nextLine = bufferedReader.readLine()) != null){
body.append(nextLine);
body.append('\n');
}
}
catch (IOException e){
return null;
}
return body.toString();
}
public static int compileShader(final int shaderType, final String shaderSource){
int shaderHandle = GLES20.glCreateShader(shaderType);
if (shaderHandle != 0){
// Pass in the shader source.
GLES20.glShaderSource(shaderHandle, shaderSource);
// Compile the shader.
GLES20.glCompileShader(shaderHandle);
// Get the compilation status.
final int[] compileStatus = new int[1];
GLES20.glGetShaderiv(shaderHandle, GLES20.GL_COMPILE_STATUS, compileStatus, 0);
// If the compilation failed, delete the shader.
if (compileStatus[0] == 0){
System.err.println("Error compiling shader: " + GLES20.glGetShaderInfoLog(shaderHandle));
GLES20.glDeleteShader(shaderHandle);
shaderHandle = 0;
}
}
if (shaderHandle == 0){
throw new RuntimeException("Error creating shader.");
}
return shaderHandle;
}
public static float[] getSquare(float upperLeftX, float upperLeftY, float width){
/*
public static float upperLeftButton[] = {
2.10f, 0.98f, 0.0f, //top left
2.10f, 0.38f, 0.0f, //bottom left
1.50f, 0.38f, 0.0f, //bottom right
1.50f, 0.98f, 0.0f //top right
};*/
float[] square = new float[12];
float zero = 0f;
square[0] = upperLeftX;
square[1] = upperLeftY;
square[2] = zero;
square[3] = upperLeftX;
square[4] = upperLeftY<0?upperLeftY + width:upperLeftY - width;
square[5] = zero;
square[6] = upperLeftX<0?upperLeftX + width:upperLeftX - width;
square[7] = upperLeftY<0?upperLeftY + width:upperLeftY - width;
square[8] = zero;
square[9] = upperLeftX<0?upperLeftX + width:upperLeftX - width;
square[10] = upperLeftY;
square[11] = zero;
// Log.e(TAG, "Square: " + Button.join(square));
return square;
}
/*
static String join(float[] s)
{
String glue = ",";
int k=s.length;
if (k==0)
return null;
StringBuilder out=new StringBuilder();
out.append(s[0]);
for (int x=1;x<k;++x)
out.append(glue).append(s[x]);
return out.toString();
}
*/
}
|
/* v models se vytvareji jednotlive tridy podle kterych si muzu vytvaret objekty */
/* zde vytvorime objekt Sin */
package models;
import org.openqa.selenium.WebElement;
import java.util.List;
public class Sin {
private String title;
private String author;
private String message;
private List<String> tags;
/* napiseme konstruktor podle ktereho si z tridy vytvorime konkretni objekt */
public Sin(String title, String author, String message) {
this.title = title;
this.author = author;
this.message = message;
}
/* getter a setter pro seznam tags*/
public List<String> getTags() { return tags; }
public void setTags(List<String> tags) { this.tags = tags; }
/* vytvorime 3 gettery (prava mys na title -> generate -> getter) */
public String getTitle() { return title; }
public String getAuthor() { return author; }
public String getMessage() { return message; }
/* vytvorime 3 settery (prava mys na title -> generate -> setter) */
public void setTitle(String title) { this.title = title; }
public void setAuthor(String author) { this.author = author; }
public void setMessage(String message) { this.message = message; }
}
|
package com.redsun.platf.entity;
/**
* <p>Title : com.webapp </p>
* <p>Copyright : Copyright (c) 2010</p>
* <p>Company : FreedomSoft </p>
*
* <pre>
* ----------------------------------------------------------------------------- </pre>
* Program ID : @See com.redsun.platf.entity.account.TxnResourceAuthority
* Program Name : 权限自定议类型
* <H3> Modification log </H3>
* <pre>
* Ver. Date Programmer Remark
* ------- --------- ------------ ---------------------------------
* 1.0 13-6-6 joker 权限码AUDIP ,和txn=>resource关联=>role
* authorCode=0x11111111;
* 16个权限码,全为1时表示所有权限
* </pre>
*/
import com.redsun.platf.util.convertor.Convertor;
import com.redsun.platf.util.convertor.Stringfier;
import org.springframework.security.acls.domain.BasePermission;
import java.io.Serializable;
import java.util.EnumSet;
import java.util.HashMap;
public enum AuthorityType implements Serializable {
/**
* 新增, "1000000000000"
* 修改, "0100000000000"
*/
SUPER(1 + 2 + 4 + 6 + 8 + 16, "所有权限"),
ADD(1, "新增"),
CREATE(2, "修改"),
DELETE(4, "删除"),
QUERY(8, "查询"),
PRINT(16, "打印");
BasePermission permission;//mask
private Integer code;
private String cnname;
private AuthorityType(Integer code, String name) {
this.code = code;
this.cnname = name;
}
public String getCnname() {
return cnname;
}
public Integer getCode() {
return code;
}
public String toString() {
return code.toString();
}
public static boolean canAll(AuthorityType c) {
return c == SUPER;
}
public static boolean canRead(AuthorityType c) {
return c == ADD;
}
public static boolean canWrite(AuthorityType c) {
return c == CREATE;
}
public static boolean canDelete(AuthorityType c) {
return c == DELETE;
}
public static boolean canQuery(AuthorityType c) {
return c == QUERY;
}
public static boolean canPrint(AuthorityType c) {
return c == PRINT;
}
/**
* 返回当前类型的所有值hashMap
*/
public static final HashMap<Integer, AuthorityType> codeMap;
static {
EnumSet<AuthorityType> set = EnumSet.allOf(AuthorityType.class);
codeMap = new HashMap<Integer, AuthorityType>(set.size());
for (AuthorityType c : set) {
codeMap.put(c.code, c);
}
}
public static AuthorityType eval(Integer str) {
if (str == 0) {
return null;
}
if (codeMap.containsKey(str)) {
return codeMap.get(str);
} else {
throw new IllegalArgumentException(String.format(
"代码\"%d\"不是一个合法的权限代码!", str));
}
}
/**
* 根据类别代码显示类别
*/
public static Convertor<Integer, AuthorityType> convertor = new Convertor<Integer, AuthorityType>() {
@Override
public AuthorityType convert(Integer s) {
return AuthorityType.eval(s);
}
};
/**
* 显示中文
*/
public static Stringfier<AuthorityType> cnStringfier = new Stringfier<AuthorityType>() {
@Override
public String convert(AuthorityType s) {
return s.getCnname();
}
};
/**
* type define
*
* @author dick pan
* @version 1.0
* @since 1.0
* <p>
* <H3>Change history</H3>
* </p>
* <p>
* 2011/3/4 : Created
* </p>
*/
// public static class Type implements EnhancedUserType {
// @Override
// public Object fromXMLString(String arg0) {
// return AuthorityType.eval(Integer.parseInt(arg0));
// }
//
// @Override
// public String objectToSQLString(Object arg0) {
// return String.format("\'%s\'", arg0.toString());
// }
//
// @Override
// public String toXMLString(Object arg0) {
// return arg0.toString();
// }
//
// @Override
// public Object assemble(Serializable arg0, Object arg1)
// throws HibernateException {
// return arg0;
// }
//
// @Override
// public Object deepCopy(Object arg0) throws HibernateException {
// return arg0;
// }
//
// @Override
// public Serializable disassemble(Object arg0) throws HibernateException {
// return (Serializable) arg0;
// }
//
// @Override
// public boolean equals(Object arg0, Object arg1)
// throws HibernateException {
// if (arg0 == arg1)
// return true;
// else
// return false;
// }
//
// @Override
// public int hashCode(Object arg0) throws HibernateException {
// return arg0.hashCode();
// }
//
// @Override
// public boolean isMutable() {
// return false;
// }
//
// @Override
// public Object nullSafeGet(ResultSet rs, String[] names, Object owner)
// throws HibernateException, SQLException {
// String code = rs.getString(names[0]);
// return rs.wasNull() ? null : AuthorityType.eval(Integer.parseInt(code));
// }
//
// @Override
// public void nullSafeSet(PreparedStatement ps, Object value, int index)
// throws HibernateException, SQLException {
// if (value == null) {
// ps.setNull(index, Types.VARCHAR);
// } else {
// ps.setString(index, value.toString());
// }
//
// }
//
// @Override
// public Object replace(Object arg0, Object arg1, Object arg2)
// throws HibernateException {
// return arg0;
// }
//
// @Override
// public Class<AuthorityType> returnedClass() {
// return AuthorityType.class;
// }
//
// @Override
// public int[] sqlTypes() {
// return new int[]{Types.VARCHAR};
// }
// }
}
|
/*
* Copyright © 2020-2022 ForgeRock AS (obst@forgerock.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.forgerock.sapi.gateway.ob.uk.common.datamodel.converter.account;
import com.forgerock.sapi.gateway.ob.uk.common.datamodel.account.FRCurrencyExchange;
import com.forgerock.sapi.gateway.ob.uk.common.datamodel.converter.common.FRAmountConverter;
import uk.org.openbanking.datamodel.account.OBCurrencyExchange5;
public class FRCurrencyExchangeConverter {
// FR to OB
public static OBCurrencyExchange5 toOBCurrencyExchange5(FRCurrencyExchange currencyExchange) {
return currencyExchange == null ? null : new OBCurrencyExchange5()
.sourceCurrency(currencyExchange.getSourceCurrency())
.targetCurrency(currencyExchange.getTargetCurrency())
.unitCurrency(currencyExchange.getUnitCurrency())
.exchangeRate(currencyExchange.getExchangeRate())
.contractIdentification(currencyExchange.getContractIdentification())
.quotationDate(currencyExchange.getQuotationDate())
.instructedAmount(FRAmountConverter.toOBCurrencyExchange5InstructedAmount(currencyExchange.getInstructedAmount()));
}
// OB to FR
public static FRCurrencyExchange toFRCurrencyExchange(OBCurrencyExchange5 currencyExchange) {
return currencyExchange == null ? null : FRCurrencyExchange.builder()
.sourceCurrency(currencyExchange.getSourceCurrency())
.targetCurrency(currencyExchange.getTargetCurrency())
.unitCurrency(currencyExchange.getUnitCurrency())
.exchangeRate(currencyExchange.getExchangeRate())
.contractIdentification(currencyExchange.getContractIdentification())
.quotationDate(currencyExchange.getQuotationDate())
.instructedAmount(FRAmountConverter.toFRAmount(currencyExchange.getInstructedAmount()))
.build();
}
}
|
package by.epam.gmail.automation.pages;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.PageFactory;
import by.epam.gmail.automation.utils.ExplicitWait;
import by.epam.gmail.automation.utils.WindowSwitcher;
public abstract class AbstractPage {
protected WebDriver driver;
protected ExplicitWait wait;
protected WindowSwitcher switcher;
protected final Logger log;
public AbstractPage(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
wait = new ExplicitWait(driver);
switcher = new WindowSwitcher(driver);
log = LogManager.getRootLogger();
}
}
|
package com.example.patricemp.scrumme;
import android.content.Context;
import android.content.Intent;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Date;
/**
* A placeholder fragment containing a simple view.
*/
public class MainActivityFragment extends Fragment
implements TaskAdapter.TaskClickListener, TaskAdapter.DeleteListener,
TaskAdapter.SprintListener, TaskAdapter.CompletedListener{
private LinearLayoutManager mLayoutManager;
private TaskAdapter mAdapter;
private Parcelable mListState;
private onTaskClickListener mCallback;
private checkInSprint mInSprintCallback;
private sprintNumProvider mGetSprintNum;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mTasksDatabaseReference;
private ChildEventListener mChildEventListener;
private Task mLastDeleted;
private int mLastDeletedPosition;
private FirebaseAuth mFirebaseAuth;
private String mOrderBy;
private String mUid;
private boolean mSprintInProgress;
private long mCurrentSprint;
private Sprint mSprint;
private DatabaseReference mSprintDatabaseReference;
private DatabaseReference mSprintStatusReference;
public MainActivityFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mFirebaseDatabase = FirebaseDatabase.getInstance();
mFirebaseAuth = FirebaseAuth.getInstance();
FirebaseUser user = mFirebaseAuth.getCurrentUser();
if(user != null){
mUid = user.getUid();
mTasksDatabaseReference = mFirebaseDatabase.getReference()
.child("users")
.child(mUid)
.child("tasks");
mSprintDatabaseReference = mFirebaseDatabase.getReference()
.child("users")
.child(mUid)
.child("sprints");
mSprintStatusReference = FirebaseDatabase.getInstance().getReference()
.child("users")
.child(mUid)
.child("sprint_status");
}
if(savedInstanceState != null){
mListState = savedInstanceState.getParcelable("state");
if(savedInstanceState.containsKey("lastRemoved")){
mLastDeleted = savedInstanceState.getParcelable("lastRemoved");
mLastDeletedPosition = savedInstanceState.getInt("lastDeletedPosition");
}
if(savedInstanceState.containsKey("list_state")){
mListState = savedInstanceState.getParcelable("list_state");
}
}
Bundle bundle = getArguments();
if(bundle != null){
mOrderBy = bundle.getString("orderBy");
}
final View rootView = inflater.inflate(R.layout.fragment_main, container, false);
RecyclerView tasksView = rootView.findViewById(R.id.rv_tasks);
if(tasksView.getLayoutManager() == null){
mLayoutManager = new LinearLayoutManager(getActivity());
tasksView.setLayoutManager(mLayoutManager);
}
if(mListState != null){
mLayoutManager.onRestoreInstanceState(mListState);
}
mAdapter = new TaskAdapter(this, this, this, this);
mAdapter.clearTasks();
tasksView.setAdapter(mAdapter);
tasksView.setHasFixedSize(true);
return rootView;
}
@Override
public void onTaskClick(Task task, View view) {
mCallback.onTaskSelected(task);
}
@Override
public void onDeleteClick(Task task) {
if(getActivity() != null){
mTasksDatabaseReference.child(task.getDatabaseKey()).removeValue();
mLastDeleted = task;
mLastDeletedPosition = mAdapter.getPosition(task);
mAdapter.deleteTask(task);
}
}
@Override
public void onSprintClick(Task task) {
if(getActivity() != null){
if(task.getInSprint()){
if (mOrderBy != null && mOrderBy.matches("inSprint")) {
mLastDeleted = task;
mLastDeletedPosition = mAdapter.getPosition(task);
mAdapter.deleteTask(task);
}
task.setInSprint(false);
task.setCompleted(false);
}else{
task.setInSprint(true);
}
mTasksDatabaseReference.child(task.getDatabaseKey()).setValue(task);
}
}
private void updateSprint(){
final ValueEventListener currentSprintListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot != null) {
mSprint = dataSnapshot.getValue(Sprint.class);
if(mSprint == null){
mSprint = new Sprint();
mSprint.setSprintNum(mCurrentSprint);
}
mSprint.setCurrentEffortPoints(mAdapter.countSprintPoints());
mSprint.setCompletedEffortPoints(mAdapter.countCompleted());
mSprintDatabaseReference.child(Long.toString(mCurrentSprint)).setValue(mSprint);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
ValueEventListener sprintStatusListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
if (dataSnapshot.hasChild("sprintInProgress")) {
mSprintInProgress = (boolean) dataSnapshot.child("sprintInProgress").getValue();
if (mCurrentSprint > 0) {
mSprintDatabaseReference
.child(Long.toString(mCurrentSprint))
.addListenerForSingleValueEvent(currentSprintListener);
}
if (dataSnapshot.hasChild("currentSprint")) {
mCurrentSprint = (long) dataSnapshot.child("currentSprint").getValue();
if (mCurrentSprint > 0 && mSprintInProgress) {
mSprintDatabaseReference
.child(Long.toString(mCurrentSprint))
.addListenerForSingleValueEvent(currentSprintListener);
}
}
}
}
}
@Override
public void onCancelled (DatabaseError databaseError){
}
};
mSprintStatusReference.addListenerForSingleValueEvent(sprintStatusListener);
}
@Override
public void onCompleteClick(Task task) {
if(getActivity() != null){
if(task.getCompleted()){ //if was previously marked complete
task.setCompleted(false);
task.setDateCompleted(null);
task.setSprintNum(0);
}else if(mInSprintCallback.isInSprint()){
task.setCompleted(true);
Long sprint = mGetSprintNum.getSprintNum();
task.setSprintNum(sprint.intValue());
task.setInSprint(true);
Date currentDate = new Date();
task.setDateCompleted(currentDate);
}else{
Toast.makeText(getContext(), getString(R.string.complete_pressed_no_sprint),
Toast.LENGTH_SHORT).show();
return;
}
mTasksDatabaseReference.child(task.getDatabaseKey()).setValue(task);
}
}
public interface onTaskClickListener{
void onTaskSelected(Task task);
}
public interface checkInSprint {
boolean isInSprint();
}
public interface sprintNumProvider{
Long getSprintNum();
}
public ArrayList<Task> getTaskList(){
return mAdapter.getTaskList();
}
@Override
public void onAttach(Context context){
super.onAttach(context);
try{
mCallback = (onTaskClickListener) context;
mInSprintCallback = (checkInSprint) context;
mGetSprintNum = (sprintNumProvider) context;
} catch(Exception e){
e.printStackTrace();
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("state", mListState);
outState.putParcelable("lastRemoved", mLastDeleted);
outState.putInt("lastRemovedPosition", mLastDeletedPosition);
outState.putParcelable("list_state", mListState);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
FloatingActionButton fab = getActivity().findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getActivity().getBaseContext(), AddTaskActivity.class);
startActivity(intent);
// Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
// .setAction("Action", null).show();
}
});
if(mChildEventListener != null){
mTasksDatabaseReference.removeEventListener(mChildEventListener);
mAdapter.clearTasks();
}
mChildEventListener = new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Task task = dataSnapshot.getValue(Task.class);
String key = dataSnapshot.getKey();
if(task != null) {
task.setDatabaseKey(key);
if (mLastDeleted != null && key.matches(mLastDeleted.getDatabaseKey())) {
mAdapter.addTask(task, mLastDeletedPosition);
} else {
mAdapter.addTask(task);
}
updateSprint();
}
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Task task = dataSnapshot.getValue(Task.class);
mAdapter.modifyTask(task);
updateSprint();
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
if(getActivity() != null){
Snackbar snacker = Snackbar.make(getActivity().findViewById(R.id.cl_main),
R.string.removed_task, Snackbar.LENGTH_LONG);
snacker.setAction(R.string.undo_remove, new View.OnClickListener() {
@Override
public void onClick(View v) {
if(mOrderBy != null && mOrderBy.matches("inSprint")){
mLastDeleted.setInSprint(true);
}
mTasksDatabaseReference
.child(mLastDeleted.getDatabaseKey())
.setValue(mLastDeleted);
}
}
);
snacker.show();
updateSprint();
}
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
if(mOrderBy != null && !mOrderBy.isEmpty()){
switch (mOrderBy){
case "inSprint":
mTasksDatabaseReference
.orderByChild(mOrderBy)
.equalTo(true)
.addChildEventListener(mChildEventListener);
break;
case "importance":
mTasksDatabaseReference
.orderByChild(mOrderBy)
.addChildEventListener(mChildEventListener);
break;
default:
mTasksDatabaseReference
.orderByChild("importance")
.addChildEventListener(mChildEventListener);
break;
}
}else{
mTasksDatabaseReference
.orderByChild("inSprint")
.equalTo(true)
.addChildEventListener(mChildEventListener);
}
}
@Override
public void onPause() {
super.onPause();
mListState = mLayoutManager.onSaveInstanceState();
}
@Override
public void onResume() {
super.onResume();
if(mListState != null){
mLayoutManager.onRestoreInstanceState(mListState);
}
}
}
|
import java.time.*;
public class TimeUtil {
public static void main(String[] args) {
System.out.println("utc " + System.currentTimeMillis());
System.out.println("msk " + LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli());
}
}
|
package com.memberComment.model;
import java.util.List;
public class TestJDBC {
public static void main(String[] args) {
MemberCommentDAO_interface dao = new MemberCommentDAO();
//All
// List<MemberCommVO> list = dao.selectAll();
// for(MemberCommVO memberCommVO : list) {
// System.out.println(memberCommVO.getComm());
// }
//All
// MemberCommentService mcs = new MemberCommentService();
// List<MemberCommentVO> list = mcs.getAllMemberCommentById("MEM00001");
// for(MemberCommentVO memberCommVO : list) {
// System.out.println(memberCommVO.getMemberCommentContent());
// System.out.println(memberCommVO.getMemberCommStatusEmp());
// System.out.println("----------------------");
// }
//One
// MemberCommentVO one = dao.findByPrimaryKey("MCOMMENT00001");
// System.out.println(one.getMemberAId());
// System.out.println(one.getMemberCommStatusEmp());
//insert
// MemberCommentVO add = new MemberCommentVO();
// add.setMemberAId("MEM00001");
// add.setMemberBId("MEM00002");
// add.setMemberCommentContent("QQQQQQQQQQQQQ");
// add.setMemberCommentLevel(4.2);
// add.setMemberCommentDate(java.sql.Date.valueOf("2020-09-01"));
// add.setMemberCommStatus("T");
// add.setMemberCommStatusEmp("T");
// add.setMemberCommStatusComm("T");
// dao.insert(add);
// System.out.println("FUCK");
//delete
// dao.delete("MCOMMENT00006");
// System.out.println("FUCK");
//update
// MemberCommentVO update = new MemberCommentVO();
// update.setMemberCommentId("MCOMMENT00005");
// update.setMemberAId("MEM00002");
// update.setMemberBId("MEM00001");
// update.setMemberCommentContent("ccccccccccccccccccccccc");
// update.setMemberCommentLevel(4.5);
// update.setMemberCommentDate(java.sql.Date.valueOf("2020-09-15"));
// update.setMemberCommStatus("A");
// update.setMemberCommStatusEmp("C");
// update.setMemberCommStatusComm("C");
// dao.update(update);
// System.out.println("FUCK");
//
}
}
|
package video.api.android.sdk.domain;
public class SourceVideo {
private String type;
private String uri;
// private String status;
// private int filesize;
// private ArrayList<ReceivedBytes> receivedBytes;
public SourceVideo() {
}
public SourceVideo(String type, String uri/*, String status, int filesize, ArrayList<ReceivedBytes> receivedBytes*/) {
this.type = type;
this.uri = uri;
// this.status = status;
// this.filesize = filesize;
// this.receivedBytes = receivedBytes;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
// public String getStatus() {
// return status;
// }
//
// public void setStatus(String status) {
// this.status = status;
// }
//
// public int getFilesize() {
// return filesize;
// }
//
// public void setFilesize(int filesize) {
// this.filesize = filesize;
// }
//
// public ArrayList<ReceivedBytes> getReceivedBytes() {
// return receivedBytes;
// }
//
// public void setReceivedBytes(ArrayList<ReceivedBytes> receivedBytes) {
// this.receivedBytes = receivedBytes;
// }
}
|
/*
* 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 human;
/**
*
* @author hugo
*/
public class HumanDemo {
public static void main(String[] args) {
Human numberOne = new Human(25,"Achilles");
System.out.println(numberOne.getAge());
System.out.println(numberOne.getName());
System.out.println(numberOne);
}
}
|
package com.whg.vrxcompare;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.whg.vrxcompare.FileUtil.FileType;
public class Main {
private static final String INPUT_PROPERTY_LIST = "C:/Rajarshi/MyLab/VRXDAMCOMPARE/proplist.csv";
private static final String OUTPUT_FILE = "C:/Rajarshi/MyLab/VRXDAMCOMPARE/output.csv";
private static final String LDRIVE_IMAGE_PATH = "//hotelgroup.com/newjersey/HIT/Rajarshi/LDrive/Images";
private static final String LDRIVE_VRX_PATH = "//hotelgroup.com/newjersey/HIT/Rajarshi/LDrive/VRX";
private static final String[] LDRIVE_IMAGES_BRANDS = new String[] {
"Days Inn", "Baymont", "Dream-Night", "Hawthorn", "Howard Johnson",
"Knights", "Microtel", "Ramada", "Super 8", "Travelodge", "TRYP",
"Wingate", "Wyndham Garden", "Wyndham Grand",
"Wyndham Hotels and Resorts" };
private static final String[] LDRIVE_VRX_BRANDS = new String[] { "Baymont",
"Days Inn", "Hawthorn", "Howard Johnson", "Knights Inn",
"Microtel", "Ramada", "Super 8", "Travelodge", "Wyndham" };
private static final HashMap<String, String> propNamevsId;
static {
propNamevsId = new HashMap<String, String>();
propNamevsId.put("Baymont", "BU");
propNamevsId.put("Days Inn", "DI");
propNamevsId.put("Ramada", "RA");
propNamevsId.put("Howard Johnson", "HJ");
propNamevsId.put("Super 8", "SE");
propNamevsId.put("Wyndham", "WY");
propNamevsId.put("Wingate By Wyndham", "WG");
propNamevsId.put("Knights Inn", "KI");
propNamevsId.put("Travelodge", "TL");
propNamevsId.put("Microtel", "MT");
propNamevsId.put("Hawthorn", "BH");
propNamevsId.put("Dream-Night", "PX");
propNamevsId.put("Knights", "KI");
propNamevsId.put("TRYP", "WT");
propNamevsId.put("Wingate", "WG");
propNamevsId.put("Wyndham Garden", "WY");
propNamevsId.put("Wyndham Grand", "WY");
propNamevsId.put("Wyndham Hotels and Resorts", "WY");
}
private List<FileMeta> finallist = new ArrayList<FileMeta>();
public static void main(String[] args) {
// Fetch the input brand and property ids
List<String> inputdata = new FileUtil(INPUT_PROPERTY_LIST).readFile();
List<FileMeta> filesetinput = new ArrayList<FileMeta>();
if (inputdata != null && inputdata.size() > 0) {
for (String brandpropline : inputdata) {
FileMeta fileMeta = new FileMeta();
String[] bparr = brandpropline.split(",");
String brandId = bparr[0], propertyId = padzero(bparr[1]);
fileMeta.setBrandId(brandId);
fileMeta.setPropertyId(propertyId);
filesetinput.add(fileMeta);
}
}
// cumilitive set of files
List<FileMeta> filesetcomplete = new ArrayList<FileMeta>();
List<FileMeta> filesetcompleteImages = new ArrayList<FileMeta>();
List<FileMeta> filesetcompleteVRX = new ArrayList<FileMeta>();
// Read L drive image folder
for (String brandfolders : LDRIVE_IMAGES_BRANDS) {
String path = LDRIVE_IMAGE_PATH + '/' + brandfolders;
List<FileMeta> ilist = new FileUtil(path).findFiles(FileType.IMAGE);
for (FileMeta fileMeta : ilist) {
fileMeta.setBrandId(propNamevsId.get(brandfolders));
fileMeta.setPropertyId(getProp(fileMeta.getFilePath()));
fileMeta.setInLDVRX("FALSE");
fileMeta.setInLDImages("TRUE");
System.out.println(fileMeta.getPropertyId());
}
filesetcompleteImages.addAll(ilist);
}
// Read L drive VRX folder
for (String brandfolders : LDRIVE_VRX_BRANDS) {
String path = LDRIVE_VRX_PATH + '/' + brandfolders;
List<FileMeta> ilist = new FileUtil(path).findFiles(FileType.IMAGE);
for (FileMeta fileMeta : ilist) {
fileMeta.setBrandId(propNamevsId.get(brandfolders));
fileMeta.setPropertyId(getProp(fileMeta.getFilePath()));
fileMeta.setInLDVRX("TRUE");
fileMeta.setInLDImages("FALSE");
System.out.println(fileMeta.getPropertyId());
}
filesetcompleteVRX.addAll(ilist);
}
filesetcomplete.addAll(filesetcompleteImages);
filesetcomplete.addAll(filesetcompleteVRX);
/*
* for (FileMeta fileMeta : filesetcompleteImages) {
* if(fileMeta.getFilePath().contains(s)) }
*/
// Generate the output
System.out.println(filesetcomplete.size());
StringBuffer sb = new StringBuffer();
for (FileMeta fileMetaOut : filesetcomplete) {
for (FileMeta fileMetaInp : filesetinput) {
if(fileMetaInp.getBrandId().equalsIgnoreCase(fileMetaOut.getBrandId())
&& fileMetaInp.getPropertyId().equalsIgnoreCase(fileMetaOut.getPropertyId())) {
fileMetaOut.setInPIMT("TRUE");
sb.append(fileMetaOut.toString()).append(System.getProperty("line.separator"));
}
}
}
new FileUtil(OUTPUT_FILE).writeFile(sb.toString());
}
private static String padzero(String id) {
return ("00000" + id).substring(id.length());
}
private static String getProp(String path) {
Matcher m = Pattern.compile("([0-9]{1,5}+)").matcher(path);
if (m.find()) {
return padzero(m.group());
}
return "00000";
}
class ReadThread extends Thread {
@Override
public void run() {
System.out.println(getName() + " is running");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(getName() + " is running");
}
}
}
|
package edu.mum.sonet.repositories;
import edu.mum.sonet.models.User;
import org.springframework.data.jpa.repository.JpaRepository;
import edu.mum.sonet.models.UserNotification;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface UserNotificationRepository extends JpaRepository<UserNotification, Long>{
List<UserNotification> findAllByOrderByIdDesc();
// @Query("select un from UserNotification un inner join un.users u where u.email =:email")
// List<UserNotification> findUserNotificationForUser(@Param("email") String email);
}
|
package com.pattern.cglib.aop;
import org.omg.PortableInterceptor.RequestInfo;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class DynamicProxyHandler implements InvocationHandler {
private RealPayment realPayment;
private Object proxiedObject;
public DynamicProxyHandler(Object proxiedObject) {
this.proxiedObject = proxiedObject;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = method.invoke(proxiedObject, args);
realPayment.pay();
return result;
}
}
|
package com.cs261.output;
import com.cs261.analysis.Node;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
public class AlertPrinter {
private List<Node> nodes;
private int id;
private String type;
private String[] headers;
public AlertPrinter(String type, List<Node> nodes) {
this.type = type;
this.nodes = nodes;
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
Date currentdate = new Date();
String dateStr = dateFormat.format(currentdate);
try {
BufferedReader br = new BufferedReader(new FileReader("data/" + dateStr + type.toLowerCase() + "store.csv"));
headers = br.readLine().split(",");
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void print() {
File[] alerts = new File("alerts").listFiles(new FilenameFilter() {
@Override
public boolean accept(File file, String s) {
return s.matches("^" + type + " [0-9]+\\.csv$");
}
});
if (alerts.length > 0) {
String oldFileName = alerts[alerts.length - 1].getName();
String oldFileName2 = oldFileName.split(" ")[1];
String oldId = oldFileName2.substring(0, oldFileName2.length() - 4);
this.id = Integer.parseInt(oldId) + 1;
}
try {
PrintWriter outputFile = new PrintWriter(new FileWriter("alerts/" + type + " " + id + ".csv", true));
for (int i = 0; i < headers.length; i++) {
outputFile.print(headers[i]);
if (i == headers.length - 1) {
outputFile.println();
} else {
outputFile.print(",");
}
}
for (Node node : nodes) {
for (int i = 0; i < node.getContent().length; i++) {
outputFile.print(node.getContent()[i]);
if (i == node.getContent().length - 1) {
outputFile.println();
} else {
outputFile.print(",");
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package net.awesomekorean.podo.challenge;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import android.content.Intent;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Shader;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingClientStateListener;
import com.android.billingclient.api.BillingFlowParams;
import com.android.billingclient.api.BillingResult;
import com.android.billingclient.api.ConsumeParams;
import com.android.billingclient.api.ConsumeResponseListener;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.PurchasesUpdatedListener;
import com.android.billingclient.api.SkuDetails;
import com.android.billingclient.api.SkuDetailsParams;
import com.android.billingclient.api.SkuDetailsResponseListener;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import com.google.firebase.messaging.FirebaseMessaging;
import net.awesomekorean.podo.MainActivity;
import net.awesomekorean.podo.PurchaseInfo;
import net.awesomekorean.podo.R;
import net.awesomekorean.podo.SharedPreferencesInfo;
import net.awesomekorean.podo.UnixTimeStamp;
import net.awesomekorean.podo.UserInformation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import me.relex.circleindicator.CircleIndicator;
public class Challenge extends AppCompatActivity implements View.OnClickListener, PurchasesUpdatedListener {
FirebaseAnalytics firebaseAnalytics;
FirebaseFirestore db = FirebaseFirestore.getInstance();
FragmentPagerAdapter adapter;
ArrayList<Integer> imageList;
ImageView btnBack;
TextView interview1;
TextView interview2;
TextView interview3;
ImageView interviewFold1;
ImageView interviewFold2;
ImageView interviewFold3;
ConstraintLayout btnChallenge;
TextView textChallenge;
boolean interviewClicked1 = false;
boolean interviewClicked2 = false;
boolean interviewClicked3 = false;
BillingClient billingClient;
SkuDetails skuDetails;
int discount = 0;
private final String DISCOUNT = "discount";
ImageView discountTape;
TextView discountPercent;
TextView priceOriginal;
TextView price;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_challenge);
btnBack = findViewById(R.id.btnBack);
interview1 = findViewById(R.id.interview_1);
interview2 = findViewById(R.id.interview_2);
interview3 = findViewById(R.id.interview_3);
interviewFold1 = findViewById(R.id.interview_fold_1);
interviewFold2 = findViewById(R.id.interview_fold_2);
interviewFold3 = findViewById(R.id.interview_fold_3);
btnChallenge = findViewById(R.id.btnChallenge);
textChallenge = findViewById(R.id.textChallenge);
discountTape = findViewById(R.id.discountTape);
discountPercent = findViewById(R.id.discountPercent);
priceOriginal = findViewById(R.id.priceOriginal);
price = findViewById(R.id.price);
btnBack.setOnClickListener(this);
interviewFold1.setOnClickListener(this);
interviewFold2.setOnClickListener(this);
interviewFold3.setOnClickListener(this);
btnChallenge.setOnClickListener(this);
Bundle bundleOpen = new Bundle();
firebaseAnalytics = FirebaseAnalytics.getInstance(getApplicationContext());
firebaseAnalytics.logEvent("challenge_open", bundleOpen);
FirebaseMessaging.getInstance().subscribeToTopic("challenge_page_open");
discount = getIntent().getIntExtra(DISCOUNT, 0);
initDiscount();
imageList = new ArrayList<>();
imageList.add(R.drawable.benefits_ads);
imageList.add(R.drawable.benefits_lessons);
imageList.add(R.drawable.benefits_progress);
imageList.add(R.drawable.benefits_points);
ViewPager viewPager = findViewById(R.id.viewPager);
adapter = new ChallengeAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
CircleIndicator indicator = findViewById(R.id.indicator);
indicator.setViewPager(viewPager);
Shader shader = new LinearGradient(0,0,100,0, new int[]{ContextCompat.getColor(getApplicationContext(), R.color.PINK2), ContextCompat.getColor(getApplicationContext(), R.color.PURPLE)}, new float[]{0, 1}, Shader.TileMode.CLAMP);
textChallenge.getPaint().setShader(shader);
btnChallenge.setEnabled(false);
btnChallenge.setBackground(ContextCompat.getDrawable(getApplicationContext(), R.drawable.bg_grey_light_10));
billingClient = BillingClient.newBuilder(getApplicationContext())
.setListener(this)
.enablePendingPurchases()
.build();
// 구글플레이에 연결하기
billingClient.startConnection(new BillingClientStateListener() {
@Override
public void onBillingSetupFinished(BillingResult billingResult) {
// 구글플레이와 연결 성공
if(billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
System.out.println("구글플레이와 연결을 성공했습니다.");
getSkuDetail();
} else {
System.out.println("구글플레이와 연결을 실패했습니다. : " + billingResult.getDebugMessage());
Toast.makeText(getApplicationContext(), "Connection failed : " + billingResult.getDebugMessage(), Toast.LENGTH_LONG).show();
Bundle bundleConnectionFail = new Bundle();
bundleConnectionFail.putInt("responseCode", billingResult.getResponseCode());
bundleConnectionFail.putString("message", billingResult.getDebugMessage());
firebaseAnalytics.logEvent("challenge_connection_fail", bundleConnectionFail);
}
}
@Override
public void onBillingServiceDisconnected() {
System.out.println("구글플레이와 연결이 끊어졌습니다.");
//todo: 연결 다시 시도하기
}
});
}
private void initDiscount() {
discountTape.setVisibility(View.GONE);
discountPercent.setVisibility(View.GONE);
priceOriginal.setVisibility(View.GONE);
}
// 상품 정보 받아오기
public void getSkuDetail() {
List<String> skuList = new ArrayList<>();
skuList.add(getString(R.string.SKU_CHALLENGER));
skuList.add(getString(R.string.SKU_CHALLENGER) + "_" + discount);
SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();
params.setSkusList(skuList).setType(BillingClient.SkuType.INAPP);
billingClient.querySkuDetailsAsync(params.build(), new SkuDetailsResponseListener() {
@Override
public void onSkuDetailsResponse(BillingResult billingResult, List<SkuDetails> list) {
if(billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
System.out.println("챌린지 상품 정보를 받았습니다.");
System.out.println("리스트 : " + list);
for(SkuDetails sku : list) {
if(sku.getSku().equals(getString(R.string.SKU_CHALLENGER))) {
priceOriginal.setText(sku.getPrice());
if(discount == 0) {
skuDetails = sku;
}
} else if(sku.getSku().equals(getString(R.string.SKU_CHALLENGER) + "_" + discount)) {
price.setText(sku.getPrice());
if(discount != 0) {
skuDetails = sku;
}
}
}
if(discount != 0) {
discountTape.setVisibility(View.VISIBLE);
discountPercent.setVisibility(View.VISIBLE);
discountPercent.setText(discount + "%");
priceOriginal.setPaintFlags(priceOriginal.getPaintFlags()| Paint.STRIKE_THRU_TEXT_FLAG);
priceOriginal.setVisibility(View.VISIBLE);
} else {
price.setText(skuDetails.getPrice());
}
btnChallenge.setEnabled(true);
btnChallenge.setBackground(ContextCompat.getDrawable(getApplicationContext(), R.drawable.bg_purple_10));
} else {
System.out.println("챌린지 상품 정보 받아오기를 실패했습니다. : " + billingResult.getDebugMessage());
Toast.makeText(getApplicationContext(), billingResult.getDebugMessage(), Toast.LENGTH_LONG).show();
Bundle bundleSkuFail = new Bundle();
bundleSkuFail.putInt("responseCode", billingResult.getResponseCode());
bundleSkuFail.putString("message", billingResult.getDebugMessage());
firebaseAnalytics.logEvent("challenge_getSku_fail", bundleSkuFail);
}
}
});
}
// 결제 처리
@Override
public void onPurchasesUpdated(BillingResult billingResult, @Nullable List<Purchase> list) {
// 결제 취소
if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.USER_CANCELED) {
System.out.println("결제를 취소했습니다.");
Bundle bundleCancel = new Bundle();
firebaseAnalytics.logEvent("challenge_cancel", bundleCancel);
} else {
PurchaseInfo purchaseInfo = new PurchaseInfo(getApplicationContext(), billingResult, list.get(0), skuDetails.getPrice());
// 결제 성공
if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
System.out.println("챌린지를 구매했습니다.");
// 정상구매
if (purchaseInfo.checkPurchase()) {
UserInformation userInformation = SharedPreferencesInfo.getUserInfo(getApplicationContext());
Long timeStart = UnixTimeStamp.getTimeNow();
Long timeExpire = timeStart + 2592000;
userInformation.setIsChallenger(1);
userInformation.setDateChallengeStart(timeStart);
userInformation.setDateChallengeExpire(timeExpire);
SharedPreferencesInfo.setUserInfo(getApplicationContext(), userInformation);
db.collection(getString(R.string.DB_USERS)).document(MainActivity.userEmail).set(userInformation).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
System.out.println("DB에 챌린지정보를 저장했습니다.:");
Toast.makeText(getApplicationContext(), getString(R.string.THANKS_PURCHASING), Toast.LENGTH_LONG).show();
FirebaseMessaging.getInstance().subscribeToTopic("purchase_challenge");
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
System.out.println("DB에 챌린지정보 저장을 실패했습니다.: " + e);
Toast.makeText(getApplicationContext(), getString(R.string.ERROR_PURCHASING) + e, Toast.LENGTH_LONG).show();
}
});
Bundle bundlePurchase = new Bundle();
firebaseAnalytics.logEvent("challenge_purchase", bundlePurchase);
Intent intent = new Intent();
setResult(RESULT_OK, intent);
// 비정상 구매
} else {
Toast.makeText(getApplicationContext(), getString(R.string.INVALID_PURCHASING), Toast.LENGTH_LONG).show();
}
// 상품 소모하기
ConsumeResponseListener consumeListener = new ConsumeResponseListener() {
@Override
public void onConsumeResponse(BillingResult billingResult, String s) {
if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
System.out.println("상품을 성공적으로 소모하였습니다.");
} else {
System.out.println("상품 소모를 실패했습니다. : " + billingResult.getResponseCode());
}
}
};
ConsumeParams consumeParams = ConsumeParams.newBuilder()
.setPurchaseToken(purchaseInfo.purchaseToken).build();
billingClient.consumeAsync(consumeParams, consumeListener);
} else {
System.out.println("결제를 실패했습니다. : " + billingResult.getResponseCode());
Bundle bundleFail = new Bundle();
firebaseAnalytics.logEvent("challenge_fail", bundleFail);
Toast.makeText(getApplicationContext(), getString(R.string.ERROR_PURCHASING), Toast.LENGTH_LONG).show();
}
purchaseInfo.uploadInfo();
}
finish();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnBack :
Bundle bundleClose = new Bundle();
firebaseAnalytics.logEvent("challenge_close", bundleClose);
finish();
break;
case R.id.interview_fold_1 :
if(!interviewClicked1) {
interviewClicked1 = true;
interview1.setText(getResources().getString(R.string.INTERVIEW_1_DETAIL));
interviewFold1.setImageResource(R.drawable.fold_up_red);
} else {
interviewClicked1 = false;
interview1.setText(getResources().getString(R.string.INTERVIEW_1_SUMMARY));
interviewFold1.setImageResource(R.drawable.fold_down_red);
}
break;
case R.id.interview_fold_2 :
if(!interviewClicked2) {
interviewClicked2 = true;
interview2.setText(getResources().getString(R.string.INTERVIEW_2_DETAIL));
interviewFold2.setImageResource(R.drawable.fold_up_red);
} else {
interviewClicked2 = false;
interview2.setText(getResources().getString(R.string.INTERVIEW_2_SUMMARY));
interviewFold2.setImageResource(R.drawable.fold_down_red);
}
break;
case R.id.interview_fold_3 :
if(!interviewClicked3) {
interviewClicked3 = true;
interview3.setText(getResources().getString(R.string.INTERVIEW_3_DETAIL));
interviewFold3.setImageResource(R.drawable.fold_up_red);
} else {
interviewClicked3 = false;
interview3.setText(getResources().getString(R.string.INTERVIEW_3_SUMMARY));
interviewFold3.setImageResource(R.drawable.fold_down_red);
}
break;
case R.id.btnChallenge :
btnChallenge.setEnabled(false);
BillingFlowParams flowParams = BillingFlowParams.newBuilder().setSkuDetails(skuDetails).build();
billingClient.launchBillingFlow(this, flowParams);
break;
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
Bundle bundleClose = new Bundle();
firebaseAnalytics.logEvent("challenge_close", bundleClose);
finish();
}
}
|
package com.flushoutsolutions.foheart.globals;
/**
* Created by Manuel on 18/08/2014.
*/
public class Config {
public static String app_id = "";
public static int user_id;
public static int user_pass;
public static final String rest_auth= "";
public static final String rest_apps = "";
}
|
package no.nav.vedtak.felles.integrasjon.organisasjon;
public interface OrgInfo {
OrganisasjonEReg hentOrganisasjon(String orgnummer);
<T> T hentOrganisasjon(String orgnummer, Class<T> clazz);
String hentOrganisasjonNavn(String orgnummer);
JuridiskEnhetVirksomheter hentOrganisasjonHistorikk(String orgnummer);
}
|
package com.ut.module_msg;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.ut.base.BaseActivity;
import com.ut.base.UIUtils.RouterUtil;
import com.ut.module_msg.databinding.ActivityApplyMessageInfoBinding;
import com.ut.database.entity.ApplyMessage;
import com.ut.module_msg.viewmodel.ApplyMessageVm;
/**
* author : chenjiajun
* time : 2018/12/3
* desc :
*/
@Route(path = RouterUtil.MsgModulePath.APPLY_INFO)
public class ApplyMessageInfoActivity extends BaseActivity {
private static final int REQUEST_CODE_SEND_KEY = 2000;
private ActivityApplyMessageInfoBinding mBinding = null;
private ApplyMessage mApplyMessage = null;
private ApplyMessageVm applyMessageVm;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBinding = DataBindingUtil.setContentView(this, R.layout.activity_apply_message_info);
initLightToolbar();
mApplyMessage = (ApplyMessage) getIntent().getSerializableExtra("applyMessage");
boolean hasDealt = getIntent().getBooleanExtra("hasDealt", false);
if (hasDealt) {
mBinding.btnLayout.setVisibility(View.GONE);
}
setTitle(mApplyMessage.getLockName());
mBinding.setApplyMessage(mApplyMessage);
applyMessageVm = ViewModelProviders.of(this).get(ApplyMessageVm.class);
mBinding.btnIgnoreApply.setOnClickListener(v -> applyMessageVm.ignoreApply(mApplyMessage.getId()));
mBinding.btnSendKey.setOnClickListener(v -> {
ARouter.getInstance().build(RouterUtil.BaseModulePath.SEND_KEY)
.withInt(RouterUtil.LockModuleExtraKey.EXTRA_LOCK_SENDKEY_RULER_TYPE, mApplyMessage.getRuleType())
.withString(RouterUtil.LockModuleExtraKey.EXTRA_LOCK_SENDKEY_MAC, mApplyMessage.getMac())
.withString(RouterUtil.LockModuleExtraKey.EXTRA_LOCK_SENDKEY_MOBILE, mApplyMessage.getMobile())
.withBoolean(RouterUtil.LockModuleExtraKey.EXTRA_CANT_EDIT_PHONE, true)
.navigation(ApplyMessageInfoActivity.this, REQUEST_CODE_SEND_KEY);
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_SEND_KEY) {
finish();
}
}
}
|
package lecturesharingproject.lecturesharing.controller;
import lecturesharingproject.lecturesharing.entity.Lecture;
import lecturesharingproject.lecturesharing.entity.Teacher;
import lecturesharingproject.lecturesharing.entity.University;
import lecturesharingproject.lecturesharing.entity.User;
import lecturesharingproject.lecturesharing.service.UniversityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/university")
@Slf4j
public class UniversityController {
@Autowired
private UniversityService universityService;
@CrossOrigin(origins = "http://localhost:4200")
@GetMapping
public List<University> getUniversity() {
return universityService.getAllUniversity();
}
@CrossOrigin(origins = "*")
@GetMapping(value = "/{id}")
public Optional<University> findUniversityById(@PathVariable int id) {
return universityService.getUniversity(id);
}
// @PostMapping
// public University insertUniversity(@RequestBody University university) {
// University newUniversity = new University(university.getId(), university.getName(), university.getAddress(), university.getPictureURL(), '');
// return universityService.insertUniversity(newUniversity);
// }
@CrossOrigin(origins = "*")
@GetMapping(value = "/{name}/users")
public List<User> findUniversityUsers(@PathVariable String name){
return universityService.findUniversityUsers(name);
}
@CrossOrigin(origins = "*")
@GetMapping(value = "/name/{name}")
public University findUniversityByName(@PathVariable String name){
return universityService.findUniversityByName(name);
}
@CrossOrigin(origins = "*")
@GetMapping(value = "/{name}/teachers")
public List<Teacher> findUniversityTeachers(@PathVariable String name){
return universityService.findUniversityTeachers(name);
}
@CrossOrigin(origins = "*")
@GetMapping(value = "/{name}/lectures")
public List<Lecture> findUniversityLectures(@PathVariable String name){
return universityService.findUniversityLectures(name);
}
@DeleteMapping(value = "/{id}")
public void deleteUniversity(@PathVariable int id) {
universityService.removeUniversity(id);
}
}
|
package com.qa.test;
import org.testng.annotations.Test;
import org.testng.annotations.Test;
import com.qa.core.Base;
public class Login extends Base {
@Test
public void TC001() {
browserSetup();
passSiteURL();
}
}
|
package be.odisee.se4.hetnest.dao;
import be.odisee.se4.hetnest.domain.Ingredient;
import org.springframework.data.repository.CrudRepository;
public interface IngredientRepository extends CrudRepository<Ingredient, Long> {
}
|
package com.sherchen.likewechatphotoviewer.ui;
import android.app.Application;
/**
* Created by dave on 2017/1/10.
*/
public class MyApplication extends Application{
}
|
package com.zhku.my21days.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.zhku.my21days.dao.TaskDAO;
import com.zhku.my21days.vo.Task;
import com.zhku.my21days.vo.TaskExample;
@Controller
@RequestMapping("/task")
public class TaskController {
@Resource
private TaskDAO taskDAO;
@RequestMapping("/getTask")
public void getTask(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/xml");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String userId=request.getParameter("userId");
TaskExample ex=new TaskExample();
com.zhku.my21days.vo.TaskExample.Criteria criteria=ex.createCriteria();
criteria.andUserIdEqualTo(userId);
List<Task> anylist= taskDAO.selectByExample(ex);
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
out.println("<?xml version='1.0' encoding='UTF-8'?>");
out.println("<tasklist>");
for (int i = 0; i <anylist.size(); i++) {
Task ay= (Task)anylist.get(i);
out.println("<task>");
out.print("<content>");
out.print(ay.getContent());
out.println("</content>");
out.print("<change>");
out.print(ay.getChangeSelf());
out.println("</change>");
out.print("<date1>");
out.print(ay.getDate1());
out.println("</date1>");
out.print("<time>");
out.print(ay.getTime());
out.println("</time>");
out.print("<onoff>");
out.print(ay.getOnoff());
out.println("</onoff>");
out.print("<alarm>");
out.print(ay.getAlarm());
out.println("</alarm>");
out.print("<dates>");
out.print(ay.getDates());
out.println("</dates>");
out.print("<status>");
out.print(ay.getStatus());
out.println("</status>");
out.print("<reward>");
out.print(ay.getReward());
out.println("</reward>");
out.print("<punishment>");
out.print(ay.getPunishment());
out.println("</punishment>");
out.print("<alarmnum>");
out.print(ay.getAlarmnum());
out.println("</alarmnum>");
out.print("<created>");
out.print(sdf.format(ay.getCreate()));
out.println("</created>");
out.println("</task>");
}
out.println("</tasklist>");
}
@RequestMapping("/saveTask")
public void saveOrUpdateTask(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
Task task=new Task();
TaskExample ex=new TaskExample();
com.zhku.my21days.vo.TaskExample.Criteria criteria=ex.createCriteria();
String flag=request.getParameter("flag");
if("true".equals(flag)){
int alarm=Integer.parseInt(request.getParameter("alarm"));
String change=request.getParameter("change");
String date1=request.getParameter("date1");
String time=request.getParameter("time");
int onoff=Integer.parseInt(request.getParameter("onoff"));
String reward=request.getParameter("reward");
String punishment=request.getParameter("punishment");
String content=request.getParameter("content");
task.setAlarm(alarm);
task.setChangeSelf(change);
task.setContent(content);
task.setDate1(date1);
task.setOnoff(onoff);
task.setPunishment(punishment);
task.setReward(reward);
task.setTime(time);
}
int taid=Integer.parseInt(request.getParameter("taid"));
String userId=request.getParameter("userId");
int alarmnum=Integer.parseInt(request.getParameter("alarmnum"));
int dates=Integer.parseInt(request.getParameter("dates"));
int status=Integer.parseInt(request.getParameter("status"));
task.setStatus(status);
task.setUserId(userId);
task.setDates(dates);
task.setAlarmnum(alarmnum);
if(taid==0){
taskDAO.insertSelective(task);
}else{
criteria.andUserIdEqualTo(userId);
criteria.andAlarmnumEqualTo(alarmnum);
taskDAO.updateByExampleSelective(task, ex);
}
}
@RequestMapping("/deleTask")
public void deleteTask(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String userId=request.getParameter("userId");
int alarmnum=Integer.parseInt(request.getParameter("alarmnum"));
TaskExample ex=new TaskExample();
com.zhku.my21days.vo.TaskExample.Criteria criteria=ex.createCriteria();
criteria.andAlarmnumEqualTo(alarmnum);
criteria.andUserIdEqualTo(userId);
taskDAO.deleteByExample(ex);
}
}
|
package chapter01;
/* Write a program that reads in two integers between 0 and 4294967295, stores them in int variables, and computes
and displays their unsigned sum, difference, product, quotient, and remainder. Do not convert them to long values.
*/
import java.util.Scanner;
public class ex07 {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Enter first integer: ");
short int1 = in.nextShort();
System.out.println("Enter second integer: ");
short int2 = in.nextShort();
System.out.println("Sum of integers: " + (Short.toUnsignedInt(int1) + Short.toUnsignedInt(int2)));
System.out.println("Difference between integers: " + (Short.toUnsignedInt(int1) - Short.toUnsignedInt(int2)));
System.out.println("Product of integers: " + (Short.toUnsignedInt(int1) * Short.toUnsignedInt(int2)));
System.out.println("Quotient of integers: " + (Short.toUnsignedInt(int1) / Short.toUnsignedInt(int2)));
System.out.println("Remainder of integers: " + (Short.toUnsignedInt(int1) % Short.toUnsignedInt(int2)));
}
}
|
import java.util.Scanner;
public class Histogram {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = Integer.parseInt(scan.nextLine());
double p1 = 0;
double p2 = 0;
double p3 = 0;
double p4 = 0;
double p5 = 0;
double p1res = 0;
double p2res = 0;
double p3res = 0;
double p4res = 0;
double p5res = 0;
for (int i = 0; i < n; i++) {
int number = Integer.parseInt(scan.nextLine());
if (number < 200) {
p1++;
} else if (number >= 200 && number <= 399) {
p2++;
} else if (number >= 400 && number <= 599) {
p3++;
} else if (number >= 600 && number <= 799) {
p4++;
} else {
p5++;
}
}
System.out.printf("%.2f%%%n", p1res = (p1 / n) * 100);
System.out.printf("%.2f%%%n", p2res = (p2 /n) * 100);
System.out.printf("%.2f%%%n", p3res = (p3 /n) * 100);
System.out.printf("%.2f%%%n", p4res = (p4 / n) * 100);
System.out.printf("%.2f%%%n", p5res = (p5 / n) * 100);
}
} |
package com.jgermaine.fyp.rest.service.impl;
import java.util.HashMap;
import java.util.List;
import javax.persistence.EntityExistsException;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.PersistenceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import com.jgermaine.fyp.rest.model.Report;
import com.jgermaine.fyp.rest.model.dao.ReportDao;
import com.jgermaine.fyp.rest.service.ReportService;
@Service
public class ReportServiceImpl implements ReportService {
@Autowired
private ReportDao reportDao;
public Report getReport() {
Report report = new Report();
report.setId(1);
report.setName("PotHole");
return report;
}
public void addReport(Report report) throws EntityExistsException, PersistenceException,
DataIntegrityViolationException, Exception {
reportDao.create(report);
}
public void removeReport(Report report) throws Exception {
reportDao.delete(report);
}
public List<Report> getReports(int index) throws Exception {
return reportDao.getAll(index);
}
public List<Report> getTodayReports(int index) throws Exception {
return reportDao.getTodaysReports(index);
}
public Report getReport(String name) throws NoResultException, NonUniqueResultException, Exception {
return reportDao.getByName(name);
}
public Report getReport(int id) throws NoResultException {
return reportDao.getById(id);
}
public void updateReport(Report report) throws Exception {
reportDao.update(report);
}
public List<Report> getReports(double lat, double lon) throws Exception {
return reportDao.getNearestReport(lat, lon);
}
public List<Report> getUnassignedNearReports(double lat, double lon) throws Exception {
return reportDao.getUnassignedNearestReport(lat, lon);
}
@Override
public Report getReportForEmp(String email) throws NoResultException, NonUniqueResultException, Exception {
return reportDao.getByEmployee(email);
}
@Override
public HashMap<String, Long> getReportStatistics() {
HashMap<String, Long> statMap = new HashMap<String, Long>();
statMap.put("report_today", reportDao.getTodayReportCount());
statMap.put("report_complete", reportDao.getCompleteReportCount());
statMap.put("report_incomplete", reportDao.getIncompleteReportCount());
return statMap;
}
public List<Report> getCompleteReports(int index) throws Exception {
return reportDao.getComplete(index);
}
public List<Report> getIncompleteReports(int index) throws Exception {
return reportDao.getIncomplete(index);
}
} |
package nightgames.skills;
import nightgames.characters.Character;
import nightgames.combat.Combat;
import nightgames.combat.Result;
import nightgames.stance.Mount;
import nightgames.stance.Stance;
public class CommandDown extends PlayerCommand {
@Override
public boolean usable(Combat c, Character target) {
return super.usable(c, target) && c.getStance().en == Stance.neutral;
}
public CommandDown(Character self) {
super("Force Down", self);
}
@Override
public String describe(Combat c) {
return "Command your opponent to lie down on the ground.";
}
@Override
public boolean resolve(Combat c, Character target) {
c.setStance(new Mount(getSelf(), target));
if (getSelf().human()) {
c.write(getSelf(), deal(c, 0, Result.normal, target));
} else {
c.write(getSelf(), receive(c, 0, Result.normal, target));
}
return true;
}
@Override
public Skill copy(Character user) {
return new CommandDown(user);
}
@Override
public Tactics type(Combat c) {
return Tactics.positioning;
}
@Override
public String deal(Combat c, int magnitude, Result modifier, Character target) {
return "Trembling under the weight of your command, " + target.name()
+ " lies down. You follow her down and mount her, facing her head.";
}
@Override
public String receive(Combat c, int magnitude, Result modifier, Character target) {
return "<<This should not be displayed, please inform The" + " Silver Bard: CommandDown-receive>>";
}
}
|
public class SubMatrixThread extends Thread {
GaussianElimination gaussianElimination;
int innerRow;
int row;
public SubMatrixThread(GaussianElimination gaussianElimination, int innerRow, int row) {
this.gaussianElimination = gaussianElimination;
this.innerRow = innerRow;
this.row = row;
}
@Override
public void run() {
double innerValue = gaussianElimination.GetMatrix()[innerRow][row];
for (int innerCol = row + 1; innerCol < gaussianElimination.getSize(); innerCol++) {
gaussianElimination.GetMatrix()[innerRow][innerCol] -= innerValue * gaussianElimination.GetMatrix()[row][innerCol];
}
gaussianElimination.GetSolutionVector()[innerRow] -= gaussianElimination.GetMatrix()[innerRow][row] * gaussianElimination.GetSolutionVector()[row];
gaussianElimination.GetMatrix()[innerRow][row] = 0.0;
}
} |
package com.Thrift_Shop;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class AddToCart
*/
@WebServlet("/AddToCart")
public class AddToCart extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public AddToCart() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setAttribute("QuantityError", "");
int qty=0;
try{
qty = Integer.parseInt(request.getParameter("qty"));
}catch(NumberFormatException e) {
request.setAttribute("QuantityError", "Quantity cannot be zero");
request.getRequestDispatcher("itemDetail.jsp").forward(request, response);
return;
}
if(qty<=0)
{
request.setAttribute("QuantityError", "Quantity cannot be zero");
request.getRequestDispatcher("itemDetail.jsp").forward(request, response);
return;
}
System.out.println("User Entered quantity: "+qty+" for buying.");
HttpSession session = request.getSession();
session.setAttribute("incaseofbuynowQuantity",qty);
int b_id=(int)session.getAttribute("uid");
int i_id=(int)session.getAttribute("viewable_iid");
System.out.println("Now adding to cart" + i_id);
try
{
Connection con=DatabaseConnection.initializeDatabase();
PreparedStatement st=con.prepareStatement("SELECT @result1");
try {
st.executeQuery();
} catch (Exception e) {
System.out.println("Exception Caught at Line 69 of AddToCart.java");
}
st=con.prepareStatement("call addtocart(?,?,?,@result1)");
st.setInt(1,i_id);
st.setInt(2,qty);
st.setInt(3,b_id);
try {
st.executeQuery();
} catch (Exception e) {
System.out.println("Exception Caught at Line 79 of AddToCart.java");
System.out.println(st);
System.out.println();
e.printStackTrace();
}
st=con.prepareStatement("Select @result1 as Result");
ResultSet rs =null;
try {
rs=st.executeQuery();
} catch (Exception e) {
System.out.println("Exception Caught at Line 77 of AddToCart.java ");
e.printStackTrace();
return;
}
try {
rs.next();
} catch (Exception e) {
System.out.println("Exception Caught at Line 85 of AddToCart.java ");
e.printStackTrace();
return;
}
int flag1=rs.getInt("Result");
if(flag1==10)
{
request.setAttribute("QuantityError", "Stock insufficient!!!");
request.getRequestDispatcher("itemDetail.jsp").forward(request, response);
return;
}
else
{
request.getRequestDispatcher("Profile.jsp").forward(request, response);
return;
}
}
catch(Exception e)
{
e.printStackTrace();
}
doGet(request, response);
}
}
|
package com.example.smklabusta.Api;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class LoginRetrofit {
public static Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.100.6/SMK_LABUSTA/index.php/ApiLogin/")
.addConverterFactory(GsonConverterFactory.create())
.build();
public static com.example.smklabusta.Api.APIservice service =
retrofit.create(com.example.smklabusta.Api.APIservice.class);
}
|
package com.jd.jarvisdemonim.ui.testadapteractivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.jd.jarvisdemonim.R;
import com.jd.jarvisdemonim.binder.BinderPool;
import com.jd.jarvisdemonim.binder.ITestBinder1;
import com.jd.jarvisdemonim.binder.ITestBinder2;
import com.jd.jarvisdemonim.service.BinderPoolService;
import com.jd.jdkit.elementkit.activity.DBaseActivity;
import com.jd.jdkit.elementkit.utils.log.LogUtils;
import butterknife.Bind;
import static com.jd.jarvisdemonim.binder.BinderPool.BINDER_CODE_TEST1;
import static com.jd.jarvisdemonim.binder.BinderPool.BINDER_CODE_TEST2;
/**
* Auther: Jarvis Dong
* Time: on 2017/3/15 0015
* Name:
* OverView: 一个binder连接池,实现多个aidl接口和一个binder连接池,转换为需要的binder对象,然后与服务绑定;
* Usage: 实现功能是可以优化一个aidl接口产生一个binder,连接一个service,因service占有系统资源,不能大量创建,
* 故使用binder连接池可创建多个aidl接口连接一个service;
*/
public class NormalTestBinderPoolActivity extends DBaseActivity {
@Bind(R.id.btn_one)
Button btnOne;
@Bind(R.id.btn_two)
Button btnTwo;
@Bind(R.id.txt_content)
TextView txtContent;
BinderPool mBinderPool;
String str = "content";
//子线程不能更改UI;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
txtContent.setText((String) msg.obj);
break;
}
}
};
@Override
public int getContentViewId() {
return R.layout.activity_binderpool;
}
@Override
protected void initView(Bundle savedInstanceState) {
}
@Override
protected void initVariable() {
}
@Override
protected void processLogic(Bundle savedInstanceState) {
btnOne.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
oneAIDL();
}
}).start();
}
});
btnTwo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
twoAIDL();
}
}).start();
}
});
}
public void oneAIDL() {
mBinderPool = BinderPool.getInstance(mContext, BinderPoolService.class);
if (mBinderPool != null) {
LogUtils.e("content", "11111111111111111111111");
IBinder iBinder = mBinderPool.queryBinderMethod(BINDER_CODE_TEST1);//获取需要的binder;
ITestBinder1 iTestBinderPool1 = (ITestBinder1) ITestBinder1.asInterface(iBinder);//获取需要的aidl接口;
StringBuilder sb = new StringBuilder();
sb.append("原来的字符串:" + str + "\n");
try {
String s = iTestBinderPool1.addFunc(str);
sb.append("运行第一个aidl接口方法一的返回值:" + s + "\n");
String s1 = iTestBinderPool1.delFunc(s);
sb.append("运行第一个aidl接口方法二的返回值:" + s1 + "\n");
} catch (RemoteException e) {
e.printStackTrace();
}
handler.obtainMessage(0, sb.toString()).sendToTarget();
LogUtils.e("content", "11111111111111111111111" + sb.toString());
}
}
public void twoAIDL() {
mBinderPool = BinderPool.getInstance(mContext, BinderPoolService.class);
if (mBinderPool != null) {
LogUtils.e("content", "11111111111111111111111");
IBinder iBinder = mBinderPool.queryBinderMethod(BINDER_CODE_TEST2);
ITestBinder2 iTestBinderPool2 = (ITestBinder2) ITestBinder2.asInterface(iBinder);
StringBuilder sb = new StringBuilder();
int a = 2;
int b = 4;
sb.append("原来的字符串:" + a + "/" + b + "\n");
try {
int add = iTestBinderPool2.add(a, b);
sb.append("运行第二个aidl接口方法的返回值:" + add + "\n");
} catch (RemoteException e) {
e.printStackTrace();
}
handler.obtainMessage(0, sb.toString()).sendToTarget();
LogUtils.e("content", "11111111111111111111111" + sb.toString());
}
}
}
|
package com.example.consultants.week4daily2.model.data.remote;
import com.example.consultants.week4daily2.model.githubresponse.GithubResponse;
import com.example.consultants.week4daily2.model.githubresponse.RepoResponse;
import java.util.List;
import io.reactivex.Observable;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
public interface RemoteService {
// using the call object
@GET("users/{user}")
Call<GithubResponse> getUserInfo(@Path("user") String login);
// using the rxjava observable
@GET("users/{user}/repos")
Observable<List<RepoResponse>> getRepositoriesObs(@Path("user") String login);
}
|
package Arrays;
public class NthBiggest {
public static void main(String[] args) {
ArrayOperation ao = ArrayOperation.getInstance();
int[] a = ao.readElement();
System.out.println("Entered array elements are: ");
ao.dispArr(a);
int biggest = ao.nthBiggest(a, 3);
System.out.println("3rd biggest element is: "+biggest);
}
}
|
package com.github.iam20.device.model;
public class TempHumidBuilder {
private TempHumid tempHumid;
public TempHumidBuilder() {
tempHumid = new TempHumid();
}
public TempHumidBuilder celcius(double value) {
tempHumid.setCelsius(value);
return this;
}
public TempHumidBuilder humid(double value) {
tempHumid.setHumid(value);
return this;
}
public TempHumid build() {
return tempHumid;
}
}
|
package com.lenovohit.ssm.base.utils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.lenovohit.core.exception.BaseException;
import com.lenovohit.core.manager.GenericManager;
import com.lenovohit.core.utils.SpringUtils;
import com.lenovohit.ssm.base.model.Sequence;
public class SequenceUtils {
private static SequenceUtils _instance = new SequenceUtils();
private static final int KEY_POOL_SIZE = 10; //Sequence值缓存大小
private Map<String, Sequence> seqKeyMap; //Sequence载体容器
private GenericManager<Sequence, String> sequenceManager;
@SuppressWarnings("unchecked")
private void init() {
seqKeyMap = new HashMap<String, Sequence>();
sequenceManager = (GenericManager<Sequence, String>)SpringUtils.getBean("sequenceManager");
List<Sequence> sl = this.sequenceManager.findAll();
for(Sequence sequence : sl){
sequence.setNextValue(sequence.getSeqValue());
seqKeyMap.put(sequence.getSeqKey(), sequence);
}
}
/**
* 禁止外部实例化
*/
private SequenceUtils() {
}
/**
* 获取SequenceUtils的单例对象
* @return SequenceUtils的单例对象
*/
public static SequenceUtils getInstance() {
return _instance;
}
//
// /**
// * Mysql 使用
// * 获取下一个 Sequence键值
// * @param seqKey Sequence名称
// * @return 下一个Sequence键值
// */
// public synchronized long getNextValue(String seqKey) {
// Sequence sequence = null;
// Long _seqValue = null;
// if(null == seqKeyMap || null == sequenceManager) {
// init();
// }
// if (seqKeyMap.containsKey(seqKey)) {
// sequence = seqKeyMap.get(seqKey);
// } else {
// sequence = new Sequence(seqKey, KEY_POOL_SIZE);
// this.sequenceManager.save(sequence);
// seqKeyMap.put(seqKey, sequence);
// }
// _seqValue = sequence.getNextSeqValue();
//
// if(_seqValue > sequence.getSeqValue()){
// sequence.setSeqValue(sequence.getSeqValue() + KEY_POOL_SIZE);
// this.sequenceManager.save(sequence);
// }
//
// return _seqValue;
// }
/**
* Oracle 使用
* 获取下一个 Sequence键值
* @param seqKey Sequence名称
* @return 下一个Sequence键值
*/
public synchronized long getNextValue(String seqKey) {
Sequence sequence = null;
String _sequence = null;
if(null == seqKeyMap || null == sequenceManager) {
init();
}
if (seqKeyMap.containsKey(seqKey)) {
sequence = seqKeyMap.get(seqKey);
} else {
throw new BaseException("未找到对应Sequence!");
}
String sql = "SELECT " + sequence.getSeqCode() +".NEXTVAL FROM DUAL";
List<?> list = (List<?>) this.sequenceManager.findBySql(sql);
if (list != null && list.size() > 0) {
_sequence = list.get(0) + "";
}
return Long.valueOf(_sequence);
}
} |
package com.github.bot.curiosone.core.nlp.tokenizer.interfaces;
import com.github.bot.curiosone.core.nlp.tokenizer.LexType;
import com.github.bot.curiosone.core.nlp.tokenizer.PosType;
import edu.mit.jwi.item.IWordID;
import java.util.List;
import java.util.Map;
/**
* Syntact/Semantic attribute of a word.
*
* @author Andrea Rivitto && Eugenio Schintu
* @see https://projects.csail.mit.edu/jwi/api/index.html
*/
public interface IWord {
/**
* Get pos.
*
* @see Word#getPos()
*/
PosType getPos();
/**
* Get lexType.
*
* @see Word#getLexType()
*/
LexType getLexType();
/**
* Get lemma.
*
* @see Word#getLemma()
*/
String getLemma();
/**
* Get WordID.
*
* @see IWordID()
*/
IWordID getWordId();
/**
* Get gloss.
*
* @see Word#getGloss()
*/
String getGloss();
/**
* Get number of occurence.
*
*/
int getNum();
/**
* Get relations.
*
* @see Word#getRelations()
*/
Map<String, List<String>> getRelations();
/**
* Get relations by PointerT.
*
* @see Word#getRelationsByPointerT()
*/
List<String> getRelationsByPointer(String pointer);
/**
* Set a new {@link #wordId} value that is provided in input.
*
* @see #wordId
*/
void setWordId(IWordID wordId);
/**
* Set a new {@link #pos} value that is provided in input.
*
* @see #pos
*/
void setPos(PosType pos);
/**
* Set a new {@link #lexType} value that is provided in input.
*
* @see #lexType
*/
void setLexType(LexType lexType);
/**
* Set a new {@link #lemma} value that is provided in input.
*
* @see #lemma
*/
void setLemma(String lemma);
/**
* Set a new {@link #gloss} value that is provided in input.
*
* @see #gloss
*/
void setGloss(String gloss);
/**
* Set the number of occurrence of word.
*
*/
void setNum(int num);
/**
* Add a new element to relations.
*
* @see #relations
*/
void addRelation(String p, String value);
/**
* Set the map of relations.
*
* @see #relations
*/
void setRelations(Map<String, List<String>> relations);
}
|
package com.vti.backent;
import java.util.Scanner;
public class Exercise_1 {
public void question_1() {
System.out.println("Question 1:");
float luong1;
float luong2;
luong1 = (float) 5240.5;
luong2 = (float) 10970.055;
System.out.println("Lương Account 1: "+luong1+" Và Lương Account 2: "+luong2);
int soluong1;
int soluong2;
soluong1 = (int) luong1;
soluong2 = (int) luong2;
System.out.println("Lương Account 1 kiểu INT: "+soluong1+ " Và Lương Account 2 kiểu INT: "+soluong2);
}
public void question_2() {
System.out.println("Question 2:");
int min = 0;
int max = 99999;
int sorandom = (int) (Math.random() * max)+min;
System.out.println("Số ngẫu nhiên có 5 chữ số: "+sorandom);
}
public void question_3() {
System.out.println("Question 3:");
int min = 0;
int max = 99999;
int sorandom = (int) (Math.random() * max)+min;
String soduoi = String.valueOf(sorandom);
System.out.println("2 số cuối của số ngẫu nhiên có 5 chữ số:" + soduoi.substring(3));
}
public void question_4() {
int a;
int b;
Scanner sc = new Scanner(System.in);
System.out.println("Mời nhập số a: ");
a = sc.nextInt();
System.out.println("Mời nhập số b: ");
b = sc.nextInt();
System.out.println("Thương của a/b: "+ (float)a / (float) b);
sc.close();
}
}
|
import java.util.*;
public class HashUnique
{
public static void main()
{
Scanner sc=new Scanner(System.in);
HashMap<Integer,Boolean> map=new HashMap<>();
int n=sc.nextInt();
int c=n;
ArrayList<Integer> arr=new ArrayList<>();
while(c!=0)
{
arr.add(c%10);
c/=10;
}
for(int i=0;i<arr.size();i++)
{
if(map.containsKey(arr.get(i)))
{
System.out.println("Not a unique number");
return;
}
map.put(arr.get(i),true);
}
System.out.println("It is a unique number");
}
}
|
package egovframework.com.file.excel.download;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.servlet.view.document.AbstractExcelView;
public class tutorExcelView extends AbstractExcelView{
private String nullValue(Object val)
{
if(val == null)
return "";
else
return val.toString();
}
@Override
protected void buildExcelDocument(Map model, HSSFWorkbook wb, HttpServletRequest request, HttpServletResponse response) throws Exception{
HSSFCell cell = null;
HSSFSheet sheet = wb.createSheet("tutor List");
sheet.setDefaultColumnWidth((short)12);
// put text in first cell
cell = getCell(sheet, 0, 0);
setText(cell, "tutor List");
Map<String, Object> map = (Map)model.get("tutorMap");
List<Object> list = (List)map.get("list");
int index = 0;
// set header information
setText(getCell(sheet, 1, index++), "No");
setText(getCell(sheet, 1, index++), "강사명");
setText(getCell(sheet, 1, index++), "아이디");
setText(getCell(sheet, 1, index++), "조직");
setText(getCell(sheet, 1, index++), "연락처");
setText(getCell(sheet, 1, index++), "은행");
setText(getCell(sheet, 1, index++), "계좌번호");
setText(getCell(sheet, 1, index++), "강사권한");
setText(getCell(sheet, 1, index++), "강사기간 - 시작일");
setText(getCell(sheet, 1, index++), "강사기간 - 종료일");
for( int i=0; i<list.size(); i++ ){
Map mp = (Map)list.get(i);
index = 0;
cell = getCell(sheet, 2+i, index++);
setText(cell, (i+1)+"");
cell = getCell(sheet, 2+i, index++);
setText(cell, this.nullValue(mp.get("name")));
cell = getCell(sheet, 2+i, index++);
setText(cell, this.nullValue(mp.get("userid")));
cell = getCell(sheet, 2+i, index++);
setText(cell, this.nullValue(mp.get("positionNm")));
cell = getCell(sheet, 2+i, index++);
setText(cell, this.nullValue(mp.get("handphone")));
cell = getCell(sheet, 2+i, index++);
setText(cell, this.nullValue(mp.get("banknm")));
cell = getCell(sheet, 2+i, index++);
setText(cell, this.nullValue(mp.get("account")));
cell = getCell(sheet, 2+i, index++);
setText(cell, this.nullValue(mp.get("ismanager")));
cell = getCell(sheet, 2+i, index++);
setText(cell, this.nullValue(mp.get("fmon")));
cell = getCell(sheet, 2+i, index++);
setText(cell, this.nullValue(mp.get("tmon")));
}
}
}
|
package eu.bittrade.steem.steemstats.dao;
import java.io.Serializable;
/**
* @author <a href="http://steemit.com/@dez1337">dez1337</a>
*/
public interface RecordDao<T, I extends Serializable> extends GenericDao<T, I> {
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.