text stringlengths 10 2.72M |
|---|
package com.mitelcel.pack.bean.api.request;
import com.google.gson.Gson;
import com.google.gson.annotations.Expose;
import com.mitelcel.pack.bean.GenericBean;
/**
* Created by sudhanshu.thanedar on 10/26/2015.
*/
public abstract class BeanGenericApi extends GenericBean {
@Expose
protected long id;
@Expose
protected String method;
@Override
public String toString() {
return new Gson().toJson(this);
}
}
|
package com.zzlz13.zmusic.adapter;
import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.transition.ChangeBounds;
import android.transition.ChangeImageTransform;
import android.transition.TransitionSet;
import android.util.Pair;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import com.bumptech.glide.Glide;
import com.zzlz13.zmusic.R;
import com.zzlz13.zmusic.ZMusicApp;
import com.zzlz13.zmusic.activity.AlbumPlusArtistActivity;
import com.zzlz13.zmusic.activity.BaseActivity;
import com.zzlz13.zmusic.adapter.holder.SongsViewHolder;
import com.zzlz13.zmusic.bean.Artist;
import com.zzlz13.zmusic.bean.EbArtists;
import java.util.ArrayList;
/**
* Created by hjr on 2016/5/12.
*/
public class LocalMusicToArtistsAdapter extends RecyclerView.Adapter{
private EbArtists mEbArtists;
private Context mContext;
public LocalMusicToArtistsAdapter(Context mContext) {
this.mContext = mContext;
}
public void setData(EbArtists artists){
if (artists == null) return;
this.mEbArtists = artists;
notifyDataSetChanged();
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new SongsViewHolder(View.inflate(mContext, R.layout.item_local_music_songs,null));
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final SongsViewHolder svh = (SongsViewHolder) holder;
ArrayList<Artist> artists = mEbArtists.mArtist;
if (artists == null || artists.size() == 0 || artists.size() < position) return;
Artist artist = artists.get(position);
svh.tvTitle.setText(artist.artist);
svh.tvArtist.setText(artist.mSongs.size()+" songs");
String iconPath = artist.coverPath;
Glide
.with(mContext)
.load(iconPath)
.error(R.mipmap.ic_item_default)
.placeholder(R.mipmap.ic_item_default)
.fitCenter()
// .skipMemoryCache(true)
.into(svh.ivHead);
svh.itemView.setTag(svh);
svh.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SongsViewHolder svh = (SongsViewHolder) v.getTag();
BaseActivity mActivity = (BaseActivity) mContext;
((ZMusicApp) (mActivity).getApplication()).mArtist = mEbArtists.mArtist.get(position);
Window window = mActivity.getWindow();
TransitionSet transitionSet = new TransitionSet();
transitionSet.addTransition(new ChangeImageTransform());
transitionSet.addTransition(new ChangeBounds());
transitionSet.setDuration(300);
window.setSharedElementEnterTransition(transitionSet);
window.setSharedElementExitTransition(null);
Intent intent = new Intent(mActivity, AlbumPlusArtistActivity.class);
intent.putExtra(AlbumPlusArtistActivity.DISPLAY_TYPE,AlbumPlusArtistActivity.TYPE_ARTIST);
Pair<View,String> image = Pair.create((View)svh.ivHead,"Cover");
ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(mActivity,image);
mActivity.startActivity(intent, options.toBundle());
}
});
}
@Override
public int getItemCount() {
if (mEbArtists == null) return 0;
if (mEbArtists.mArtist == null) return 0;
return mEbArtists.mArtist.size();
}
}
|
package com.prism.Product_Finder;
import java.util.HashMap;
/**
* Created by hadoop on 2017. 6. 15..
*/
public class Shop_AddressTable {
public static HashMap<String, String> Map_ShopAddress = new HashMap<String, String>();
}
|
package com.rastiehaiev.notebook.service;
/**
* @author Roman Rastiehaiev
* Created on 14.10.15.
*/
public interface ISystemService {
void justLog();
}
|
package app.commands;
import app.ConsoleManager;
import app.FileProperties;
import app.ZipFileManager;
import app.exceptions.PathIsNotFoundException;
import java.util.List;
public class ZipContentCommand extends ZipCommand {
@Override
public void execute() throws Exception {
try {
ConsoleManager.writeMessage("Looking through the archive content");
ZipFileManager zipFileManager = getZipFileManager();
List<FileProperties> pathList = zipFileManager.getFilesList();
ConsoleManager.writeMessage("Archive content: ");
for (FileProperties p : pathList) {
ConsoleManager.writeMessage(p.toString());
}
} catch (PathIsNotFoundException e) {
ConsoleManager.writeMessage("Path doesn't exist");
}
}
}
|
package com.cs4125.bookingapp.services;
import com.cs4125.bookingapp.model.UserFactory;
import com.cs4125.bookingapp.model.entities.User;
import com.cs4125.bookingapp.services.interceptor.Target;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cs4125.bookingapp.model.repositories.UserRepository;
@Service
public class UserServiceImpl implements UserService, Target {
private final UserRepository userRepository;
private final UserFactory userFactory;
private EncryptionService encryptor = new EncryptionServiceImpl();
@Autowired
public UserServiceImpl(UserRepository userRepository, UserFactory userFactory) {
this.userRepository = userRepository;
this.userFactory = userFactory;
}
@Override
public String execute(String request) {
String result = "";
String str[] = request.split(",");
User u;
switch(str[0]) {
case("register"):
u = userFactory.getUser("NORMAL_USER", str[1], str[2], str[3]);
result = register(u);
break;
case("login"):
result = login(str[1], str[2]);
break;
default:
return "FAILURE: 1";
}
return result;
}
/**
* Registers the user
* @param u User to be registered
* @return SUCCESS: userid if registration was successful, else FAILURE: error code
*/
@Override
public String register(User u) {
if(u == null) {
return "FAILURE: 1";
}
if (userRepository.existsByUsername(u.getUsername())) {
return "FAILURE: 2";
}
u.setUsername(u.getUsername().toLowerCase());
u.setPassword(encryptor.encryptString(u.getPassword()));
User resUser = userRepository.save(u);
return "SUCCESS: " + resUser.getUser_id();
}
/**
* Logs in the user
* @param name username or email
* @param password The password
* @return SUCCESS: userid if login was successful, else FAILURE: error code
*/
@Override
public String login(String name, String password) {
// Provided name could be the username or email
name = name.toLowerCase();
if(!userRepository.existsByUsernameOrEmail(name, name)) {
return "FAILURE: 1";
}
User resUser = userRepository.findByUsernameAndPassword(name, encryptor.encryptString(password));
if(resUser == null) {
return "FAILURE: 2";
}
return "SUCCESS: " + resUser.getUser_id();
}
}
|
package com.linkedbook.service;
import java.util.List;
import com.linkedbook.dto.chat.createChatRoom.CreateChatRoomInput;
import com.linkedbook.dto.chat.selectChatRoom.SelectChatRoomInput;
import com.linkedbook.dto.chat.selectChatRoom.SelectChatRoomOutput;
import com.linkedbook.entity.ChatRoomDB;
import com.linkedbook.response.Response;
public interface ChatRoomService {
Response<List<SelectChatRoomOutput>> findAllRoom(SelectChatRoomInput selectChatRoomInput);
Response<ChatRoomDB> findByRoomId(String id);
Response<ChatRoomDB> createChatRoom(CreateChatRoomInput createChatRoomInput);
void setUserEnterInfo(String sessionId, String roomId);
String getUserEnterRoomId(String sessionId);
void removeUserEnterInfo(String sessionId);
}
|
package xyz.ashioto.ashioto;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatRadioButton;
import android.support.v7.widget.AppCompatTextView;
import android.widget.RadioGroup;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import app.akexorcist.bluetotohspp.library.BluetoothSPP;
import app.akexorcist.bluetotohspp.library.BluetoothState;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit.Call;
import retrofit.Callback;
import retrofit.Response;
import retrofit.Retrofit;
import xyz.ashioto.ashioto.retrofitClasses.CountUpdateResponse;
public class BluetoothActivity extends AppCompatActivity {
//BluetoothSPP setup
BluetoothSPP spp = new BluetoothSPP(BluetoothActivity.this);
//ProgressDialog
ProgressDialog progressDialog;
//TextView for count
@BindView(R.id.mainCount)
AppCompatTextView countTextView;
@BindView(R.id.gatesRadioGroup)
RadioGroup gatesRadioGroup;
SharedPreferences sharedPreferences;
SharedPreferences.Editor sharedPrefEditor;
Callback<CountUpdateResponse> countUpdateResponseCallback = new Callback<CountUpdateResponse>() {
@Override
public void onResponse(Response<CountUpdateResponse> response, Retrofit retrofit) {
if (!response.body().error) {
t("Data Synced");
} else {
t("Unable To Synced");
}
}
@Override
public void onFailure(Throwable t) {
t("Data Sync Failed");
}
};
//Connection listener to handle bluetooth related tasks
BluetoothSPP.BluetoothConnectionListener bluetoothConnectionListener = new BluetoothSPP.BluetoothConnectionListener() {
@Override
public void onDeviceConnected(String name, String address) {
//If connected successfully, dismiss ProgressDialog and give a toast to user
progressDialog.dismiss();
t("Connected");
}
@Override
public void onDeviceDisconnected() {
//If disconnected, finish activity and notify user
// TODO: 21/11/16 Give reconnection option
t("Disconnected");
finish();
}
@Override
public void onDeviceConnectionFailed() {
//If connection fails, finish activity and give a toast to the user
t("Connection Failed");
finish();
}
};
//DataReceive listener
BluetoothSPP.OnDataReceivedListener dataReceivedListener = new BluetoothSPP.OnDataReceivedListener() {
@Override
public void onDataReceived(byte[] data, String message) {
String count = message.substring(message.lastIndexOf('#') + 1, message.lastIndexOf('$')); //Get the subtring between # and $ (logic from old code)
countTextView.setText(count);
}
};
private String current_event;
//Device mac address
private String mDeviceAddress;
@OnClick(R.id.syncbutton)
void syncData() {
if (!current_event.equals("na")) {
HashMap<String, String> countHashmap = new HashMap<>();
countHashmap.put("count", countTextView.getText().toString());
countHashmap.put("gateID", String.valueOf(gatesRadioGroup.indexOfChild(findViewById(gatesRadioGroup.getCheckedRadioButtonId())) + 1));
countHashmap.put("eventCode", current_event);
Call<CountUpdateResponse> updateResponseCall = ApplicationClass.getRetrofitInterface().syncData(countHashmap);
updateResponseCall.enqueue(countUpdateResponseCallback);
} else {
t("No Event Set!");
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth);
ButterKnife.bind(this);
//Get device address to connect to
mDeviceAddress = getIntent().getStringExtra("device-address");
//Setup bluetooth service
spp.setupService();
spp.startService(BluetoothState.DEVICE_OTHER);
//ProgressDialog setup
progressDialog = new ProgressDialog(BluetoothActivity.this); //Assignment done here because doing it with declaration would crash the app
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setIndeterminate(true);
// TODO: 23/11/16 The spinner is not showing. Fix it.
progressDialog.setTitle("Connecting To Ashioto");
progressDialog.show();
}
@Override
protected void onStart() {
super.onStart();
//Set connection listener for bluetooth spp
spp.setBluetoothConnectionListener(bluetoothConnectionListener);
//Set data receiver for bluetooth spp
spp.setOnDataReceivedListener(dataReceivedListener);
//Sharepreferences
sharedPreferences = getSharedPreferences("sharedprefs", MODE_PRIVATE);
sharedPrefEditor = sharedPreferences.edit();
current_event = sharedPreferences.getString("current_event", "na");
setUpGates();
}
@Override
protected void onResume() {
super.onResume();
spp.connect(mDeviceAddress);
}
@Override
protected void onPause() {
super.onPause();
spp.disconnect();
}
//Easier toast
private void t(String message) {
Toast.makeText(BluetoothActivity.this, message, Toast.LENGTH_SHORT).show();
}
private void setUpGates() {
ArrayList<String> gateNames = getIntent().getStringArrayListExtra("event_gates");
for (String gate : gateNames) {
AppCompatRadioButton gateRadio = new AppCompatRadioButton(BluetoothActivity.this);
gateRadio.setText(gate);
gatesRadioGroup.addView(gateRadio);
}
}
}
|
package it.usi.xframe.xas.bfimpl.sms.providers.vodafonepop;
public class VodafoneException extends Exception
{
public VodafoneException(String message) {
super(message);
}
public VodafoneException(String message, Throwable throwable) {
super(message, throwable);
}
}
|
package com.hs.example.javaproxy.intercept;
public class MyInterceptor implements Interceptor{
@Override
public boolean before() {
System.out.println("before sayHello......");
return false;
}
@Override
public void after() {
System.out.println("after sayHello......");
}
}
|
package com.yunhe.billmanagement.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yunhe.billmanagement.entity.FinanceClassify;
import com.yunhe.billmanagement.entity.FinanceOrder;
import com.yunhe.billmanagement.service.IFinanceClassifyService;
import com.yunhe.billmanagement.service.IFinanceOrderService;
import com.yunhe.core.common.annotion.WebLog;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <p>
* 收支分类管理表(ymy) 前端控制器
* </p>
*
* @author 杨明月
* @since 2019-01-02
*/
@RestController
@RequestMapping("/billManagement/finance-classify")
public class FinanceClassifyController {
@Resource
IFinanceClassifyService financeClassifyService;
@Resource
IFinanceOrderService financeOrderService;
/**
* <P>
* 进入收支分类管理页面
* </P>
* @return 进入bill-FinanceClassify.html
*/
@WebLog("进入收支分类管理页面")
@RequestMapping("/toFc")
public ModelAndView toFc(){
return new ModelAndView("billmanagement/bill-FinanceClassify");
}
/**
* <P>
* 分页
* </P>
* @param current 当前页数
* @param size 每页条数
* @return 收支分类管理表:分页的结果集
*/
@WebLog("查看收支分类")
@RequestMapping(value = "/selectFcPage",method = RequestMethod.GET)
public Map selectFcPage(int current, int size, FinanceClassify financeClassify) {
return financeClassifyService.selectFcPage(current, size,financeClassify);
}
/**
* <P>
* 查询数据
* </P>
* @return 收支分类管理表:查询的结果集
*/
@WebLog("查询所有收支分类")
@RequestMapping(value = "/selectFc",method = RequestMethod.POST)
public List<FinanceClassify> selectFc() {
return financeClassifyService.selectFc();
}
/**
* <P>
* 通过条件查询数据
* </P>
* @param financeClassify 查询条件放在对象里
* @return 收支分类管理表:查询的结果集
*/
@WebLog("通过类别查看收支分类")
@RequestMapping(value = "/selectFcBySort",method = RequestMethod.POST)
public List<FinanceClassify> selectFcBySort(FinanceClassify financeClassify) {
return financeClassifyService.selectFcBySort(financeClassify);
}
/**
* <P>
* 进入增加页面
* </P>
* @return 进入bill-FC-add.html
*/
@WebLog("进入增加收支分类页面")
@RequestMapping("/toAdd")
public ModelAndView toAdd(){
return new ModelAndView("billmanagement/bill-FC-add");
}
/**
* <P>
* 增加数据
* </P>
* @param financeClassify 增加的参数放到一个对象
* @return 收支分类管理表:增加是否成功true or false
*/
@WebLog("增加收支分类")
@RequestMapping(value = "/insertFc",method = RequestMethod.GET)
public int insertFc(FinanceClassify financeClassify) {
return financeClassifyService.insertFc(financeClassify);
}
/**
* <P>
* 增加数据之前检查账目名是否已存在
* </P>
* @param financeClassify 查询条件
* @return
*/
@WebLog("增加数据之前检查收支分类是否存在")
@RequestMapping(value = "/checkFcExit",method = RequestMethod.GET)
public boolean checkFcExit(FinanceClassify financeClassify){
return financeClassifyService.checkFcExit(financeClassify);
}
/**
* <P>
* 进入修改页面
* </P>
* @param id 要修改的数据的id值
* @param session 要传到前端的值存在session
* @return 进入bill-FC-update.html
*/
@WebLog("进入收支分类修改页面")
@RequestMapping("/toUpdate")
public ModelAndView toUpdate(int id, HttpSession session){
FinanceClassify financeClassify = financeClassifyService.selectFcById(id);
session.setAttribute("financeClassify",financeClassify);
return new ModelAndView("billmanagement/bill-FC-update");
}
/**
* <P>
* 修改数据
* </P>
* @param financeClassify 修改的参数放到一个对象
* @return 收支分类管理表:修改是否成功true or false
*/
@WebLog("修改收支分类")
@RequestMapping(value = "/updateFc",method = RequestMethod.GET)
public int updateFc(FinanceClassify financeClassify) {
return financeClassifyService.updateFc(financeClassify);
}
/**
* <P>
* 删除数据
* </P>
* @param id 通过id删除
* @return 收支分类管理表:删除是否成功true or false
*/
@WebLog("删除收支分类")
@RequestMapping(value = "/deleteFc",method = RequestMethod.GET)
public int deleteFc(int id) {
int i =1;//1代表不能删,0代表可以删
List<FinanceOrder> list = financeOrderService.list(new QueryWrapper<FinanceOrder>().eq("fc_id", id));
if(list.size()>0){
i=1;
}else {
i=0;
financeClassifyService.deleteFc(id);
}
return i;
}
/**
* <P>
* Excel导出
* </P>
* @param response 响应
* @return Excel导出到本地
* @throws IOException
*/
@WebLog("Excel导出收支分类")
@RequestMapping("/export")
public String createExcel(HttpServletResponse response) throws IOException {
//获取查询结果的数据,只要对其进行封装就行了
List<FinanceClassify> newlist = financeClassifyService.selectFc();
//数据封装,这里的map之所以敢这样add是因为这里的add顺序和hql中的select字段顺序是一样的,总共就查询那么多字段
List<Map<String,Object>> solist = new ArrayList();
for(FinanceClassify obj:newlist){
//每次循环都要重新new一个map,表示不同对象
Map<String,Object> map = new HashMap();
map.put("id", obj.getId());
map.put("fcType",obj.getFcType());
map.put("fcSort",obj.getFcSort());
map.put("fcRemark",obj.getFcRemark());
solist.add(map);
}
//创建HSSFWorkbook对象(excel的文档对象)
HSSFWorkbook wb = new HSSFWorkbook();
//建立新的sheet对象(excel的表单)
HSSFSheet sheet=wb.createSheet("报表");
//在sheet里创建第一行,参数为行索引(excel的行),可以是0~65535之间的任何一个
HSSFRow row1=sheet.createRow(0);
//创建单元格(excel的单元格,参数为列索引,可以是0~255之间的任何一个
HSSFCell cell=row1.createCell(0);
// 1.生成字体对象
HSSFFont font = wb.createFont();
font.setFontHeightInPoints((short) 12);
font.setFontName("新宋体");
// 2.生成样式对象,这里的设置居中样式和版本有关,我用的poi用HSSFCellStyle.ALIGN_CENTER会报错,所以用下面的
HSSFCellStyle style = wb.createCellStyle();
//设置居中样式
/*style.setAlignment(HSSFCellStyle.ALIGN_CENTER);*/
// 调用字体样式对象
style.setFont(font);
style.setWrapText(true);
style.setAlignment(HorizontalAlignment.CENTER);//设置居中样式
// 3.单元格应用样式
cell.setCellStyle(style);
//设置单元格内容
cell.setCellValue("报表");
//合并单元格CellRangeAddress构造参数依次表示起始行,截至行,起始列, 截至列
sheet.addMergedRegion(new CellRangeAddress(0,0,0,9));
//在sheet里创建第二行
HSSFRow row2=sheet.createRow(1);
//创建单元格并设置单元格内容及样式
HSSFCell cell0=row2.createCell(0);
cell0.setCellStyle(style);
cell0.setCellValue("序号");
HSSFCell cell1=row2.createCell(1);
cell1.setCellStyle(style);
cell1.setCellValue("账目类型");
HSSFCell cell2=row2.createCell(2);
cell2.setCellStyle(style);
cell2.setCellValue("收支类别");
HSSFCell cell3=row2.createCell(3);
cell3.setCellStyle(style);
cell3.setCellValue("备注");
//单元格宽度自适应
sheet.autoSizeColumn((short)3);
sheet.autoSizeColumn((short)4);
sheet.autoSizeColumn((short)5);
sheet.autoSizeColumn((short)6);
sheet.autoSizeColumn((short)7);
sheet.autoSizeColumn((short)8);
sheet.autoSizeColumn((short)9);
//宽度自适应可自行选择自适应哪一行,这里写在前面的是适应第二行,写在后面的是适应第三行
for (int i = 0; i < solist.size(); i++) {
//单元格宽度自适应
sheet.autoSizeColumn((short)0);
sheet.autoSizeColumn((short)1);
sheet.autoSizeColumn((short)2);
//从sheet第三行开始填充数据
HSSFRow rowx=sheet.createRow(i+2);
Map<String,Object> map = solist.get(i);
//这里的hospitalid,idnumber等都是前面定义的全局变量
HSSFCell cell00=rowx.createCell(0);
cell00.setCellStyle(style);
cell00.setCellValue((Integer) map.get("id"));
HSSFCell cell01=rowx.createCell(1);
cell01.setCellStyle(style);
cell01.setCellValue((String) map.get("fcType"));
HSSFCell cell02=rowx.createCell(2);
cell02.setCellStyle(style);
cell02.setCellValue((String) map.get("fcSort"));
HSSFCell cell03=rowx.createCell(3);
cell03.setCellStyle(style);
cell03.setCellValue((String) map.get("fcRemark"));
}
//输出Excel文件
OutputStream output=response.getOutputStream();
response.reset();
//文件名这里可以改
response.setHeader("Content-disposition", "attachment; filename=finance_classify.xls");
response.setContentType("application/excel");
wb.write(output);
output.close();
return "SUCCESS";
}
}
|
package com.estrelladelsur.abstractclases;
public class Fixture {
private int ID_FIXTURE;
private int ID_EQUIPO_LOCAL;
private int ID_EQUIPO_VISITA;
private int ID_DIVISION;
private int ID_TORNEO;
private int ID_CANCHA;
private int ID_FECHA;
private int ID_ANIO;
private String DIA;
private String HORA;
private String NOMBRE_USUARIO;
private String FECHA_CREACION;
private String FECHA_ACTUALIZACION;
private String ESTADO;
private String TABLA;
public Fixture(int id, int id_equipo_local, int id_equipo_visita, int id_division, int id_torneo,int id_cancha, int id_fecha,int id_anio,String dia,String hora, String usuario,
String fechaCreacion, String fechaActualizacion, String estado,
String tabla) {
ID_FIXTURE = id;
ID_EQUIPO_LOCAL=id_equipo_local;
ID_EQUIPO_VISITA=id_equipo_visita;
ID_DIVISION=id_division;
ID_TORNEO=id_torneo;
ID_CANCHA=id_cancha;
ID_FECHA=id_fecha;
ID_ANIO=id_anio;
DIA = dia;
HORA = hora;
NOMBRE_USUARIO = usuario;
FECHA_CREACION = fechaCreacion;
FECHA_ACTUALIZACION = fechaActualizacion;
ESTADO = estado;
TABLA = "FIXTURE_ADEFUL";
}
public int getID_FIXTURE() {
return ID_FIXTURE;
}
public void setID_FIXTURE(int iD_FIXTURE) {
ID_FIXTURE = iD_FIXTURE;
}
public int getID_EQUIPO_LOCAL() {
return ID_EQUIPO_LOCAL;
}
public void setID_EQUIPO_LOCAL(int iD_EQUIPO_LOCAL) {
ID_EQUIPO_LOCAL = iD_EQUIPO_LOCAL;
}
public int getID_EQUIPO_VISITA() {
return ID_EQUIPO_VISITA;
}
public void setID_EQUIPO_VISITA(int iD_EQUIPO_VISITA) {
ID_EQUIPO_LOCAL = iD_EQUIPO_VISITA;
}
public int getID_DIVISION() {
return ID_DIVISION;
}
public void setID_DIVISION(int iD_DIVISION) {
ID_DIVISION = iD_DIVISION;
}
public int getID_TORNEO() {
return ID_TORNEO;
}
public void setID_TORNEO(int iD_TORNEO) {
ID_TORNEO = iD_TORNEO;
}
public int getID_CANCHA() {
return ID_CANCHA;
}
public void setID_CANCHA(int iD_CANCHA) {
ID_CANCHA = iD_CANCHA;
}
public int getID_FECHA() {
return ID_FECHA;
}
public void setID_FECHA(int iD_FECHA) {
ID_FECHA = iD_FECHA;
}
public int getID_ANIO() {
return ID_ANIO;
}
public void setID_ANIO(int iD_ANIO) {
ID_ANIO = iD_ANIO;
}
public String getDIA() {
return DIA;
}
public void setDIA(String dIA) {
DIA = dIA;
}
public String getHORA() {
return HORA;
}
public void setHORA(String hORA) {
HORA = hORA;
}
public String getNOMBRE_USUARIO() {
return NOMBRE_USUARIO;
}
public void setNOMBRE_USUARIO(String nOMBRE_USUARIO) {
NOMBRE_USUARIO = nOMBRE_USUARIO;
}
public String getFECHA_CREACION() {
return FECHA_CREACION;
}
public void setFECHA_CREACION(String fECHA_CREACION) {
FECHA_CREACION = fECHA_CREACION;
}
public String getFECHA_ACTUALIZACION() {
return FECHA_ACTUALIZACION;
}
public void setFECHA_ACTUALIZACION(String fECHA_ACTUALIZACION) {
FECHA_ACTUALIZACION = fECHA_ACTUALIZACION;
}
public String getESTADO() {
return ESTADO;
}
public void setESTADO(String eSTADO) {
ESTADO = eSTADO;
}
public String getTABLA() {
return TABLA;
}
public void setTABLA(String tABLA) {
TABLA = tABLA;
}
} |
public class Caramel extends CoffeeDecorator {
private double cost = .75;
Caramel(Coffee specialCoffee){
super(specialCoffee);
}
public double makeCoffee() {
return specialCoffee.makeCoffee() + addCaramel();
}
private double addCaramel() {
System.out.println(" + pump of caramel: $.75");
return cost;
}
}
|
package com.mylnz.byteland;
import com.mylnz.byteland.ifc.LandStructureUtilsIfc;
import java.util.*;
import java.util.stream.Collectors;
/**
* Created by mylnz on 14.11.2016.
* structure/restructure Utils
*/
public class LandStructureUtils implements LandStructureUtilsIfc {
public Map<Integer, Set<Integer>> getCityConnectionMap(List<Integer> roadConnectionList) {
Map<Integer, Set<Integer>> cityConnectedMap = getInitializedCityMap(roadConnectionList);
Integer i = 0;
for (Integer input : roadConnectionList) {
cityConnectedMap.get(input).add(++i);
}
return cityConnectedMap;
}
private Map<Integer, Set<Integer>> getInitializedCityMap(List<Integer> roadConnectionList) {
Map<Integer, Set<Integer>> initCityMap = new HashMap<>();
roadConnectionList.forEach(connectedCity -> initCityMap.put(connectedCity, new HashSet<>()));
return initCityMap;
}
public Set<Integer> getNodeSet(Map<Integer, Set<Integer>> cityConnectionMap) {
return cityConnectionMap.keySet();
}
private Set<Integer> getNodeSet(List<Integer> roadConnectionList) {
return roadConnectionList.stream().distinct().collect(Collectors.toSet());
}
public Set<Integer> getLeafCitySet(List<Integer> roadConnectionList) {
Set<Integer> nodeSet = getNodeSet(roadConnectionList);
Integer cityCount = roadConnectionList.size() + 1;
Set<Integer> leafCitySet = new HashSet<>();
for (int i = 0; i < cityCount; i++) {
if (!nodeSet.contains(i)) {
leafCitySet.add(i);
}
}
return leafCitySet;
}
public int getMaxLeafCount(Map<Integer, Set<Integer>> cityConnectedMap) {
final Long[] maxLeafCount = {0L};
Set<Integer> nodeSet = cityConnectedMap.keySet();
cityConnectedMap.forEach((node, connectedCitySet) -> {
final Long tempMaxLeafCount = connectedCitySet.stream().filter(val -> !nodeSet.contains(val)).count();
if (maxLeafCount[0] < tempMaxLeafCount) {
maxLeafCount[0] = tempMaxLeafCount;
}
});
return maxLeafCount[0].intValue() == 1 ? 0 : maxLeafCount[0].intValue();
}
}
|
package com.originalandtest.tx.downloaddemo.download;
import android.content.Context;
import android.os.Build;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class DownLoadTask implements Runnable {
private static final String TAG = "VideoDoanLoadTask";
private int mMediaType = MediaUitl.TYPE_VOICE;
public String mUrl;
long downloadPosition;
boolean mPauseRequired;
boolean mCancelRequired;
public HttpClient httpClient;
private Context mContext;
private static final int BUFFER = 4096;
private VideoLoadListener mListener;
public interface VideoLoadListener {
void onDownLoadSucceed(String filePath);
void onDownLoading(int progress);
void onDownLoadFailure();
void onDownloadPause();
void onDownloadCancel();
}
public DownLoadTask(VideoLoadListener listener, String url, Context context) {
this(listener, url, MediaUitl.TYPE_VOICE, context);
}
public DownLoadTask(VideoLoadListener listener, String url, int mediaType, Context context) {
mContext = context;
mListener = listener;
mUrl = url;
switch(mediaType){
case MediaUitl.TYPE_IMAGE:
case MediaUitl.TYPE_VOICE:
case MediaUitl.TYPE_DLOAD:
this.mMediaType = mediaType;
break;
default:
this.mMediaType = MediaUitl.TYPE_VOICE;
}
determineStatusAndProgress();
disableConnectionReuseIfNecessary();
}
private String getFilePath(){
String path = null;
switch(mMediaType){
case MediaUitl.TYPE_IMAGE:
path = MediaUitl.getNetworkVoicePath(mContext, mUrl);
break;
case MediaUitl.TYPE_VOICE:
path = MediaUitl.getAdPicturePath(mContext, mUrl);
break;
case MediaUitl.TYPE_DLOAD:
path = MediaUitl.getNetworkDownloadPath(mContext, mUrl);
break;
}
return path;
}
private void determineStatusAndProgress() {
File file = new File(getFilePath() + ".temp");
if (file.isFile() && file.exists()) {
downloadPosition = file.length();
} else {
file.getParentFile().mkdirs();
}
}
/*不过在Android 2.2版本之前, HttpURLConnection一直存在着一些令人厌烦的bug.
比如说对一个可读的InputStream调用close()方法时,就有可能会导致连接池失效了。
那么我们通常的解决办法就是直接禁用掉连接池的功能:*/
private void disableConnectionReuseIfNecessary() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
System.setProperty("http.keepAlive", "false");
}
}
@Override
public void run() {
FileOutputStream fos = null;
InputStream is = null;
HttpGet request = null;
try {
request = new HttpGet(mUrl);
request.setHeader("Connection", "keep-alive");
if (downloadPosition > 0) {
request.setHeader("Range", "bytes=" + downloadPosition + "-");
}
onStart();
HttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
if (null == entity) {
throw new IOException("entity is null");
}
is = entity.getContent();
if (null == is) {
throw new IOException("inputstream is null");
}
long length = entity.getContentLength();
if (Configuration.DEBUG_VERSION) {
Log.i(TAG, "content length is " + length);
}
fos = new FileOutputStream(getFilePath() + ".temp", true);
byte[] buffer = new byte[BUFFER];
int bytesRead = is.read(buffer);
//加一个控制的标识。 暂停,加入数据库 。
while (-1 != bytesRead) {
boolean pauseRequired = false;
boolean cancelRequired = false;
synchronized (this) {
pauseRequired = mPauseRequired;
cancelRequired = mCancelRequired;
}
if (!pauseRequired) {
fos.write(buffer, 0, bytesRead);
downloadPosition += bytesRead;
bytesRead = is.read(buffer);
} else {
if (cancelRequired) {
onCancel();
} else {
boolean complete = -1 == is.read();
if (complete) {
reameTo(mUrl);
onComplete();
} else {
onPause();
}
}
break;
}
if(mListener != null){
mListener.onDownLoading((int) ((100*downloadPosition)/length));
Log.e("taxi",(int) ((100*downloadPosition)/length)+"" );
}
}
//判断download file大小,如果下载成功,则成功。
Log.e("taxi", "1");
boolean pauseRequired = false;
boolean cancelRequired = false;
synchronized (this) {
pauseRequired = mPauseRequired;
cancelRequired = mCancelRequired;
}
if (!pauseRequired) {
if (cancelRequired) {
onCancel();
} else {
Log.e("taxi", "2");
//加完整性判断
onComplete();
Log.e("taxi", "3");
reameTo(mUrl);
Log.e("taxi", "4");
}
}
} catch (Exception e) {
if (Configuration.DEBUG_VERSION) {
e.printStackTrace();
}
onException();
} finally {
if (null != fos) {
try {
fos.close();
} catch (IOException e) {
}
}
if (null != request) {
request.abort();
}
if (null != is) {
try {
is.close();
is = null;
} catch (IOException e) {
}
}
}
}
private void onStart() {
}
private void onException() {
if (mListener != null) {
mListener.onDownLoadFailure();
downloadPosition = 0;
}
}
private void onCancel() {
if (mListener != null) {
// mListener.onDownLoadFailure();
mListener.onDownloadCancel();
}
}
private void onPause() {
if (mListener != null) {
mListener.onDownloadPause();
}
}
private void onComplete() {
if (mListener != null) {
Log.e("taxi", "finish---------------");
mListener.onDownLoadSucceed(getFilePath());
downloadPosition = 0;
}
}
private synchronized boolean reameTo(String url) {
final String targetPath = getFilePath();
final String tempPath = getFilePath() + ".temp";
File file = new File(tempPath);
if (file.exists()) {
return file.renameTo(new File(targetPath));
} else {
return false;
}
}
}
|
package io.netty.example.jdkSerialize.nettyExample;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
public class SubReqClientHandler extends ChannelHandlerAdapter {
public SubReqClientHandler() {
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
for (int i = 0; i < 10; i++) {
ctx.write(subReq(i));
}
ctx.flush();
}
private SubscribeReq subReq(int i){
SubscribeReq req = new SubscribeReq();
req.subReqId = i;
req.userName = "lanker";
req.productName = "netty";
req.phoneNumber = "18632165487";
req.address = "深圳市香港村";
return req;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
System.out.println("Receive server response :["+msg+"]");
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
cause.printStackTrace();
ctx.close();
}
}
|
package rainbowsort;
public class Solution {
}
|
package com.example.android.rangga_1202154227_studycase4;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void MHS(View view) {
Intent intent = new Intent(this,AsyncTaskActivity.class);
startActivity(intent);
}
public void GMB(View view) {
Intent intent = new Intent(this,CariGambarActivity.class);
startActivity(intent);
}
}
|
/*
* created 11.08.2006
*
* Copyright 2009, ByteRefinery
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* $Id$
*/
package com.byterefinery.rmbench.external.database.jdbc;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import com.byterefinery.rmbench.external.IMetaDataAccess;
import com.byterefinery.rmbench.external.model.IColumn;
import com.byterefinery.rmbench.external.model.IDataType;
/**
* this IMetaDataAccess implementation simply wraps the standard JDBC MetaData object. It can be
* used as a superclass by implementors who only wish to modify specific aspects of JDBC driver behavior
*
* @author cse
*/
public class JdbcMetaDataAdapter implements IMetaDataAccess {
public static final IMetaDataAccess.Factory FACTORY = new IMetaDataAccess.Factory() {
public IMetaDataAccess createMetaData(Connection connection, boolean option) throws SQLException {
return new JdbcMetaDataAdapter(connection.getMetaData());
}
};
protected final DatabaseMetaData metaData;
protected JdbcMetaDataAdapter(DatabaseMetaData metaData) {
this.metaData = metaData;
}
public ResultSet getSchemas() throws SQLException {
return new JdbcResultSetAdapter(metaData.getSchemas()) {
public String getString(int index) throws SQLException {
if(index == 2) {
try {
return super.getString(2);
}
catch(Exception x) {
return null; //non-3.0 driver will throw exception, we return null instead
}
}
else
return super.getString(index);
}
};
}
public ResultSet getTables(String catalogName, String schemaName, String[] types) throws SQLException {
return new JdbcResultSetAdapter(metaData.getTables(catalogName, schemaName, null, types));
}
public ResultSet getColumns(String catalogName, String schemaName, String tableName) throws SQLException {
return new JdbcResultSetAdapter(metaData.getColumns(catalogName, schemaName, tableName, null));
}
public ResultSet getPrimaryKeys(String catalogName, String schemaName, String tableName) throws SQLException {
return new JdbcResultSetAdapter(metaData.getPrimaryKeys(catalogName, schemaName, tableName));
}
public ResultSet getImportedKeys(String catalogName, String schemaName, String tableName) throws SQLException {
return new JdbcResultSetAdapter(metaData.getImportedKeys(catalogName, schemaName, tableName));
}
public ResultSet getIndexInfo(String catalogName, String schemaName, String tableName) throws SQLException {
return new JdbcResultSetAdapter(metaData.getIndexInfo(catalogName, schemaName, tableName, false, false));
}
/**
* The default implementation of the method does nothing
* @see {@link IMetaDataAccess}
*
*/
public void loadExtraData(IColumn column, IDataType dataType) {
}
}
|
package cn.e3mall.common.util;
import java.util.Random;
/**
*
* @author Dragon
*
*/
public class CommonUtils {
/**
* 生成ID
*/
public static long getId() {
//取当前时间的长整形值包含毫秒
long millis = System.currentTimeMillis();
//加上两位随机数
Random random = new Random();
int end2 = random.nextInt(99);
//如果不足两位前面补0
String str = millis + String.format("%02d", end2);
long id = new Long(str);
return id;
}
}
|
package algorithm.swea.D5;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
/*
입력 BufferedReader, toCharArray()
BFS 큐
(악마들, 수연) < 같은 레벨에 악마먼저 넣고 수연
BFS는 해당 노드의 자식들을 다 꺼내는 방식이기 때문에 가지고있는 모든 정보를 알 수 있어야 함
따라서 클래스를 정의해서 사용
*/
public class _7793_OhMyGoddess_필기 {
private static int N, M;
private static char[][] map;
private static Queue<Point> q;
private static int min;
private static int[] dr = {-1, 1, 0, 0};
private static int[] dc = {0, 0, -1, 1};
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
int TC = Integer.parseInt(br.readLine());
for (int tc = 1; tc <= TC; tc++) {
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken()); // N 행, 2 <= R <= 50
M = Integer.parseInt(st.nextToken()); // M 열, 2 <= C <= 50
q = new LinkedList<Point>();
Point sPoint = null; // 수연위치
//수연이의 위치는 ‘S’, 여신의 공간은 ‘D’, 돌의 위치는 ‘X’, 악마는 ‘*’
map = new char[N][];
for (int i = 0; i < map.length; i++) {
map[i] = br.readLine().toCharArray();
for (int j = 0; j < M; j++) {
if (map[i][j] == '*') {
q.offer(new Point(i, j, true));
} else if (map[i][j] == 'S') {
sPoint = new Point(i, j, false);
}
}
}
q.offer(sPoint); // 수연이 마지막에 넣기
min = Integer.MAX_VALUE;
bfs(); /// 수연이가 악마에게 잡힐지 GAME OVER/ 여신을 만날 수 있을지 최단거리 출력
sb.append('#').append(tc).append(' ').append(min == Integer.MAX_VALUE ? "GAME OVER" : min).append('\n');
} // end of for test case
System.out.print(sb);
} // end of main
private static void bfs() {
int cnt = 1; // 여신을 만나는 이동횟수
// 큐에 시작좌표 넣기
ex:
while (!q.isEmpty()) {
int size = q.size(); // 같은 형제들의 개수
while (--size >= 0) {
Point point = q.poll();
int r = point.r; // 반복문 내에서는 지역변수를 사용하는 것이 속도에 더 유리
int c = point.c;
boolean isDevil = point.isDevil;
for (int i = 0; i < dr.length; i++) {
int nr = r + dr[i];
int nc = c + dc[i];
if (0 <= nr && nr < N && 0 <= nc && nc < M) {
if (isDevil) { // 악마이면
if (map[nr][nc] == '.' || map[nr][nc] == 'S') {
map[nr][nc] = '*'; // 악마의 숨결 표시 - 방문처리효과
q.offer(new Point(nr, nc, true));
}
} else { // 수연이면
if (map[nr][nc] == 'D') { // 여신을 만나면 종료
min = cnt;
break ex;
} else if (map[nr][nc] == '.'){ // 평범한 지역
map[nr][nc] = 'S';
q.offer(new Point(nr, nc, false));
}
}
}
}
}
// 바로 위의 while문이 1초에 일어나는 일들임
cnt++;
}//end of while (!q.isEmpty()){
}// end of bfs
public static class Point {
int r;
int c;
boolean isDevil; // 악마인지, 수연인지
public Point(int r, int c, boolean isDevil) {
this.r = r;
this.c = c;
this.isDevil = isDevil;
}
}
} // end of class |
package LaunchBrowser;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.opera.OperaDriver;
import org.testng.annotations.*;
import io.github.bonigarcia.wdm.WebDriverManager;
public class LaunchOperaBrowser {
public static WebDriver opera_driver;
@BeforeMethod
public void OperaSetup() {
WebDriverManager.operadriver().setup();
}
@BeforeTest
public void LaunchOpera() {
opera_driver = new OperaDriver();
opera_driver.manage().window().maximize();
}
@AfterMethod
public void CloseBrowser() {
opera_driver.close();
opera_driver.quit();
}
}
|
/* *** This file is given as part of the programming assignment. *** */
import java.util.ArrayList;
public class Parser {
// tok is global to all these parsing methods;
// scan just calls the scanner's scan method and saves the result in tok.
private Token tok; // the current token
private ArrayList<ArrayList<String>> symbolTable;
private void scan() {
tok = scanner.scan();
}
private Scan scanner;
Parser(Scan scanner) {
this.scanner = scanner;
this.symbolTable = new ArrayList<ArrayList<String>>();
scan();
program();
if( tok.kind != TK.EOF )
parse_error("junk after logical end of program");
}
// program() parsing method
private void program() {
System.out.println("#include <stdio.h>");
System.out.println("main()");
block();
}
// block() parsing method
private void block(){
this.symbolTable.add(new ArrayList<String>()); // Adds new list to symbol table to hold legal variables in this new block
System.out.println("{");
declaration_list();
statement_list();
System.out.println("}");
this.symbolTable.remove(this.symbolTable.size() - 1); // List for this block is popped from the stack since block has ended
}
// declaration_list() parsing method
private void declaration_list() {
// below checks whether tok is in first set of declaration.
// here, that's easy since there's only one token kind in the set.
// in other places, though, there might be more.
// so, you might want to write a general function to handle that.
while( is(TK.DECLARE) ) {
declaration();
}
}
// declaration() parsing method
private void declaration() {
System.out.println("int");
mustbe(TK.DECLARE);
int varCount = 0; // Used to determine whether or not commas need to be printed (for multiple variable declarations on the same line)
// Prints redeclaration error if most recent list in symbol table already contains the variable.
// Else, adds the variable to the most recent list in symbol table
if (this.symbolTable.get(symbolTable.size() - 1).contains(tok.string)) {
System.err.println("redeclaration of variable " + tok.string);
} else {
varCount++;
this.symbolTable.get(symbolTable.size() - 1).add(tok.string);
int scopeLvl = symbolTable.size() - 1; // Used in print statement to munge identifiers for implementing levels for the E scoping operator in C.
System.out.println("x_" + scopeLvl + tok.string);
}
mustbe(TK.ID);
while( is(TK.COMMA) ) {
mustbe(TK.COMMA);
// Prints redeclaration error if most recent list in symbol table already contains the variable.
// Else, adds the variable to the most recent list in symbol table
if (this.symbolTable.get(symbolTable.size() - 1).contains(tok.string)) {
System.err.println("redeclaration of variable " + tok.string);
} else {
if (varCount >= 1) {
System.out.println(",");
}
varCount++;
this.symbolTable.get(symbolTable.size() - 1).add(tok.string);
int scopeLvl = symbolTable.size() - 1; // Used in print statement to munge identifiers for implementing levels for the E scoping operator in C.
System.out.println("x_" + scopeLvl + tok.string);
}
mustbe(TK.ID);
}
System.out.println(";");
}
// statement_list() parsing method
private void statement_list() {
while ( first(TK.TILDE, TK.ID, TK.PRINT, TK.DO, TK.IF, TK.FOR) ) {
statement();
} // checks for "FOR" token as well to account for it being added to the statement_list definition
}
// statement() parsing method
private void statement() {
if (first(TK.TILDE, TK.ID)) {
assignment();
} else if (is(TK.PRINT)) {
print();
} else if (is(TK.DO)) {
Do();
} else if (is(TK.IF)) {
If();
} else if (is(TK.FOR)) { // checks for "FOR" token as well to account for it being added to the statement definition
For();
} else {
System.err.println( "Error: Should not get here.");
}
}
// For() parsing method
private void For() {
System.out.println("for(;");
mustbe(TK.FOR);
ref_id();
System.out.println(" < ");
System.out.println(tok.string + ";");
mustbe(TK.NUM);
assignment();
System.out.println(")");
System.out.println("{");
mustbe(TK.STARTFOR);
block();
System.out.println("}");
mustbe(TK.ENDFOR);
}
// assignment() parsing method
private void assignment() {
ref_id();
System.out.println("=");
mustbe(TK.ASSIGN);
expr();
if (!is(TK.STARTFOR)) { // Added to check if assignment is within for loop condition. If so, do not print semicolon, or else it will disturb C syntax.
System.out.println(";");
}
}
// ref_id() parsing method
private void ref_id() {
if ( is(TK.TILDE) ) {
mustbe(TK.TILDE);
boolean isGlobal = true; // Used to determine whether or not variable is global (without scoping number). Needed to check its existence separately.
if (is(TK.NUM)) {
isGlobal = false;
int blockLevel = Integer.parseInt(tok.string); // Translates string scope number into integer scope number so that it can be used to index symbol table.
mustbe(TK.NUM);
// If block level is greater than current depth of nesting, variable does not exist.
if (blockLevel > symbolTable.size() - 1) {
System.err.println("no such variable ~" + blockLevel + tok.string + " on line " + tok.lineNumber);
System.exit(1);
}
// If correct list (scope) does not contain variable, then variable does not exist.
if (!this.symbolTable.get(symbolTable.size() - blockLevel - 1).contains(tok.string)) {
System.err.println("no such variable ~" + blockLevel + tok.string + " on line " + tok.lineNumber);
System.exit(1);
}
int scopeLvl = symbolTable.size() - blockLevel - 1; // Used in print statement to munge identifiers for implementing levels for the E scoping operator in C.
System.out.println("x_" + scopeLvl + tok.string);
}
// If global list (scope) does not contain global variable, variable does not exist
if (isGlobal && !this.symbolTable.get(0).contains(tok.string)) {
System.err.println("no such variable ~" + tok.string + " on line " + tok.lineNumber);
System.exit(1);
}
if (isGlobal) {
System.out.println("x_0" + tok.string);
}
mustbe(TK.ID);
} else if (is(TK.ID)) {
int scopeLvl = isDeclared(tok.string); // Used in print statement to munge identifiers for implementing levels for the E scoping operator in C.
// If symbol table does not contain variable, then variable does not exist.
if (scopeLvl == symbolTable.size()) {
System.err.println(tok.string + " is an undeclared variable on line " + tok.lineNumber);
System.exit(1);
}
System.out.println("x_" + scopeLvl + tok.string);
mustbe(TK.ID);
} else {
System.err.println( "Error: Should not get here.");
}
}
// expr() parsing method
private void expr() {
term();
while (first(TK.PLUS, TK.MINUS)) {
addop();
term();
}
}
// term() parsing method
private void term() {
factor();
while (first(TK.TIMES, TK.DIVIDE)) {
multop();
factor();
}
}
// addop() parsing method
private void addop() {
if (is(TK.PLUS)) {
System.out.println("+");
scan();
} else if (is(TK.MINUS)) {
System.out.println("-");
scan();
} else {
System.err.println("Error: Should not get here.");
}
}
// factor() parsing method
private void factor() {
if (is(TK.LPAREN)) {
System.out.println("(");
mustbe(TK.LPAREN);
expr();
System.out.println(")");
mustbe(TK.RPAREN);
} else if (first(TK.TILDE, TK.ID) ) {
ref_id();
} else if (is(TK.NUM)) {
System.out.println(tok.string);
mustbe(TK.NUM);
} else {
System.err.println( "Error: Should not get here.");
}
}
// multop() parsing method
private void multop() {
if (is(TK.TIMES)) {
System.out.println("*");
scan();
} else if (is(TK.DIVIDE)) {
System.out.println("/");
scan();
} else {
System.err.println("Error: Should not get here.");
}
}
// print() parsing method
private void print() {
System.out.print("printf(\"%d\\n\",");
mustbe(TK.PRINT);
expr();
System.out.println(");");
}
// Do() parsing method
private void Do() {
System.out.println("while (");
mustbe(TK.DO);
guarded_command();
System.out.println("}");
mustbe(TK.ENDDO);
}
// guarded_command() parsing method
private void guarded_command() {
expr();
System.out.println(" <= 0)");
System.out.println("{");
mustbe(TK.THEN);
block();
}
// If() parsing method
private void If() {
System.out.println("if (");
mustbe(TK.IF);
guarded_command();
System.out.println("}");
while (is(TK.ELSEIF)) {
System.out.println("else if (");
mustbe(TK.ELSEIF);
guarded_command();
System.out.println("}");
}
if (is(TK.ELSE)) {
System.out.println("else {");
mustbe(TK.ELSE);
block();
System.out.println("}");
}
mustbe(TK.ENDIF);
}
// Returns true if character being scanned is the first of a nonterminal with 6 terminals in its first set.
private boolean first(TK tk1, TK tk2, TK tk3, TK tk4, TK tk5, TK tk6) {
return (tk1 == tok.kind || tk2 == tok.kind || tk3 == tok.kind
|| tk4 == tok.kind || tk5 == tok.kind || tk6 == tok.kind);
}
// Returns true if character being scanned is the first of a nonterminal with 2 terminals in its first set.
private boolean first(TK tk1, TK tk2) {
return (tk1 == tok.kind || tk2 == tok.kind);
}
// Used to determine if a variable without the scoping operator has been declared.
// Does this by searching from most recent list of symbol table to oldest list of symbol table.
// Returns position of symbol table if variable is found, otherwise returns size of symbol table to indicate that variable is not found.
private int isDeclared(String tk) {
for (int i = symbolTable.size() - 1; i >= 0; i--) {
if (symbolTable.get(i).contains(tk)) {
return i;
}
}
return symbolTable.size();
}
// is current token what we want?
private boolean is(TK tk) {
return tk == tok.kind;
}
// ensure current token is tk and skip over it.
private void mustbe(TK tk) {
if( tok.kind != tk ) {
System.err.println( "mustbe: want " + tk + ", got " +
tok);
parse_error( "missing token (mustbe)" );
}
scan();
}
private void parse_error(String msg) {
System.err.println( "can't parse: line "
+ tok.lineNumber + " " + msg );
System.exit(1);
}
}
|
package com.ar.auto.cases.mtbf;
import com.ar.auto.common.AutoTestCase;
import com.ar.auto.common.CaseName;
import org.junit.Test;
public class AppStoreAndDownloadStability extends AutoTestCase {
/**
* 5.1.5.1: Open/Close the Store Front Client
*
* Number of loops: 20
*
* 1. Open and close the Store Front client the required number of iterations
*/
@CaseName("打开关闭Appstore")
@Test
public void testOpenCloseAppStore() {
}
/**
* 5.1.5.2: Download a Java application/game
*
* Number of loops:
* 10 3G for a 3G device
* 4 3G, 6 LTE for a LTE device
*/
@CaseName("下载应用或者游戏")
@Test
public void testDownloadAppOrGame() {
}
/**
* 5.1.5.3: Storefront Application download
*
* Number of loops:
* 10 3G for a 3G device
* 4 3G, 6 LTE for a LTE device
*
* 1. Download a free Native application from the storefront supported on the device
*/
@CaseName("下载应用")
@Test
public void testDownloadApplication() {
}
/**
* 5.1.5.4: Close the application store front
*
* Number of loops: 1
*/
@CaseName("关闭应用商店")
@Test
public void testCloseAppStore() {
}
/**
* 5.1.5.5: Open a downloaded Java Game and then close a Java Game
*
* Number of loops: 10
*
* 1. If the device supports Java and a native execution environment then execute this step 10 times
* 2. If the device does not support a native execution environment then execute this step 20 times
*/
@CaseName("打开下载的游戏并关闭游戏")
@Test
public void testOpenAndCloseGame() {
}
/**
* 5.1.5.6: Open a downloaded application from the storefront
*
* Number of loops: 10
*
* 1. If the device support Java and a native execution environment then execute this step 10 times
* 2. If the device does not support a native execution environment then execute this step 20 times
*/
@CaseName("打开下载的应用并关闭应用")
@Test
public void testOpenCloseApplication() {
}
/**
* 5.1.5.7: Delete a downloaded Java game
*
* Number of loops:
*
* Delete all Java applications/games downloaded previously in this section
*/
@CaseName("删除下载的游戏")
@Test
public void testUninstallAllDownloadedGame() {
}
/**
* 5.1.5.8: Delete a downloaded Native application
*
* Number of loops:
*
* Delete all native applications downloaded previously in this section
*/
@CaseName("删除下载的应用程序")
@Test
public void testUninstallAllDownloadedApplication() {
}
}
|
package br.udesc.controller;
import br.udesc.controller.tablemodel.SalaModel;
import br.udesc.model.dao.SalaJpaController;
import br.udesc.model.dao.exceptions.NonexistentEntityException;
import br.udesc.model.entidade.Sala;
import br.udesc.view.TelaCadastroSala;
import br.udesc.view.TelaTableSala;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Classe resposável pelo controle do módulo que exibe a tabela de salas.
* @author PIN2
*/
public class ControladorTelaTableSala {
private TelaTableSala tts;
private Sala sa;
private SalaModel sm;
private List<Sala> listaSala;
private SalaJpaController slc;
/**
* Construtor intanciando os objetos necessários e iniciando os componentes da Tela.
*/
public ControladorTelaTableSala() {
tts = new TelaTableSala();
sa = new Sala();
sm = new SalaModel();
slc = new SalaJpaController();
tts.tabelaSalas.setModel(sm);
carregarSala();
iniciar();
}
/**
* Método responsável por carregar salas existentes na tabela.
*/
public void carregarSala() {
sm.limpar();
listaSala = slc.listarSala();
for (Sala listaSalas : listaSala) {
sm.anuncioAdd(listaSalas);
}
tts.tabelaSalas.getSelectionModel().addSelectionInterval(0, 0);
}
/**
* Método responsável por guardar a sala selecionada na variável do "sa" do tipo Sala.
* @param linha Linha selecionada da table.
*/
public void pegarLinha(int linha) {
sa.setId((long) tts.tabelaSalas.getValueAt(linha, 0));
sa.setNumero((String) tts.tabelaSalas.getValueAt(linha, 1));
sa.setLimite((int) tts.tabelaSalas.getValueAt(linha, 2));
String comparar = ((String) tts.tabelaSalas.getValueAt(linha, 3));
if (comparar.equalsIgnoreCase("Laboratorio")) {
sa.setTipo(true);
} else {
sa.setTipo(false);
}
}
/**
* Método que inicia os componentes do JFrame (Botões etc).
*/
public void iniciar() {
tts.botaoAdicionar.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
ControladorTelaCadastroSala cts = new ControladorTelaCadastroSala();
cts.executar();
tts.dispose();
}
});
tts.botaoEditar.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
ControladorTelaCadastroSala cts = new ControladorTelaCadastroSala();
int linha = tts.tabelaSalas.getSelectedRow();
pegarLinha(linha);
cts.executar();
cts.editar(sa);
tts.dispose();
}
});
tts.boataoExcluir.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int linha = tts.tabelaSalas.getSelectedRow();
pegarLinha(linha);
try {
slc.destroy(sa.getId());
} catch (NonexistentEntityException ex) {
Logger.getLogger(ControladorTelaTableSala.class.getName()).log(Level.SEVERE, null, ex);
}
carregarSala();
}
});
tts.botaoInicio.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae
) {
ControladorTelaInicio cti = new ControladorTelaInicio();
cti.executar();
tts.dispose();
}
}
);
tts.botaoProfessor.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae
) {
ControladorTelaTableProfessor ctp = new ControladorTelaTableProfessor();
ctp.executar();
tts.setVisible(false);
}
}
);
tts.botaoDisciplina.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae
) {
ControladorTelaTableDisciplina cttd = new ControladorTelaTableDisciplina();
cttd.executar();
tts.setVisible(false);
}
}
);
tts.botaoVincular.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e
) {
ControladorTelaVinculo ctv = new ControladorTelaVinculo();
ctv.executar();
tts.setVisible(false);
}
}
);
tts.botaoCurso.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ControladorTelaTableCurso cttc = new ControladorTelaTableCurso();
cttc.executar();
tts.dispose();
}
});
}
/**
* Método responsável por inicializar a tela controlada por esta classe.
*/
public void executar() {
tts.setVisible(true);
}
}
|
/*
* 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 agencia;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
/**
* FXML Controller class
*
* @author ruben
*/
public class ComprarController implements Initializable {
@FXML
private TextField id_compra;
@FXML
private TextField origen_compra;
@FXML
private TextField destino_compra;
@FXML
private TextField fecha_compra;
@FXML
private TextField hora_compra;
@FXML
private TextField num_asientos_compra;
@FXML
private TextField precio_compra;
@FXML
public void comprar(ActionEvent event) throws IOException{
String cuentaOrigen = "5701538517696901";
String cuentaDestino = "2930187744831753";
String id = id_compra.getText().toString();
String origen = origen_compra.getText().toString();
String destino = destino_compra.getText().toString();
String fecha = fecha_compra.getText().toString();
String hora = hora_compra.getText().toString();
int asientos = Integer.parseInt(num_asientos_compra.getText().toString());
int precio = Integer.parseInt(precio_compra.getText().toString());
comprarBoleto_1(id,origen,destino,fecha,hora,asientos,precio);
transaccion(cuentaOrigen, cuentaDestino,precio_compra.getText().toString());
Alert dialogo = new Alert(Alert.AlertType.INFORMATION);
dialogo.setTitle("Boleto comprado");
dialogo.setHeaderText(null);
dialogo.setContentText("Boleto comprado cerrar ventana");
dialogo.initStyle(StageStyle.UTILITY);
dialogo.showAndWait();
}
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
private static boolean comprarBoleto_1(java.lang.String id, java.lang.String origen, java.lang.String destino, java.lang.String fecha, java.lang.String hora, int numAsientos, int precio) {
controlador.SWTransporteAdministrador service = new controlador.SWTransporteAdministrador();
controlador.SWTransporte port = service.getSWTransportePort();
return port.comprarBoleto(id, origen, destino, fecha, hora, numAsientos, precio);
}
private static String transaccion(java.lang.String noCuentaOrigen, java.lang.String noCuentaDestino, java.lang.String monto) {
registro.pasarela.Pasarela_Service service = new registro.pasarela.Pasarela_Service();
registro.pasarela.Pasarela port = service.getPasarelaPort();
return port.transaccion(noCuentaOrigen, noCuentaDestino, monto);
}
}
|
import processing.core.*;
import processing.data.*;
import processing.event.*;
import processing.opengl.*;
import java.util.HashMap;
import java.util.ArrayList;
import java.io.File;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
public class Chemotaxis extends PApplet {
//declare bacteria variables here
Bacteria joe;
Bacteria [] bob;
public void setup()
{
//initialize bacteria variables here
size(500, 500);
frameRate(100);
bob = new Bacteria[1000];
for(int i = 0; i < bob.length; i++)
{
bob[i] = new Bacteria();
//System.out.println("ok");
}
}
public void draw()
{
//move and show the bacteria
background(0, 0, 0);
for(int i = 0; i < bob.length; i++)
{
bob[i].show();
bob[i].move();
//System.out.println("ok");
}
}
class Bacteria
{
//lots of java!
int x2;
int y2;
int bacteriaOutlineColor;
int bacteriaColor;
Bacteria()
{
x2 = width/2;
y2 = height/2;
bacteriaOutlineColor = color((int)(Math.random()*255), (int)(Math.random()*255), (int)(Math.random()*255), (int)(Math.random()*255));
bacteriaColor = color((int)(Math.random()*255), (int)(Math.random()*255), (int)(Math.random()*255), (int)(Math.random()*255));
}
public void move()
{
/*if(mousePressed)
{
if(x2 < 250 && y2 < 250)
{
y2 = y2 + (int)(Math.random()*20 - 15);
x2 = x2 + (int)(Math.random()*20 - 15);
}
if(x2 < 500 && x2 > 250 && y2 < 500 && y2 > 250)
{
y2 = y2 + (int)(Math.random()*20 - 15);
x2 = x2 + (int)(Math.random()*20 + 15);
}
if(x2 < 250 && y2 < 500 && y2 > 250)
{
y2 = y2 + (int)(Math.random()*20 - 15);
x2 = x2 + (int)(Math.random()*20 + 15);
}
if(x2 > 250 && x2 < 500 && y2 > 250 && y2 < 500)
{
y2 = y2 + (int)(Math.random()*20 + 15);
x2 = x2 + (int)(Math.random()*20 + 15);
}
}
*/
y2 = y2 - (int)(Math.random()*20 - 10);
x2 = x2 - (int)(Math.random()*20 - 10);
}
public void show()
{
stroke(bacteriaOutlineColor);
fill(bacteriaColor);
ellipse(x2, y2, 10, 10);
}
}
static public void main(String[] passedArgs) {
String[] appletArgs = new String[] { "Chemotaxis" };
if (passedArgs != null) {
PApplet.main(concat(appletArgs, passedArgs));
} else {
PApplet.main(appletArgs);
}
}
}
|
package com.nevin.pjm;
import java.util.concurrent.TimeUnit;
import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.pool.PooledConnectionFactory;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
public class JmsConsumer implements MessageListener {
private static BrokerService broker;
public static void main(String[] args) throws Exception {
try {
//startBroker();
JmsConsumer jmsConsumer = new JmsConsumer ();
CamelContext ctx = jmsConsumer.createCamelContext();
//ctx.start();
/*ctx.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
Our direct route will take a message, and set the message to group 1 if the body is an integer,
* otherwise set the group to 2.
*
* This demonstrates the following concepts:
* 1) Header Manipulation
* 2) Checking the payload type of the body and using it in a choice.
* 3) JMS Message groups
from("direct:begin")
.choice()
.when(body().isInstanceOf(Integer.class)).setHeader("JMSXGroupID",constant("1"))
.otherwise().setHeader("JMSXGroupID",constant("2"))
.end()
.to("amq:queue:Message.Group.Test");
These two are competing consumers
from("amq:queue:Message.Group.Test").routeId("Route A").log("Received: ${body}");
from("amq:queue:Message.Group.Test").routeId("Route B").log("Received: ${body}");
}
});*/
//sendMessages(ctx.createProducerTemplate());
Thread.sleep(TimeUnit.SECONDS.toMillis(2));
//stopBroker();
} catch (Exception e) {
e.printStackTrace();
}
}
private CamelContext createCamelContext() throws Exception {
CamelContext camelContext = new DefaultCamelContext();
//ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory("vm://localhost/");
ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
activeMQConnectionFactory.setUserName("admin");
activeMQConnectionFactory.setPassword("admin");
PooledConnectionFactory pooledConnectionFactory = new PooledConnectionFactory(activeMQConnectionFactory);
pooledConnectionFactory.setMaxConnections(8);
Connection conn = pooledConnectionFactory.createConnection();
conn.start();
Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination dest = sess.createQueue("Consumer.A.VirtualTopic.InputRecv");
MessageConsumer cons = sess.createConsumer(dest);
cons.setMessageListener(this);
// pooledConnectionFactory.setMaximumActive(500);
// ActiveMQComponent activeMQComponent = ActiveMQComponent.activeMQComponent();
//activeMQComponent.setUsePooledConnection(true);
//activeMQComponent.setConnectionFactory(pooledConnectionFactory);
//camelContext.addComponent("amq", activeMQComponent);
return camelContext;
}
private static void sendMessages(ProducerTemplate pt) throws Exception {
for (int i = 0; i < 10; i++) {
pt.sendBody("direct:begin", Integer.valueOf(i));
}
for (int i = 0; i < 10; i++) {
pt.sendBody("direct:begin", "next group");
}
pt.sendBody("direct:begin", Integer.valueOf(1));
pt.sendBody("direct:begin", "foo");
pt.sendBody("direct:begin", Integer.valueOf(2));
}
private static void startBroker() throws Exception {
broker = new BrokerService();
//broker.addConnector("vm://localhost");
broker.addConnector("tcp://localhost:61616");
broker.start();
}
private static void stopBroker() throws Exception {
broker.stop();
}
public void onMessage(Message arg0) {
// TODO Auto-generated method stub
}
} |
package com.nxtlife.mgs.jpa;
import java.util.List;
import java.util.Set;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.nxtlife.mgs.entity.common.UserRoleKey;
import com.nxtlife.mgs.entity.user.UserRole;
public interface UserRoleRepository extends JpaRepository<UserRole, UserRoleKey> {
@Modifying
@Query(value = "insert into role_user(user_id,role_id) values (?1,?2)", nativeQuery = true)
public int save(Long userId, Long roleId);
@Query(value = "select role_id from role_user where user_id=?1", nativeQuery = true)
public Set<Long> findRoleIdsByUserId(Long userId);
@Query(value = "select ur.role.id from UserRole ur where ur.user.cid=?1")
public Set<Long> findRoleIdsByUserCid(String userId);
@Query(value = "select role_id from role_user u_r inner join role r on u_r.role_id=r.id where user_id=?1 and r.active = ?2", nativeQuery = true)
public Set<Long> findRoleIdsByUserIdAndRoleActive(Long userId, Boolean roleActive);
@Query(value = "select ur.role.id from UserRole ur where ur.user.cid=?1 and ur.user.active =?2")
public Set<Long> findRoleIdsByUserCidAndRoleActive(String userId, Boolean roleActive);
@Query(value = "SELECT * FROM role_user u_r inner join role r where u_r.user_id = ?1 and u_r.role_id=r.id", nativeQuery = true)
public List<UserRole> findByUserId(Long userId);
public List<UserRole> findByUserCid(String userId);
@Query(value = "select ur.user.id from UserRole ur where ur.role.id=:roleId")
public Set<Long> findUserIdsByRoleId(@Param("roleId") Long roleId);
@Query(value = "select ur.user.cid from UserRole ur where ur.role.id=:roleId")
public Set<String> findUserCidsByRoleId(@Param("roleId") Long roleId);
@Modifying
@Query(value = "delete from role_user where user_id=?1 and role_id=?2", nativeQuery = true)
public int delete(Long userId, Long roleId);
@Modifying
@Query(value = "delete from UserRole ur where ur.user.cid=?1 and ur.role.id=?2")
public int delete(String userId, Long roleId);
}
|
package com.leyou.item.api;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.pojo.Sku;
import com.leyou.item.pojo.Spu;
import com.leyou.item.pojo.SpuDetail;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
/**
* @author: HuYi.Zhang
* @create: 2018-07-26 09:55
**/
public interface GoodsApi {
@GetMapping("/spu/page")
PageResult<Spu> querySpuByPage(
@RequestParam(value="page", defaultValue = "1") Integer page,
@RequestParam(value="rows", defaultValue = "5") Integer rows,
@RequestParam(value="key", required = false) String key,
@RequestParam(value="saleable", required = false) Boolean saleable);
@GetMapping("/spu/detail/{spuId}")
SpuDetail queryDetailBySpuId(@PathVariable("spuId")Long spuId);
@GetMapping("/sku/list")
List<Sku> querySkuBySpuId(@RequestParam("id") Long spuId);
@GetMapping("spu/{spuId}")
Spu querySpuById(@RequestParam("spuId")Long spuId);
}
|
/*
* Copyright (C) 2015 Miquel Sas
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
package com.qtplaf.library.trading.chart.parameters;
import java.awt.BasicStroke;
import java.awt.Color;
/**
* Bar plot parameters.
*
* @author Miquel Sas
*/
public class BarPlotParameters {
/**
* Stroke.
*/
private BasicStroke stroke = new BasicStroke();
/**
* Color.
*/
private Color color = Color.BLACK;
/**
*
*/
public BarPlotParameters() {
super();
}
/**
* Returns the stroke.
*
* @return The stroke.
*/
public BasicStroke getStroke() {
return stroke;
}
/**
* Set the stroke.
*
* @param stroke The bar stroke.
*/
public void setStroke(BasicStroke stroke) {
this.stroke = stroke;
}
/**
* Returns the color.
*
* @return The color.
*/
public Color getColor() {
return color;
}
/**
* Set the color.
*
* @param color The color.
*/
public void setColor(Color color) {
this.color = color;
}
}
|
package pl.java.scalatech.jms;
import java.util.HashMap;
import java.util.Map;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Queue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessagePostProcessor;
import org.springframework.stereotype.Component;
/**
* @author przodownik
* Module name : jmsSpringKata
* Creating time : 10:23:43 PM
*/
@Component
public class SendingMapMessage {
@Autowired
private JmsTemplate jmsTemplate;
@Autowired
@Qualifier("queueA")
private Queue queueA;
public void sendWithConversion() {
Map<String, Object> map = new HashMap<>();
map.put("Name", "Mark");
map.put("Age", new Integer(47));
jmsTemplate.convertAndSend(queueA, map, new MessagePostProcessor() {
@Override
public Message postProcessMessage(Message message) throws JMSException {
message.setIntProperty("AccountID", 1234);
message.setJMSCorrelationID("123-00001");
return message;
}
});
}
}
|
package com.example.bomber;
import java.io.Serializable;
public class DatosEmergencia implements Serializable {
protected int emergencia_id;
protected String lugar;
protected String tipo;
protected String telefono;
protected Double latitude;
protected Double longitude;
private int imagen;
public DatosEmergencia(){
this (0,"", "", "", 0.0, 0.0);
}
public DatosEmergencia(int emergencia_id,String lugar, String tipo,String telefono, Double latitude, Double longitude){
this.emergencia_id = emergencia_id;
this.lugar =lugar;
this.tipo = tipo;
this.telefono = telefono;
this.latitude = latitude;
this.longitude = longitude;
}
public String getLugar(){
return lugar;
}
public String getTipo(){
return tipo;
}
public String getTelefono(){
return telefono;
}
public Double getLatitude(){
return latitude;
}
public Double getLongitude(){
return longitude;
}
public int getImagen(){
return imagen;
}
public void setImagen(int imagen){
this.imagen=imagen;
}
public int getEmergencia_id(){
return emergencia_id;
}
@Override
public String toString(){return lugar+":"+telefono;}
}
|
package polozov;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class MapRoadStorage {
public static Map<City, Set<Road>> MAP_ROAD = new HashMap<>();
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.print("Enter command - (1 - addCity | 2 - addRoad | 3 - deleteRoad | 4 - getCity | 5 - getList | 6 - printAll | 7 - saveToFile): ");
String[] command = reader.readLine().trim().split(" ");
if (command.length != 1) {
System.out.println("Неверная команда.");
continue;
}
switch (command[0]) {
case "1":
System.out.println("Enter city name");
String name = reader.readLine();
System.out.println("Enter X-coordinate:");
String tmp = reader.readLine();
int x = Integer.parseInt(tmp);
System.out.println("Enter Y-coordinate:");
tmp = reader.readLine();
int y = Integer.parseInt(tmp);
MapRoadStorage.MAP_ROAD.put(new City(name, x, y), new HashSet<>());
break;
case "2":
System.out.println("Enter first name of city");
String nameFirst = reader.readLine();
System.out.println("Enter second name of city");
String nameSecond = reader.readLine();
Road road = new Road(Objects.requireNonNull(City.get(nameFirst)), Objects.requireNonNull(City.get(nameSecond)));
MAP_ROAD.get(City.get(nameFirst)).add(road);
MAP_ROAD.get(City.get(nameSecond)).add(road);
break;
case "3":
System.out.println("Enter road name for removing");
String roadName = reader.readLine();
if (Road.setOfRoads.contains(Road.get(roadName))) {
for(City key : MAP_ROAD.keySet()) {
MAP_ROAD.get(key).remove(Road.get(roadName));
}
}
Road.setOfRoads.remove(Road.get(roadName));
break;
case "4":
System.out.println("Enter name of city");
String city = reader.readLine();
System.out.println(City.get(city));
break;
case "5":
System.out.println("Enter name of city");
String listRoads = reader.readLine();
printStorageByCity(City.get(listRoads));
break;
case "6":
printAll();
break;
case "7":
try(FileWriter writer = new FileWriter("src/polozov/text", false))
{
for(Map.Entry<City, Set<Road>> entry : MAP_ROAD.entrySet() ) {
writer.write(String.valueOf(entry.getKey()));
writer.append('\n');
writer.write(String.valueOf(entry.getValue()));
}
writer.flush();
}
catch(IOException ex){
System.out.println(ex.getMessage());
}
break;
default:
System.out.println("Неверная команда.");
break;
}
}
}
public static void printStorageByCity(City city){
if (MAP_ROAD.containsKey(city)) {
Set<Road> set = MAP_ROAD.get(city);
for (Road road: set) {
System.out.println(road);
}
} else {
System.out.println("Roads weren't found");
}
}
public static void printAll() {
for (City key : MAP_ROAD.keySet()) {
System.out.println(key + ":");
Set<Road> set = MAP_ROAD.get(key);
if (set.isEmpty()) {
System.out.println("Roads weren't found");
}
for (Road road: set) {
System.out.println(road);
}
}
}
}
|
package activites;
import services.MyApplication;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import com.eskaa.callLog.R;
import db.DBHelper;
import entity.CurrencyStatus;
public class SelectPlanActivity extends Activity implements OnClickListener {
Button butEdit;
Button butCancel;
RadioButton radioPre, radioPost;
int selecteditem;
DBHelper mydb;
Integer getRadioAsync;
MyApplication s;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.select_plan_layout);
butEdit = (Button) findViewById(R.id.buttonEdit);
butEdit.setOnClickListener(this);
butCancel = (Button) findViewById(R.id.buttonCancel);
butCancel.setOnClickListener(this);
radioPre = (RadioButton) findViewById(R.id.radioPrepaid);
radioPost = (RadioButton) findViewById(R.id.radioPostpaid);
mydb = new DBHelper(this);
s = MyApplication.getInstance();
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
// Retrieve the selected plan from database
int getradioValue = 0;
try {
getradioValue = s.getRadioValue();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (getradioValue == 0) {
radioPre.setChecked(true);
} else if (getradioValue == 1) {
radioPost.setChecked(true);
}
}
public void onClick(View v) {
// TODO Auto-generated method stub
// Assign the selected plan to the database
if (v.getId() == R.id.buttonEdit) {
if (radioPre.isChecked() == true) {
selecteditem = 0;
mydb.addRadioValue(new CurrencyStatus(selecteditem));
s.setRadioValue();
Intent i = new Intent(this, PrepaidActivity.class);
startActivity(i);
} else if (radioPost.isChecked() == true) {
selecteditem = 1;
mydb.addRadioValue(new CurrencyStatus(selecteditem));
s.setRadioValue();
Intent i = new Intent(this, PostpaidActivity.class);
startActivity(i);
}
} else if (v.getId() == R.id.buttonCancel) {
finish();
}
}
} |
package com.qihoo.finance.chronus.worker.bo;
import com.qihoo.finance.chronus.metadata.api.task.entity.TaskEntity;
import com.qihoo.finance.chronus.metadata.api.task.entity.TaskRuntimeEntity;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public final class JobContext {
private String key;
private TaskEntity taskEntity;
private volatile TaskRuntimeEntity taskRuntime;
}
|
package org.newdawn.slick;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import org.lwjgl.LWJGLException;
import org.lwjgl.input.Controller;
import org.lwjgl.input.Controllers;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.Display;
import org.newdawn.slick.util.Log;
public class Input {
public static final int ANY_CONTROLLER = -1;
private static final int MAX_BUTTONS = 100;
public static final int KEY_ESCAPE = 1;
public static final int KEY_1 = 2;
public static final int KEY_2 = 3;
public static final int KEY_3 = 4;
public static final int KEY_4 = 5;
public static final int KEY_5 = 6;
public static final int KEY_6 = 7;
public static final int KEY_7 = 8;
public static final int KEY_8 = 9;
public static final int KEY_9 = 10;
public static final int KEY_0 = 11;
public static final int KEY_MINUS = 12;
public static final int KEY_EQUALS = 13;
public static final int KEY_BACK = 14;
public static final int KEY_TAB = 15;
public static final int KEY_Q = 16;
public static final int KEY_W = 17;
public static final int KEY_E = 18;
public static final int KEY_R = 19;
public static final int KEY_T = 20;
public static final int KEY_Y = 21;
public static final int KEY_U = 22;
public static final int KEY_I = 23;
public static final int KEY_O = 24;
public static final int KEY_P = 25;
public static final int KEY_LBRACKET = 26;
public static final int KEY_RBRACKET = 27;
public static final int KEY_RETURN = 28;
public static final int KEY_ENTER = 28;
public static final int KEY_LCONTROL = 29;
public static final int KEY_A = 30;
public static final int KEY_S = 31;
public static final int KEY_D = 32;
public static final int KEY_F = 33;
public static final int KEY_G = 34;
public static final int KEY_H = 35;
public static final int KEY_J = 36;
public static final int KEY_K = 37;
public static final int KEY_L = 38;
public static final int KEY_SEMICOLON = 39;
public static final int KEY_APOSTROPHE = 40;
public static final int KEY_GRAVE = 41;
public static final int KEY_LSHIFT = 42;
public static final int KEY_BACKSLASH = 43;
public static final int KEY_Z = 44;
public static final int KEY_X = 45;
public static final int KEY_C = 46;
public static final int KEY_V = 47;
public static final int KEY_B = 48;
public static final int KEY_N = 49;
public static final int KEY_M = 50;
public static final int KEY_COMMA = 51;
public static final int KEY_PERIOD = 52;
public static final int KEY_SLASH = 53;
public static final int KEY_RSHIFT = 54;
public static final int KEY_MULTIPLY = 55;
public static final int KEY_LMENU = 56;
public static final int KEY_SPACE = 57;
public static final int KEY_CAPITAL = 58;
public static final int KEY_F1 = 59;
public static final int KEY_F2 = 60;
public static final int KEY_F3 = 61;
public static final int KEY_F4 = 62;
public static final int KEY_F5 = 63;
public static final int KEY_F6 = 64;
public static final int KEY_F7 = 65;
public static final int KEY_F8 = 66;
public static final int KEY_F9 = 67;
public static final int KEY_F10 = 68;
public static final int KEY_NUMLOCK = 69;
public static final int KEY_SCROLL = 70;
public static final int KEY_NUMPAD7 = 71;
public static final int KEY_NUMPAD8 = 72;
public static final int KEY_NUMPAD9 = 73;
public static final int KEY_SUBTRACT = 74;
public static final int KEY_NUMPAD4 = 75;
public static final int KEY_NUMPAD5 = 76;
public static final int KEY_NUMPAD6 = 77;
public static final int KEY_ADD = 78;
public static final int KEY_NUMPAD1 = 79;
public static final int KEY_NUMPAD2 = 80;
public static final int KEY_NUMPAD3 = 81;
public static final int KEY_NUMPAD0 = 82;
public static final int KEY_DECIMAL = 83;
public static final int KEY_F11 = 87;
public static final int KEY_F12 = 88;
public static final int KEY_F13 = 100;
public static final int KEY_F14 = 101;
public static final int KEY_F15 = 102;
public static final int KEY_KANA = 112;
public static final int KEY_CONVERT = 121;
public static final int KEY_NOCONVERT = 123;
public static final int KEY_YEN = 125;
public static final int KEY_NUMPADEQUALS = 141;
public static final int KEY_CIRCUMFLEX = 144;
public static final int KEY_AT = 145;
public static final int KEY_COLON = 146;
public static final int KEY_UNDERLINE = 147;
public static final int KEY_KANJI = 148;
public static final int KEY_STOP = 149;
public static final int KEY_AX = 150;
public static final int KEY_UNLABELED = 151;
public static final int KEY_NUMPADENTER = 156;
public static final int KEY_RCONTROL = 157;
public static final int KEY_NUMPADCOMMA = 179;
public static final int KEY_DIVIDE = 181;
public static final int KEY_SYSRQ = 183;
public static final int KEY_RMENU = 184;
public static final int KEY_PAUSE = 197;
public static final int KEY_HOME = 199;
public static final int KEY_UP = 200;
public static final int KEY_PRIOR = 201;
public static final int KEY_LEFT = 203;
public static final int KEY_RIGHT = 205;
public static final int KEY_END = 207;
public static final int KEY_DOWN = 208;
public static final int KEY_NEXT = 209;
public static final int KEY_INSERT = 210;
public static final int KEY_DELETE = 211;
public static final int KEY_LWIN = 219;
public static final int KEY_RWIN = 220;
public static final int KEY_APPS = 221;
public static final int KEY_POWER = 222;
public static final int KEY_SLEEP = 223;
public static final int KEY_LALT = 56;
public static final int KEY_RALT = 184;
private static final int LEFT = 0;
private static final int RIGHT = 1;
private static final int UP = 2;
private static final int DOWN = 3;
private static final int BUTTON1 = 4;
private static final int BUTTON2 = 5;
private static final int BUTTON3 = 6;
private static final int BUTTON4 = 7;
private static final int BUTTON5 = 8;
private static final int BUTTON6 = 9;
private static final int BUTTON7 = 10;
private static final int BUTTON8 = 11;
private static final int BUTTON9 = 12;
private static final int BUTTON10 = 13;
public static final int MOUSE_LEFT_BUTTON = 0;
public static final int MOUSE_RIGHT_BUTTON = 1;
public static final int MOUSE_MIDDLE_BUTTON = 2;
private static boolean controllersInited = false;
private static ArrayList controllers = new ArrayList();
private int lastMouseX;
private int lastMouseY;
protected boolean[] mousePressed = new boolean[10];
private boolean[][] controllerPressed = new boolean[100][100];
protected char[] keys = new char[1024];
protected boolean[] pressed = new boolean[1024];
protected long[] nextRepeat = new long[1024];
private boolean[][] controls = new boolean[10][110];
protected boolean consumed = false;
protected HashSet allListeners = new HashSet();
protected ArrayList keyListeners = new ArrayList();
protected ArrayList keyListenersToAdd = new ArrayList();
protected ArrayList mouseListeners = new ArrayList();
protected ArrayList mouseListenersToAdd = new ArrayList();
protected ArrayList controllerListeners = new ArrayList();
private int wheel;
private int height;
private boolean displayActive = true;
private boolean keyRepeat;
private int keyRepeatInitial;
private int keyRepeatInterval;
private boolean paused;
private float scaleX = 1.0F;
private float scaleY = 1.0F;
private float xoffset = 0.0F;
private float yoffset = 0.0F;
private int doubleClickDelay = 250;
private long doubleClickTimeout = 0L;
private int clickX;
private int clickY;
private int clickButton;
private int pressedX = -1;
private int pressedY = -1;
private int mouseClickTolerance = 5;
public static void disableControllers() {
controllersInited = true;
}
public Input(int height) {
init(height);
}
public void setDoubleClickInterval(int delay) {
this.doubleClickDelay = delay;
}
public void setMouseClickTolerance(int mouseClickTolerance) {
this.mouseClickTolerance = mouseClickTolerance;
}
public void setScale(float scaleX, float scaleY) {
this.scaleX = scaleX;
this.scaleY = scaleY;
}
public void setOffset(float xoffset, float yoffset) {
this.xoffset = xoffset;
this.yoffset = yoffset;
}
public void resetInputTransform() {
setOffset(0.0F, 0.0F);
setScale(1.0F, 1.0F);
}
public void addListener(InputListener listener) {
addKeyListener(listener);
addMouseListener(listener);
addControllerListener(listener);
}
public void addKeyListener(KeyListener listener) {
this.keyListenersToAdd.add(listener);
}
private void addKeyListenerImpl(KeyListener listener) {
if (this.keyListeners.contains(listener))
return;
this.keyListeners.add(listener);
this.allListeners.add(listener);
}
public void addMouseListener(MouseListener listener) {
this.mouseListenersToAdd.add(listener);
}
private void addMouseListenerImpl(MouseListener listener) {
if (this.mouseListeners.contains(listener))
return;
this.mouseListeners.add(listener);
this.allListeners.add(listener);
}
public void addControllerListener(ControllerListener listener) {
if (this.controllerListeners.contains(listener))
return;
this.controllerListeners.add(listener);
this.allListeners.add(listener);
}
public void removeAllListeners() {
removeAllKeyListeners();
removeAllMouseListeners();
removeAllControllerListeners();
}
public void removeAllKeyListeners() {
this.allListeners.removeAll(this.keyListeners);
this.keyListeners.clear();
}
public void removeAllMouseListeners() {
this.allListeners.removeAll(this.mouseListeners);
this.mouseListeners.clear();
}
public void removeAllControllerListeners() {
this.allListeners.removeAll(this.controllerListeners);
this.controllerListeners.clear();
}
public void addPrimaryListener(InputListener listener) {
removeListener(listener);
this.keyListeners.add(0, listener);
this.mouseListeners.add(0, listener);
this.controllerListeners.add(0, listener);
this.allListeners.add(listener);
}
public void removeListener(InputListener listener) {
removeKeyListener(listener);
removeMouseListener(listener);
removeControllerListener(listener);
}
public void removeKeyListener(KeyListener listener) {
this.keyListeners.remove(listener);
if (!this.mouseListeners.contains(listener) && !this.controllerListeners.contains(listener))
this.allListeners.remove(listener);
}
public void removeControllerListener(ControllerListener listener) {
this.controllerListeners.remove(listener);
if (!this.mouseListeners.contains(listener) && !this.keyListeners.contains(listener))
this.allListeners.remove(listener);
}
public void removeMouseListener(MouseListener listener) {
this.mouseListeners.remove(listener);
if (!this.controllerListeners.contains(listener) && !this.keyListeners.contains(listener))
this.allListeners.remove(listener);
}
void init(int height) {
this.height = height;
this.lastMouseX = getMouseX();
this.lastMouseY = getMouseY();
}
public static String getKeyName(int code) {
return Keyboard.getKeyName(code);
}
public boolean isKeyPressed(int code) {
if (this.pressed[code]) {
this.pressed[code] = false;
return true;
}
return false;
}
public boolean isMousePressed(int button) {
if (this.mousePressed[button]) {
this.mousePressed[button] = false;
return true;
}
return false;
}
public boolean isControlPressed(int button) {
return isControlPressed(button, 0);
}
public boolean isControlPressed(int button, int controller) {
if (this.controllerPressed[controller][button]) {
this.controllerPressed[controller][button] = false;
return true;
}
return false;
}
public void clearControlPressedRecord() {
for (int i = 0; i < controllers.size(); i++)
Arrays.fill(this.controllerPressed[i], false);
}
public void clearKeyPressedRecord() {
Arrays.fill(this.pressed, false);
}
public void clearMousePressedRecord() {
Arrays.fill(this.mousePressed, false);
}
public boolean isKeyDown(int code) {
return Keyboard.isKeyDown(code);
}
public int getAbsoluteMouseX() {
return Mouse.getX();
}
public int getAbsoluteMouseY() {
return this.height - Mouse.getY();
}
public int getMouseX() {
return (int)(Mouse.getX() * this.scaleX + this.xoffset);
}
public int getMouseY() {
return (int)((this.height - Mouse.getY()) * this.scaleY + this.yoffset);
}
public boolean isMouseButtonDown(int button) {
return Mouse.isButtonDown(button);
}
private boolean anyMouseDown() {
for (int i = 0; i < 3; i++) {
if (Mouse.isButtonDown(i))
return true;
}
return false;
}
public int getControllerCount() {
try {
initControllers();
} catch (SlickException e) {
throw new RuntimeException("Failed to initialise controllers");
}
return controllers.size();
}
public int getAxisCount(int controller) {
return ((Controller)controllers.get(controller)).getAxisCount();
}
public float getAxisValue(int controller, int axis) {
return ((Controller)controllers.get(controller)).getAxisValue(axis);
}
public String getAxisName(int controller, int axis) {
return ((Controller)controllers.get(controller)).getAxisName(axis);
}
public boolean isControllerLeft(int controller) {
if (controller >= getControllerCount())
return false;
if (controller == -1) {
for (int i = 0; i < controllers.size(); i++) {
if (isControllerLeft(i))
return true;
}
return false;
}
return !(((Controller)controllers.get(controller)).getXAxisValue() >= -0.5F && (
(Controller)controllers.get(controller)).getPovX() >= -0.5F);
}
public boolean isControllerRight(int controller) {
if (controller >= getControllerCount())
return false;
if (controller == -1) {
for (int i = 0; i < controllers.size(); i++) {
if (isControllerRight(i))
return true;
}
return false;
}
return !(((Controller)controllers.get(controller)).getXAxisValue() <= 0.5F && (
(Controller)controllers.get(controller)).getPovX() <= 0.5F);
}
public boolean isControllerUp(int controller) {
if (controller >= getControllerCount())
return false;
if (controller == -1) {
for (int i = 0; i < controllers.size(); i++) {
if (isControllerUp(i))
return true;
}
return false;
}
return !(((Controller)controllers.get(controller)).getYAxisValue() >= -0.5F && (
(Controller)controllers.get(controller)).getPovY() >= -0.5F);
}
public boolean isControllerDown(int controller) {
if (controller >= getControllerCount())
return false;
if (controller == -1) {
for (int i = 0; i < controllers.size(); i++) {
if (isControllerDown(i))
return true;
}
return false;
}
return !(((Controller)controllers.get(controller)).getYAxisValue() <= 0.5F && (
(Controller)controllers.get(controller)).getPovY() <= 0.5F);
}
public boolean isButtonPressed(int index, int controller) {
if (controller >= getControllerCount())
return false;
if (controller == -1) {
for (int i = 0; i < controllers.size(); i++) {
if (isButtonPressed(index, i))
return true;
}
return false;
}
return ((Controller)controllers.get(controller)).isButtonPressed(index);
}
public boolean isButton1Pressed(int controller) {
return isButtonPressed(0, controller);
}
public boolean isButton2Pressed(int controller) {
return isButtonPressed(1, controller);
}
public boolean isButton3Pressed(int controller) {
return isButtonPressed(2, controller);
}
public void initControllers() throws SlickException {
if (controllersInited)
return;
controllersInited = true;
try {
Controllers.create();
int count = Controllers.getControllerCount();
int i;
for (i = 0; i < count; i++) {
Controller controller = Controllers.getController(i);
if (controller.getButtonCount() >= 3 && controller.getButtonCount() < 100)
controllers.add(controller);
}
Log.info("Found " + controllers.size() + " controllers");
for (i = 0; i < controllers.size(); i++)
Log.info(String.valueOf(i) + " : " + ((Controller)controllers.get(i)).getName());
} catch (LWJGLException e) {
if (e.getCause() instanceof ClassNotFoundException)
throw new SlickException("Unable to create controller - no jinput found - add jinput.jar to your classpath");
throw new SlickException("Unable to create controllers");
} catch (NoClassDefFoundError noClassDefFoundError) {}
}
public void consumeEvent() {
this.consumed = true;
}
private class NullOutputStream extends OutputStream {
public void write(int b) throws IOException {}
}
private int resolveEventKey(int key, char c) {
if (c == '=' || key == 0)
return 13;
return key;
}
public void considerDoubleClick(int button, int x, int y) {
if (this.doubleClickTimeout == 0L) {
this.clickX = x;
this.clickY = y;
this.clickButton = button;
this.doubleClickTimeout = System.currentTimeMillis() + this.doubleClickDelay;
fireMouseClicked(button, x, y, 1);
} else if (this.clickButton == button &&
System.currentTimeMillis() < this.doubleClickTimeout) {
fireMouseClicked(button, x, y, 2);
this.doubleClickTimeout = 0L;
}
}
public void poll(int width, int height) {
if (this.paused) {
clearControlPressedRecord();
clearKeyPressedRecord();
clearMousePressedRecord();
do {
} while (Keyboard.next());
do {
} while (Mouse.next());
return;
}
if (!Display.isActive()) {
clearControlPressedRecord();
clearKeyPressedRecord();
clearMousePressedRecord();
}
int i;
for (i = 0; i < this.keyListenersToAdd.size(); i++)
addKeyListenerImpl(this.keyListenersToAdd.get(i));
this.keyListenersToAdd.clear();
for (i = 0; i < this.mouseListenersToAdd.size(); i++)
addMouseListenerImpl(this.mouseListenersToAdd.get(i));
this.mouseListenersToAdd.clear();
if (this.doubleClickTimeout != 0L &&
System.currentTimeMillis() > this.doubleClickTimeout)
this.doubleClickTimeout = 0L;
this.height = height;
Iterator<ControlledInputReciever> allStarts = this.allListeners.iterator();
while (allStarts.hasNext()) {
ControlledInputReciever listener = allStarts.next();
listener.inputStarted();
}
while (Keyboard.next()) {
if (Keyboard.getEventKeyState()) {
int k = resolveEventKey(Keyboard.getEventKey(), Keyboard.getEventCharacter());
this.keys[k] = Keyboard.getEventCharacter();
this.pressed[k] = true;
this.nextRepeat[k] = System.currentTimeMillis() + this.keyRepeatInitial;
this.consumed = false;
for (int m = 0; m < this.keyListeners.size(); m++) {
KeyListener listener = this.keyListeners.get(m);
if (listener.isAcceptingInput()) {
listener.keyPressed(k, Keyboard.getEventCharacter());
if (this.consumed)
break;
}
}
continue;
}
int eventKey = resolveEventKey(Keyboard.getEventKey(), Keyboard.getEventCharacter());
this.nextRepeat[eventKey] = 0L;
this.consumed = false;
for (int j = 0; j < this.keyListeners.size(); j++) {
KeyListener listener = this.keyListeners.get(j);
if (listener.isAcceptingInput()) {
listener.keyReleased(eventKey, this.keys[eventKey]);
if (this.consumed)
break;
}
}
}
while (Mouse.next()) {
if (Mouse.getEventButton() >= 0) {
if (Mouse.getEventButtonState()) {
this.consumed = false;
this.mousePressed[Mouse.getEventButton()] = true;
this.pressedX = (int)(this.xoffset + Mouse.getEventX() * this.scaleX);
this.pressedY = (int)(this.yoffset + (height - Mouse.getEventY()) * this.scaleY);
for (int k = 0; k < this.mouseListeners.size(); k++) {
MouseListener listener = this.mouseListeners.get(k);
if (listener.isAcceptingInput()) {
listener.mousePressed(Mouse.getEventButton(), this.pressedX, this.pressedY);
if (this.consumed)
break;
}
}
continue;
}
this.consumed = false;
this.mousePressed[Mouse.getEventButton()] = false;
int releasedX = (int)(this.xoffset + Mouse.getEventX() * this.scaleX);
int releasedY = (int)(this.yoffset + (height - Mouse.getEventY()) * this.scaleY);
if (this.pressedX != -1 &&
this.pressedY != -1 &&
Math.abs(this.pressedX - releasedX) < this.mouseClickTolerance &&
Math.abs(this.pressedY - releasedY) < this.mouseClickTolerance) {
considerDoubleClick(Mouse.getEventButton(), releasedX, releasedY);
this.pressedX = this.pressedY = -1;
}
for (int j = 0; j < this.mouseListeners.size(); j++) {
MouseListener listener = this.mouseListeners.get(j);
if (listener.isAcceptingInput()) {
listener.mouseReleased(Mouse.getEventButton(), releasedX, releasedY);
if (this.consumed)
break;
}
}
continue;
}
if (Mouse.isGrabbed() && this.displayActive && (
Mouse.getEventDX() != 0 || Mouse.getEventDY() != 0)) {
this.consumed = false;
for (int j = 0; j < this.mouseListeners.size(); j++) {
MouseListener listener = this.mouseListeners.get(j);
if (listener.isAcceptingInput()) {
if (anyMouseDown()) {
listener.mouseDragged(0, 0, Mouse.getEventDX(), -Mouse.getEventDY());
} else {
listener.mouseMoved(0, 0, Mouse.getEventDX(), -Mouse.getEventDY());
}
if (this.consumed)
break;
}
}
}
int dwheel = Mouse.getEventDWheel();
this.wheel += dwheel;
if (dwheel != 0) {
this.consumed = false;
for (int j = 0; j < this.mouseListeners.size(); j++) {
MouseListener listener = this.mouseListeners.get(j);
if (listener.isAcceptingInput()) {
listener.mouseWheelMoved(dwheel);
if (this.consumed)
break;
}
}
}
}
if (!this.displayActive || Mouse.isGrabbed()) {
this.lastMouseX = getMouseX();
this.lastMouseY = getMouseY();
} else if (this.lastMouseX != getMouseX() || this.lastMouseY != getMouseY()) {
this.consumed = false;
for (int j = 0; j < this.mouseListeners.size(); j++) {
MouseListener listener = this.mouseListeners.get(j);
if (listener.isAcceptingInput()) {
if (anyMouseDown()) {
listener.mouseDragged(this.lastMouseX, this.lastMouseY, getMouseX(), getMouseY());
} else {
listener.mouseMoved(this.lastMouseX, this.lastMouseY, getMouseX(), getMouseY());
}
if (this.consumed)
break;
}
}
this.lastMouseX = getMouseX();
this.lastMouseY = getMouseY();
}
if (controllersInited)
for (int j = 0; j < getControllerCount(); j++) {
int count = ((Controller)controllers.get(j)).getButtonCount() + 3;
count = Math.min(count, 24);
for (int c = 0; c <= count; c++) {
if (this.controls[j][c] && !isControlDwn(c, j)) {
this.controls[j][c] = false;
fireControlRelease(c, j);
} else if (!this.controls[j][c] && isControlDwn(c, j)) {
this.controllerPressed[j][c] = true;
this.controls[j][c] = true;
fireControlPress(c, j);
}
}
}
if (this.keyRepeat)
for (int j = 0; j < 1024; j++) {
if (this.pressed[j] && this.nextRepeat[j] != 0L &&
System.currentTimeMillis() > this.nextRepeat[j]) {
this.nextRepeat[j] = System.currentTimeMillis() + this.keyRepeatInterval;
this.consumed = false;
for (int k = 0; k < this.keyListeners.size(); k++) {
KeyListener listener = this.keyListeners.get(k);
if (listener.isAcceptingInput()) {
listener.keyPressed(j, this.keys[j]);
if (this.consumed)
break;
}
}
}
}
Iterator<ControlledInputReciever> all = this.allListeners.iterator();
while (all.hasNext()) {
ControlledInputReciever listener = all.next();
listener.inputEnded();
}
if (Display.isCreated())
this.displayActive = Display.isActive();
}
public void enableKeyRepeat(int initial, int interval) {
Keyboard.enableRepeatEvents(true);
}
public void enableKeyRepeat() {
Keyboard.enableRepeatEvents(true);
}
public void disableKeyRepeat() {
Keyboard.enableRepeatEvents(false);
}
public boolean isKeyRepeatEnabled() {
return Keyboard.areRepeatEventsEnabled();
}
private void fireControlPress(int index, int controllerIndex) {
this.consumed = false;
for (int i = 0; i < this.controllerListeners.size(); i++) {
ControllerListener listener = this.controllerListeners.get(i);
if (listener.isAcceptingInput()) {
switch (index) {
case 0:
listener.controllerLeftPressed(controllerIndex);
break;
case 1:
listener.controllerRightPressed(controllerIndex);
break;
case 2:
listener.controllerUpPressed(controllerIndex);
break;
case 3:
listener.controllerDownPressed(controllerIndex);
break;
default:
listener.controllerButtonPressed(controllerIndex, index - 4 + 1);
break;
}
if (this.consumed)
break;
}
}
}
private void fireControlRelease(int index, int controllerIndex) {
this.consumed = false;
for (int i = 0; i < this.controllerListeners.size(); i++) {
ControllerListener listener = this.controllerListeners.get(i);
if (listener.isAcceptingInput()) {
switch (index) {
case 0:
listener.controllerLeftReleased(controllerIndex);
break;
case 1:
listener.controllerRightReleased(controllerIndex);
break;
case 2:
listener.controllerUpReleased(controllerIndex);
break;
case 3:
listener.controllerDownReleased(controllerIndex);
break;
default:
listener.controllerButtonReleased(controllerIndex, index - 4 + 1);
break;
}
if (this.consumed)
break;
}
}
}
private boolean isControlDwn(int index, int controllerIndex) {
switch (index) {
case 0:
return isControllerLeft(controllerIndex);
case 1:
return isControllerRight(controllerIndex);
case 2:
return isControllerUp(controllerIndex);
case 3:
return isControllerDown(controllerIndex);
}
if (index >= 4)
return isButtonPressed(index - 4, controllerIndex);
throw new RuntimeException("Unknown control index");
}
public void pause() {
this.paused = true;
clearKeyPressedRecord();
clearMousePressedRecord();
clearControlPressedRecord();
}
public void resume() {
this.paused = false;
}
private void fireMouseClicked(int button, int x, int y, int clickCount) {
this.consumed = false;
for (int i = 0; i < this.mouseListeners.size(); i++) {
MouseListener listener = this.mouseListeners.get(i);
if (listener.isAcceptingInput()) {
listener.mouseClicked(button, x, y, clickCount);
if (this.consumed)
break;
}
}
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\org\newdawn\slick\Input.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ |
package com.tkb.elearning.action.admin;
import java.io.IOException;
import java.util.List;
import com.tkb.elearning.model.EnsureRight;
import com.tkb.elearning.service.EnsureRightService;
import com.tkb.elearning.util.VerifyBaseAction;
public class EnsureRightAction extends VerifyBaseAction {
private static final long serialVersionUID = 1L;
private EnsureRightService ensureRightService; //品保權益服務
private List<EnsureRight> ensureRightList; //品保權益清單
private EnsureRight ensureRight; //品保權益資料
private int pageNo; //頁碼
private int[] deleteList; //刪除的ID清單
/**
* 清單頁面
* @return
*/
public String index() {
if(ensureRight == null) {
ensureRight = new EnsureRight();
}
pageTotalCount = ensureRightService.getCount(ensureRight);
pageNo = super.pageSetting(pageNo);
ensureRightList = ensureRightService.getList(pageCount, pageStart, ensureRight);
return "list";
}
/**
* 新增頁面
* @return
*/
public String add() {
ensureRight = new EnsureRight();
return "form";
}
/**
* 新增資料
* @return
* @throws IOException
*/
public String addSubmit() throws IOException {
ensureRightService.add(ensureRight);
return "index";
}
/**
* 修改頁面
* @return
*/
public String update() {
ensureRight = ensureRightService.getData(ensureRight);
return "form";
}
/**
* 修改最新消息
* @return
* @throws IOException
*/
public String updateSubmit() throws IOException {
ensureRightService.update(ensureRight);
return "index";
}
/**
* 刪除最新消息
* @return
*/
public String delete() throws IOException {
for(int id : deleteList) {
ensureRight.setId(id);
ensureRight = ensureRightService.getData(ensureRight);
ensureRightService.delete(id);
}
return "index";
}
/**
* 瀏覽頁面
* @return
*/
public String view(){
ensureRight=ensureRightService.getData(ensureRight);
System.out.println(ensureRight.getId());
return "view";
}
public EnsureRightService getEnsureRightService() {
return ensureRightService;
}
public void setEnsureRightService(EnsureRightService ensureRightService) {
this.ensureRightService = ensureRightService;
}
public List<EnsureRight> getEnsureRightList() {
return ensureRightList;
}
public void setEnsureRightList(List<EnsureRight> ensureRightList) {
this.ensureRightList = ensureRightList;
}
public EnsureRight getEnsureRight() {
return ensureRight;
}
public void setEnsureRight(EnsureRight ensureRight) {
this.ensureRight = ensureRight;
}
public int getPageNo() {
return pageNo;
}
public void setPageNo(int pageNo) {
this.pageNo = pageNo;
}
public int[] getDeleteList() {
return deleteList;
}
public void setDeleteList(int[] deleteList) {
this.deleteList = deleteList;
}
}
|
package com.udem.ift6243.dao;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.udem.ift6243.model.Solution;
import com.udem.ift6243.sql.schema.SolutionSchema;
public class SolutionDao
{
private Context context;
public SolutionDao(Context context)
{
this.context = context;
}
public boolean updateSolution(Solution solution)
{
boolean error = true;
DatabaseHandler dbHandler = new DatabaseHandler(this.context);
SQLiteDatabase db = dbHandler.getReadableDatabase();
db.beginTransaction();
try
{
ContentValues values = new ContentValues();
values.put(SolutionSchema.TABLE_COL_CATEGORY_ID, solution.getCategoryId());
values.put(SolutionSchema.TABLE_COL_NAME, solution.getName());
values.put(SolutionSchema.TABLE_COL_DESCRIPTION, solution.getDescription());
values.put(SolutionSchema.TABLE_COL_DURATION, solution.getDuration());
values.put(SolutionSchema.TABLE_COL_PRIORITY, solution.getPriority());
int nbRows = db.update(SolutionSchema.TABLE_NAME, values,
SolutionSchema.TABLE_COL_ID + " = ?",
new String[] { String.valueOf(solution.getId()) });
db.setTransactionSuccessful();
if(nbRows > 0)
{
error = false;
}
}
finally
{
db.endTransaction();
db.close();
}
return !error;
}
/**
* Get solution from id
* @param id de la solution
* @return Solution
*/
public Solution getSolution(Integer id)
{
Solution solution = null;
DatabaseHandler dbHandler = new DatabaseHandler(context);
SQLiteDatabase db = dbHandler.getReadableDatabase();
Cursor cursor_solution = null;
db.beginTransaction();
try
{
cursor_solution = db.query(SolutionSchema.TABLE_NAME,
null,
SolutionSchema.TABLE_COL_ID + " = ?",
new String[] { String.valueOf(id.intValue()) },
null, null, null, null);
if (cursor_solution != null && cursor_solution.moveToLast())
{
solution = this.createSolutionFromCursor(cursor_solution);
}
db.setTransactionSuccessful();
}
finally
{
db.endTransaction();
db.close();
if(cursor_solution != null) cursor_solution.close();
}
return solution;
}
public ArrayList<Solution> getSolution()
{
ArrayList<Solution> solutionList = new ArrayList<Solution>();
Solution solution = null;
DatabaseHandler dbHandler = new DatabaseHandler(this.context);
SQLiteDatabase db = dbHandler.getReadableDatabase();
Cursor cursor_solution = null;
db.beginTransaction();
try
{
cursor_solution = db.query(SolutionSchema.TABLE_NAME,
null, null, null, null, null, null, null);
if (cursor_solution != null && cursor_solution.moveToFirst())
{
while (cursor_solution.isAfterLast() == false)
{
solution = this.createSolutionFromCursor(cursor_solution);
solutionList.add(solution);
cursor_solution.moveToNext();
}
}
db.setTransactionSuccessful();
}
finally
{
db.endTransaction();
db.close();
if(cursor_solution != null) cursor_solution.close();
}
return solutionList;
}
private Solution createSolutionFromCursor(Cursor cursor_solution)
{
Solution solution = null;
Integer solutionId = Integer.valueOf(cursor_solution.getInt(0));
Integer categoryId = Integer.valueOf(cursor_solution.getInt(1));
String name = cursor_solution.getString(2);
String description = cursor_solution.getString(3);
Double duration = Double.valueOf(cursor_solution.getDouble(4));
Double priority = Double.valueOf(cursor_solution.getDouble(5));
solution = new Solution(solutionId, categoryId, name, description,
duration, priority);
return solution;
}
}
|
package com.alibaba.otter.canal.client.adapter.rdb.service;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class BatchExecutor {
private static final Logger logger = LoggerFactory.getLogger(BatchExecutor.class);
private Integer key;
private Connection conn;
private AtomicInteger idx = new AtomicInteger(0);
private ExecutorService executor = Executors.newFixedThreadPool(1);
private Lock commitLock = new ReentrantLock();
private Condition condition = commitLock.newCondition();
public BatchExecutor(Integer key, Connection conn){
this.key = key;
this.conn = conn;
try {
this.conn.setAutoCommit(false);
} catch (SQLException e) {
logger.error(e.getMessage(), e);
}
}
public Integer getKey() {
return key;
}
public Connection getConn() {
return conn;
}
public static void setValue(List<Map<String, ?>> values, int type, Object value) {
Map<String, Object> valueItem = new HashMap<>();
valueItem.put("type", type);
valueItem.put("value", value);
values.add(valueItem);
}
public void execute(String sql, List<Map<String, ?>> values) {
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
int len = values.size();
for (int i = 0; i < len; i++) {
int type = (Integer) values.get(i).get("type");
Object value = values.get(i).get("value");
RdbSyncService.setPStmt(type, pstmt, value, i + 1);
}
pstmt.execute();
} catch (SQLException e) {
logger.error(e.getMessage(), e);
}
}
public void commit() {
try {
commitLock.lock();
conn.commit();
if (logger.isTraceEnabled()) {
logger.trace("Batch executor: " + key + " commit " + idx.get() + " rows");
}
condition.signal();
idx.set(0);
} catch (SQLException e) {
logger.error(e.getMessage(), e);
} finally {
commitLock.unlock();
}
}
public void close() {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
logger.error(e.getMessage(), e);
}
}
executor.shutdown();
}
}
|
package com.example.ducnhan.dulichphuquy;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
//to exit the application when back button '<- ' is clicked on toolbar
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar); //will display the toolbar along with App's name i.e Delhi06
getSupportActionBar().setDisplayHomeAsUpEnabled(true);//will display the back arrow '<-' button
//set adapter to viewpager
final ViewPager viewPager = (ViewPager) findViewById(R.id.tab_viewpager);
SimpleFragmentPagerAdapter adapter = new SimpleFragmentPagerAdapter(this, getSupportFragmentManager());
viewPager.setAdapter(adapter);
//set viewpager with tablayout
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
//when a tab is clicked or selected via scrolling horizontally
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
//adding animation to images corresponding to whatever category is selected
Animation mAnim = AnimationUtils.loadAnimation(MainActivity.this, android.R.anim.fade_in);
mAnim.setInterpolator(new DecelerateInterpolator());
mAnim.setDuration(1100);
ImageView i = (ImageView) findViewById(R.id.top_image);
i.startAnimation(mAnim);
int position = tab.getPosition();
if (position == 0) {
i.setImageResource(R.drawable.thangcanh);
} else if (position == 1) {
i.setImageResource(R.drawable.restaurant);
} else if (position == 2) {
i.setImageResource(R.drawable.shopping);
} else {
i.setImageResource(R.drawable.muasam);
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
//do nothing
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
//do nothing
}
});
}
}
|
package it.polimi.ingsw.GC_21.BOARD;
import static org.junit.Assert.*;
import org.junit.Test;
import it.polimi.ingsw.GC_21.GAMECOMPONENTS.DevCardType;
import it.polimi.ingsw.GC_21.GAMEMANAGEMENT.Game;
import it.polimi.ingsw.GC_21.PLAYER.Color;
import it.polimi.ingsw.GC_21.PLAYER.FamilyMemberColor;
import it.polimi.ingsw.GC_21.PLAYER.Player;
public class TowerTest {
@Test
public void checkFMPresenceTest() {
Game testGame = new Game("aaa");
Player testPlayer = new Player("aaa", Color.Blue, testGame);
Tower.factoryTowers(testGame);
testGame.getBoard().getSpecificTower(DevCardType.Building).getFloors()[0].getSingleActionSpace().placeFamilyMember(testPlayer.getSpecificFamilyMember(FamilyMemberColor.Orange));
boolean result = testGame.getBoard().getSpecificTower(DevCardType.Building).checkFamilyMemberPresence();
assertTrue(result);
}
@Test public void checkFMOfMineTest(){
Game testGame = new Game("aaa");
Player testPlayer = new Player("aaa", Color.Blue, testGame);
Tower.factoryTowers(testGame);
testGame.getBoard().getSpecificTower(DevCardType.Building).getFloors()[0].getSingleActionSpace().placeFamilyMember(testPlayer.getSpecificFamilyMember(FamilyMemberColor.Orange));
boolean result = testGame.getBoard().getSpecificTower(DevCardType.Building).checkTowerFamilyMemberOfMine(testPlayer);
assertTrue(result);
}
}
|
package com.tencent.mm.plugin.wallet_core.c;
import com.tencent.mm.ab.b;
import com.tencent.mm.ab.b.a;
import com.tencent.mm.ab.e;
import com.tencent.mm.ab.l;
import com.tencent.mm.network.k;
import com.tencent.mm.network.q;
import com.tencent.mm.protocal.c.uk;
import com.tencent.mm.protocal.c.ul;
import com.tencent.mm.sdk.platformtools.x;
public final class j extends l implements k {
private e diJ;
private b eAN;
private boolean pjf;
private uk pjl;
public ul pjm;
public j(String str, boolean z) {
this.pjf = z;
a aVar = new a();
aVar.dIG = new uk();
aVar.dIH = new ul();
if (z) {
aVar.dIF = 2529;
aVar.uri = "/cgi-bin/mmpay-bin/mktf2fmodifyexposure";
} else {
aVar.dIF = 2888;
aVar.uri = "/cgi-bin/mmpay-bin/mktmodifyexposure";
}
aVar.dII = 0;
aVar.dIJ = 0;
this.eAN = aVar.KT();
this.pjl = (uk) this.eAN.dID.dIL;
this.pjl.rxR = str;
}
public final int getType() {
if (this.pjf) {
return 2529;
}
return 2888;
}
public final int a(com.tencent.mm.network.e eVar, e eVar2) {
this.diJ = eVar2;
return a(eVar, this.eAN, this);
}
public final void a(int i, int i2, int i3, String str, q qVar, byte[] bArr) {
x.i("MicroMsg.NetSceneMktModifyExposure", "onGYNetEnd, netId: %s, errType: %s, errCode: %s, errMsg: %s", new Object[]{Integer.valueOf(i), Integer.valueOf(i2), Integer.valueOf(i3), str});
this.pjm = (ul) ((b) qVar).dIE.dIL;
if (this.diJ != null) {
this.diJ.a(i2, i3, str, this);
}
}
}
|
package de.ur.mi.android.lauflog.log;
/**
* Dieses Enum bildet die verschiedene Modi für die Sortierung der Log-Einträge ab. Einträge können
* nach Zeitpunk, zurückgelegter Strecke oder durchschnittlicher Geschwindigkeit sortiert werden.
*/
public enum LogSortMode {
DATE,
DISTANCE,
PACE
}
|
package com.tencent.mm.plugin.account.ui;
import android.text.Editable;
import android.text.TextWatcher;
class RegByMobileRegAIOUI$21 implements TextWatcher {
final /* synthetic */ RegByMobileRegAIOUI eVb;
RegByMobileRegAIOUI$21(RegByMobileRegAIOUI regByMobileRegAIOUI) {
this.eVb = regByMobileRegAIOUI;
}
public final void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
public final void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
public final void afterTextChanged(Editable editable) {
RegByMobileRegAIOUI.b(this.eVb);
}
}
|
package uz.kassa.test.service.security;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import uz.kassa.test.domain.entity.Employee;
import java.util.Collection;
/** Author: Khumoyun Khujamov Date: 11/13/20 Time: 2:34 PM */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class LoggedUser implements UserDetails {
private Long id;
private String username;
@JsonIgnore
private String password;
private Collection<? extends GrantedAuthority> authorities;
public static LoggedUser create(Employee employee) {
return new LoggedUser(employee.getId(), employee.getUsername(), employee.getPassword());
}
public LoggedUser(Long id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}
@Override
public String getPassword() {
return this.password;
}
@Override
public String getUsername() {
return this.username;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
|
package Day2;
import java.util.InputMismatchException;
import java.util.Scanner;
public class CalculateAreaWithValidation {
static double length,width;
static String choice;
public static void main(String[] args) throws MyOutOfRangeException {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
choice = "y";
System.out.println("Welcome to the Area and Perimeter Calculator");
while (!choice.equalsIgnoreCase("n"))
{
// get the input from the user
length = getDoubleLengthWithinRange(sc,choice,0.0,1000000.0);
//System.out.print("Enter width: ");
width = getDoubleWidthWithinRange(sc,choice,0.0,1000000.0);
//calculate area and perimeter
double area = length*width;
double perimeter=2*(length+width);
System.out.println("Area: "+area);
System.out.println("Perimeter: "+perimeter);
System.out.println();
// see if the user wants to continue
choice=getChoiceValue(sc);
System.out.println();
}
}
//Validation for getting length as double and within range
public static double getDoubleLengthWithinRange(Scanner sc,String prompt,double min,double max){
boolean flag;
double length=0;
do{
try{
flag=true;
System.out.print("Enter length: ");
length=sc.nextDouble();
if(length<min || length>max){
flag=false;
throw new MyOutOfRangeException("Error! Length must be greater than 0.0 and less than 1000000.0");
}
}
catch(InputMismatchException e){
flag=false;
System.out.println("Error! Invalid decimal value.Try again.");
sc.nextLine();
System.out.println();
//System.out.println("Flag value is :"+flag);
}
catch(MyOutOfRangeException e){
flag=false;
System.out.println("Error! Length must be greater than 0.0 and less than 1000000.0");
sc.nextLine();
System.out.println();
}
}while(flag==false);
return length;
}
//Validation for getting width as double and within range
public static double getDoubleWidthWithinRange(Scanner sc,String prompt,double min,double max){
boolean flag;
double width=0;
do{
try{
flag=true;
System.out.print("Enter width: ");
width=sc.nextDouble();
if(width<min || width>max){
throw new MyOutOfRangeException("Error! Length must be greater than 0.0 and less than 1000000.0");
}
}
catch(InputMismatchException e){
System.out.println("Error! Invalid decimal value.Try again.");
sc.nextLine();
System.out.println();
flag=false;
}
catch(MyOutOfRangeException e){
System.out.println("Error! Width must be greater than 0.0 and less than 1000000.0");
sc.nextLine();
System.out.println();
flag=false;
}
}
while(flag==false);
return width;
}
//Validation for getting user choice as y or n only
public static String getChoiceValue(Scanner sc){
boolean flag;
String choice1="";
do{
flag=true;
System.out.print("Continue? (y/n): ");
choice1 = sc.nextLine();
if(choice1.equals("")){
System.out.println("This field is required.Try again");
flag=false;
}
else if(!(choice1.equalsIgnoreCase("y")) && !(choice1.equalsIgnoreCase("n"))){
System.out.println("Please enter only y or n as the choice");
flag=false;
}
else{
break;
}
}while(flag==false);
return choice1;
}
}
class MyOutOfRangeException extends Exception{
MyOutOfRangeException(String message){
super(message);
}
}
|
import java.util.Objects;
public class Security extends AbstractWorker {
protected double area;
final int BASE = 1000;
final int CONST1 = 30;
public Security() {
}
public Security(String name, String organization, double coefficient, double area) {
super(name, organization, coefficient);
this.area = area;
}
@Override
public String toString() {
return super.toString() + "Area: " + this.area;
}
public double getArea() {
return area;
}
public void setArea(double area) {
this.area = area;
}
@Override
public double calculateSalary() {
return round(BASE * this.coefficient * this.area / CONST1);
}
}
|
package gov.ssa.functionalfitness.dao;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;
import gov.ssa.functionalfitness.entity.User;
@Repository
public class UserDAO implements IUserDAO {
@Autowired
private HibernateTemplate hibernateTemplate;
@Override
public User getUserById(int profileID) {
return hibernateTemplate.get(User.class, profileID);
}
@SuppressWarnings("unchecked")
@Override
public List<User> getAllUsers() {
String hql = "FROM User as u ORDER BY u.profileID";
return (List<User>) hibernateTemplate.find(hql);
}
@Override
public boolean addUser(User user) {
hibernateTemplate.save(user);
return false;
}
@Override
public void updateUser(User user) {
User record = getUserById(user.getProfileID());
record.setUsername(user.getUsername());
record.setPassword(user.getPassword());
record.setFirstName(user.getFirstName());
record.setLastName(user.getLastName());
record.setEmail(user.getEmail());
record.setEquipment(user.getEquipment());
record.setAge(user.getAge());
record.setWeight(user.getWeight());
record.setSex(user.getSex());
hibernateTemplate.update(record);
}
@Override
public void deleteUser(int profileID) {
hibernateTemplate.delete(getUserById(profileID));
}
@SuppressWarnings("unchecked")
@Override
public List<User> login(String password, String username) {
String hql = "FROM User where username = '" + username + "'";
return (List<User>)hibernateTemplate.find(hql);
}
}
|
package pe.edu.upc.demo.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import pe.edu.upc.demo.entity.Atencion;
public interface AtencionRepository extends JpaRepository<Atencion, Integer>{
}
|
package plattern.BridgePattern;
public interface Color {
public String description ();
}
|
package com.bridgeit.algorithmprogram;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class OrderedList {
public static void main(String[] args) throws Exception {
FileReader file = new FileReader(
"//home//bridgeit//Documents//workspace-sts-3.9.3.RELEASE//Java-Program//src//com//bridgeit//ordered.txt");
BufferedReader br = new BufferedReader(file);
String str = br.readLine();
System.out.println("the files contains are:");
System.out.println(str);
}
}
|
package com.tencent.mm.plugin.account.friend.ui;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
class FindMContactAddUI$3 implements OnCancelListener {
final /* synthetic */ FindMContactAddUI eLW;
FindMContactAddUI$3(FindMContactAddUI findMContactAddUI) {
this.eLW = findMContactAddUI;
}
public final void onCancel(DialogInterface dialogInterface) {
}
}
|
package com.noteshare.course;
import com.noteshare.common.utils.cache.impl.CurrentCacheImpl;
public class CourseConstant {
/**
* 课程头部推荐课程开始值
*/
public static final Integer COURSE_RECOMMEND_START = 0;
/**
* 课程头部推荐课程结束值
*/
public static final Integer COURSE_RECOMMEND_END = 15;
/**
* 默认缓存ip访问记录时间10分钟,10分钟后再操作才增加一次访问记录
*/
public static final int CACHETIME = 10 * 60;
/**
* 设置缓存每5分钟检测一次是否有记录已经过期
*/
public static final int EXPIRYINTERVAL = 5 * 60;
public static final Integer MODULESIZE = 10;
/**
* TODO:文章访问记录缓存,其实这里的缓存应该不需要使用map用list即可,后续再编写一套配套记录缓存方案
*/
public static final CurrentCacheImpl ARTICLEACCESSCACHE = new CurrentCacheImpl(EXPIRYINTERVAL, MODULESIZE);
/**
* 存放课程图片的文件夹
*/
public static final String PICFILENAME = "pic";
/**
* 存放课程相关文档的文件夹
*/
public static final String DOCFILENAME = "doc";
/**
* 课程相关附件路径配置名
*/
public static final String COURSEFILEPATH = "course.filePath";
/**
* 当获取文章图片未找到时返回默认图片,默认图片放置在根目录下的该文件
*/
public static final String ARTICLEDEFAULTPIC = "/commonImages/default.jpg";
}
|
import java.util.*;
import java.lang.*;
public class Letter {
//CAMPI
private Random r = new Random();
private char c;
private boolean visited;
//COSTRUTTORE
/*public Letter(char c) {
this.c = c; //(char)(r.nextInt(26) + 'a');
visited = false;
}*/
public Letter() {
c = (char)(r.nextInt(26) + 'a');
visited = false;
}
//METODI
public String toStringU() {
return Character.toString(c).toUpperCase();
}
public void visited(boolean b) {
visited = b;
}
public boolean isVisited() {
return visited;
}
public char get() {
return c;
}
public String toString() {
return Character.toString(c);
}
} |
package com.delaroystudios.smartlock;
/**
* Created by delaroystudios on 10/13/2016.
*/
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class ContentActivity extends AppCompatActivity {
private static final String TAG = "ContentActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content);
Button logoutButton = (Button) findViewById(R.id.logoutButton);
logoutButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
});
Button changeCredsButton = (Button) findViewById(R.id.changeCredsButton);
changeCredsButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(v.getContext(), ChangeCredActivity.class));
}
});
}
}
|
package collections.optinal.mains;
import collections.optinal.SortList;
import java.io.IOException;
import java.util.ArrayList;
public class MainSortList {
public static void main(String[] args) throws IOException {
ArrayList<String> list = SortList.sortList("src/main/resources/fileForSortAndCountWords.txt");
for (String line : list) {
System.out.println(line);
}
}
}
|
package com.shopify.admin.cs;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.shopify.admin.AdminData;
import com.shopify.common.SpConstants;
import com.shopify.common.util.UtilFn;
@Controller
@SpringBootApplication
/**
* CS관리 컨트롤러
*
*/
public class AdminCsController {
@Autowired private AdminCsService csService;
@Autowired private UtilFn util;
private Logger LOGGER = LoggerFactory.getLogger(AdminCsController.class);
/**
* CS관리 > 배송목록
* @param model
* @return
*/
@GetMapping(value = "/admin/cs/adminDeliveryList")
public String selectAdminDeliveryList(Model model, @ModelAttribute AdminCsData csData, HttpSession sess) {
int currentPage = csData.getCurrentPage();
if(currentPage == 0) csData.setCurrentPage(1);
int pageSize = csData.getPageSize();
if(pageSize == 0) csData.setPageSize(SpConstants.PAGE_BLOCK_SIZE);
// 날짜 매달 1~30일인데 현재 날짜 기준으로 과거 30일로 검색 기간 조정
String searchDateStart = csData.getSearchDateStart();
String searchDateEnd = csData.getSearchDateEnd();
if (true) {
// 검색기간 정보가 비어있을 경우, 지난 일주일의 데이터를 출력한다.
int nPrevDays = 30 ;
String sDateFormat = "YYYY-MM-dd" ;
// 종료일자 : 오늘
if (searchDateEnd == null || "".equals(searchDateEnd)) {
searchDateEnd = util.getToday(sDateFormat) ;
csData.setSearchDateEnd(searchDateEnd) ;
}
// 시작일자 : 30일전
if (searchDateStart == null || "".equals(searchDateStart)) {
searchDateStart = util.getPrevDate(nPrevDays, sDateFormat) ;
csData.setSearchDateStart(searchDateStart) ;
}
}
// 그룹 코드 지정
csData.setStateGroup(SpConstants.STATE_GROUP_DELIVERY);
Map<String, Object> map = csService.selectAdminCsDeliveryList(csData, sess);
model.addAttribute("search", csData);
model.addAttribute("list", map.get("list"));
model.addAttribute("paging", map.get("paging"));
return "/admin/cs/adminDeliveryList";
}
/**
* CS관리 > 에러목록
* @param model
* @return
*/
@GetMapping(value = "/admin/cs/adminErrorList")
public String selectAdminErrorList(Model model, @ModelAttribute AdminCsData csData, HttpSession sess) {
LOGGER.debug("----------adminErrorList----------------");
int currentPage = csData.getCurrentPage();
if(currentPage == 0) csData.setCurrentPage(1);
int pageSize = csData.getPageSize();
csData.setSearchState("A020025");
if(pageSize == 0) csData.setPageSize(SpConstants.PAGE_BLOCK_SIZE);
// 날짜 매달 1~30일인데 현재 날짜 기준으로 과거 30일로 검색 기간 조정
String searchDateStart = csData.getSearchDateStart();
String searchDateEnd = csData.getSearchDateEnd();
if (true) {
// 검색기간 정보가 비어있을 경우, 지난 일주일의 데이터를 출력한다.
int nPrevDays = 30 ;
String sDateFormat = "YYYY-MM-dd" ;
// 종료일자 : 오늘
if (searchDateEnd == null || "".equals(searchDateEnd)) {
searchDateEnd = util.getToday(sDateFormat) ;
csData.setSearchDateEnd(searchDateEnd) ;
}
// 시작일자 : 30일전
if (searchDateStart == null || "".equals(searchDateStart)) {
searchDateStart = util.getPrevDate(nPrevDays, sDateFormat) ;
csData.setSearchDateStart(searchDateStart) ;
}
}
// 그룹 코드 지정
// csData.setStateGroup(SpConstants.STATE_GROUP_BACK);
Map<String, Object> map = csService.selectAdminCsDeliveryList(csData, sess);
model.addAttribute("search", csData);
model.addAttribute("list", map.get("list"));
model.addAttribute("paging", map.get("paging"));
return "/admin/cs/adminErrorList";
}
/**
* CS관리 > 반송목록
* @param model
* @return
*/
@GetMapping(value = "/admin/cs/adminBackList")
public String selectAdminBackList(Model model, @ModelAttribute AdminCsData csData, HttpSession sess) {
int currentPage = csData.getCurrentPage();
if(currentPage == 0) csData.setCurrentPage(1);
int pageSize = csData.getPageSize();
if(pageSize == 0) csData.setPageSize(SpConstants.PAGE_BLOCK_SIZE);
// 날짜 매달 1~30일인데 현재 날짜 기준으로 과거 30일로 검색 기간 조정
String searchDateStart = csData.getSearchDateStart();
String searchDateEnd = csData.getSearchDateEnd();
if (true) {
// 검색기간 정보가 비어있을 경우, 지난 일주일의 데이터를 출력한다.
int nPrevDays = 30 ;
String sDateFormat = "YYYY-MM-dd" ;
// 종료일자 : 오늘
if (searchDateEnd == null || "".equals(searchDateEnd)) {
searchDateEnd = util.getToday(sDateFormat) ;
csData.setSearchDateEnd(searchDateEnd) ;
}
// 시작일자 : 30일전
if (searchDateStart == null || "".equals(searchDateStart)) {
searchDateStart = util.getPrevDate(nPrevDays, sDateFormat) ;
csData.setSearchDateStart(searchDateStart) ;
}
}
// 그룹 코드 지정
csData.setStateGroup(SpConstants.STATE_GROUP_BACK);
Map<String, Object> map = csService.selectAdminCsDeliveryList(csData, sess);
model.addAttribute("search", csData);
model.addAttribute("list", map.get("list"));
model.addAttribute("paging", map.get("paging"));
return "/admin/cs/adminBackList";
}
/**
* CS관리 > 교환목록
* @param model
* @return
*/
@GetMapping(value = "/admin/cs/adminExchangeList")
public String selectAdminExchangeList(Model model, @ModelAttribute AdminCsData csData, HttpSession sess) {
int currentPage = csData.getCurrentPage();
if(currentPage == 0) csData.setCurrentPage(1);
int pageSize = csData.getPageSize();
if(pageSize == 0) csData.setPageSize(SpConstants.PAGE_BLOCK_SIZE);
// 날짜 매달 1~30일인데 현재 날짜 기준으로 과거 30일로 검색 기간 조정
String searchDateStart = csData.getSearchDateStart();
String searchDateEnd = csData.getSearchDateEnd();
if (true) {
// 검색기간 정보가 비어있을 경우, 지난 일주일의 데이터를 출력한다.
int nPrevDays = 30 ;
String sDateFormat = "YYYY-MM-dd" ;
// 종료일자 : 오늘
if (searchDateEnd == null || "".equals(searchDateEnd)) {
searchDateEnd = util.getToday(sDateFormat) ;
csData.setSearchDateEnd(searchDateEnd) ;
}
// 시작일자 : 30일전
if (searchDateStart == null || "".equals(searchDateStart)) {
searchDateStart = util.getPrevDate(nPrevDays, sDateFormat) ;
csData.setSearchDateStart(searchDateStart) ;
}
}
// 그룹 코드 지정
csData.setStateGroup(SpConstants.STATE_GROUP_EXCHANGE);
Map<String, Object> map = csService.selectAdminCsDeliveryList(csData, sess);
model.addAttribute("search", csData);
model.addAttribute("list", map.get("list"));
model.addAttribute("paging", map.get("paging"));
return "/admin/cs/adminExchangeList";
}
/**
* CS관리 > 반품목록
* @param model
* @return
*/
@GetMapping(value = "/admin/cs/adminReturnList")
public String selectAdminReturnList(Model model, @ModelAttribute AdminCsData csData, HttpSession sess) {
int currentPage = csData.getCurrentPage();
if(currentPage == 0) csData.setCurrentPage(1);
int pageSize = csData.getPageSize();
if(pageSize == 0) csData.setPageSize(SpConstants.PAGE_BLOCK_SIZE);
// 날짜 매달 1~30일인데 현재 날짜 기준으로 과거 30일로 검색 기간 조정
String searchDateStart = csData.getSearchDateStart();
String searchDateEnd = csData.getSearchDateEnd();
if (true) {
// 검색기간 정보가 비어있을 경우, 지난 일주일의 데이터를 출력한다.
int nPrevDays = 30 ;
String sDateFormat = "YYYY-MM-dd" ;
// 종료일자 : 오늘
if (searchDateEnd == null || "".equals(searchDateEnd)) {
searchDateEnd = util.getToday(sDateFormat) ;
csData.setSearchDateEnd(searchDateEnd) ;
}
// 시작일자 : 30일전
if (searchDateStart == null || "".equals(searchDateStart)) {
searchDateStart = util.getPrevDate(nPrevDays, sDateFormat) ;
csData.setSearchDateStart(searchDateStart) ;
}
}
// 그룹 코드 지정
csData.setStateGroup(SpConstants.STATE_GROUP_RETURN);
Map<String, Object> map = csService.selectAdminCsDeliveryList(csData, sess);
model.addAttribute("search", csData);
model.addAttribute("list", map.get("list"));
model.addAttribute("paging", map.get("paging"));
return "/admin/cs/adminReturnList";
}
/**
* CS관리 > 추가요금목록
* @param model
* @return
*/
@GetMapping(value = "/admin/cs/adminPaymentList")
public String selectPaymentList(Model model, AdminCsData csData, HttpSession sess
, @RequestParam(value = "currentPage", required = false, defaultValue = "1") int currentPage
, @RequestParam(value = "searchState", required = false, defaultValue = "") String searchState
, @RequestParam(value = "searchType", required = false, defaultValue = "") String searchType
, @RequestParam(value = "searchWord", required = false, defaultValue = "") String searchWord
, @RequestParam(value = "searchDateStart", required = false, defaultValue = "") String searchDateStart
, @RequestParam(value = "searchDateEnd", required = false, defaultValue = "") String searchDateEnd
, @RequestParam(value = "pageSize", required = false, defaultValue = "10") int pageSize
) {
// 날짜 매달 1~30일인데 현재 날짜 기준으로 과거 30일로 검색 기간 조정
searchDateStart = csData.getSearchDateStart();
searchDateEnd = csData.getSearchDateEnd();
if (true) {
// 검색기간 정보가 비어있을 경우, 지난 일주일의 데이터를 출력한다.
int nPrevDays = 30 ;
String sDateFormat = "YYYY-MM-dd" ;
// 종료일자 : 오늘
if (searchDateEnd == null || "".equals(searchDateEnd)) {
searchDateEnd = util.getToday(sDateFormat) ;
csData.setSearchDateEnd(searchDateEnd) ;
}
// 시작일자 : 30일전
if (searchDateStart == null || "".equals(searchDateStart)) {
searchDateStart = util.getPrevDate(nPrevDays, sDateFormat) ;
csData.setSearchDateStart(searchDateStart) ;
}
}
csData.setCurrentPage(currentPage);
csData.setSearchState(searchState);
csData.setSearchType(searchType);
csData.setSearchWord(searchWord);
csData.setSearchDateStart(searchDateStart);
csData.setSearchDateEnd(searchDateEnd);
csData.setPageSize(pageSize);
Map<String, Object> map = csService.selectAdminPaymentList(csData, sess);
model.addAttribute("search", csData);
model.addAttribute("list", map.get("list"));
model.addAttribute("paging", map.get("paging"));
return "/admin/cs/adminPaymentList";
}
/**
* CS관리 > 배송목록 엑셀다운
* @param model
* @return
*/
@SuppressWarnings("null")
@GetMapping("/admin/cs/adminDeliveryListExcel")
public String adminDeliveryListExcel(@ModelAttribute AdminCsData csData, Model model, HttpSession sess
) {
LOGGER.debug("-----<EXCEL>-------");
AdminData shop = (AdminData) sess.getAttribute(SpConstants.ADMIN_SESSION_KEY);
String searchDateStart = csData.getSearchDateStart();
String searchDateEnd = csData.getSearchDateEnd();
int currentPage = 0;
int pageSize = csData.getPageSize();
LOGGER.debug(">searchDateStart:" + searchDateStart);
LOGGER.debug(">searchDateEnd:" + searchDateEnd);
// 기본 기간 검색 추가 (매월1일~매월말일)
if(searchDateStart == null || "".equals(searchDateStart)) {
searchDateStart = util.getDateElement("yymm") + "-01";
csData.setSearchDateStart(searchDateStart);
}
// 기본 기간 검색 추가 (매월1일~매월말일)
if(searchDateEnd == null || "".equals(searchDateEnd)) {
searchDateEnd = util.getDateElement("yymm") + "-" + util.getDateElement("ld");
csData.setSearchDateEnd(searchDateEnd);
}
if(pageSize == 0) pageSize = 10;
csData.setSearchDateStart(searchDateStart);
csData.setSearchDateEnd(searchDateEnd);
csData.setCurrentPage(currentPage);
csData.setPageSize(pageSize);
// 그룹 코드 지정
//csData.setStateGroup(SpConstants.STATE_GROUP_DELIVERY);
Map<String, Object> map = csService.selectAdminDeliveryList(csData, sess);
model.addAttribute("search", csData);
model.addAttribute("list", map.get("list"));
model.addAttribute("paging", map.get("paging"));
return "/admin/cs/adminDeliveryListExcel";
}
/**
* CS관리 > 에러목록 엑셀다운
* @param model
* @return
*/
@SuppressWarnings("null")
@GetMapping("/admin/cs/adminErrorListExcel")
public String adminErrorListExcel(@ModelAttribute AdminCsData csData, Model model, HttpSession sess
) {
LOGGER.debug("-----<EXCEL>-------");
AdminData shop = (AdminData) sess.getAttribute(SpConstants.ADMIN_SESSION_KEY);
String searchDateStart = csData.getSearchDateStart();
String searchDateEnd = csData.getSearchDateEnd();
int currentPage = 0;
int pageSize = csData.getPageSize();
csData.setSearchState("A020025");
LOGGER.debug(">searchDateStart:" + searchDateStart);
LOGGER.debug(">searchDateEnd:" + searchDateEnd);
// 기본 기간 검색 추가 (매월1일~매월말일)
if(searchDateStart == null || "".equals(searchDateStart)) {
searchDateStart = util.getDateElement("yymm") + "-01";
csData.setSearchDateStart(searchDateStart);
}
// 기본 기간 검색 추가 (매월1일~매월말일)
if(searchDateEnd == null || "".equals(searchDateEnd)) {
searchDateEnd = util.getDateElement("yymm") + "-" + util.getDateElement("ld");
csData.setSearchDateEnd(searchDateEnd);
}
if(pageSize == 0) pageSize = 10;
csData.setSearchDateStart(searchDateStart);
csData.setSearchDateEnd(searchDateEnd);
csData.setCurrentPage(currentPage);
csData.setPageSize(pageSize);
// 그룹 코드 지정
//csData.setStateGroup(SpConstants.STATE_GROUP_DELIVERY);
Map<String, Object> map = csService.selectAdminDeliveryList(csData, sess);
model.addAttribute("search", csData);
model.addAttribute("list", map.get("list"));
model.addAttribute("paging", map.get("paging"));
return "/admin/cs/adminErrorListExcel";
}
/**
* CS관리 > 반송목록 엑셀다운
* @param model
* @return
*/
@SuppressWarnings("null")
@GetMapping("/admin/cs/adminBackListExcel")
public String adminBackListExcel(@ModelAttribute AdminCsData csData, Model model, HttpSession sess
) {
AdminData shop = (AdminData) sess.getAttribute(SpConstants.ADMIN_SESSION_KEY);
String searchDateStart = csData.getSearchDateStart();
String searchDateEnd = csData.getSearchDateEnd();
int currentPage = 0;
int pageSize = csData.getPageSize();
// 기본 기간 검색 추가 (매월1일~매월말일)
if(searchDateStart == null || "".equals(searchDateStart)) {
searchDateStart = util.getDateElement("yymm") + "-01";
csData.setSearchDateStart(searchDateStart);
}
// 기본 기간 검색 추가 (매월1일~매월말일)
if(searchDateEnd == null || "".equals(searchDateEnd)) {
searchDateEnd = util.getDateElement("yymm") + "-" + util.getDateElement("ld");
csData.setSearchDateEnd(searchDateEnd);
}
if(pageSize == 0) pageSize = 10;
csData.setSearchDateStart(searchDateStart);
csData.setSearchDateEnd(searchDateEnd);
csData.setCurrentPage(currentPage);
csData.setPageSize(pageSize);
Map<String, Object> map = csService.selectAdminExcelList(csData, sess);
model.addAttribute("search", csData);
model.addAttribute("list", map.get("list"));
model.addAttribute("paging", map.get("paging"));
return "/admin/cs/adminBackListExcel";
}
/**
* CS관리 > 교환목록 엑셀다운
* @param model
* @return
*/
@SuppressWarnings("null")
@GetMapping("/admin/cs/adminExchangeListExcel")
public String adminExchangeListExcel(@ModelAttribute AdminCsData csData, Model model, HttpSession sess
) {
AdminData shop = (AdminData) sess.getAttribute(SpConstants.ADMIN_SESSION_KEY);
String searchDateStart = csData.getSearchDateStart();
String searchDateEnd = csData.getSearchDateEnd();
int currentPage = 0;
int pageSize = csData.getPageSize();
// 기본 기간 검색 추가 (매월1일~매월말일)
if(searchDateStart == null || "".equals(searchDateStart)) {
searchDateStart = util.getDateElement("yymm") + "-01";
csData.setSearchDateStart(searchDateStart);
}
// 기본 기간 검색 추가 (매월1일~매월말일)
if(searchDateEnd == null || "".equals(searchDateEnd)) {
searchDateEnd = util.getDateElement("yymm") + "-" + util.getDateElement("ld");
csData.setSearchDateEnd(searchDateEnd);
}
if(pageSize == 0) pageSize = 10;
csData.setSearchDateStart(searchDateStart);
csData.setSearchDateEnd(searchDateEnd);
csData.setCurrentPage(currentPage);
csData.setPageSize(pageSize);
Map<String, Object> map = csService.selectAdminExcelList(csData, sess);
model.addAttribute("search", csData);
model.addAttribute("list", map.get("list"));
model.addAttribute("paging", map.get("paging"));
return "/admin/cs/adminExchangeListExcel";
}
/**
* CS관리 > 반품목록 엑셀다운
* @param model
* @return
*/
@SuppressWarnings("null")
@GetMapping("/admin/cs/adminReturnListExcel")
public String adminReturnListExcel(@ModelAttribute AdminCsData csData, Model model, HttpSession sess
) {
AdminData shop = (AdminData) sess.getAttribute(SpConstants.ADMIN_SESSION_KEY);
String searchDateStart = csData.getSearchDateStart();
String searchDateEnd = csData.getSearchDateEnd();
int currentPage = 0;
int pageSize = csData.getPageSize();
// 기본 기간 검색 추가 (매월1일~매월말일)
if(searchDateStart == null || "".equals(searchDateStart)) {
searchDateStart = util.getDateElement("yymm") + "-01";
csData.setSearchDateStart(searchDateStart);
}
// 기본 기간 검색 추가 (매월1일~매월말일)
if(searchDateEnd == null || "".equals(searchDateEnd)) {
searchDateEnd = util.getDateElement("yymm") + "-" + util.getDateElement("ld");
csData.setSearchDateEnd(searchDateEnd);
}
if(pageSize == 0) pageSize = 10;
csData.setSearchDateStart(searchDateStart);
csData.setSearchDateEnd(searchDateEnd);
csData.setCurrentPage(currentPage);
csData.setPageSize(pageSize);
Map<String, Object> map = csService.selectAdminExcelList(csData, sess);
model.addAttribute("search", csData);
model.addAttribute("list", map.get("list"));
model.addAttribute("paging", map.get("paging"));
return "/admin/cs/adminReturnListExcel";
}
/**
* CS관리 > 추가요금 엑셀다운
* @param model
* @return
*/
@SuppressWarnings("null")
@GetMapping("/admin/cs/adminPaymentListExcel")
public String paymentListExcel(@ModelAttribute AdminCsData csData, Model model, HttpSession sess
) {
AdminData shop = (AdminData) sess.getAttribute(SpConstants.ADMIN_SESSION_KEY);
String searchDateStart = csData.getSearchDateStart();
String searchDateEnd = csData.getSearchDateEnd();
int currentPage = 0;
int pageSize = csData.getPageSize();
// 기본 기간 검색 추가 (매월1일~매월말일)
if(searchDateStart == null || "".equals(searchDateStart)) {
searchDateStart = util.getDateElement("yymm") + "-01";
csData.setSearchDateStart(searchDateStart);
}
// 기본 기간 검색 추가 (매월1일~매월말일)
if(searchDateEnd == null || "".equals(searchDateEnd)) {
searchDateEnd = util.getDateElement("yymm") + "-" + util.getDateElement("ld");
csData.setSearchDateEnd(searchDateEnd);
}
if(pageSize == 0) pageSize = 10;
csData.setSearchDateStart(searchDateStart);
csData.setSearchDateEnd(searchDateEnd);
csData.setCurrentPage(currentPage);
csData.setPageSize(pageSize);
Map<String, Object> map = csService.selectAdminExcelList(csData, sess);
model.addAttribute("search", csData);
model.addAttribute("list", map.get("list"));
model.addAttribute("paging", map.get("paging"));
return "/admin/cs/adminPaymentListExcel";
}
/**
* CS 관리 > 추가요금 상태변경
* @return
*/
@PostMapping(value = "/admin/cs/adminUpdateStatus")
public ModelAndView adminUpdateStatus(@RequestBody AdminCsData csData, HttpSession sess) throws Exception {
int result = csService.updateAdminCsPaymentStatus(csData, sess);
ModelAndView mv = new ModelAndView("jsonView");
if(result > 0) {
mv.addObject("result", result);
mv.addObject("errCode", true);
mv.addObject("errMsg", "성공");
}else {
mv.addObject("result", result);
mv.addObject("errCode", false);
mv.addObject("errMsg", "실패");
}
return mv;
}
/**
* CS 관리 > 메일발송
* @return
*/
@PostMapping(value = "/admin/cs/adminSendMail")
public ModelAndView adminSendMail(@RequestBody AdminCsData csData, HttpSession sess) throws Exception {
int result = csService.sendMailAdminCs(csData, sess);
ModelAndView mv = new ModelAndView("jsonView");
if(result == -1) {
mv.addObject("result", result);
mv.addObject("errCode", false);
mv.addObject("errMsg", "실패");
}else {
mv.addObject("result", result);
mv.addObject("errCode", true);
mv.addObject("errMsg", "성공");
}
return mv;
}
}
|
package com.niubimq.thread;
/**
* @Description:
* @author junjin4838
* @date 2016年9月2日
* @version 1.0
*/
public interface LifecycleListener {
public void lifecycleEvent(int state);
}
|
package org.bofur.search.statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.text.TextUtils;
public class CompositStatement implements Statement{
List<String> statements;
public CompositStatement() {
statements = new ArrayList<String>();
}
public void add(Statement statement) {
statements.add(statement.generate());
}
public String generate() {
statements.removeAll(Arrays.asList("", null));
return TextUtils.join(" AND ", statements);
}
}
|
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package BPMN.impl;
import BPMN.BPMNEventEndUsed;
import BPMN.BPMNPackage;
import org.eclipse.emf.ecore.EClass;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Event End Used</b></em>'.
* <!-- end-user-doc -->
* <p>
* </p>
*
* @generated
*/
public class BPMNEventEndUsedImpl extends BPMNModelElementImpl implements BPMNEventEndUsed {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected BPMNEventEndUsedImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected EClass eStaticClass() {
return BPMNPackage.Literals.BPMN_EVENT_END_USED;
}
} //BPMNEventEndUsedImpl
|
package hu.aensys.exception.wrap;
import hu.aensys.exception.wrap.parser.Parser;
import hu.aensys.exception.wrap.parser.StdParser;
import hu.aensys.exception.wrap.parser.StringParser;
/**
* @author David Szendrei <david.szendrei@aensys.hu>
*/
public class MainWrap {
public static void main(String[] args) {
MainWrap.execute(new StdParser());
MainWrap.execute(new StringParser("2348"));
}
private static void execute(final Parser parser) {
System.out.println("Calling parse of " + parser.getClass().getSimpleName());
try {
System.out.println("The parsed number is:\t" + parser.parse());
} catch (BusinessException ex) {
ex.printStackTrace(System.err);
}
}
}
|
package com.hqhcn.android.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.hqh.android.dao.GpsMapper;
import com.hqh.android.entity.Exampreasign;
import com.hqh.android.entity.Gps;
import com.hqh.android.entity.GpsExample;
import com.hqh.android.service.*;
import com.hqh.android.tool.AttrUtils;
import com.hqh.android.tool.DateTools;
import com.hqh.android.webservice.TmriInvoker;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@Service
public class GpsServiceImpl implements GpsService {
@Autowired
private GpsMapper mapper;
@Autowired
private ExamProcService procService;
@Autowired
private KsxmService ksxmService;
@Autowired
private ExamineeService examineeService;
@Autowired
private TmriInvoker tmri;
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
public List<Gps> selectByExample(GpsExample example) {
return mapper.selectByExampleWithBLOBs(example);
}
@Override
public Gps select(String lsh, int kscs, String ksxm) {
GpsExample example = new GpsExample();
example.createCriteria().andKsLshEqualTo(lsh).andKscsEqualTo(kscs).andKsxmEqualTo(ksxm);
Optional<List<Gps>> ss = Optional.ofNullable(selectByExample(example));
return ss.filter(o->o.size()>0).map(o->o.get(0)).orElse(new Gps());
}
@Override
public List<Gps> select(String lsh, int kscs) {
GpsExample example = new GpsExample();
example.createCriteria().andKsLshEqualTo(lsh).andKscsEqualTo(kscs);
return selectByExample(example);
}
@Override
@Transactional(rollbackFor = Exception.class)
public int kskmbegin(String kskm, String jlcxh, String lsh, int kscs, Date kssj) {
// 将 该考生 设置成 考试中
examineeService.writeZTByLSH(lsh, ExamineeService.ZT_EXAMING);
// 先在gps表中新建该科目所有的考试项目
List<String> ksxms = ksxmService.getKSXMcode(kskm);
for (String sub_ksxm : ksxms) {
Gps gps = new Gps();
gps.setKskm(kskm);
gps.setKsxm(sub_ksxm);
gps.setCarinfoId(jlcxh);
gps.setKsLsh(lsh);
gps.setKscs(kscs);
mapper.insertSelective(gps);
}
// 再过程表中记录过程记录
procService.begin(lsh, kscs, kskm, jlcxh, kssj, kskm);
// 发六合一
Exampreasign exampreasign = examineeService.queryByLsh(lsh);
String zp="";
try {
zp= com.alibaba.druid.util.Base64.byteArrayToBase64(FileUtils.readFileToByteArray(new File(exampreasign.getPhoto())));
} catch (Exception e) {
logger.error("照片转换失败!!" + exampreasign.getPhoto());
zp = "";
}
// TODO: 2018/1/19 0019 考试系统编号,考试员身份证号以后要填
if (tmri.enabled17C51) {
Date tmriDate = DateUtils.addSeconds(new Date(), tmri.tmriOffSetSecond);
JSONObject result = tmri.jk17C51(lsh, kskm, AttrUtils.考试系统编号.toString(),
exampreasign.getSfzmhm(), null == exampreasign.getKsy1() ? "" : exampreasign.getKsy1(), "zp", DateTools.getFormatDate(tmriDate,"YYYY/MM/DD HH:mm:ss"), "",exampreasign.getHphm());
String code = (String) ((Map) result.get("head")).get("code");
if (!"1".equals(code)) {
logger.error("[" + lsh + "]六合一发送失败,");
throw new RuntimeException("[" + lsh + "]六合一发送失败,");
}
}
// 初始考试成绩
Exampreasign exampreasign100 = new Exampreasign();
exampreasign100.setLsh(lsh);
exampreasign100.setKscj(100);
examineeService.updateSelective(exampreasign100);
return 0;
}
@Override
public int addGPS(String lsh, int kscs, String ksxm, String GPS) {
Gps gps = new Gps();
gps.setKsxm(ksxm);
gps.setKsLsh(lsh);
gps.setKscs(kscs);
gps.setGps(GPS);
return mapper.updateByPrimaryKeySelective(gps);
}
@Override
public void moveByKscs(String lsh, String kskm, int ori, int des) {
Gps desGPS = new Gps();
desGPS.setKscs(des);
GpsExample oriExample = new GpsExample();
oriExample.createCriteria().andKscsEqualTo(ori).andKsLshEqualTo(lsh).andKskmEqualTo(kskm);
mapper.updateByExampleSelective(desGPS, oriExample);
}
}
|
package org.newdawn.slick;
public interface KeyListener extends ControlledInputReciever {
void keyPressed(int paramInt, char paramChar);
void keyReleased(int paramInt, char paramChar);
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\org\newdawn\slick\KeyListener.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ |
/*
* Copyright 2017 Sanjin Sehic
*
* 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 simple.actor;
/**
* Base class that all actors have to extend to be able to receive messages. All received messages
* have to be of the generic type {@code M}.
*
* @param <M> The type of received messages.
*/
public abstract class Actor<M> {
/** Receive and process the given message. This method must be implemented by actors. */
protected abstract void onMessage(M m);
/**
* Callback for when actor is started. Actor will be asynchronously started when registered to a
* group.
*
* @param self the {@link Channel} for actor to send messages to itself.
* @param context the view of actor's group.
*/
protected void onStart(final Channel<M> self, final Context context) {}
/**
* Callback for when actor is stopped. Actor will be asynchronously stopped when its {@link
* Channel} is {@link Channel#stop stopped}.
*/
protected void onStop() {}
}
|
package com.example.pattern.state.order.state;
import com.example.pattern.state.order.OrderSate;
/**
*/
public class OrderStateContext {
private Order order;
private OrderSate newOrderState;
private OrderSate registeredState;
private OrderSate grantedState;
private OrderSate shipedState;
private OrderSate invoicedState;
private OrderSate cancelledState;
private OrderSate currentState;
private OrderStateContext(Order order) {
this.order = order;
this.newOrderState = new NewOrder(this);
assignCurrentState(newOrderState);
this.registeredState = new Registered(this);
assignCurrentState(registeredState);
this.grantedState = new Granted(this);
assignCurrentState(grantedState);
this.shipedState = new Shipped(this);
assignCurrentState(shipedState);
this.invoicedState = new Invoiced(this);
assignCurrentState(invoicedState);
this.cancelledState = new Cancelled(this);
assignCurrentState(cancelledState);
}
public Order getOrder() {
return order;
}
OrderSate getCurrentState() {
return currentState;
}
void changeState(OrderSate newState) {
this.currentState = newState;
this.order.setStatus(newState.getState());
}
private void assignCurrentState(OrderSate state) {
if (state.isCurrentState(order)) {
this.currentState = state;
}
}
public static OrderStateContext of(Order order) {
OrderStateContext context = new OrderStateContext(order);
return context;
}
OrderSate getNewOrderState() {
return newOrderState;
}
OrderSate getRegisteredState() {
return registeredState;
}
OrderSate getGrantedState() {
return grantedState;
}
OrderSate getShipedState() {
return shipedState;
}
OrderSate getInvoicedState() {
return invoicedState;
}
OrderSate getCancelledState() {
return cancelledState;
}
public OrderStateContext cancel() {
String oldState = currentState.getState();
currentState.cancel();
String newState = currentState.getState();
System.out.println("订单从:" + oldState + " --> " + newState);
return this;
}
public OrderStateContext register() {
String oldState = currentState.getState();
currentState.register();
String newState = currentState.getState();
System.out.println("订单从:" + oldState + " --> " + newState);
return this;
}
public OrderStateContext grant() {
String oldState = currentState.getState();
currentState.grant();
String newState = currentState.getState();
System.out.println("订单从:" + oldState + " --> " + newState);
return this;
}
public OrderStateContext ship() {
String oldState = currentState.getState();
currentState.ship();
String newState = currentState.getState();
System.out.println("订单从:" + oldState + " --> " + newState);
return this;
}
public OrderStateContext invoice() {
String oldState = currentState.getState();
currentState.invoice();
String newState = currentState.getState();
System.out.println("订单从:" + oldState + " --> " + newState);
return this;
}
public OrderStateContext addOrderLine() {
currentState.addOrderLine();
return this;
}
public static class Order {
private String status;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
}
|
/*
* Copyright 2009 Kjetil Valstadsve
*
* 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 vanadis.common.time;
import vanadis.core.collections.Generic;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static java.util.concurrent.TimeUnit.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
final class TimeSpanParser {
private static final Map<String, TimeUnit> SUFFS = Generic.linkedHashMap();
private static final Map<String, Integer> FACTORS = Generic.linkedHashMap();
static {
storeSuffix("micros", MICROSECONDS);
storeSuffix("microsecs", MICROSECONDS);
storeSuffix("microsecond", MICROSECONDS);
storeSuffix("microseconds", MICROSECONDS);
storeSuffix("nanosecs", NANOSECONDS);
storeSuffix("nanosecond", NANOSECONDS);
storeSuffix("nanoseconds", NANOSECONDS);
storeSuffix("?", MICROSECONDS);
storeSuffix("m", SECONDS, 60);
storeSuffix("min", SECONDS, 60);
storeSuffix("mins", SECONDS, 60);
storeSuffix("ns", NANOSECONDS);
storeSuffix("hs", SECONDS, 3600);
storeSuffix("hours", SECONDS, 3600);
storeSuffix("millis", MILLISECONDS);
storeSuffix("millisecs", MILLISECONDS);
storeSuffix("millisecond", MILLISECONDS);
storeSuffix("milliseconds", MILLISECONDS);
storeSuffix("ms", MILLISECONDS);
storeSuffix("second", SECONDS);
storeSuffix("seconds", SECONDS);
storeSuffix("secs", SECONDS);
storeSuffix("s", SECONDS);
}
private static final Pattern PARSE = Pattern.compile("^(\\d*)\\s*([a-zA-Z]*)$");
private static void storeSuffix(String key, TimeUnit value) {
storeSuffix(key, value, 1);
}
private static void storeSuffix(String key, TimeUnit value, int factor) {
SUFFS.put(key, value);
FACTORS.put(key, factor);
}
static TimeSpan parse(String str) {
if (str.trim().equalsIgnoreCase(TimeSpan.FOREVER_STRING)) {
return TimeSpan.FOREVER;
}
Matcher matcher = PARSE.matcher(str.trim());
if (!matcher.matches()) {
throw new IllegalArgumentException("Unparseable: " + str);
}
String num = matcher.group(1);
long time;
try {
time = Long.parseLong(num);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Illegal number part: " + str, e);
}
String suff = matcher.group(2);
if (suff.trim().length() == 0) {
return TimeSpan.create(time, TimeUnit.SECONDS);
}
if (!SUFFS.containsKey(suff)) {
throw new IllegalArgumentException("Unknown unit: " + str);
}
if (time <= 0) {
return TimeSpan.INSTANT;
}
return TimeSpan.create(time * FACTORS.get(suff), SUFFS.get(suff));
}
private TimeSpanParser() {
}
}
|
/**
* @author smxknife
* 2018-12-20
*/
package com.smxknife.log.log4j; |
package com.zihui.cwoa.system.pojo;
import java.util.List;
public class sys_task {
private Integer taskId;
private Integer taskUserId;
private String taskRemark;
private Integer taskStatus;
private String attachment;
private String ts;
private String tempVar1;
private String tempVar2;
private Integer tempInt1;
private Integer tempInt2;
private List<sys_task_b> taskBs;
private sys_users users;
private sys_file file;
public sys_file getFile() {
return file;
}
public void setFile(sys_file file) {
this.file = file;
}
public List<sys_task_b> getTaskBs() {
return taskBs;
}
public void setTaskBs(List<sys_task_b> taskBs) {
this.taskBs = taskBs;
}
public sys_users getUsers() {
return users;
}
public void setUsers(sys_users users) {
this.users = users;
}
public Integer getTaskId() {
return taskId;
}
public void setTaskId(Integer taskId) {
this.taskId = taskId;
}
public Integer getTaskUserId() {
return taskUserId;
}
public void setTaskUserId(Integer taskUserId) {
this.taskUserId = taskUserId;
}
public String getTaskRemark() {
return taskRemark;
}
public void setTaskRemark(String taskRemark) {
this.taskRemark = taskRemark == null ? null : taskRemark.trim();
}
public Integer getTaskStatus() {
return taskStatus;
}
public void setTaskStatus(Integer taskStatus) {
this.taskStatus = taskStatus;
}
public String getAttachment() {
return attachment;
}
public void setAttachment(String attachment) {
this.attachment = attachment == null ? null : attachment.trim();
}
public String getTs() {
return ts;
}
public void setTs(String ts) {
this.ts = ts == null ? null : ts.trim();
}
public String getTempVar1() {
return tempVar1;
}
public void setTempVar1(String tempVar1) {
this.tempVar1 = tempVar1 == null ? null : tempVar1.trim();
}
public String getTempVar2() {
return tempVar2;
}
public void setTempVar2(String tempVar2) {
this.tempVar2 = tempVar2 == null ? null : tempVar2.trim();
}
public Integer getTempInt1() {
return tempInt1;
}
public void setTempInt1(Integer tempInt1) {
this.tempInt1 = tempInt1;
}
public Integer getTempInt2() {
return tempInt2;
}
public void setTempInt2(Integer tempInt2) {
this.tempInt2 = tempInt2;
}
} |
import java.util.ArrayList;
import java.util.Collections;
/**
* Created with IntelliJ IDEA.
* User: ngupta
* Date: 27/10/19
* Time: 12:00 PM
*/
/**
* To get a Collatz sequence from a number, if it's even, divide it by two, and if it's odd, multiply it by three and add one.
* Continue the operation on the result of the previous operation until the number becomes 1.
*/
public class LargestPowerOfTwoInCollatzSequence {
public static void main(String[] args) {
int num = 7;
ArrayList<Integer> sequence = collatzSequence(num);
System.out.println(sequence);
System.out.println(maxPowerOfTwo(sequence));
System.out.println(maxPowerOfTwoCleanApproach(num));
}
public static int maxPowerOfTwo(ArrayList<Integer> list) {
Collections.sort(list, Collections.reverseOrder());
for (Integer i : list) {
if (isPowerOfTwo(i))
return i;
}
return 1;
}
public static boolean isPowerOfTwo(int n) {
if (n == 0)
return false;
while (n != 1) {
if (n % 2 != 0)
return false;
n = n / 2;
}
return true;
}
public static int maxPowerOfTwoCleanApproach(int n) {
if (n == 4 || n == 2 || n == 1)
return 4;
else if (n % 2 == 0)
if (isPowerOfTwo(n))
return n;
return maxPowerOfTwoCleanApproach(nextCollatz(n));
}
public static int nextCollatz(int n) {
return n % 2 == 0 ? n / 2 : 3 * n + 1;
}
public static ArrayList<Integer> collatzSequence(int n) {
ArrayList<Integer> arrayList = new ArrayList();
if (n == 4) {
//list.add(4); list.add(2); list.add(1);
arrayList.addAll(Arrays.asList(4, 2, 1));
return arrayList;
}
arrayList.add(n);
arrayList.addAll(collatzSequence(nextCollatz(n)));
return arrayList;
}
}
|
package com.zihui.cwoa.routine.dao;
import com.zihui.cwoa.routine.pojo.rw_mail;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface rw_mailMapper {
int deleteByPrimaryKey(Integer mailId);
int insertSelective(rw_mail record);
rw_mail selectByPrimaryKey(Integer mailId);
int updateByPrimaryKeySelective(rw_mail record);
List<rw_mail> selectInbox(@Param("userId")Integer userId, @Param("content")String content,
@Param("page")Integer page, @Param("limit") Integer limit);
Integer selectInboxCount(@Param("userId")Integer userId, @Param("content")String content);
List<rw_mail> selectOutbox(@Param("userId")Integer userId, @Param("content")String content,
@Param("page")Integer page, @Param("limit") Integer limit);
Integer selectOutboxCount(@Param("userId")Integer userId, @Param("content")String content);
List<rw_mail> selectStarMail(@Param("userId")Integer userId, @Param("content")String content,
@Param("page")Integer page, @Param("limit") Integer limit);
Integer selectStarMailCount(@Param("userId")Integer userId, @Param("content")String content);
List<rw_mail> selectDrafts(@Param("userId")Integer userId, @Param("content")String content,
@Param("page")Integer page, @Param("limit") Integer limit);
Integer selectDraftsCount(@Param("userId")Integer userId, @Param("content")String content);
rw_mail selectInboxInfo(@Param("mailId")Integer mailId);
rw_mail selectOutboxInfo(@Param("mailId")Integer mailId);
Integer selectNoLookCount(@Param("userId")Integer userId);
} |
/**
*/
package PetrinetDSL.util;
import PetrinetDSL.*;
import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.emf.common.notify.impl.AdapterFactoryImpl;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* The <b>Adapter Factory</b> for the model.
* It provides an adapter <code>createXXX</code> method for each class of the model.
* <!-- end-user-doc -->
* @see PetrinetDSL.PetrinetDSLPackage
* @generated
*/
public class PetrinetDSLAdapterFactory extends AdapterFactoryImpl {
/**
* The cached model package.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected static PetrinetDSLPackage modelPackage;
/**
* Creates an instance of the adapter factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public PetrinetDSLAdapterFactory() {
if (modelPackage == null) {
modelPackage = PetrinetDSLPackage.eINSTANCE;
}
}
/**
* Returns whether this factory is applicable for the type of the object.
* <!-- begin-user-doc -->
* This implementation returns <code>true</code> if the object is either the model's package or is an instance object of the model.
* <!-- end-user-doc -->
* @return whether this factory is applicable for the type of the object.
* @generated
*/
@Override
public boolean isFactoryForType(Object object) {
if (object == modelPackage) {
return true;
}
if (object instanceof EObject) {
return ((EObject)object).eClass().getEPackage() == modelPackage;
}
return false;
}
/**
* The switch that delegates to the <code>createXXX</code> methods.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected PetrinetDSLSwitch<Adapter> modelSwitch =
new PetrinetDSLSwitch<Adapter>() {
@Override
public Adapter casePetrinet(Petrinet object) {
return createPetrinetAdapter();
}
@Override
public Adapter caseNode(Node object) {
return createNodeAdapter();
}
@Override
public Adapter caseEdge(Edge object) {
return createEdgeAdapter();
}
@Override
public Adapter caseToken(Token object) {
return createTokenAdapter();
}
@Override
public Adapter caseTransition(Transition object) {
return createTransitionAdapter();
}
@Override
public Adapter casePlace(Place object) {
return createPlaceAdapter();
}
@Override
public Adapter casePTEdge(PTEdge object) {
return createPTEdgeAdapter();
}
@Override
public Adapter caseTPEdge(TPEdge object) {
return createTPEdgeAdapter();
}
@Override
public Adapter defaultCase(EObject object) {
return createEObjectAdapter();
}
};
/**
* Creates an adapter for the <code>target</code>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param target the object to adapt.
* @return the adapter for the <code>target</code>.
* @generated
*/
@Override
public Adapter createAdapter(Notifier target) {
return modelSwitch.doSwitch((EObject)target);
}
/**
* Creates a new adapter for an object of class '{@link PetrinetDSL.Petrinet <em>Petrinet</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see PetrinetDSL.Petrinet
* @generated
*/
public Adapter createPetrinetAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link PetrinetDSL.Node <em>Node</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see PetrinetDSL.Node
* @generated
*/
public Adapter createNodeAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link PetrinetDSL.Edge <em>Edge</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see PetrinetDSL.Edge
* @generated
*/
public Adapter createEdgeAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link PetrinetDSL.Token <em>Token</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see PetrinetDSL.Token
* @generated
*/
public Adapter createTokenAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link PetrinetDSL.Transition <em>Transition</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see PetrinetDSL.Transition
* @generated
*/
public Adapter createTransitionAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link PetrinetDSL.Place <em>Place</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see PetrinetDSL.Place
* @generated
*/
public Adapter createPlaceAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link PetrinetDSL.PTEdge <em>PT Edge</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see PetrinetDSL.PTEdge
* @generated
*/
public Adapter createPTEdgeAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link PetrinetDSL.TPEdge <em>TP Edge</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see PetrinetDSL.TPEdge
* @generated
*/
public Adapter createTPEdgeAdapter() {
return null;
}
/**
* Creates a new adapter for the default case.
* <!-- begin-user-doc -->
* This default implementation returns null.
* <!-- end-user-doc -->
* @return the new adapter.
* @generated
*/
public Adapter createEObjectAdapter() {
return null;
}
} //PetrinetDSLAdapterFactory
|
package com.zhonghuilv.shouyin.service;
/**
* Created by llk2014 on 2018-07-04 17:13:48
*/
public interface OrderBackDetailsService {
}
|
package com.tencent.mm.ui.chatting.h.a;
class a$b$a {
}
|
package ajedrez;
import java.util.LinkedList;
public class Peon extends Figura {
private final static int valor=1;
/**
* Figura de ajedrez: Peon.
* @author POO.
* @param color Color de la Figura.
* @param posicion Posición inicial de la Figura.
*/
public Peon(Color color, Posicion posicion) {
super(color, posicion);
}
public int getValor() {
return valor;
}
public char getRepresentacion() {
return 'P';
}
public Figura clone() {
return new Peon(getColor(),getPosicion());
}
// Blancas comienzas en posiciones bajas de y (y=1 e y=2). Negras en posiciones altas de y (Y=8 e y=7).
public LinkedList<Posicion> movimientos(ITablero tablero) {
LinkedList<Posicion> movimientos = new LinkedList<Posicion>();
int xDestino,yDestino;
Posicion posicion;
boolean hayFigura;
int x = getPosicion().getX();int y = getPosicion().getY();
if (getColor() == Figura.Color.NEGRA) {
xDestino=x-1; yDestino=y-1; // diagonal izquierda (visión negras)
if (xDestino>=0&&yDestino>=0) {
posicion = new Posicion(xDestino,yDestino);
hayFigura = tablero.get(posicion)!=null;
if (hayFigura&&tablero.get(posicion).getColor()!=getColor()) // Hay una figura del otro jugador
movimientos.add(posicion);
}
xDestino=x+1; yDestino=y-1; // diagonal derecha (visión negras)
if (xDestino<ITablero.SIZE&&yDestino>=0) {
posicion = new Posicion(xDestino,yDestino);
hayFigura = tablero.get(posicion)!=null;
if (hayFigura&&tablero.get(posicion).getColor()!=getColor()) // Hay una figura del otro jugador
movimientos.add(posicion);
}
xDestino=x; yDestino=y-1; // arriba una posición
if (yDestino>=0) {
posicion = new Posicion(xDestino,yDestino);
hayFigura = tablero.get(posicion)!=null;
if (!hayFigura)
movimientos.add(posicion);
}
xDestino=x; yDestino=y-2; // arriba dos posiciones
if (y==6) { // fila inicial de los peones NEGROS
posicion = new Posicion(xDestino,yDestino);
hayFigura = tablero.get(posicion)!=null;
if (!hayFigura&&tablero.get(new Posicion(x,y-1))==null) // No hay figuras delante
movimientos.add(posicion);
}
} else { // BLANCA
xDestino=x-1; yDestino=y+1; // diagonal derecha (visión blancas)
if (xDestino>=0&&yDestino<ITablero.SIZE) {
posicion = new Posicion(xDestino,yDestino);
hayFigura = tablero.get(posicion)!=null;
if (hayFigura&&tablero.get(posicion).getColor()!=getColor()) // Hay una figura del otro jugador
movimientos.add(posicion);
}
xDestino=x+1; yDestino=y+1; // diagonal izquierda (visión blancas)
if (xDestino<ITablero.SIZE&&yDestino<ITablero.SIZE) {
posicion = new Posicion(xDestino,yDestino);
hayFigura = tablero.get(posicion)!=null;
if (hayFigura&&tablero.get(posicion).getColor()!=getColor()) // Hay una figura del otro jugador
movimientos.add(posicion);
}
xDestino=x; yDestino=y+1; // arriba una posición
if (yDestino>=0) {
posicion = new Posicion(xDestino,yDestino);
hayFigura = tablero.get(posicion)!=null;
if (!hayFigura)
movimientos.add(posicion);
}
xDestino=x; yDestino=y+2; // arriba dos posiciones
if (y==1) { // fila inicial de los peones BLANCOS
posicion = new Posicion(xDestino,yDestino);
hayFigura = tablero.get(posicion)!=null;
if (!hayFigura&&tablero.get(new Posicion(x,y+1))==null) // No hay figuras delante
movimientos.add(posicion);
}
}
return movimientos;
}
}
|
/**
* Javassonne
* http://code.google.com/p/javassonne/
*
* @author Hamilton Turner
* @date Jan 20, 2009
*
* Copyright 2009 Javassonne Team
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.javassonne.ui.controls;
import java.awt.Dimension;
import javax.swing.JDesktopPane;
import javax.swing.JLayeredPane;
import org.javassonne.ui.map.MapLayer;
/**
* @author Hamilton Turner
*
* LayeredDisplayPane acts as a logical container to hold all of the
* layers that are displayed on the screen. Typically classes interface
* to this using the DisplayHelper, which allows them to show and place
* JPanels on the screen.
*
*/
public class DisplayDesktopPane extends JDesktopPane {
/**
* Constructor. Creates the MapLayer, passing it the screenSize. Also adds
* the MapLayer to the default layer of the JLayeredPane, effectively making
* it the only object on the default layer (because DisplayHelper does not
* provide functionality to add items to the default layer)
*
* It also creates the MapScrollEdges class that listens for mouse movement
* and scrolls the view. This is added to the palette Layer.
*
* @param screenSize
* The amount of the screen that the map is allowed to use for
* rendering itself.
*/
public DisplayDesktopPane(Dimension screenSize) {
// Create the map layer
MapLayer map = new MapLayer(screenSize);
// Add the mapLayer. The DisplayHelper does not have functionality to
// draw on the default layer, so the MapLayer should be the only item on
// the Default Layer
add(map, JLayeredPane.DEFAULT_LAYER);
// NOTE: You should not add all of your layers here. Add them as needed
// using the functions in the singleton DisplayHelper.
}
} // End WorldCanvas |
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloSecretController {
String greeting = "Hi1234";
@GetMapping("/java")
public String hello() {
return greeting + " World!";
}
} |
execute(des, src, registers, memory) {
Calculator c = new Calculator(registers, memory);
String destination;
String source;
int desSize = 0;
String countStr;
int totalHexSize = 0;
boolean isSizeAllowable = false;
int[] addMode = new int[2];
for(int x = 0; x < 2; x++) {
addMode[x] = 0;
}
if(des.isRegister()) {
destination = registers.get(des);
desSize = registers.getBitSize(des);
}
if(src.isRegister()) {
if( (registers.getBitSize(src) == 64 || registers.getBitSize(src) == 128) && desSize == registers.getBitSize(src) ) {
srcSize = registers.getBitSize(src);
source = registers.get(src);
totalHexSize = (srcSize / 8);
isSizeAllowable = true;
}
}
else if(src.isMemory()) {
if( (memory.getBitSize(src) == 64 || memory.getBitSize(src) == 128 || memory.getBitSize(src) == 0)) {
srcSize = memory.getBitSize(src);
if(srcSize == 0) {
srcSize = desSize;
}
source = memory.read(src, desSize);
totalHexSize = (srcSize / 8);
isSizeAllowable = true;
}
}
int a = 0;
if(des.isRegister() && isSizeAllowable && srcSize == desSize) {
String sourceHex = source;
String destinationHex = destination;
String resultAddAll = "";
for(int x = 0; x < totalHexSize * 2; x = x + 2) {
String partialDes = destinationHex.substring(x, x + 2);
String partialSrc = sourceHex.substring(x, x + 2);
int result = Math.abs(Integer.parseInt(partialDes, 16) - Integer.parseInt(partialSrc, 16));
switch(srcSize) {
case 64:
addMode[0] += result;
break;
case 128:
if(x < 16)
addMode[0] += result;
else
addMode[1] += result;
break;
}
}
switch(srcSize) {
case 64:
resultAddAll = "000000000000" + c.hexZeroExtend(new BigInteger(Integer.toString(addMode[0]), 10) + resultAddAll, 4);
break;
case 128:
resultAddAll = "000000000000" + c.hexZeroExtend(new BigInteger(Integer.toString(addMode[1]), 10) + resultAddAll, 4) + "000000000000" + c.hexZeroExtend(new BigInteger(Integer.toString(addMode[0]), 10) + resultAddAll, 4);
break;
}
registers.set(des, resultAddAll);
}
}
|
package com.mcf.manage.web.controller.news;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.mcf.base.common.annotation.SameURLData;
import com.mcf.base.common.page.Pager;
import com.mcf.base.model.ResponseData;
import com.mcf.base.pojo.NewsContent;
import com.mcf.manage.web.controller.common.BaseController;
import com.mcf.service.INewsContentService;
/**
* Title. <br>
* Description.
* <p>
* Copyright: Copyright (c) 2016年12月17日 下午2:43:56
* <p>
* Author: 10003/sunaiqiang saq691@126.com
* <p>
* Version: 1.0
* <p>
*/
@Controller
@RequestMapping("/news")
public class NewsController extends BaseController {
@Resource
private INewsContentService newsContentService;
/**
* 动态列表页面
*
* @param model
* @return
*/
@RequestMapping(value = "/list.html", method = RequestMethod.GET)
public ModelAndView list(String keywords, Pager pager) {
Map<String, Object> parameter = new HashMap<String, Object>();
parameter.put("keywords", keywords);
Map<String, Object> result = newsContentService.getNewsList(parameter, pager);
ModelAndView mv = new ModelAndView();
mv.addObject("selected", "news");
mv.addObject("result", result);
mv.setViewName("news_list");
return mv;
}
/**
* 新增或者修改页面
*
* @param model
* @return
*/
@RequestMapping(value = "/add.html", method = RequestMethod.GET)
public ModelAndView addNews() {
ModelAndView mv = new ModelAndView();
mv.addObject("selected", "news");
mv.setViewName("news_add");
return mv;
}
/**
* 新增或者修改新闻资讯内容
*
* @param newsContent
* @return
*/
@RequestMapping(value = "/saveUpdate", method = RequestMethod.POST)
@SameURLData
public ModelAndView saveUpdate(
@ModelAttribute("NewsContent") NewsContent newsContent) {
ModelAndView mv = new ModelAndView();
boolean status = newsContentService.saveOrUpdate(newsContent);
if (status) {
mv.setViewName("redirect:/news/list.html");
} else {
mv.addObject("selected", "news");
mv.addObject("newsContent", newsContent);
mv.setViewName("news_add");
}
return mv;
}
/**
* 根据id获取新闻动态详情
*
* @param newsType
* @return
*/
@RequestMapping(value = "/{id}.html", method = RequestMethod.GET)
public ModelAndView detail(@PathVariable("id") String id) {
ModelAndView mv = new ModelAndView();
NewsContent newsContent = newsContentService.getById(id);
if (newsContent != null) {
mv.addObject("selected", "news");
mv.addObject("newsContent", newsContent);
mv.setViewName("news_add");
} else {
mv.setViewName("redirect:/404.html");
}
return mv;
}
/**
* 显示
*
* @param newsContent
* @return
*/
@RequestMapping(value = "/showStatus", method = RequestMethod.POST)
@ResponseBody
public ResponseData showStatus(String id) {
boolean status = newsContentService.updateShow(id);
ResponseData responseData = null;
if (status) {
responseData = new ResponseData(status, "设置显示成功!");
} else {
responseData = new ResponseData(status, "设置显示失败!");
}
return responseData;
}
/**
* 隐藏
*
* @param newsContent
* @return
*/
@RequestMapping(value = "/hideStatus", method = RequestMethod.POST)
@ResponseBody
public ResponseData hideStatus(String id) {
boolean status = newsContentService.updateHide(id);
ResponseData responseData = null;
if (status) {
responseData = new ResponseData(status, "设置隐藏成功!");
} else {
responseData = new ResponseData(status, "设置隐藏失败!");
}
return responseData;
}
/**
* 置顶
*
* @param newsContent
* @return
*/
@RequestMapping(value = "/successStick", method = RequestMethod.POST)
@ResponseBody
public ResponseData successStick(String id) {
boolean status = newsContentService.successStick(id);
ResponseData responseData = null;
if (status) {
responseData = new ResponseData(status, "置顶成功!");
} else {
responseData = new ResponseData(status, "置顶失败!");
}
return responseData;
}
/**
* 取消置顶
*
* @param newsContent
* @return
*/
@RequestMapping(value = "/cancelStick", method = RequestMethod.POST)
@ResponseBody
public ResponseData cancelStick(String id) {
boolean status = newsContentService.cancelStick(id);
ResponseData responseData = null;
if (status) {
responseData = new ResponseData(status, "取消置顶成功!");
} else {
responseData = new ResponseData(status, "取消置顶失败!");
}
return responseData;
}
/**
* 删除
*
* @param id
* @return
*/
@RequestMapping(value = "/delete", method = RequestMethod.POST)
@ResponseBody
public ResponseData delete(String[] ids) {
boolean status = newsContentService.batchDelete(ids);
ResponseData responseData = null;
if (status) {
responseData = new ResponseData(status, "删除成功!");
} else {
responseData = new ResponseData(status, "删除成功!");
}
return responseData;
}
}
|
package com.upside.echo.dao;
import com.upside.echo.model.Greeting;
import com.upside.model.jdbi.argument.UUIDArgumentFactory;
import java.util.Collection;
import java.util.UUID;
import org.skife.jdbi.v2.sqlobject.Bind;
import org.skife.jdbi.v2.sqlobject.SqlQuery;
import org.skife.jdbi.v2.sqlobject.SqlUpdate;
import org.skife.jdbi.v2.sqlobject.customizers.RegisterArgumentFactory;
import org.skife.jdbi.v2.sqlobject.customizers.RegisterMapper;
/**
* <p>DAO for our Greeting POJO</p>
*/
@RegisterMapper(GreetingMapper.class)
@RegisterArgumentFactory(UUIDArgumentFactory.class)
public interface GreetingDAO {
@SqlQuery("select * from greeting")
Collection<Greeting> findGreetings();
@SqlQuery("select * from greeting where uuid = :uuid")
Greeting findByUuid(@Bind("uuid") UUID uuid);
@SqlUpdate("insert into greeting (uuid, "
+ " greeting) "
+ " values (:uuid,"
+ " :greeting) "
+ "on duplicate key update greeting = :greeting")
void upsert(@GreetingBinder Greeting greeting);
}
|
package com.tencent.mm.ab;
public interface g$a {
void wd();
}
|
package com.funkygames.funkyhilo.services;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.funkygames.funkyhilo.constants.Choice;
import com.funkygames.funkyhilo.constants.ReplayChoice;
import com.funkygames.funkyhilo.exception.InvalidChoiceException;
public class WebMessageService implements MessageService {
private HttpServletRequest req;
private HttpServletResponse resp;
public WebMessageService(HttpServletRequest req, HttpServletResponse resp) {
this.req = req;
this.resp = resp;
}
@Override
public void displayMessage(String message) {
try {
resp.getWriter().write("\n" + message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public Choice getPlayerChoice() throws InvalidChoiceException {
String userChoice = req.getParameter("choice");
Choice choice = Choice.parse(userChoice);
return choice;
}
@Override
public ReplayChoice getReplayChoice() {
// TODO Auto-generated method stub
return null;
}
}
|
package com.mx.profuturo.bolsa.service.reports;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import com.mx.profuturo.bolsa.model.reports.templates.CandidateComInformationTemplate;
import com.mx.profuturo.bolsa.model.reports.templates.CandidateCorpInformationTemplate;
import com.mx.profuturo.bolsa.model.reports.templates.CandidatosFinalistasTemplate;
import com.mx.profuturo.bolsa.model.reports.templates.ContratacionesNivelPuestoTemplate;
import com.mx.profuturo.bolsa.model.reports.templates.ContratacionesPorAnalistaTemplate;
import com.mx.profuturo.bolsa.model.reports.templates.ContratacionesPorMesTemplate;
import com.mx.profuturo.bolsa.model.reports.templates.FuentesReclutamientoTemplate;
import com.mx.profuturo.bolsa.model.reports.templates.MotivosRechazoTemplate;
import com.mx.profuturo.bolsa.model.reports.templates.TipoEntrevistaTemplate;
import com.mx.profuturo.bolsa.model.reports.templates.XLSTemplate;
import com.mx.profuturo.bolsa.model.reports.vo.ReportVO;
import com.mx.profuturo.bolsa.model.service.candidates.dto.CandidateComInfo;
import com.mx.profuturo.bolsa.model.service.candidates.dto.CandidateCorpInfo;
@Service
@Scope("request")
public class ExcelServiceImpl implements ExcelService {
@Override
public void downloadXLSXFile(HttpServletResponse response, ReportVO report) throws IOException {
XLSTemplate template = this.buildTemplate(report.getCode(), report.getBranch());
response.setHeader("Content-disposition",
new StringBuilder("attachment; filename=").append(template.getFileName()).toString());
Integer rowNum = 0;
//build a file from scratch and then download
Workbook workbook = new XSSFWorkbook();
Sheet x = workbook.createSheet(report.getTitle());
Row header = x.createRow(rowNum);
header = template.getXLSHeaders(header, x, report.getTipoVacante());
Cell tmpCell = null;
CellStyle headerStyle = this.getHeaderStyle(workbook);
for(int i = 0; i < header.getLastCellNum();i++) {
tmpCell = header.getCell(i);
tmpCell.setCellStyle(headerStyle);
}
Row row = null;
for(Object data: report.getReportData()) {
row = x.createRow(++rowNum);
row = template.getXLSRowMapping(row,x, data, report.getTipoVacante());
}
// if(report.getBranch().equals("COM")){
// Integer p = 0;
// for(Object data: report.getReportData()) {
// row = x.createRow(++rowNum);
// row = template.getXLSRowMapping(row, x, data, p);
//// System.out.println(rowNum);
// }
// }else if (report.getBranch().equals("CORP")){
// for(Object data: report.getReportData()) {
// Integer p = 0;
// row = x.createRow(++rowNum);
// row = template.getXLSCORPRowMapping(row, x, data, p);
//// System.out.println(rowNum);
// }
// }
workbook.write(response.getOutputStream());
}
// protected Row getXLSCORPRowMapping(Row row, Sheet s, Object o, Integer p) {
// CandidateCorpInfo vo = (CandidateCorpInfo)o;
//
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getFechaPostulacion());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getPostuladoOcartera());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getVacanteAplicada());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getAreaInteres());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getSubAreaInteres());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getNombreCompleto());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getFuente());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getResidencia());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getMunicipio());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getCelular());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getCorreo());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getCurp());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getRfc());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getGenero());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getEdad());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getEscolaridad());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getEspecialidad());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getEstadoCivil());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getDivisional());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getRegional());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getGerencia());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getFiltroTelefonico());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getDescarteTelefonico());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getTipoPrimerEntrevista());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getFechaPrimerEntrevista());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getHoraPrimerEntrevista());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getResultadoPrimerEntrevista());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getMotivoDescartePrimerEntrevista());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getComentariosPrimerEntrevista());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getD());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getI());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getS());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getC());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getExamenConfianza());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getResultadoExamenConfianza());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getExamenPsicometrico());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getResultadoExamenPsicometrico());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getNombreEntrevistador());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getTipoSegundaEntrevista());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getFechaSegundaEntrevista());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getHoraSegundaEntrevista());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getResultadoSegundaEntrevista());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getMotivoDescarteSegundaEntrevista());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getComentariosSegundaEntrevista());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getResponsableVacante());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getAceptaOferta());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getMotivoNoAceptaOferta());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getComentariosOferta());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getSolicitudEmpleo());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getSocioEconomico());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getContratado());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getMotivoNoContratado());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getComentarios());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getRespostulado());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getEmpresaAnterior());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getPuestoAnterior());
// // s.autoSizeColumn(p);
//
//
// return row;
// }
//
//
// protected Row getXLSCOMRowMapping(Row row, Sheet s, Object o, Integer p) {
// CandidateComInfo vo = (CandidateComInfo)o;
//
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getFechaPostulacion());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getPostuladoOcartera());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getVacanteAplicada());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getAreaInteres());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getSubAreaInteres());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getNombreCompleto());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getFuente());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getResidencia());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getMunicipio());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getCelular());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getCorreo());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getCurp());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getRfc());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getGenero());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getEdad());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getEscolaridad());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getEspecialidad());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getEstadoCivil());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getDivisional());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getRegional());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getGerencia());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getFiltroTelefonico());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getDescarteTelefonico());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getTipoPrimerEntrevista());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getFechaPrimerEntrevista());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getHoraPrimerEntrevista());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getResultadoPrimerEntrevista());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getMotivoDescartePrimerEntrevista());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getComentariosPrimerEntrevista());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getD());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getI());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getS());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getC());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getAmitai());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getNombreEntrevistador());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getTipoSegundaEntrevista());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getFechaSegundaEntrevista());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getHoraSegundaEntrevista());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getResultadoSegundaEntrevista());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getMotivoDescarteSegundaEntrevista());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getComentariosSegundaEntrevista());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getResponsableVacante());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getAceptaOferta());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getMotivoNoAceptaOferta());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getComentariosOferta());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getSolicitudEmpleo());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getSocioEconomico());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getContratado());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getMotivoNoContratado());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getComentarios());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getRespostulado());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getEmpresaAnterior());
// // s.autoSizeColumn(p);
// row.createCell(p++).setCellValue(vo.getPuestoAnterior());
// // s.autoSizeColumn(p);
//
//
// return row;
// }
private CellStyle getHeaderStyle(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
// Setting Background color
style.setFillForegroundColor(IndexedColors.BLUE.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
Font font = workbook.createFont();
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
font.setColor(IndexedColors.WHITE.getIndex());
style.setFont(font);
return style;
}
private XLSTemplate buildTemplate(String reportCode, String branch) {
XLSTemplate template = null;
if("MOR".equals(reportCode)) {
template = new MotivosRechazoTemplate(branch);
}else if("MORPE".equals(reportCode)) {
template = new MotivosRechazoTemplate(branch);
}else if("EAB".equals(reportCode)) {
template = new MotivosRechazoTemplate(branch);
}else if("CFC".equals(reportCode)) {
template = new CandidatosFinalistasTemplate(branch);
}else if("CNP".equals(reportCode)) {
template = new ContratacionesNivelPuestoTemplate(branch);
}else if("CPM".equals(reportCode)) {
template = new ContratacionesPorMesTemplate(branch);
}else if("CAN".equals(reportCode)) {
template = new ContratacionesPorAnalistaTemplate(branch);
}else if("FRE".equals(reportCode)) {
template = new FuentesReclutamientoTemplate(branch);
}else if("TIE".equals(reportCode)) {
template = new TipoEntrevistaTemplate(branch);
}
else if("CANINFO".equals(reportCode) && "COM".equals(branch)) {
template = new CandidateComInformationTemplate(branch);
}
else if("CANINFO".equals(reportCode) && "CORP".equals(branch)) {
template = new CandidateCorpInformationTemplate(branch);
}
return template ;
}
}
|
package algorithms.sorting;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.Arrays;
import java.util.UUID;
import java.util.stream.Stream;
public abstract class Sort<T extends Comparable<? super T>> {
private static final Logger LOGGER = LogManager.getLogger(Sort.class);
public abstract void sort(Comparable<T>[] items);
public abstract void sort(Comparable<T>[] items, int lo, int hi);
void swap(T[] array, int i, int j) {
T k = array[i];
array[i] = array[j];
array[j] = k;
}
boolean less(T[] array, int i, int j) {
return array[i].compareTo(array[j]) < 0;
}
public static void main(String[] args) {
testAllSortingImplementations();
}
private static void testAllSortingImplementations() {
LOGGER.info("-- Test all sorting implementation");
int size = 10000;
LOGGER.info("-- sample array size is " + size);
String[] testArray = createTestArray(size);
for (int i = 0; i < 10; i++) {
testImpementations(Arrays.copyOf(testArray, testArray.length), i == 9);
}
}
private static void testImpementations(String[] testArray, boolean isReal) {
if (!isReal) {
LOGGER.info("Warming up...");
new InsertionSort().sort(Arrays.copyOf(testArray, testArray.length));
new SelectionSort().sort(Arrays.copyOf(testArray, testArray.length));
new ShellSort().sort(Arrays.copyOf(testArray, testArray.length));
} else {
LOGGER.info("Testing...");
LOGGER.info("-- selection sort");
long start = System.currentTimeMillis();
new SelectionSort().sort(Arrays.copyOf(testArray, testArray.length));
long end = System.currentTimeMillis();
LOGGER.info("Sorted in " + (end - start) / 1000.0 + " secs");
LOGGER.info("-- insertion sort");
start = System.currentTimeMillis();
new InsertionSort().sort(Arrays.copyOf(testArray, testArray.length));
end = System.currentTimeMillis();
LOGGER.info("Sorted in " + (end - start) / 1000.0 + " secs");
LOGGER.info("-- shell sort");
start = System.currentTimeMillis();
new ShellSort().sort(Arrays.copyOf(testArray, testArray.length));
end = System.currentTimeMillis();
LOGGER.info("Sorted in " + (end - start) / 1000.0 + " secs");
LOGGER.info("-- quicksort");
start = System.currentTimeMillis();
new QuickSort().sort(Arrays.copyOf(testArray, testArray.length));
end = System.currentTimeMillis();
LOGGER.info("Sorted in " + (end - start) / 1000.0 + " secs");
LOGGER.info("-- quicksort 3-way");
start = System.currentTimeMillis();
new QuickSort3Way().sort(Arrays.copyOf(testArray, testArray.length));
end = System.currentTimeMillis();
LOGGER.info("Sorted in " + (end - start) / 1000.0 + " secs");
LOGGER.info("-- system sort");
start = System.currentTimeMillis();
Arrays.sort(Arrays.copyOf(testArray, testArray.length));
end = System.currentTimeMillis();
LOGGER.info("Sorted in " + (end - start) / 1000.0 + " secs");
}
}
private static String[] createTestArray(int size) {
return Stream.generate(UUID::randomUUID).limit(size).map(u -> u.toString()).toArray(String[]::new);
}
}
|
package com.example.demodatapassingtext;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class thirdActivity extends AppCompatActivity {
TextView tvChar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
tvChar = findViewById(R.id.tvChar);
Intent intentReceived = getIntent();
tvChar.setText("Character value received is: " + intentReceived.getCharExtra("value",'z'));
}
} |
package com.project.homes.app.common.comment.service;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
import com.project.homes.app.common.comment.dto.CommentDto;
import com.project.homes.app.common.comment.mapper.CommentMapper;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
@Service
public class CommentService {
private final CommentMapper commentMapper;
//댓글 달기
public long insertComment(CommentDto commentDto) {
return commentMapper.insertComment(commentDto);
}
//디테일 페이지에 댓글 리스트 보여주기
@Transactional
public List<CommentDto> commentList(@RequestParam("id") long id){
return commentMapper.commentList(id);
}
//댓글 삭제하기
public long deleteComment(long id) {
return commentMapper.deleteComment(id);
}
//댓글 수정하기
public long editComment(CommentDto commentDto) {
return commentMapper.editComment(commentDto);
}
//댓글에 답글 달기
public long replyComment(CommentDto commentDto
,@RequestParam("id") long id
,@RequestParam("groupOrder") long groupOrder) {
long res = commentMapper.replyComment(commentDto);
commentMapper.groupOrderUpdate(id, groupOrder);
return res;
}
//댓글 개수
public long countComment(@RequestParam("id") long id) {
return commentMapper.countComment(id);
}
}
|
/*
* FileName: AutoBinderMultiActionController.java
* Description:
* Company: 南宁超创信息工程有限公司
* Copyright: ChaoChuang (c) 2005
* History: 2005-12-16 (guig) 1.0 Create
*/
package com.spower.basesystem.common.controller;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import com.spower.basesystem.common.Constants;
import com.spower.basesystem.dictionary.service.DictionaryLoader;
import com.spower.basesystem.propertyeditor.support.AbstractPropertyEditorBind;
import com.spower.utils.GBRedirectView;
/**
* @author guig
* @version 1.0 2005-12-16
*/
public class AutoBinderMultiActionController extends MultiActionController {
private static String FLAG_FOR_REDIRECTVIEW = ".do";
/** 所有submit函数的successView */
private Map viewMap;
/**
* 通过函数名获取该submit函数的successView
* @param functionName submit函数
* @return successView字符串
*/
protected String getSuccessView(String functionName) {
return (String) viewMap.get(functionName);
}
/**
* 根据viewName来建立ModelAndView,如果viewName中有".do"则建立GBRedirectView的ModelAndView,
* 其他情况下在model中加入dicData字典数据并以一般方式建立ModelAndView。
* @param request request对象
* @param viewName view的名字
* @param model 模式数据
* @return ModelAndView对象
*/
protected ModelAndView initModelAndView(HttpServletRequest request, String viewName, Map model) {
ModelAndView result = null;
if (viewName != null) {
if (viewName.toLowerCase().indexOf(FLAG_FOR_REDIRECTVIEW) == -1) {
model.put("dicData", DictionaryLoader.getInstance().getAllDictionary());
model.put("currentUser", Constants.getCurrentLoginUser(request));
result = new ModelAndView(viewName, model);
} else {
Map filterModel = new HashMap();
for (Iterator iter = model.entrySet().iterator(); iter.hasNext();) {
Map.Entry element = (Map.Entry) iter.next();
if (String.class.isInstance(element.getValue()) || Number.class.isInstance(element.getValue())) {
filterModel.put(element.getKey(), element.getValue());
}
}
result = new ModelAndView(new GBRedirectView(viewName), filterModel);
}
}
return result;
}
/** (non Javadoc)
* @see org.springframework.web.servlet.mvc.multiaction.MultiActionController#initBinder(javax.servlet.ServletRequest, org.springframework.web.bind.ServletRequestDataBinder)
*/
protected void initBinder(ServletRequest request, ServletRequestDataBinder binder) throws Exception {
super.initBinder(request, binder);
AbstractPropertyEditorBind.initBinder((HttpServletRequest) request, binder);
}
/**
* @return 返回 viewMap。
*/
public Map getViewMap() {
return viewMap;
}
/**
* @param viewMap 要设置的 viewMap。
*/
public void setViewMap(Map viewMap) {
this.viewMap = viewMap;
}
}
|
//package nl.jtosti.hermes.entities;
//
//import org.junit.jupiter.api.DisplayName;
//import org.junit.jupiter.api.Test;
//import org.springframework.security.core.authority.SimpleGrantedAuthority;
//import org.springframework.security.core.userdetails.UserDetails;
//
//import java.util.ArrayList;
//import java.util.Collections;
//
//import static org.assertj.core.api.Java6Assertions.assertThat;
//
//class ScreenTest {
// private Screen screen;
//
// private Location location = new Location("Alex coffee", "Alexstreet", "1", "1234AB", "Coffee", "land", new User());
//
// @Test
// @DisplayName("Test no args constructor")
// void testNoArgsConstructor() {
// screen = new Screen();
//
// assertThat(screen.getId()).isNull();
// assertThat(screen.getName()).isNull();
// assertThat(screen.getHeight()).isEqualTo(0);
// assertThat(screen.getWidth()).isEqualTo(0);
// assertThat(screen.getLocation()).isNull();
// assertThat(screen.getImages()).hasSize(0);
// }
//
// @Test
// @DisplayName("Test no list constructor")
// void testNoListConstructor() {
// int width = 1920;
// int height = 1080;
// String name = "Screen 1";
// screen = new Screen(name, width, height, location);
//
// assertThat(screen.getId()).isNull();
// assertThat(screen.getName()).isEqualTo(name);
// assertThat(screen.getHeight()).isEqualTo(height);
// assertThat(screen.getWidth()).isEqualTo(width);
// assertThat(screen.getLocation()).isEqualTo(location);
// assertThat(screen.getImages()).hasSize(0);
// }
//
// @Test
// @DisplayName("Test setters and getters")
// void testSettersAndGetters() {
// screen = new Screen("Screen 1", 1920, 1080, location, new ArrayList<>());
//
// Image image = new Image();
//
// String name = "Screen 2";
// int width = 1000;
// int height = 1000;
//
// Location location = new Location("Alex coffee", "Alexstreet", "1", "1234AB", "Coffee", "land", new User());
//
// screen.setName(name);
// screen.setHeight(height);
// screen.setWidth(width);
// screen.setImages(Collections.singletonList(image));
// screen.setLocation(location);
//
// assertThat(screen.getName()).isEqualTo(name);
// assertThat(screen.getHeight()).isEqualTo(height);
// assertThat(screen.getWidth()).isEqualTo(width);
// assertThat(screen.getImages()).hasSize(1);
// assertThat(screen.getImages().get(0)).isEqualTo(image);
//
// screen = new Screen("Screen 1", 1920, 1080, location, new ArrayList<>());
// screen.addImage(image);
//
// assertThat(screen.getImages()).hasSize(1);
// assertThat(screen.getImages().get(0)).isEqualTo(image);
// }
//
// @Test
// @DisplayName("Test equals")
// void testEquals() {
// screen = new Screen("Alex Coffee", 1920, 1080, location);
// screen.setId(1L);
//
// Screen screen1 = new Screen("Alex Coffee", 1920, 1080, location);
// screen1.setId(1L);
//
// assertThat(screen.equals(screen1)).isTrue();
//
// Object image = new Image();
//
// assertThat(screen.equals(image)).isFalse();
//
// screen1.setName("Jane Coffee");
// assertThat(screen.equals(screen1)).isFalse();
// screen1.setWidth(1000);
// assertThat(screen.equals(screen1)).isFalse();
// screen1.setHeight(1000);
// assertThat(screen.equals(screen1)).isFalse();
// screen1.setId(2L);
// assertThat(screen.equals(screen1)).isFalse();
// }
//
// @Test
// @DisplayName("Test hashcode")
// void testHashCode() {
// screen = new Screen("Screen 1", 1920, 1080, location);
// assertThat(screen.hashCode()).isEqualTo(screen.hashCode());
//
// Screen screen1 = new Screen();
// assertThat(screen.hashCode()).isNotEqualTo(screen1.hashCode());
// }
//
// @Test
// @DisplayName("Test toString")
// void testToString() {
// screen = new Screen("Screen 1", 1920, 1080, location);
// assertThat(screen.toString()).isEqualTo(String.format("<Screen: %s>", screen.getName()));
// screen.setId(1L);
// assertThat(screen.toString()).isEqualTo(String.format("<Screen %s: %s>", screen.getId(), screen.getName()));
// }
//
// @Test
// @DisplayName("Test setting password")
// void testSetPassword() {
// String password = "test";
// screen = new Screen("Screen 1", 1920, 1080, location);
// assertThat(screen.isToReceivePassword()).isTrue();
// screen.setPassword(password);
// assertThat(screen.isToReceivePassword()).isFalse();
// assertThat(screen.getPassword()).isNotEqualTo(password);
// }
//
// @Test
// @DisplayName("Convert to UserDetails")
// void shouldConvertToUserDetails() {
// String password = "test";
// screen = new Screen("Screen 1", 1920, 1080, location);
// screen.setId(1L);
// UserDetails userDetails = screen.toUserDetails();
// assertThat(userDetails).isInstanceOf(ApplicationScreen.class);
// assertThat(userDetails.getUsername()).isEqualTo(screen.getId().toString());
// assertThat(userDetails.isCredentialsNonExpired()).isFalse();
// screen.setPassword(password);
// userDetails = screen.toUserDetails();
// assertThat(userDetails.getPassword()).isEqualTo(screen.getPassword());
// assertThat(userDetails.isCredentialsNonExpired()).isTrue();
// assertThat(userDetails.isEnabled()).isTrue();
// assertThat(userDetails.isAccountNonExpired()).isTrue();
// assertThat(userDetails.isAccountNonLocked()).isTrue();
// assertThat(userDetails.getAuthorities().size()).isEqualTo(1);
// assertThat(userDetails.getAuthorities().iterator().next()).isEqualTo(new SimpleGrantedAuthority("SCREEN"));
// }
//} |
package com.tencent.mm.plugin.subapp.jdbiz;
import com.tencent.mm.g.a.km;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.sdk.b.a;
import com.tencent.mm.sdk.b.b;
import com.tencent.mm.sdk.b.c;
import com.tencent.mm.sdk.platformtools.bi;
class a$1 extends c<km> {
final /* synthetic */ a oqE;
a$1(a aVar) {
this.oqE = aVar;
this.sFo = km.class.getName().hashCode();
}
public final /* synthetic */ boolean a(b bVar) {
km kmVar = (km) bVar;
if ((kmVar instanceof km) && kmVar.bUM.bUO != null && kmVar.bUM.bUN != null && "bizjd".equals(kmVar.bUM.bUN)) {
String aG = bi.aG(kmVar.bUM.bUO.getString("activity_id"), "");
String aG2 = bi.aG(kmVar.bUM.bUO.getString("jump_url"), "");
h.mEJ.h(11179, new Object[]{aG2, c.bGg().bGq().oqH, Integer.valueOf(4)});
b bGl = c.bGg().bGq();
if (!(bGl == null || bGl.oqH == null || !bGl.oqH.equals(aG))) {
c.bGg().bGk();
c.bGg().bGj();
}
a.sFg.c(this.oqE.oqD);
}
return false;
}
}
|
/*
* 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 Entidades;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author axeld
*/
@Entity
@SequenceGenerator(name="TIPO_CREDITO_GEN",sequenceName = "TIPO_CREDITO_SEQ", allocationSize = 1)
@Table(name = "TIPO_CREDITO")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "TipoCredito.findAll", query = "SELECT t FROM TipoCredito t")
, @NamedQuery(name = "TipoCredito.findByIdTipoCredito", query = "SELECT t FROM TipoCredito t WHERE t.idTipoCredito = :idTipoCredito")
, @NamedQuery(name = "TipoCredito.findByNombre", query = "SELECT t FROM TipoCredito t WHERE t.nombre = :nombre")})
public class TipoCredito implements Serializable {
private static final long serialVersionUID = 1L;
// @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
@Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="TIPO_CREDITO_GEN")
@Basic(optional = false)
@Column(name = "ID_TIPO_CREDITO")
private BigDecimal idTipoCredito;
@Basic(optional = false)
@Column(name = "NOMBRE")
private String nombre;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "tipoCredito")
private List<Creditos> creditosList;
public TipoCredito() {
}
public TipoCredito(BigDecimal idTipoCredito) {
this.idTipoCredito = idTipoCredito;
}
public TipoCredito(BigDecimal idTipoCredito, String nombre) {
this.idTipoCredito = idTipoCredito;
this.nombre = nombre;
}
public BigDecimal getIdTipoCredito() {
return idTipoCredito;
}
public void setIdTipoCredito(BigDecimal idTipoCredito) {
this.idTipoCredito = idTipoCredito;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
@XmlTransient
public List<Creditos> getCreditosList() {
return creditosList;
}
public void setCreditosList(List<Creditos> creditosList) {
this.creditosList = creditosList;
}
@Override
public int hashCode() {
int hash = 0;
hash += (idTipoCredito != null ? idTipoCredito.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof TipoCredito)) {
return false;
}
TipoCredito other = (TipoCredito) object;
if ((this.idTipoCredito == null && other.idTipoCredito != null) || (this.idTipoCredito != null && !this.idTipoCredito.equals(other.idTipoCredito))) {
return false;
}
return true;
}
@Override
public String toString() {
return "Entidades.TipoCredito[ idTipoCredito=" + idTipoCredito + " ]";
}
}
|
package com.facemelt.spitter.dao;
import java.util.List;
import com.facemelt.spitter.domain.Spitter;
import com.facemelt.spitter.domain.Spittle;
public interface SpittleDAO {
public void addSpittle(Spittle spittle);
public List<Spittle> getSpittles();
public void removeSpittle(Long id);
}
|
package zystudio.cases.prepare;
/**
* 关于import java.lang.ref.ReferenceQueue的 case的,我意识到这好像是一个有用的东西
*/
public class CaseForReferenceQueue {
}
|
import java.util.Map;
import java.util.TreeMap;
/**
* Created by user on 23/06/2017.
*/
public class BlocksFromSymbolsFactory {
private Map<String, Block> blocks;
private Map<String, Integer> spacerWidths;
/**
* constructs a BlocksFromSymbolsFactory object from two maps:
* first map: string -> block.
* second map: string -> integer.
* @param blocks the first map.
* @param spacerWidths the second map.
*/
public BlocksFromSymbolsFactory(Map<String, Block> blocks,
Map<String, Integer> spacerWidths) {
this.blocks = blocks;
this.spacerWidths = spacerWidths;
}
/**
* constructs a new BlocksFromSymbolsFactory object.
*/
public BlocksFromSymbolsFactory() {
this.blocks = new TreeMap<String, Block>();
this.spacerWidths = new TreeMap<String, Integer>();
}
/**
* this method gets a string and checks if
* there is a mapping from it to a spacer.
* @param s the given string.
* @return true if there is a mapping.
*/
public boolean isSpaceSymbol(String s) {
return spacerWidths.containsKey(s);
}
/**
* this method gets a string and checks if
* there is a mapping from it to a block.
* @param s the given string.
* @return true if there is a mapping.
*/
public boolean isBlockSymbol(String s) {
return blocks.containsKey(s);
}
/**
* this method gets a string and return the corresponding spacer width.
* @param s the given string.
* @return the spacer width.
*/
public int getSpacerWidth(String s) {
return this.spacerWidths.get(s);
}
/**
* this method gets a string and two coordinates
* and return the corresponding block.
* @param s the given string.
* @param x the x coordinate.
* @param y the y coordinate.
* @return the corresponding block.
*/
public Block getBlock(String s, int x, int y) {
Block block = new Block(this.blocks.get(s));
block.setUpperLeft(x, y);
return block;
}
/**
* this method gets a string and a block and put them in the blocks map.
* @param string the given string.
* @param block the given block.
*/
public void putBlock(String string, Block block) {
this.blocks.put(string, block);
}
/**
* this method gets a string and a spacer width
* and put them in the spacers map.
* @param string the given string.
* @param num the given spacer width.
*/
public void putSpaceWidth(String string, Integer num) {
this.spacerWidths.put(string, num);
}
} |
package com.tencent.tinker.loader;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.os.Build.VERSION;
import android.util.ArrayMap;
import com.tencent.tinker.loader.shareutil.SharePatchFileUtil;
import com.tencent.tinker.loader.shareutil.ShareReflectUtil;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
class TinkerResourcePatcher {
private static Method vtA = null;
private static Field vtB = null;
private static Field vtC = null;
private static Field vtD = null;
private static Field vtE = null;
private static Field vtF = null;
private static Field vtG = null;
private static Field vtH = null;
private static Collection<WeakReference<Resources>> vtw = null;
private static Object vtx = null;
private static AssetManager vty = null;
private static Method vtz = null;
TinkerResourcePatcher() {
}
public static void hR(Context context) {
Class cls;
Class cls2 = Class.forName("android.app.ActivityThread");
vtx = ShareReflectUtil.c(context, cls2);
try {
cls = Class.forName("android.app.LoadedApk");
} catch (ClassNotFoundException e) {
cls = Class.forName("android.app.ActivityThread$PackageInfo");
}
vtD = ShareReflectUtil.d(cls, "mResDir");
vtE = ShareReflectUtil.d(cls2, "mPackages");
if (VERSION.SDK_INT < 27) {
vtF = ShareReflectUtil.d(cls2, "mResourcePackages");
}
AssetManager assets = context.getAssets();
vtz = ShareReflectUtil.b(assets, "addAssetPath", String.class);
try {
vtH = ShareReflectUtil.b(assets, "mStringBlocks");
vtA = ShareReflectUtil.b(assets, "ensureStringBlocks", new Class[0]);
} catch (Throwable th) {
}
vty = (AssetManager) ShareReflectUtil.a(assets, new Class[0]).newInstance(new Object[0]);
if (VERSION.SDK_INT >= 19) {
cls2 = Class.forName("android.app.ResourcesManager");
Object invoke = ShareReflectUtil.c(cls2, "getInstance", new Class[0]).invoke(null, new Object[0]);
try {
vtw = ((ArrayMap) ShareReflectUtil.d(cls2, "mActiveResources").get(invoke)).values();
} catch (NoSuchFieldException e2) {
vtw = (Collection) ShareReflectUtil.d(cls2, "mResourceReferences").get(invoke);
}
} else {
vtw = ((HashMap) ShareReflectUtil.d(cls2, "mActiveResources").get(vtx)).values();
}
if (vtw == null) {
throw new IllegalStateException("resource references is null");
}
Resources resources = context.getResources();
if (VERSION.SDK_INT >= 24) {
try {
vtC = ShareReflectUtil.b(resources, "mResourcesImpl");
} catch (Throwable th2) {
vtB = ShareReflectUtil.b(resources, "mAssets");
}
} else {
vtB = ShareReflectUtil.b(resources, "mAssets");
}
try {
vtG = ShareReflectUtil.d(ApplicationInfo.class, "publicSourceDir");
} catch (NoSuchFieldException e3) {
}
}
public static void bQ(Context context, String str) {
if (str != null) {
ApplicationInfo applicationInfo = context.getApplicationInfo();
Field[] fieldArr;
if (VERSION.SDK_INT < 27) {
fieldArr = new Field[]{vtE, vtF};
} else {
fieldArr = new Field[]{vtE};
}
for (Field field : fieldArr) {
for (Entry value : ((Map) field.get(vtx)).entrySet()) {
Object obj = ((WeakReference) value.getValue()).get();
if (obj != null) {
if (applicationInfo.sourceDir.equals((String) vtD.get(obj))) {
vtD.set(obj, str);
}
}
}
}
if (((Integer) vtz.invoke(vty, new Object[]{str})).intValue() == 0) {
throw new IllegalStateException("Could not create new AssetManager");
}
if (!(vtH == null || vtA == null)) {
vtH.set(vty, null);
vtA.invoke(vty, new Object[0]);
}
for (WeakReference weakReference : vtw) {
Resources resources = (Resources) weakReference.get();
if (resources != null) {
try {
vtB.set(resources, vty);
} catch (Throwable th) {
Object obj2 = vtC.get(resources);
ShareReflectUtil.b(obj2, "mAssets").set(obj2, vty);
}
c(resources);
resources.updateConfiguration(resources.getConfiguration(), resources.getDisplayMetrics());
}
}
if (VERSION.SDK_INT >= 24) {
try {
if (vtG != null) {
vtG.set(context.getApplicationInfo(), str);
}
} catch (Throwable th2) {
}
}
if (!hS(context)) {
throw new TinkerRuntimeException("checkResInstall failed");
}
}
}
private static void c(Resources resources) {
try {
Object obj = ShareReflectUtil.d(Resources.class, "mTypedArrayPool").get(resources);
do {
} while (ShareReflectUtil.b(obj, "acquire", new Class[0]).invoke(obj, new Object[0]) != null);
} catch (Throwable th) {
new StringBuilder("clearPreloadTypedArrayIssue failed, ignore error: ").append(th);
}
}
private static boolean hS(Context context) {
Object open;
Object obj = null;
try {
open = context.getAssets().open("only_use_to_test_tinker_resource.txt");
} catch (Throwable th) {
open = th;
StringBuilder stringBuilder = new StringBuilder("checkResUpdate failed, can't find test resource assets file only_use_to_test_tinker_resource.txt e:");
open = open.getMessage();
stringBuilder.append(open);
return false;
} finally {
SharePatchFileUtil.ar(
/*
Method generation error in method: com.tencent.tinker.loader.TinkerResourcePatcher.hS(android.content.Context):boolean, dex:
jadx.core.utils.exceptions.CodegenException: Error generate insn: 0x0027: INVOKE (wrap: java.lang.Object
?: MERGE (r3_1 java.lang.Object) = (r3_0 'obj' java.lang.Object), (r0_5 'open' java.lang.Object)) com.tencent.tinker.loader.shareutil.SharePatchFileUtil.ar(java.lang.Object):void type: STATIC in method: com.tencent.tinker.loader.TinkerResourcePatcher.hS(android.content.Context):boolean, dex:
at jadx.core.codegen.InsnGen.makeInsn(InsnGen.java:226)
at jadx.core.codegen.InsnGen.makeInsn(InsnGen.java:203)
at jadx.core.codegen.RegionGen.makeSimpleBlock(RegionGen.java:100)
at jadx.core.codegen.RegionGen.makeRegion(RegionGen.java:50)
at jadx.core.codegen.RegionGen.makeSimpleRegion(RegionGen.java:87)
at jadx.core.codegen.RegionGen.makeRegion(RegionGen.java:53)
at jadx.core.codegen.RegionGen.makeRegionIndent(RegionGen.java:93)
at jadx.core.codegen.RegionGen.makeTryCatch(RegionGen.java:298)
at jadx.core.codegen.RegionGen.makeRegion(RegionGen.java:63)
at jadx.core.codegen.RegionGen.makeSimpleRegion(RegionGen.java:87)
at jadx.core.codegen.RegionGen.makeRegion(RegionGen.java:53)
at jadx.core.codegen.MethodGen.addInstructions(MethodGen.java:186)
at jadx.core.codegen.ClassGen.addMethod(ClassGen.java:320)
at jadx.core.codegen.ClassGen.addMethods(ClassGen.java:257)
at jadx.core.codegen.ClassGen.addClassBody(ClassGen.java:220)
at jadx.core.codegen.ClassGen.addClassCode(ClassGen.java:110)
at jadx.core.codegen.ClassGen.makeClass(ClassGen.java:75)
at jadx.core.codegen.CodeGen.visit(CodeGen.java:10)
at jadx.core.ProcessClass.process(ProcessClass.java:38)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:286)
at jadx.api.JavaClass.decompile(JavaClass.java:62)
at jadx.api.JadxDecompiler.lambda$appendSourcesSave$0(JadxDecompiler.java:201)
Caused by: jadx.core.utils.exceptions.CodegenException: Error generate insn: ?: MERGE (r3_1 java.lang.Object) = (r3_0 'obj' java.lang.Object), (r0_5 'open' java.lang.Object) in method: com.tencent.tinker.loader.TinkerResourcePatcher.hS(android.content.Context):boolean, dex:
at jadx.core.codegen.InsnGen.makeInsn(InsnGen.java:226)
at jadx.core.codegen.InsnGen.addArg(InsnGen.java:101)
at jadx.core.codegen.InsnGen.generateMethodArguments(InsnGen.java:686)
at jadx.core.codegen.InsnGen.makeInvoke(InsnGen.java:656)
at jadx.core.codegen.InsnGen.makeInsnBody(InsnGen.java:338)
at jadx.core.codegen.InsnGen.makeInsn(InsnGen.java:220)
... 21 more
Caused by: jadx.core.utils.exceptions.CodegenException: MERGE can be used only in fallback mode
at jadx.core.codegen.InsnGen.fallbackOnlyInsn(InsnGen.java:537)
at jadx.core.codegen.InsnGen.makeInsnBody(InsnGen.java:509)
at jadx.core.codegen.InsnGen.makeInsn(InsnGen.java:211)
... 26 more
*/
}
|
package com.hesoyam.pharmacy.util.report.calculator;
import com.hesoyam.pharmacy.pharmacy.model.Sale;
import com.hesoyam.pharmacy.util.report.ReportData;
import com.hesoyam.pharmacy.util.report.label.QuarterlyReportLabel;
import java.time.LocalDateTime;
import java.time.Month;
import java.util.EnumMap;
public class QuarterlySalesCalculator<V extends Sale> extends SalesCalculator<QuarterlyReportLabel, V> {
private static final EnumMap<Month, Integer> QUARTERS = new EnumMap<>(Month.class);
static {
QUARTERS.put(Month.JANUARY, 1);
QUARTERS.put(Month.FEBRUARY, 1);
QUARTERS.put(Month.MARCH, 1);
QUARTERS.put(Month.APRIL, 2);
QUARTERS.put(Month.MAY, 2);
QUARTERS.put(Month.JUNE, 2);
QUARTERS.put(Month.JULY, 3);
QUARTERS.put(Month.AUGUST, 3);
QUARTERS.put(Month.SEPTEMBER, 3);
QUARTERS.put(Month.OCTOBER, 4);
QUARTERS.put(Month.NOVEMBER, 4);
QUARTERS.put(Month.DECEMBER, 4);
}
@Override
protected ReportData<QuarterlyReportLabel> getSaleReport(Sale sale) {
LocalDateTime date = sale.getDateOfSale();
Month month = date.getMonth();
QuarterlyReportLabel label = new QuarterlyReportLabel(date.getYear(), QUARTERS.get(month));
return new ReportData<>(label, 1);
}
}
|
package com.hesoyam.pharmacy.pharmacy.mapper;
import com.hesoyam.pharmacy.pharmacy.dto.CreateOfferDTO;
import com.hesoyam.pharmacy.pharmacy.dto.OfferDTO;
import com.hesoyam.pharmacy.pharmacy.model.Offer;
public class OfferMapper {
private OfferMapper() {}
public static Offer mapCreateOfferDTOToOffer(CreateOfferDTO createOfferDTO){
return new Offer(createOfferDTO.getTotalPrice(), createOfferDTO.getDeliveryDate());
}
public static OfferDTO mapOfferToOfferDTO(Offer offer){
return new OfferDTO(offer.getId(),offer.getTotalPrice(), offer.getDeliveryDate(), offer.getOfferStatus(), offer.getOrder().getId());
}
}
|
package com.tencent.mm.protocal;
import com.tencent.mm.protocal.c.g;
public class c$jg extends g {
public c$jg() {
super("stopRecord", "stopRecord", 98, false);
}
}
|
package chapter06;
public class Exercise06_01 {
public static void main(String[] args) {
final int NUMBER_OF_LOOP = 100;
final int NUMBER_OF_LINE = 10;
for (int i = 1; i <= NUMBER_OF_LOOP; i++) {
System.out.printf("%-6d", getPentagonalNumberOneByOne(i));
if (i % NUMBER_OF_LINE == 0)
System.out.println();
}
System.out.println("--------------------------------------");
getPentagonalNumber(1);
}
public static int getPentagonalNumberOneByOne(int n) {
n = n * (3 * n - 1) / 2;
return n;
}
public static void getPentagonalNumber(int n) {
for (int i = 1; i <= 100; i++) {
int equation = n * (3 * n - 1) / 2;
System.out.printf("%-6d", equation);
n++;
if (i % 10 == 0) {
System.out.println();
}
}
}
}
|
package main.java.model.calculator;
// Author: Alexander Larnemo Ask, Jonatan Bunis, Vegard Landrö, Mohamad Melhem, Alexander Larsson Vahlberg
// Responsibility: Datastructure for the input and output of the calculators.
// Used by: ModelFacade, ModelAggregate, CalculatorFacade, ResultViewController, [Each Calculator implementation].
// Uses: Provides a datastructure for calculations with multiple parameters and outputs.
public enum DataKey {
SOLAR_PANEL_EFFICIENCY,
ELECTRICITY_PRODUCTION_CAPACITY("Produktion i KW"),
MONTHLY_ELECTRICITY_CONSUMPTION,
SURPLUS("Överskott av energi:"),
INSTALLATION_COST ("Installationskostnad:"),
GOVERNMENT_SUBVENTION ("Statlig subvention:"),
SUBVENTED_INSTALLATION_COST ("Totalkostnad efter subvention:"),
AVAILABLE_SPACE,
ELECTRICITY_SELL_PRICE,
PANEL_SIZE,
PANEL_PRICE,
LEVELIZED_ELECTRICITY_COST ("Utjämnad energikostnad:"),
ANNUAL_ELECTRICITY_PRODUCTION("Årlig elproduktion:"),
ANNUAL_OPERATION_COST("Underhållskostnad per år:"),
EXPECTED_LIFESPAN,
SOLAR_PANEL_COVERAGE("coverage : "),
AVERAGE_SOLAR_RADIATION,
SOLAR_PANEL_PERFORMANCE_RATIO,
MONTHLY_ELECTRICITY_PRICE,
YEARS_TO_BREAK_EVEN ("Tid till vinst:");
private String description = "Value";
DataKey(String description) {
this.description = description;
}
DataKey() {
}
public String getDescription() {
return description;
}
}
|
package com.sunteam.library.parse;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;
import com.sunteam.library.entity.BookmarkEntity;
import com.sunteam.library.utils.LogUtils;
//解析书签列表
public class GetBookMarkParseResponse extends AbsParseResponse
{
public static final String TAG = "GetBookMarkParseResponse";
/**
* 方法(解析items)
*
* @param jsonArray
* @param list
* @return
* @author wzp
* @Created 2017/02/14
*/
private void parseItems( JSONArray jsonArray, ArrayList<BookmarkEntity> list )
{
for( int i = 0; i < jsonArray.length(); i++ )
{
JSONObject obj = jsonArray.optJSONObject(i);
BookmarkEntity entity = new BookmarkEntity();
entity.id = obj.optInt("Id"); //记录id
entity.userName = obj.optString("UserName"); //用户名
entity.bookId = obj.optString("BookId"); //书目ID
entity.begin = obj.optInt("Begin"); //开始位置
entity.chapterIndex = obj.optInt("ChapterIndex"); //章节序号
entity.chapterTitle = obj.optString("ChapterTitle"); //章节标题
entity.markName = obj.optString("MarkName"); //书签名称
entity.percent = obj.optString("Percent"); //进度
entity.addedTime = obj.optString("AddedTime"); //创建时间
list.add(entity);
}
}
@Override
public Object parseResponse(String responseStr) throws Exception
{
// TODO Auto-generated method stub
LogUtils.e(TAG,"responseStr---" + responseStr);
try
{
JSONObject jsonObject = new JSONObject(responseStr);
Boolean result = jsonObject.optBoolean("IsException") ;
if( result )
{
return null;
}
JSONArray jsonArray = jsonObject.optJSONArray("Items");
if( ( null == jsonArray ) || ( 0 == jsonArray.length() ) )
{
return null;
}
ArrayList<BookmarkEntity> list = new ArrayList<BookmarkEntity>();
parseItems( jsonArray, list );
return list;
}
catch( Exception e )
{
e.printStackTrace();
}
return null;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.