text stringlengths 10 2.72M |
|---|
package com.eomcs.basic.oop.ex06.aa;
public class Exam210 {
public static void main(String args) {
Vehicle v1 = new Sedan();
v1.model = "티코";
v1.capacity = 5;
Sedan s = (Sedan)v1;
s.auto = true;
s.sunroof = true;
s.cc = 1960;
s.value = 24;
}
}
|
package com.github.olly.workshop.trafficgen.model;
public enum TransformationType {
rotate,
grayscale,
resize,
flip
}
|
package com.java.springboot.service;
import com.java.springboot.entity.Emp;
import java.util.Map;
public interface EmpService {
//分页查询员工业务接口
Map<String,Object> findPageEmp(Integer page,Integer limit) throws Exception;
/**
* @Description: 删除员工信息
* @Param: [empno]
* @return:
* @Author: Mr.Yu
* @Date:
*/
String scEmpByEmpno(Integer empno) throws Exception;
/**
* @Description: 修改员工信息
* @Param: [emp]
* @return:
* @Author: Mr.Yu
* @Date:
*/
String updEmpByEmpno(Emp emp) throws Exception;
/**
* @Description: 添加员工信息
* @Param: [emp]
* @return:
* @Author: Mr.Yu
* @Date:
*/
String insEmp(Emp emp) throws Exception;
}
|
package xyz.hxworld.codetimeline;
import android.content.Context;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by Kshitij Nagvekar on 3/7/2016.
*/
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private ArrayList<EventModel> events;
public RecyclerViewAdapter(ArrayList<EventModel> events) {
this.events = new ArrayList<>(events);
}
@Override
public RecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View eventView = inflater.inflate(R.layout.list_row, null);
ViewHolder viewHolder = new ViewHolder(eventView);
return viewHolder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
final EventModel e = events.get(position);
// TextView titleTextView = holder.titleTextView;
// titleTextView.setText(e.getTitle());
//
// TextView urlTextView = holder.urlTextView;
// urlTextView.setText(e.getUrl());
//
// TextView dateTextView = holder.dateTextView;
// dateTextView.setText(e.getStartTime() + " - " + e.getEndTime());
holder.bind(e);
}
@Override
public int getItemCount() {
return events.size();
}
public void setEvents(ArrayList<EventModel> events) {
this.events = new ArrayList<>(events);
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public CardView cardView;
public TextView titleTextView;
public TextView urlTextView;
public TextView dateTextView;
public ViewHolder(View itemView) {
super(itemView);
cardView = (CardView) itemView.findViewById(R.id.card_view);
titleTextView = (TextView) itemView.findViewById(R.id.title);
urlTextView = (TextView) itemView.findViewById(R.id.url);
dateTextView = (TextView) itemView.findViewById(R.id.date);
}
public void bind(EventModel eventModel) {
titleTextView.setText(eventModel.getTitle());
urlTextView.setText(eventModel.getUrl());
dateTextView.setText(eventModel.getStartTime() + " - " + eventModel.getEndTime());
}
}
public EventModel removeItem(int position) {
final EventModel model = events.remove(position);
notifyItemRemoved(position);
return model;
}
public void addItem(int position, EventModel eventModel) {
events.add(position, eventModel);
notifyItemInserted(position);
}
public void moveItem(int fromPosition, int toPosition) {
final EventModel eventModel = events.remove(fromPosition);
events.add(toPosition, eventModel);
notifyItemMoved(fromPosition, toPosition);
}
public void animateTo(ArrayList<EventModel> e) {
applyAndAnimateRemovals(e);
applyAndAnimateAdditions(e);
applyAndAnimateMovedItems(e);
}
private void applyAndAnimateRemovals(ArrayList<EventModel> newModels) {
for (int i = events.size() - 1; i >= 0; i--) {
final EventModel model = events.get(i);
if (!newModels.contains(model)) {
removeItem(i);
}
}
}
private void applyAndAnimateAdditions(ArrayList<EventModel> newModels) {
for (int i = 0, count = newModels.size(); i < count; i++) {
final EventModel model = newModels.get(i);
if (!events.contains(model)) {
addItem(i, model);
}
}
}
private void applyAndAnimateMovedItems(ArrayList<EventModel> newModels) {
for (int toPosition = newModels.size() - 1; toPosition >= 0; toPosition--) {
final EventModel model = newModels.get(toPosition);
final int fromPosition = events.indexOf(model);
if (fromPosition >= 0 && fromPosition != toPosition) {
moveItem(fromPosition, toPosition);
}
}
}
}
|
package vostore.apptualidade.Fragments;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import vostore.apptualidade.Inicio;
import vostore.apptualidade.Login;
import vostore.apptualidade.R;
import vostore.apptualidade.Simulado.QuizActivity;
public class Regras extends AppCompatActivity {
private Button btncomecar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_regras);
btncomecar = findViewById(R.id.botao_regra);
btncomecar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
btncomecar.setBackgroundResource(R.drawable.comecar_regra2);
Intent intent = new Intent(Regras.this, QuizActivity.class);
startActivity(intent);
finish();
}
});
}
}
|
package com.symphox.deprecated.model.json;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import org.hibernate.validator.constraints.NotEmpty;
@Entity
@Table(name="PROJECT_DATA")
public class ProjectData implements Serializable {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer pro_id;
@NotEmpty
@Column(name="PRO_NAME", unique=true, nullable=false)
private String pro_name;
@NotEmpty
@Column(name="PRO_USER", nullable=false)
private String pro_user;
@NotEmpty
@Column(name="PRO_STATUS", nullable=false)
private String pro_status;
@NotEmpty
@Column(name="PRO_START_DATE", nullable=false)
private String pro_start_date;
@NotEmpty
@Column(name="PRO_END_DATE", nullable=false)
private String pro_end_date;
@NotEmpty
@Column(name="PRO_DEPT_CODE", nullable=false)
private String pro_dept_code;
@NotEmpty
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "PROJECT_DATA_PROFECT_DATA_DETAIL",
joinColumns = { @JoinColumn(name = "ID") },
inverseJoinColumns = { @JoinColumn(name = "PRO_ID") })
private Set<ProjectDataDetail> dataDetail = new HashSet<ProjectDataDetail>();
public Integer getPro_id() {
return pro_id;
}
public void setPro_id(Integer pro_id) {
this.pro_id = pro_id;
}
public String getPro_name() {
return pro_name;
}
public void setPro_name(String pro_name) {
this.pro_name = pro_name;
}
public String getPro_user() {
return pro_user;
}
public void setPro_user(String pro_user) {
this.pro_user = pro_user;
}
public String getPro_status() {
return pro_status;
}
public void setPro_status(String pro_status) {
this.pro_status = pro_status;
}
public String getPro_start_date() {
return pro_start_date;
}
public void setPro_start_date(String pro_start_date) {
this.pro_start_date = pro_start_date;
}
public String getPro_end_date() {
return pro_end_date;
}
public void setPro_end_date(String pro_end_date) {
this.pro_end_date = pro_end_date;
}
public String getPro_dept_code() {
return pro_dept_code;
}
public void setPro_dept_code(String pro_dept_code) {
this.pro_dept_code = pro_dept_code;
}
public Set<ProjectDataDetail> getDataDetail() {
return dataDetail;
}
public void setDataDetail(Set<ProjectDataDetail> dataDetail) {
this.dataDetail = dataDetail;
}
} |
package com.example.riccardo.chat_rev.chat;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.riccardo.chat_rev.R;
import com.example.riccardo.chat_rev.db.DbAdapter;
import com.example.riccardo.chat_rev.db.DbInit;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by riccardo on 04/12/15.
*/
public class ActivityLogin extends Activity implements View.OnClickListener {
private Button buttonLogin; //pulsante per il login
private EditText editTextUser; //textbox per l'username
private EditText editTextPassword; //textbox per la password
private TextView textViewRegistrazione; //label per registrarsi
private ProgressBar loginProgressBar; //progress bar per il login remoto
private SharedPreferences sharedPreferences; //shared preferences
private String user;
private String password;
private Then t=new Then(){
@Override
public void onTaskCompleted(String result) {
remoteLogin(result);
}
@Override
public void execute() {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//prendo i riferimenti dei controlli della GUI
buttonLogin=(Button) findViewById(R.id.btn_login);
editTextUser = (EditText)findViewById(R.id.txt_user);
editTextPassword = (EditText)findViewById(R.id.txt_password);
textViewRegistrazione = (TextView)findViewById(R.id.lbl_regist);
loginProgressBar = (ProgressBar)findViewById(R.id.loginProgress);
buttonLogin.setOnClickListener(this);
textViewRegistrazione.setOnClickListener(this);
//Prendo le shared preferences
sharedPreferences=getSharedPreferences(Const.SP_NAME, Context.MODE_PRIVATE);
if(sharedPreferences.contains(Const.SP_USER)){
//se l'utente si è loggato almeno una volta passo direttamente all'activity delle chat
user=sharedPreferences.getString(Const.SP_USER,"");
startActivity(new Intent(getApplicationContext(), ActivityChatList.class));
}
}
@Override
public void onClick(View v) {
if(v.getId()==buttonLogin.getId()){ //se è stato cliccato il pulsante di login
buttonLogin.setEnabled(false);
//prendo i valori delle text box
user=editTextUser.getText().toString();
password=editTextPassword.getText().toString();
//faccio girare la il caricamento
findViewById(R.id.loginProgress).setVisibility(View.VISIBLE);
//controllo le credenziali e loggo
checkLogin();
}else if(v.getId()==textViewRegistrazione.getId()){//se è stato premuto registrati
//spedisco all'activity di registrazione
Intent i = new Intent(getApplicationContext(), ActivitySignIn.class);
startActivity(i);
}
}
private void checkLogin(){
//creo il json
JSONObject json = null;
//se l'utente ha inserito i dati
if ((!user.equals("")) && (!password.equals(""))) {
try {
//popolo l'oggetto json e lo sparo alle API
json = new JSONObject();
json.put(Const.API_USER, user);
json.put(Const.API_PASSWORD, password);
//mostro il caricamento
loginProgressBar.setVisibility(View.VISIBLE);
//faccio la richiesta
new APIRequest(t).execute(json.toString(), Const.API_PAGE_LOGIN);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void remoteLogin(String res){
//trimmo la stringa
res = res.replaceAll(" ", "");
//controllo il risultato
if (res.equals(Const.API_OK)) {
//salvo le credenziali in locale
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Const.SP_USER, user);
editor.putString(Const.SP_PW, password);
editor.commit();
//popolo il db locale
new DbInit(user, getApplicationContext(), new DbAdapter(getApplicationContext()), new Then() {
@Override
public void onTaskCompleted(String result) {
if (result.equals(Const.DB_INIT_ENDED)) {
//rimuovo il progress di caricamento
loginProgressBar.setVisibility(View.INVISIBLE);
//faccio partire l'activity quando il db è stato popolato
startActivity(new Intent(getApplicationContext(), ActivityChatList.class));
}
}
@Override
public void execute() {
}
});
} else{
buttonLogin.setEnabled(true);
//rimuovo il progress di caricamento
loginProgressBar.setVisibility(View.INVISIBLE);
//altrimenti notifico l'errore, in entrambi i casi.
Toast.makeText(getApplicationContext(),R.string.AUTH_ERROR, Toast.LENGTH_SHORT).show();
}
}
}
|
package com.codingchili.instance.model.movement;
import com.codingchili.instance.context.GameContext;
import com.codingchili.instance.model.entity.Creature;
import com.codingchili.instance.model.entity.Vector;
import com.codingchili.instance.model.stats.Attribute;
/**
* A behaviour that causes one creature to flee from another.
*/
public class FleeBehaviour implements MovementBehaviour {
private static int FLEE_RANGE = 512;
private Creature source;
private Creature target;
/**
* @param source the creature that will be fleeing the target.
* @param target the creature being fled from by source.
*/
public FleeBehaviour(Creature source, Creature target) {
this.source = source;
this.target = target;
}
@Override
public boolean active(GameContext game) {
return game.exists(source.getId()) && game.exists(target.getId());
}
@Override
public void update(GameContext game) {
Vector vector = source.getVector();
Vector following = target.getVector();
float targetX = following.getX();
float targetY = following.getY();
if (vector.distance(targetX, targetY) < FLEE_RANGE) {
float direction = vector.targetAngle(targetX, targetY);
direction += Math.toRadians(180);
vector.setDirection(direction);
vector.setVelocity((float) source.getStats().get(Attribute.movement));
game.movement().update(source);
} else {
if (vector.isMoving()) {
vector.stop();
game.publish(new MovementEvent(vector, source.getId()));
}
}
}
}
|
package List;
public class LinkedList {
public static void main(String[] args) {
java.util.LinkedList ll=new java.util.LinkedList();
//1.to add the element in linked-list
ll.add("Jenkins");
ll.add("Selenium");
ll.add("Maven");
ll.add("Test");
ll.add("Jenkins");
ll.add("GitHub");
for (Object link : ll) {
System.out.println(link);
}
System.out.println("*******************");
java.util.LinkedList ll2=new java.util.LinkedList();
//2.to check the size of linked-list
ll2.add("Test");
ll2.add("Selenium");
ll2.add("Maven");
ll2.add("Test");
System.out.println(ll2.size());
System.out.println("*******************");
java.util.LinkedList ll3=new java.util.LinkedList();
//3.to fetch the specific element of linked-list on the basis of index
ll3.add("Test");
ll3.add("Selenium");
ll3.add("Maven");
ll3.add("Test");
System.out.println(ll3.get(3));
System.out.println("*******************");
//4.to remove the element from linked-list on the basis of index
java.util.LinkedList ll4=new java.util.LinkedList();
ll4.add("Selenium");
ll4.add("Maven");
ll4.add("Test");
ll4.add("Jenkins");
ll4.add("GitHub");
ll4.remove(2);
for (Object linked : ll4) {
System.out.println(linked);
}
System.out.println("*******************");
//5.to add the element on the first index of linked-list
java.util.LinkedList ll5=new java.util.LinkedList();
ll5.add("Selenium");
ll5.add("Maven");
ll5.add("Test");
ll5.add("Jenkins");
ll5.add("GitHub");
ll5.addFirst("Page Object Model");
for (Object LOL : ll5) {
System.out.println(LOL);
}
System.out.println("*******************");
//6.to add the element on the last index of linked-list
java.util.LinkedList ll6=new java.util.LinkedList();
ll6.add("Selenium");
ll6.add("Maven");
ll6.add("Test");
ll6.add("Jenkins");
ll6.add("GitHub");
ll6.addLast("Data Driven");
for (Object LIK : ll6) {
System.out.println(LIK);
}
System.out.println("*******************");
//7.to remove the element on the first index of linked-list
java.util.LinkedList ll7=new java.util.LinkedList();
ll7.add("Selenium");
ll7.add("Maven");
ll7.add("Test");
ll7.add("Jenkins");
ll7.add("GitHub");
ll7.removeFirst();
for (Object LIKe : ll7) {
System.out.println(LIKe);
}
System.out.println("*******************");
//8.to remove the element on the last index of linked-list
java.util.LinkedList ll8=new java.util.LinkedList();
ll8.add("Selenium");
ll8.add("Maven");
ll8.add("Test");
ll8.add("Jenkins");
ll8.add("GitHub");
ll8.removeLast();
for (Object LOI : ll8) {
System.out.println(LOI);
}
System.out.println("*******************");
//9.to replace the element to another element on the basis of index
java.util.LinkedList ll9=new java.util.LinkedList();
ll9.add("Selenium");
ll9.add("Maven");
ll9.add("Test");
ll9.add("Jenkins");
ll9.add("GitHub");
ll9.set(0, "QTP");
for (Object LO : ll9) {
System.out.println(LO);
}
System.out.println("*******************");
}
}
|
package juniorandkarlson;
public class Mother extends Parent{
public Mother(String name, int age) {
super(name, age);
setGender(Gender.FEMALE);
}
public Mother(String name) {
super(name);
setGender(Gender.FEMALE);
}
public Mother(String name, boolean b) {
super(name, b);
setGender(Gender.FEMALE);
}
@Override
public String say() {
String s = "";
if (this.getLaugh()){
s = "и сказала:";
laughFalse();
}
return s;
}
@Override
public void laugh() {
this.laughTrue();
System.out.print("Тут мама рассмеялась " + say() + "\nРаз ");
}
@Override
public String good(){
return "хорошая.";
}
@Override
public String bad(){
return "плохая.";
}
} |
package com.geimu.gui;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.geimu.domain.Enemy;
import com.geimu.domain.Message;
import com.geimu.domain.Player;
import com.geimu.service.BattleService;
import com.geimu.service.PlayerService;
import com.geimu.service.SkillService;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.JOptionPane;
import javax.swing.JToolTip;
import javax.swing.Timer;
public class NewGeimuUI extends javax.swing.JFrame {
public static Player player = new Player();
private static Enemy enemy;
private Timer mpRecoverTimer = null;
private Timer playerTimer = null;
private Timer enemyTimer = null;
private Timer bladeTimer = null;
private Timer blessTimer = null;
private Timer fireCoolDownTimer = null;
private Timer bladeCoolDownTimer = null;
private Timer healCoolDownTimer = null;
private Timer blessCoolDownTimer = null;
private Timer curseCoolDownTimer = null;
private final BattleService battleService = new BattleService();
private final PlayerService playerService = new PlayerService();
private final SkillService skillService = new SkillService();
/**
* Creates new form NewGeimuUI
*/
public NewGeimuUI() {
initComponents();
this.setLocationRelativeTo(null);
initGeimu();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
mainPanel = new javax.swing.JPanel();
playerPanel = new javax.swing.JPanel();
playerTextLabel = new javax.swing.JLabel();
levelTextLabel = new javax.swing.JLabel();
levelLabel = new javax.swing.JLabel();
hpTextLabel = new javax.swing.JLabel();
hpLabel = new javax.swing.JLabel();
hpSplitTextLabel = new javax.swing.JLabel();
hpMaxLabel = new javax.swing.JLabel();
mpTextLabel = new javax.swing.JLabel();
mpLabel = new javax.swing.JLabel();
mpSplitTextLabel = new javax.swing.JLabel();
mpMaxLabel = new javax.swing.JLabel();
expTextLabel = new javax.swing.JLabel();
expLabel = new javax.swing.JLabel();
expSplitTextLabel = new javax.swing.JLabel();
expMaxLabel = new javax.swing.JLabel();
saveButton = new javax.swing.JButton();
loadButton = new javax.swing.JButton();
expProgressBar = new javax.swing.JProgressBar();
statusPanel = new javax.swing.JPanel();
statusTextLabel = new javax.swing.JLabel();
strTextLabel = new javax.swing.JLabel();
strLabel = new javax.swing.JLabel();
addStrLabel = new javax.swing.JLabel();
agiTextLabel = new javax.swing.JLabel();
agiLabel = new javax.swing.JLabel();
addAgiLabel = new javax.swing.JLabel();
vitTextLabel = new javax.swing.JLabel();
vitLabel = new javax.swing.JLabel();
addVitLabel = new javax.swing.JLabel();
wisTextLabel = new javax.swing.JLabel();
wisLabel = new javax.swing.JLabel();
addWisLabel = new javax.swing.JLabel();
dexTextLabel = new javax.swing.JLabel();
dexLabel = new javax.swing.JLabel();
addDexLabel = new javax.swing.JLabel();
lukTextLabel = new javax.swing.JLabel();
lukLabel = new javax.swing.JLabel();
addLukLabel = new javax.swing.JLabel();
pointsTextLabel = new javax.swing.JLabel();
pointsLabel = new javax.swing.JLabel();
battleMsgPanel = new javax.swing.JPanel();
ballteMsgScrollPane = new javax.swing.JScrollPane();
battleMsg = new javax.swing.JTextArea();
enemyPanel = new javax.swing.JPanel();
monNameTextLabel = new javax.swing.JLabel();
monLevelTextLabel = new javax.swing.JLabel();
monLevelLabel = new javax.swing.JLabel();
monHpTextLabel = new javax.swing.JLabel();
monHpLabel = new javax.swing.JLabel();
monHpSplitTextLabel = new javax.swing.JLabel();
monHpMaxLabel = new javax.swing.JLabel();
travelButton = new javax.swing.JButton();
skillPanel = new javax.swing.JPanel();
skillsTextLabel = new javax.swing.JLabel();
skillPointsTextLabel = new javax.swing.JLabel();
skillPointsLabel = new javax.swing.JLabel();
fireToggleButton = new javax.swing.JToggleButton(){ public JToolTip createToolTip() { JToolTip tip = super.createToolTip(); tip.setFont(new Font("微軟正黑體", 0, 12)); tip.setBackground(new Color(242,242,189)); tip.setBorder(BorderFactory.createLineBorder(new Color(146,151,161), 1, true)); return tip; } }; ;
fireLevelTextLabel = new javax.swing.JLabel();
fireLevelLabel = new javax.swing.JLabel();
addFireLabel = new javax.swing.JLabel();
bladeToggleButton = new javax.swing.JToggleButton(){
public JToolTip createToolTip() {
JToolTip tip = super.createToolTip();
tip.setFont(new Font("微軟正黑體", 0, 12));
tip.setBackground(new Color(242,242,189));
tip.setBorder(BorderFactory.createLineBorder(new Color(146,151,161), 1, true));
return tip;
}
};
;
bladeLevelTextLabel = new javax.swing.JLabel();
bladeLevelLabel = new javax.swing.JLabel();
addBladeLabel = new javax.swing.JLabel();
healToggleButton = new javax.swing.JToggleButton(){ public JToolTip createToolTip() { JToolTip tip = super.createToolTip(); tip.setFont(new Font("微軟正黑體", 0, 12)); tip.setBackground(new Color(242,242,189)); tip.setBorder(BorderFactory.createLineBorder(new Color(146,151,161), 1, true)); return tip; } }; ;
healLevelTextLabel = new javax.swing.JLabel();
healLevelLabel = new javax.swing.JLabel();
addHealLabel = new javax.swing.JLabel();
blessToggleButton = new javax.swing.JToggleButton(){ public JToolTip createToolTip() { JToolTip tip = super.createToolTip(); tip.setFont(new Font("微軟正黑體", 0, 12)); tip.setBackground(new Color(242,242,189)); tip.setBorder(BorderFactory.createLineBorder(new Color(146,151,161), 1, true)); return tip; } }; ;
blessLevelTextLabel = new javax.swing.JLabel();
blessLevelLabel = new javax.swing.JLabel();
addBlessLabel = new javax.swing.JLabel();
curseToggleButton = new javax.swing.JToggleButton(){ public JToolTip createToolTip() { JToolTip tip = super.createToolTip(); tip.setFont(new Font("微軟正黑體", 0, 12)); tip.setBackground(new Color(242,242,189)); tip.setBorder(BorderFactory.createLineBorder(new Color(146,151,161), 1, true)); return tip; } }; ;
curseLevelTextLabel = new javax.swing.JLabel();
curseLevelLabel = new javax.swing.JLabel();
addCurseLabel = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Geimu");
mainPanel.setLayout(new java.awt.BorderLayout());
playerPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
playerTextLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
playerTextLabel.setText("玩家");
levelTextLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
levelTextLabel.setText("等級:");
levelLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
levelLabel.setText("-");
hpTextLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
hpTextLabel.setText("HP:");
hpLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
hpLabel.setText("-");
hpSplitTextLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
hpSplitTextLabel.setText("/");
hpMaxLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
hpMaxLabel.setText("-");
mpTextLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
mpTextLabel.setText("MP:");
mpLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
mpLabel.setText("-");
mpSplitTextLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
mpSplitTextLabel.setText("/");
mpMaxLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
mpMaxLabel.setText("-");
expTextLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
expTextLabel.setText("經驗值:");
expLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
expLabel.setText("-");
expSplitTextLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
expSplitTextLabel.setText("/");
expMaxLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
expMaxLabel.setText("-");
saveButton.setText("存檔");
saveButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
saveButtonActionPerformed(evt);
}
});
loadButton.setText("讀取");
loadButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
loadButtonActionPerformed(evt);
}
});
expProgressBar.setForeground(new java.awt.Color(0, 255, 0));
expProgressBar.setToolTipText("0%");
expProgressBar.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
expProgressBar.setString("");
javax.swing.GroupLayout playerPanelLayout = new javax.swing.GroupLayout(playerPanel);
playerPanel.setLayout(playerPanelLayout);
playerPanelLayout.setHorizontalGroup(
playerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(playerPanelLayout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(playerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(expProgressBar, javax.swing.GroupLayout.PREFERRED_SIZE, 517, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(playerPanelLayout.createSequentialGroup()
.addComponent(playerTextLabel)
.addGap(18, 18, 18)
.addComponent(levelTextLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(levelLabel)
.addGap(18, 18, 18)
.addComponent(hpTextLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(hpLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(hpSplitTextLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(hpMaxLabel)
.addGap(18, 18, 18)
.addComponent(mpTextLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(mpLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(mpSplitTextLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(mpMaxLabel))
.addGroup(playerPanelLayout.createSequentialGroup()
.addComponent(expTextLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(expLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(expSplitTextLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(expMaxLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(saveButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(loadButton)))
.addGap(25, 25, 25))
);
playerPanelLayout.setVerticalGroup(
playerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(playerPanelLayout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(playerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(playerTextLabel)
.addComponent(levelTextLabel)
.addComponent(levelLabel)
.addComponent(hpTextLabel)
.addComponent(hpLabel)
.addComponent(hpSplitTextLabel)
.addComponent(hpMaxLabel)
.addComponent(mpTextLabel)
.addComponent(mpLabel)
.addComponent(mpSplitTextLabel)
.addComponent(mpMaxLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(playerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(expTextLabel)
.addComponent(expLabel)
.addComponent(expSplitTextLabel)
.addComponent(expMaxLabel)
.addComponent(saveButton)
.addComponent(loadButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(expProgressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(20, Short.MAX_VALUE))
);
mainPanel.add(playerPanel, java.awt.BorderLayout.NORTH);
statusPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
statusTextLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
statusTextLabel.setText("素質");
strTextLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
strTextLabel.setText("STR:");
strLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
strLabel.setText("-");
addStrLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
addStrLabel.setText("[+]");
addStrLabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
addStrLabelMouseClicked(evt);
}
});
agiTextLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
agiTextLabel.setText("AGI:");
agiLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
agiLabel.setText("-");
addAgiLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
addAgiLabel.setText("[+]");
addAgiLabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
addAgiLabelMouseClicked(evt);
}
});
vitTextLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
vitTextLabel.setText("VIT:");
vitLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
vitLabel.setText("-");
addVitLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
addVitLabel.setText("[+]");
addVitLabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
addVitLabelMouseClicked(evt);
}
});
wisTextLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
wisTextLabel.setText("WIS:");
wisLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
wisLabel.setText("-");
addWisLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
addWisLabel.setText("[+]");
addWisLabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
addWisLabelMouseClicked(evt);
}
});
dexTextLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
dexTextLabel.setText("DEX:");
dexLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
dexLabel.setText("-");
addDexLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
addDexLabel.setText("[+]");
addDexLabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
addDexLabelMouseClicked(evt);
}
});
lukTextLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
lukTextLabel.setText("LUK:");
lukLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
lukLabel.setText("-");
addLukLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
addLukLabel.setText("[+]");
addLukLabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
addLukLabelMouseClicked(evt);
}
});
pointsTextLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
pointsTextLabel.setText("剩餘點數:");
pointsLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
pointsLabel.setText("-");
javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
statusPanel.setLayout(statusPanelLayout);
statusPanelLayout.setHorizontalGroup(
statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(statusPanelLayout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(statusTextLabel)
.addGroup(statusPanelLayout.createSequentialGroup()
.addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(strTextLabel)
.addComponent(agiTextLabel)
.addComponent(vitTextLabel)
.addComponent(wisTextLabel)
.addComponent(dexTextLabel)
.addComponent(lukTextLabel)
.addComponent(pointsTextLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(strLabel, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(agiLabel, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(vitLabel, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(wisLabel, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(dexLabel, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(lukLabel, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(pointsLabel, javax.swing.GroupLayout.Alignment.TRAILING))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(addStrLabel)
.addComponent(addAgiLabel)
.addComponent(addVitLabel)
.addComponent(addWisLabel)
.addComponent(addDexLabel)
.addComponent(addLukLabel))))
.addContainerGap(19, Short.MAX_VALUE))
);
statusPanelLayout.setVerticalGroup(
statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(statusPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(statusTextLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(addStrLabel, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(strTextLabel, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(strLabel, javax.swing.GroupLayout.Alignment.TRAILING))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(agiTextLabel)
.addComponent(agiLabel)
.addComponent(addAgiLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(vitTextLabel)
.addComponent(vitLabel)
.addComponent(addVitLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(wisTextLabel)
.addComponent(wisLabel)
.addComponent(addWisLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(dexTextLabel)
.addComponent(dexLabel)
.addComponent(addDexLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lukTextLabel)
.addComponent(lukLabel)
.addComponent(addLukLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(pointsTextLabel)
.addComponent(pointsLabel))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
mainPanel.add(statusPanel, java.awt.BorderLayout.WEST);
battleMsgPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
battleMsg.setEditable(false);
battleMsg.setFont(new java.awt.Font("新細明體", 0, 12)); // NOI18N
battleMsg.setLineWrap(true);
battleMsg.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
battleMsgKeyReleased(evt);
}
});
ballteMsgScrollPane.setViewportView(battleMsg);
javax.swing.GroupLayout battleMsgPanelLayout = new javax.swing.GroupLayout(battleMsgPanel);
battleMsgPanel.setLayout(battleMsgPanelLayout);
battleMsgPanelLayout.setHorizontalGroup(
battleMsgPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(ballteMsgScrollPane)
);
battleMsgPanelLayout.setVerticalGroup(
battleMsgPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(ballteMsgScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 198, javax.swing.GroupLayout.PREFERRED_SIZE)
);
mainPanel.add(battleMsgPanel, java.awt.BorderLayout.CENTER);
enemyPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
monNameTextLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
monNameTextLabel.setText("敵人");
monLevelTextLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
monLevelTextLabel.setText("等級:");
monLevelLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
monLevelLabel.setText("-");
monHpTextLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
monHpTextLabel.setText("HP:");
monHpLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
monHpLabel.setText("-");
monHpSplitTextLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
monHpSplitTextLabel.setText("/");
monHpMaxLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
monHpMaxLabel.setText("-");
travelButton.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
travelButton.setText("開始戰鬥");
travelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
travelButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout enemyPanelLayout = new javax.swing.GroupLayout(enemyPanel);
enemyPanel.setLayout(enemyPanelLayout);
enemyPanelLayout.setHorizontalGroup(
enemyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(enemyPanelLayout.createSequentialGroup()
.addGap(22, 22, 22)
.addGroup(enemyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(travelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(enemyPanelLayout.createSequentialGroup()
.addComponent(monHpTextLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(monHpLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(monHpSplitTextLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(monHpMaxLabel))
.addGroup(enemyPanelLayout.createSequentialGroup()
.addComponent(monNameTextLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(monLevelTextLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(monLevelLabel)))
.addGap(29, 29, 29))
);
enemyPanelLayout.setVerticalGroup(
enemyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(enemyPanelLayout.createSequentialGroup()
.addGap(29, 29, 29)
.addGroup(enemyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(monNameTextLabel)
.addComponent(monLevelTextLabel)
.addComponent(monLevelLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(enemyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(monHpTextLabel)
.addComponent(monHpLabel)
.addComponent(monHpSplitTextLabel)
.addComponent(monHpMaxLabel))
.addGap(46, 46, 46)
.addComponent(travelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
mainPanel.add(enemyPanel, java.awt.BorderLayout.EAST);
skillPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
skillsTextLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
skillsTextLabel.setText("技能");
skillPointsTextLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
skillPointsTextLabel.setText("剩餘技能點數:");
skillPointsLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
skillPointsLabel.setText("-");
fireToggleButton.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
fireToggleButton.setText("火球術");
fireToggleButton.setToolTipText("直接對敵人造成火焰傷害,冷卻時間5秒(效果受到WIS影響)");
fireToggleButton.setEnabled(false);
fireToggleButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fireToggleButtonActionPerformed(evt);
}
});
fireLevelTextLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
fireLevelTextLabel.setText("Lv.");
fireLevelLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
fireLevelLabel.setText("-");
addFireLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
addFireLabel.setText("[+]");
addFireLabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
addFireLabelMouseClicked(evt);
}
});
bladeToggleButton.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
bladeToggleButton.setText("魔力劍");
bladeToggleButton.setToolTipText("對武器注入魔力,持續40秒,冷卻時間15秒(效果受到WIS影響)");
bladeToggleButton.setEnabled(false);
bladeToggleButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bladeToggleButtonActionPerformed(evt);
}
});
bladeLevelTextLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
bladeLevelTextLabel.setText("Lv.");
bladeLevelLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
bladeLevelLabel.setText("-");
addBladeLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
addBladeLabel.setText("[+]");
addBladeLabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
addBladeLabelMouseClicked(evt);
}
});
healToggleButton.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
healToggleButton.setText("治癒術");
healToggleButton.setToolTipText("立即恢復玩家生命值,冷卻時間10秒(效果受到WIS影響)");
healToggleButton.setEnabled(false);
healToggleButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
healToggleButtonActionPerformed(evt);
}
});
healLevelTextLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
healLevelTextLabel.setText("Lv.");
healLevelLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
healLevelLabel.setText("-");
addHealLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
addHealLabel.setText("[+]");
addHealLabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
addHealLabelMouseClicked(evt);
}
});
blessToggleButton.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
blessToggleButton.setText("祝福術");
blessToggleButton.setToolTipText("使玩家全能力提升,持續30秒,冷卻時間15秒");
blessToggleButton.setEnabled(false);
blessToggleButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
blessToggleButtonActionPerformed(evt);
}
});
blessLevelTextLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
blessLevelTextLabel.setText("Lv.");
blessLevelLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
blessLevelLabel.setText("-");
addBlessLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
addBlessLabel.setText("[+]");
addBlessLabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
addBlessLabelMouseClicked(evt);
}
});
curseToggleButton.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
curseToggleButton.setText("詛咒術");
curseToggleButton.setToolTipText("大幅降低敵人所有能力,冷卻時間40秒");
curseToggleButton.setEnabled(false);
curseToggleButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
curseToggleButtonActionPerformed(evt);
}
});
curseLevelTextLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
curseLevelTextLabel.setText("Lv.");
curseLevelLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
curseLevelLabel.setText("-");
addCurseLabel.setFont(new java.awt.Font("微軟正黑體", 0, 12)); // NOI18N
addCurseLabel.setText("[+]");
addCurseLabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
addCurseLabelMouseClicked(evt);
}
});
javax.swing.GroupLayout skillPanelLayout = new javax.swing.GroupLayout(skillPanel);
skillPanel.setLayout(skillPanelLayout);
skillPanelLayout.setHorizontalGroup(
skillPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(skillPanelLayout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(skillPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(skillPanelLayout.createSequentialGroup()
.addGroup(skillPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(fireToggleButton)
.addGroup(skillPanelLayout.createSequentialGroup()
.addComponent(fireLevelTextLabel)
.addGap(2, 2, 2)
.addComponent(fireLevelLabel))
.addComponent(addFireLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(skillPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(bladeToggleButton)
.addGroup(skillPanelLayout.createSequentialGroup()
.addComponent(bladeLevelTextLabel)
.addGap(2, 2, 2)
.addComponent(bladeLevelLabel))
.addComponent(addBladeLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(skillPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(healToggleButton)
.addGroup(skillPanelLayout.createSequentialGroup()
.addComponent(healLevelTextLabel)
.addGap(2, 2, 2)
.addComponent(healLevelLabel))
.addComponent(addHealLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(skillPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(blessToggleButton)
.addGroup(skillPanelLayout.createSequentialGroup()
.addComponent(blessLevelTextLabel)
.addGap(2, 2, 2)
.addComponent(blessLevelLabel))
.addComponent(addBlessLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(skillPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(curseToggleButton)
.addGroup(skillPanelLayout.createSequentialGroup()
.addComponent(curseLevelTextLabel)
.addGap(2, 2, 2)
.addComponent(curseLevelLabel))
.addComponent(addCurseLabel)))
.addGroup(skillPanelLayout.createSequentialGroup()
.addComponent(skillsTextLabel)
.addGap(45, 45, 45)
.addComponent(skillPointsTextLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(skillPointsLabel)))
.addContainerGap(166, Short.MAX_VALUE))
);
skillPanelLayout.setVerticalGroup(
skillPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(skillPanelLayout.createSequentialGroup()
.addGap(22, 22, 22)
.addGroup(skillPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(skillsTextLabel)
.addComponent(skillPointsTextLabel)
.addComponent(skillPointsLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(skillPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(fireToggleButton, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(bladeToggleButton, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(healToggleButton, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(blessToggleButton, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(curseToggleButton, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(skillPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(fireLevelTextLabel)
.addComponent(fireLevelLabel)
.addComponent(bladeLevelTextLabel)
.addComponent(bladeLevelLabel)
.addComponent(healLevelTextLabel)
.addComponent(healLevelLabel)
.addComponent(blessLevelTextLabel)
.addComponent(blessLevelLabel)
.addComponent(curseLevelTextLabel)
.addComponent(curseLevelLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(skillPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(addFireLabel)
.addComponent(addBladeLabel)
.addComponent(addHealLabel)
.addComponent(addBlessLabel)
.addComponent(addCurseLabel))
.addContainerGap(19, Short.MAX_VALUE))
);
mainPanel.add(skillPanel, java.awt.BorderLayout.SOUTH);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(mainPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(mainPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void addLukLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_addLukLabelMouseClicked
playerService.addPoint(player, "luk", bladeTimer != null ? bladeTimer.isRunning() : false, blessTimer != null ? blessTimer.isRunning() : false);
lukLabel.setText(String.valueOf(player.getLuk()));
pointsLabel.setText(String.valueOf(player.getPoints()));
}//GEN-LAST:event_addLukLabelMouseClicked
private void addDexLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_addDexLabelMouseClicked
playerService.addPoint(player, "dex", bladeTimer != null ? bladeTimer.isRunning() : false, blessTimer != null ? blessTimer.isRunning() : false);
dexLabel.setText(String.valueOf(player.getDex()));
pointsLabel.setText(String.valueOf(player.getPoints()));
}//GEN-LAST:event_addDexLabelMouseClicked
private void addWisLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_addWisLabelMouseClicked
playerService.addPoint(player, "wis", bladeTimer != null ? bladeTimer.isRunning() : false, blessTimer != null ? blessTimer.isRunning() : false);
wisLabel.setText(String.valueOf(player.getWis()));
mpLabel.setText(String.valueOf(player.getMp()));
mpMaxLabel.setText(String.valueOf(player.getMpMax()));
pointsLabel.setText(String.valueOf(player.getPoints()));
}//GEN-LAST:event_addWisLabelMouseClicked
private void addVitLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_addVitLabelMouseClicked
playerService.addPoint(player, "vit", bladeTimer != null ? bladeTimer.isRunning() : false, blessTimer != null ? blessTimer.isRunning() : false);
vitLabel.setText(String.valueOf(player.getVit()));
hpLabel.setText(String.valueOf(player.getHp()));
hpMaxLabel.setText(String.valueOf(player.getHpMax()));
pointsLabel.setText(String.valueOf(player.getPoints()));
}//GEN-LAST:event_addVitLabelMouseClicked
private void addAgiLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_addAgiLabelMouseClicked
playerService.addPoint(player, "agi", bladeTimer != null ? bladeTimer.isRunning() : false, blessTimer != null ? blessTimer.isRunning() : false);
agiLabel.setText(String.valueOf(player.getAgi()));
pointsLabel.setText(String.valueOf(player.getPoints()));
if (playerTimer != null && playerTimer.isRunning()) {
playerTimer.setDelay(battleService.getPlayerAttackRate(player));
}
}//GEN-LAST:event_addAgiLabelMouseClicked
private void addStrLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_addStrLabelMouseClicked
playerService.addPoint(player, "str", bladeTimer != null ? bladeTimer.isRunning() : false, blessTimer != null ? blessTimer.isRunning() : false);
strLabel.setText(String.valueOf(player.getStr()));
pointsLabel.setText(String.valueOf(player.getPoints()));
}//GEN-LAST:event_addStrLabelMouseClicked
private void addCurseLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_addCurseLabelMouseClicked
playerService.addSkill(player, "curse");
if (player.getCurseLevel() == 1) {
curseToggleButton.setEnabled(true);
}
curseLevelLabel.setText(String.valueOf(player.getCurseLevel()));
skillPointsLabel.setText(String.valueOf(player.getSkillPoints()));
}//GEN-LAST:event_addCurseLabelMouseClicked
private void addBlessLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_addBlessLabelMouseClicked
if (blessTimer != null && blessTimer.isRunning()) {
return;
}
playerService.addSkill(player, "bless");
if (player.getBlessLevel() == 1) {
blessToggleButton.setEnabled(true);
}
blessLevelLabel.setText(String.valueOf(player.getBlessLevel()));
skillPointsLabel.setText(String.valueOf(player.getSkillPoints()));
}//GEN-LAST:event_addBlessLabelMouseClicked
private void addHealLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_addHealLabelMouseClicked
playerService.addSkill(player, "heal");
if (player.getHealLevel() == 1) {
healToggleButton.setEnabled(true);
}
healLevelLabel.setText(String.valueOf(player.getHealLevel()));
skillPointsLabel.setText(String.valueOf(player.getSkillPoints()));
}//GEN-LAST:event_addHealLabelMouseClicked
private void addBladeLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_addBladeLabelMouseClicked
if (bladeTimer != null && bladeTimer.isRunning()) {
return;
}
playerService.addSkill(player, "blade");
if (player.getBladeLevel() == 1) {
bladeToggleButton.setEnabled(true);
}
bladeLevelLabel.setText(String.valueOf(player.getBladeLevel()));
skillPointsLabel.setText(String.valueOf(player.getSkillPoints()));
}//GEN-LAST:event_addBladeLabelMouseClicked
private void travelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_travelButtonActionPerformed
if (loadButton.isVisible()) {
int result = JOptionPane.showConfirmDialog(null, Message.LOAD_ALERT[0], Message.LOAD_ALERT[1], JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
System.out.println(result);
if (result != JOptionPane.OK_OPTION) {
return;
}
loadButton.setVisible(false);
}
if (player.getHp() == 0 || (playerTimer != null && playerTimer.isRunning())) {
return;
}
enemy = new Enemy(player.getLevel());
showEnemy();
battleMsg.setText("");
battleMsg.append(Message.MEET_MSG);
playerTimer = new Timer(battleService.getPlayerAttackRate(player), new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int playerDmg = battleService.getPlayerDamage(player, enemy);
battleMsg.append(Message.getPlayerDmgMsg(playerDmg));
if (battleService.playerAttack(enemy, playerDmg)) {
playerTimer.stop();
enemyTimer.stop();
playerService.gainExp(player, enemy);
battleMsg.append(Message.getWinMsg(enemy.getExp()));
}
showPlayer();
showEnemy();
}
});
enemyTimer = new Timer(battleService.getEnemyAttackRate(enemy), new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int enemyDmg = battleService.getEnemyDamage(enemy, player);
battleMsg.append(Message.getEnemyDmgMsg(enemyDmg));
if (battleService.enemyAttack(player, enemyDmg)) {
playerTimer.stop();
enemyTimer.stop();
battleMsg.append(Message.LOSE_MSG);
JOptionPane.showConfirmDialog(null, Message.LOSE_ALERT[0], Message.LOSE_ALERT[1], JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
showPlayer();
showEnemy();
}
});
playerTimer.start();
enemyTimer.start();
}//GEN-LAST:event_travelButtonActionPerformed
private void addFireLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_addFireLabelMouseClicked
playerService.addSkill(player, "fire");
if (player.getFireLevel() == 1) {
fireToggleButton.setEnabled(true);
}
fireLevelLabel.setText(String.valueOf(player.getFireLevel()));
skillPointsLabel.setText(String.valueOf(player.getSkillPoints()));
}//GEN-LAST:event_addFireLabelMouseClicked
private void curseToggleButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_curseToggleButtonActionPerformed
if (enemy == null || enemy.getHp() == 0) {
curseToggleButton.setSelected(false);
battleMsg.append(Message.NOT_AVAILABLE_SKILL);
return;
}
if (player.getMp() < SkillService.CURSE_MP) {
curseToggleButton.setSelected(false);
battleMsg.append(Message.NOT_ENOUGH_MP);
return;
}
curseToggleButton.setEnabled(false);
skillService.useCurse(player, enemy);
showPlayer();
battleMsg.append(Message.CURSE_MSG);
curseToggleButton.setText("冷卻中");
curseCoolDownTimer = new Timer(SkillService.CURSE_COOL_DOWN, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
curseToggleButton.setEnabled(true);
curseToggleButton.setSelected(false);
curseToggleButton.setText("詛咒術");
curseCoolDownTimer.stop();
}
});
curseCoolDownTimer.start();
}//GEN-LAST:event_curseToggleButtonActionPerformed
private void blessToggleButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_blessToggleButtonActionPerformed
if (player.getHp() == 0) {
blessToggleButton.setSelected(false);
battleMsg.append(Message.NOT_AVAILABLE_SKILL);
return;
}
if (player.getMp() < SkillService.BLESS_MP) {
blessToggleButton.setSelected(false);
battleMsg.append(Message.NOT_ENOUGH_MP);
return;
}
blessToggleButton.setEnabled(false);
skillService.enableBless(player);
showPlayer();
battleMsg.append(Message.BLESS_ENABLE_MSG);
blessTimer = new Timer(SkillService.BLESS_TIME, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
skillService.disableBless(player);
blessTimer.stop();
blessCoolDown();
}
});
blessTimer.start();
}//GEN-LAST:event_blessToggleButtonActionPerformed
private void blessCoolDown() {
blessToggleButton.setText("冷卻中");
battleMsg.append(Message.BLESS_DISABLE_MSG);
blessCoolDownTimer = new Timer(SkillService.BLESS_COOL_DOWN, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
blessToggleButton.setEnabled(true);
blessToggleButton.setSelected(false);
blessToggleButton.setText("祝福術");
blessCoolDownTimer.stop();
}
});
blessCoolDownTimer.start();
}
private void healToggleButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_healToggleButtonActionPerformed
if (player.getHp() == 0 || player.getHp() == player.getHpMax()) {
healToggleButton.setSelected(false);
battleMsg.append(Message.NOT_AVAILABLE_SKILL);
return;
}
if (player.getMp() < SkillService.HEAL_MP) {
healToggleButton.setSelected(false);
battleMsg.append(Message.NOT_ENOUGH_MP);
return;
}
healToggleButton.setEnabled(false);
battleMsg.append(Message.getHealMsg(skillService.useHeal(player)));
showPlayer();
healToggleButton.setText("冷卻中");
healCoolDownTimer = new Timer(SkillService.HEAL_COOL_DOWN, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
healToggleButton.setEnabled(true);
healToggleButton.setSelected(false);
healToggleButton.setText("治癒術");
healCoolDownTimer.stop();
}
});
healCoolDownTimer.start();
}//GEN-LAST:event_healToggleButtonActionPerformed
private void bladeToggleButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bladeToggleButtonActionPerformed
if (player.getHp() == 0) {
bladeToggleButton.setSelected(false);
battleMsg.append(Message.NOT_AVAILABLE_SKILL);
return;
}
if (player.getMp() < SkillService.BLADE_MP) {
bladeToggleButton.setSelected(false);
battleMsg.append(Message.NOT_ENOUGH_MP);
return;
}
bladeToggleButton.setEnabled(false);
skillService.enableBlade(player);
showPlayer();
battleMsg.append(Message.BLADE_ENABLE_MSG);
bladeTimer = new Timer(SkillService.BLADE_TIME, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
skillService.disableBlade(player);
bladeTimer.stop();
bladeCoolDown();
}
});
bladeTimer.start();
}//GEN-LAST:event_bladeToggleButtonActionPerformed
private void bladeCoolDown() {
bladeToggleButton.setText("冷卻中");
battleMsg.append(Message.BLADE_DISABLE_MSG);
bladeCoolDownTimer = new Timer(SkillService.BLADE_COOL_DOWN, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
bladeToggleButton.setEnabled(true);
bladeToggleButton.setSelected(false);
bladeToggleButton.setText("魔力劍");
bladeCoolDownTimer.stop();
}
});
bladeCoolDownTimer.start();
}
private void fireToggleButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fireToggleButtonActionPerformed
if (enemy == null || enemy.getHp() == 0 || player.getHp() == 0) {
fireToggleButton.setSelected(false);
battleMsg.append(Message.NOT_AVAILABLE_SKILL);
return;
}
if (player.getMp() < SkillService.FIRE_MP) {
fireToggleButton.setSelected(false);
battleMsg.append(Message.NOT_ENOUGH_MP);
return;
}
fireToggleButton.setEnabled(false);
battleMsg.append(Message.getFireDmgMsg(skillService.useFire(player, enemy)));
if (enemy.getHp() == 0) {
playerTimer.stop();
enemyTimer.stop();
playerService.gainExp(player, enemy);
battleMsg.append(Message.getWinMsg(enemy.getExp()));
}
showPlayer();
showEnemy();
fireToggleButton.setText("冷卻中");
fireCoolDownTimer = new Timer(SkillService.FIRE_COOL_DOWN, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
fireToggleButton.setEnabled(true);
fireToggleButton.setSelected(false);
fireToggleButton.setText("火球術");
fireCoolDownTimer.stop();
}
});
fireCoolDownTimer.start();
}//GEN-LAST:event_fireToggleButtonActionPerformed
private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
if (playerTimer != null && playerTimer.isRunning()) {
battleMsg.append(Message.NOT_AVAILABLE_SAVE);
return;
}
playerService.savePlayer(player);
battleMsg.append(Message.SAVE_SUCCESS);
}//GEN-LAST:event_saveButtonActionPerformed
private void loadButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadButtonActionPerformed
Player loadPlayer = playerService.loadPlayer();
if (loadPlayer != null) {
player = playerService.loadPlayer();
skillService.calculateMp(player);
showPlayer();
showSkills();
battleMsg.append(Message.LOAD_SUCCESS);
loadButton.setVisible(false);
} else {
battleMsg.append(Message.LOAD_FAIL);
}
}//GEN-LAST:event_loadButtonActionPerformed
private void battleMsgKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_battleMsgKeyReleased
int key = evt.getKeyCode();
if (key == KeyEvent.VK_P) {
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
try {
System.out.println(ow.writeValueAsString(player));
} catch (JsonProcessingException ex) {
Logger.getLogger(NewGeimuUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (key == KeyEvent.VK_G) {
player.setExp(player.getExp() + 10000);
showPlayer();
}
}//GEN-LAST:event_battleMsgKeyReleased
private void showPlayer() {
levelLabel.setText(String.valueOf(player.getLevel()));
hpLabel.setText(String.valueOf(player.getHp()));
hpMaxLabel.setText(String.valueOf(player.getHpMax()));
mpLabel.setText(String.valueOf(player.getMp()));
mpMaxLabel.setText(String.valueOf(player.getMpMax()));
expLabel.setText(String.valueOf(player.getExp()));
expMaxLabel.setText(String.valueOf(player.getExpMax()));
expProgressBar.setMaximum(player.getExpMax());
expProgressBar.setValue(player.getExp());
expProgressBar.setToolTipText(Math.round((double) player.getExp() / (double) player.getExpMax() * 10000.0) / 100.0 + "%");
strLabel.setText(String.valueOf(player.getStr()));
agiLabel.setText(String.valueOf(player.getAgi()));
vitLabel.setText(String.valueOf(player.getVit()));
wisLabel.setText(String.valueOf(player.getWis()));
dexLabel.setText(String.valueOf(player.getDex()));
lukLabel.setText(String.valueOf(player.getLuk()));
pointsLabel.setText(String.valueOf(player.getPoints()));
skillPointsLabel.setText(String.valueOf(player.getSkillPoints()));
fireLevelLabel.setText(String.valueOf(player.getFireLevel()));
bladeLevelLabel.setText(String.valueOf(player.getBladeLevel()));
healLevelLabel.setText(String.valueOf(player.getHealLevel()));
blessLevelLabel.setText(String.valueOf(player.getBlessLevel()));
curseLevelLabel.setText(String.valueOf(player.getCurseLevel()));
}
private void showEnemy() {
monLevelLabel.setText(String.valueOf(enemy.getLevel()));
monHpLabel.setText(String.valueOf(enemy.getHp()));
monHpMaxLabel.setText(String.valueOf(enemy.getHpMax()));
}
private void showSkills() {
fireToggleButton.setEnabled(player.getFireLevel() > 0);
bladeToggleButton.setEnabled(player.getBladeLevel() > 0);
healToggleButton.setEnabled(player.getHealLevel() > 0);
blessToggleButton.setEnabled(player.getBlessLevel() > 0);
curseToggleButton.setEnabled(player.getCurseLevel() > 0);
}
private void setMpRecoverTimer() {
mpRecoverTimer = new Timer(10000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
playerService.recoverMp(player);
showPlayer();
}
});
mpRecoverTimer.start();
}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewGeimuUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new NewGeimuUI().setVisible(true);
}
});
}
private void initGeimu() {
showPlayer();
setMpRecoverTimer();
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel addAgiLabel;
private javax.swing.JLabel addBladeLabel;
private javax.swing.JLabel addBlessLabel;
private javax.swing.JLabel addCurseLabel;
private javax.swing.JLabel addDexLabel;
private javax.swing.JLabel addFireLabel;
private javax.swing.JLabel addHealLabel;
private javax.swing.JLabel addLukLabel;
private javax.swing.JLabel addStrLabel;
private javax.swing.JLabel addVitLabel;
private javax.swing.JLabel addWisLabel;
private javax.swing.JLabel agiLabel;
private javax.swing.JLabel agiTextLabel;
private javax.swing.JScrollPane ballteMsgScrollPane;
private javax.swing.JTextArea battleMsg;
private javax.swing.JPanel battleMsgPanel;
private javax.swing.JLabel bladeLevelLabel;
private javax.swing.JLabel bladeLevelTextLabel;
private javax.swing.JToggleButton bladeToggleButton;
private javax.swing.JLabel blessLevelLabel;
private javax.swing.JLabel blessLevelTextLabel;
private javax.swing.JToggleButton blessToggleButton;
private javax.swing.JLabel curseLevelLabel;
private javax.swing.JLabel curseLevelTextLabel;
private javax.swing.JToggleButton curseToggleButton;
private javax.swing.JLabel dexLabel;
private javax.swing.JLabel dexTextLabel;
private javax.swing.JPanel enemyPanel;
private javax.swing.JLabel expLabel;
private javax.swing.JLabel expMaxLabel;
private javax.swing.JProgressBar expProgressBar;
private javax.swing.JLabel expSplitTextLabel;
private javax.swing.JLabel expTextLabel;
private javax.swing.JLabel fireLevelLabel;
private javax.swing.JLabel fireLevelTextLabel;
private javax.swing.JToggleButton fireToggleButton;
private javax.swing.JLabel healLevelLabel;
private javax.swing.JLabel healLevelTextLabel;
private javax.swing.JToggleButton healToggleButton;
private javax.swing.JLabel hpLabel;
private javax.swing.JLabel hpMaxLabel;
private javax.swing.JLabel hpSplitTextLabel;
private javax.swing.JLabel hpTextLabel;
private javax.swing.JLabel levelLabel;
private javax.swing.JLabel levelTextLabel;
private javax.swing.JButton loadButton;
private javax.swing.JLabel lukLabel;
private javax.swing.JLabel lukTextLabel;
private javax.swing.JPanel mainPanel;
private javax.swing.JLabel monHpLabel;
private javax.swing.JLabel monHpMaxLabel;
private javax.swing.JLabel monHpSplitTextLabel;
private javax.swing.JLabel monHpTextLabel;
private javax.swing.JLabel monLevelLabel;
private javax.swing.JLabel monLevelTextLabel;
private javax.swing.JLabel monNameTextLabel;
private javax.swing.JLabel mpLabel;
private javax.swing.JLabel mpMaxLabel;
private javax.swing.JLabel mpSplitTextLabel;
private javax.swing.JLabel mpTextLabel;
private javax.swing.JPanel playerPanel;
private javax.swing.JLabel playerTextLabel;
private javax.swing.JLabel pointsLabel;
private javax.swing.JLabel pointsTextLabel;
private javax.swing.JButton saveButton;
private javax.swing.JPanel skillPanel;
private javax.swing.JLabel skillPointsLabel;
private javax.swing.JLabel skillPointsTextLabel;
private javax.swing.JLabel skillsTextLabel;
private javax.swing.JPanel statusPanel;
private javax.swing.JLabel statusTextLabel;
private javax.swing.JLabel strLabel;
private javax.swing.JLabel strTextLabel;
private javax.swing.JButton travelButton;
private javax.swing.JLabel vitLabel;
private javax.swing.JLabel vitTextLabel;
private javax.swing.JLabel wisLabel;
private javax.swing.JLabel wisTextLabel;
// End of variables declaration//GEN-END:variables
}
|
package com.dx.decorater;
/**
* Created by dx on 2017/3/30.
* 抽象装饰角色,
*/
public abstract class GirlDecorator extends Girl {
public abstract String getDescription();
}
|
class NewSkeleton
{
public static void main(String args[])
{
System.out.println("New MakeFile !");
}
}
|
package com.prolific.vidmediaplayer.BroadcastReceiversForVideo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.prolific.vidmediaplayer.Activities.VideoPlayerActivity;
import com.prolific.vidmediaplayer.Activities.MainActivity;
import com.prolific.vidmediaplayer.Services.BackgroundPlay;
public class NotificationClickBroadcast extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
MainActivity.isStartedFromNotificationCLick = true;
VideoPlayerActivity.mVideoPath = BackgroundPlay.songPath;
Intent intent2 = new Intent(context, VideoPlayerActivity.class);
intent2.putExtra("path",intent.getStringExtra("path"));
intent2.putExtra("name", intent.getStringExtra("name"));
intent2.putExtra("position", intent.getIntExtra("position", 0));
intent2.putExtra("seekPosition", intent.getIntExtra("seekPosition", 0));
if (VideoPlayerActivity.mWhereFrom == 2) {
intent2.putExtra("bucketName", intent.getStringExtra("bucketName"));
}
intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent2);
}
}
|
package com.school.sms.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.school.sms.dao.ReportDao;
import com.school.sms.model.ExtraMailRecipient;
import com.school.sms.model.SendCustomSMS;
import com.school.sms.model.Student;
import com.school.sms.model.StudentFeeDetails;
import com.school.sms.service.ReportService;
@Service("reportService")
public class ReportServiceImpl implements ReportService{
@Resource(name = "reportDaoService")
private ReportDao reportDao;
@Override
public List<StudentFeeDetails> loadStudentFixedFeeDetailsList() {
return reportDao.loadStudentFixedFeeDetailsList();
}
@Override
public Student loadStudent(String enrolementNo) {
// TODO Auto-generated method stub
return reportDao.loadStudent(enrolementNo);
}
@Override
public void updateExtraMailRecipient(ExtraMailRecipient extraMailRecipient) {
reportDao.updateExtraMailRecipient(extraMailRecipient);
}
@Override
public void deleteExtraMailRecipient(ExtraMailRecipient extraMailRecipient) {
reportDao.deleteExtraMailRecipient(extraMailRecipient);
}
@Override
public List<ExtraMailRecipient> loadExtraMailRecipients() {
return reportDao.loadExtraMailRecipients();
}
@Override
public void sendCustomSMS(SendCustomSMS sendCustomSMS) {
reportDao.sendCustomSMS(sendCustomSMS);
}
@Override
public List<SendCustomSMS> loadSentMessages() {
return reportDao.loadSentMessages();
}
}
|
package kz.greetgo.file_storage.impl;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;
import kz.greetgo.file_storage.errors.FileIdAlreadyExists;
import kz.greetgo.file_storage.errors.NoFileWithId;
import kz.greetgo.file_storage.errors.Ora00972_IdentifierIsTooLong;
import kz.greetgo.file_storage.impl.jdbc.Inserting;
import kz.greetgo.file_storage.impl.jdbc.Merging;
import kz.greetgo.file_storage.impl.jdbc.Query;
import static kz.greetgo.file_storage.impl.IdGeneratorType.STR13;
public class MonoDbOperationsOracle extends MonoDbOperationsPostgres {
MonoDbOperationsOracle(FileStorageBuilderMonoDbImpl builder) {
super(builder);
if (builder.paramsTable.length() > 30) {
throw new Ora00972_IdentifierIsTooLong("builder.paramsTable = '"
+ builder.paramsTable + "' is too long. Specify at most 30 characters.");
}
if (builder.dataTable.length() > 30) {
throw new Ora00972_IdentifierIsTooLong("builder.dataTable = '"
+ builder.dataTable + "' is too long. Specify at most 30 characters.");
}
if (builder.paramsTableMimeType.length() > 30) {
throw new Ora00972_IdentifierIsTooLong(
"builder.paramsTableMimeType = '" + builder.paramsTableMimeType + "' is too long. Specify at most 30 characters.");
}
}
@Override
public String createNew(byte[] data, CreateNewParams params) throws DatabaseNotPrepared {
try {
return createNewEx(data, params);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
private String createNewEx(byte[] data, CreateNewParams params) throws SQLException {
String sha1sum = sha1sum(data);
try (Connection connection = builder.dataSource.getConnection()) {
connection.setAutoCommit(false);
try {
try {
StringBuilder sql = new StringBuilder();
// structure.append("merge into __dataTable__ dest using ( select ? as id1, ? as data1 from dual ) src ");
// structure.append(" on (dest.__dataTableId__ = src.id1 and dest.__dataTableData__ = src.data1)");
// structure.append(" when not matched then insert (dest.__dataTableId__, dest.__dataTableData__)");
// structure.append(" values ( src.id1, src.data1 )");
sql.append("insert into __dataTable__ (__dataTableId__, __dataTableData__)");
sql.append(" values (?, ?)");
try (Query query = new Query(connection)) {
query.sql.append(sql(sql.toString()));
query.params.add(sha1sum);
query.params.add(data);
query.update();
}
} catch (Exception e) {
String trimmedMessage = e.getMessage() == null ? "" : e.getMessage().trim();
if (trimmedMessage.startsWith("ORA-00942:")) {
throw new DatabaseNotPrepared();
}
boolean throwError = true;
if (trimmedMessage.startsWith("ORA-00001:")) {
throwError = false;
}
if (throwError) {
if (e instanceof SQLException) {
throw (SQLException) e;
}
//noinspection ConstantConditions
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new RuntimeException(e);
}
}
String id = params.presetFileId != null ? params.presetFileId : builder.parent.idGenerator(STR13).get();
try {
Inserting.with(connection)
.sqlPreparation(this::sql)
.into("__paramsTable__")
.field("__paramsTableId__", id)
.field("__paramsTableName__", params.name)
.field("__paramsTableMimeType__", params.mimeType)
.field("__paramsTableDataId__", sha1sum)
.fieldTimestamp("__paramsTableLastModifiedAt__", params.createdAt, true)
.go()
;
} catch (SQLException e) {
String trimmedMessage = e.getMessage() == null ? "" : e.getMessage().trim();
if (trimmedMessage.startsWith("ORA-00001:")) {
throw new FileIdAlreadyExists(id);
}
throw e;
}
if (params.param != null) {
params.param.forEach((key, value) -> {
try {
Inserting.with(connection)
.sqlPreparation(this::sql)
.into("__fileParameterTable__")
.field("__fileParameterId__", id)
.field("__fileParameterName__", key)
.field("__fileParameterValue__", value)
.go()
;
} catch (SQLException e) {
String trimmedMessage = e.getMessage() == null ? "" : e.getMessage().trim();
if (trimmedMessage.startsWith("ORA-00001:")) {
throw new FileIdAlreadyExists(id);
}
throw new RuntimeException(e);
}
});
}
connection.commit();
return id;
} catch (SQLException | RuntimeException e) {
connection.rollback();
throw e;
} finally {
connection.setAutoCommit(true);
}
}
}
@Override
public void prepareDatabase(DatabaseNotPrepared context) {
try {
prepareDatabaseEx(context);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public void updateParam(String fileId, Map<String, String> param) {
try (Connection connection = builder.dataSource.getConnection()) {
for( Map.Entry<String, String> entry : param.entrySet()){
Merging.MergingInto mergingInto = Merging.with(connection).sqlPreparation(this::sql)
.into("__fileParameterTable__")
.onConflict("__fileParameterId__")
.onConflict("__fileParameterName__");
if(entry.getKey() != null){
mergingInto
.field("__fileParameterId__", fileId)
.field("__fileParameterName__", entry.getKey())
.field("__fileParameterValue__", entry.getValue());
if(entry.getValue() == null) {
deleteExParamByName(fileId, entry.getKey());
continue;
}
mergingInto.update(entry.getKey(), entry.getValue(), builder.fileParameterValue);
}
mergingInto.go();
}
} catch (SQLException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
private void prepareDatabaseEx(@SuppressWarnings("unused") DatabaseNotPrepared context) throws SQLException {
int idLen = builder.parent.fileIdLength;
try (Connection connection = builder.dataSource.getConnection()) {
try (Query query = new Query(connection)) {
query.exec(sql("create table __dataTable__ (" +
" __dataTableId__ varchar2(40) not null primary key" +
", __dataTableData__ blob" +
")"));
query.exec(sql("create table __paramsTable__ (" +
" __paramsTableId__ varchar2(" + idLen + ") not null primary key" +
", __paramsTableName__ varchar2(" + builder.paramsTableNameLength + ")" +
", __paramsTableMimeType__ varchar2(" + builder.paramsTableMimeTypeLength + ")" +
", __paramsTableDataId__ varchar2(40) not null references __dataTable__" +
", __paramsTableLastModifiedAt__ timestamp default systimestamp not null" +
")"));
query.exec(sql("create table __fileParameterTable__ (" +
" __fileParameterId__ varchar2(255)" +
", __fileParameterName__ varchar2(255)" +
", __fileParameterValue__ varchar2(255)" +
", PRIMARY KEY ( __fileParameterId__ , __fileParameterName__) " +
")"));
}
}
}
@Override
protected String loadSha1SumSql() {
return "select __paramsTableDataId__ from __paramsTable__ where __paramsTableId__ = ?";
}
protected void deleteEx(String fileId) throws SQLException, NoFileWithId {
try (Connection connection = builder.dataSource.getConnection()) {
String sha1sum = loadSha1sumByFileId(connection, fileId);
doDelete(connection, "delete from __paramsTable__ where __paramsTableId__ = ?", fileId, fileId, true);
doDelete(connection, "delete from __dataTable__ where __dataTableId__ = ?", sha1sum, fileId, true);
}
}
}
|
/*
Copyright (C) 2013-2014, Securifera, Inc
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Securifera, Inc nor the names of its contributors may be
used to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
================================================================================
Pwnbrew is provided under the 3-clause BSD license above.
The copyright on this package is held by Securifera, Inc
*/
/*
* XmlHandler.java
*
* Created on June 21, 2013, 9:21:32 PM
*/
package pwnbrew.xml;
import pwnbrew.exception.XmlObjectCreationException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import pwnbrew.log.Log;
import pwnbrew.log.LoggableException;
/**
*
*/
@SuppressWarnings("ucd")
public class XmlHandler extends DefaultHandler {
private static final String NAME_Class = XmlHandler.class.getSimpleName();
private boolean skipTheElement = false;
private ArrayList<XmlObject> theObjectStack = new ArrayList<>();
private XmlObject theXmlObject = null;
private String errorMessage = null;
private Locator theLocator = null;
// ==========================================================================
/**
* Constructor
*/
public XmlHandler() {
}
// ==========================================================================
/**
* Creates a new instance of {@link XmlHandler}.
*/
XmlHandler( boolean headerOnly ) {
}
// ==========================================================================
/**
* Returns the finished {@link XmlObject}.
*
* @return the finished {@code XmlObject}
*/
public XmlObject getFinishedXmlObject() {
XmlObject rtnXB = null;
if( theObjectStack.isEmpty() == false )
rtnXB = theObjectStack.get( 0 );
theObjectStack = null; //Null the reference
return rtnXB;
}
// ==========================================================================
/**
*
* @param uri
* @param atts
* @param localName
* @param qName
*/
@Override
public void startElement( String uri, String localName, String qName, Attributes atts ) {
try {
try {
theXmlObject = (XmlObject) XmlObjectFactory.instantiateClassByName( localName ); //Get a new instance of the appropriate Class
} catch (IllegalAccessException | InstantiationException ex) {
throw new LoggableException(ex);
}
} catch( LoggableException ex ) {
StringBuilder strBld = new StringBuilder( "Could not instantiate the class \"" );
strBld.append( localName ).append( "\"." );
if( theObjectStack.isEmpty() == false ) { //If there are no objects on the stack...
strBld.append( "\n" );
strBld.append( " The object stack:" );
String id;
for( XmlObject xb : theObjectStack ) { //For each XmlObject on the stack...
strBld.append( "\n" );
strBld.append( " Class: \"" ).append( xb.getClass().getSimpleName() ).append( " Id: " );
id = xb.getId(); //Get the XmlObject's id
if( id.isEmpty() ) //If the id is an empty String...
strBld.append( "<empty>" );
else //If the id is not an empty String...
strBld.append( "\"" ).append( id ).append( "\"" );
}
}
Log.log( Level.WARNING, NAME_Class, "startElement()", strBld.toString(), null );
}
if( theXmlObject == null )
throw new XmlObjectCreationException("Invalid XmlObject class '" + localName + "'");
else if( theXmlObject instanceof FileContent){
skipTheElement = true;
return;
}
//Populate the object's data fields...
for( int i = 0; i < atts.getLength(); i++ ) { //For each attribute...
theXmlObject.setProperty( atts.getQName( i ), atts.getValue( i ) ); //Set the XmlObject's attribute
}
theObjectStack.add( theXmlObject );
theXmlObject = null;
}
// ==========================================================================
/**
*
* @param uri
* @param qName
* @param localName
*/
@Override
public void endElement( String uri, String localName, String qName ) {
if( skipTheElement == false ) { //If the element is not being skipped...
int stackSize = theObjectStack.size(); //Get the number of objects on the stack
if( stackSize > 1 ) { //If there are at least two objects on the stack...
//Remove (pop) the last object from the stack and add it as a component to the next-to-last object
( theObjectStack.get( stackSize - 2 ) ).addChildObject( theObjectStack.remove( stackSize - 1 ) );
} else if( stackSize == 1 ) { //If there is only one object on the stack...
theObjectStack.trimToSize(); //Remove any unused space
} else { //If there are no objects on the stack...
///////////////////////
// Possible???
///////////////////////
}
} else
skipTheElement = false;
}
// ==========================================================================
/**
*
* @return
*/
public String getErrorMessage() {
return errorMessage;
}
// ==========================================================================
/**
*
* @param name
*/
@Override
public void skippedEntity( String name ) {
}
// ==========================================================================
/**
*
* @param target
* @param data
*/
@Override
public void processingInstruction( String target, String data ) {
}
// ==========================================================================
/**
*
* @param ch
* @param length
* @param start
*/
@Override
public void ignorableWhitespace( char[] ch, int start, int length ) {
}
// ==========================================================================
/**
*
* @param prefix
*/
@Override
public void endPrefixMapping( String prefix ) {
}
// ==========================================================================
/**
*
* @param prefix
* @param uri
*/
@Override
public void startPrefixMapping( String prefix, String uri ) {
}
// ==========================================================================
/**
*
*/
@Override
public void endDocument() {
}
// ==========================================================================
/**
*
*/
@Override
public void startDocument() {
}
// ==========================================================================
/**
*
* @return
*/
public Locator getDocumentLocator() {
return theLocator;
}
// ==========================================================================
/**
*
* @param locator
*/
@Override
public void setDocumentLocator( Locator locator ) {
theLocator = locator;
}
/**
* Report a fatal XML parsing error.
*
* <p>The default implementation throws a SAXParseException.
* Application writers may override this method in a subclass if
* they need to take specific actions for each fatal error (such as
* collecting all of the errors into a single report): in any case,
* the application must stop all regular processing when this
* method is invoked, since the document is no longer reliable, and
* the parser may no longer report parsing events.</p>
*
* @param e The error information encoded as an exception.
* @exception org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ErrorHandler#fatalError
* @see org.xml.sax.SAXParseException
*/
@Override
public void fatalError (SAXParseException e) throws SAXException {
errorMessage = e.getMessage();
throw e;
}
/**
* Receive notification of a recoverable parser error.
*
* <p>The default implementation does nothing. Application writers
* may override this method in a subclass to take specific actions
* for each error, such as inserting the message in a log file or
* printing it to the console.</p>
*
* @param e The error information encoded as an exception.
* @exception org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ErrorHandler#warning
* @see org.xml.sax.SAXParseException
*/
@Override
public void error (SAXParseException e) throws SAXException {
errorMessage = e.getMessage();
}
/**
* Resolve an external entity.
*
* <p>Always return null, so that the parser will use the system
* identifier provided in the XML document. This method implements
* the SAX default behaviour: application writers can override it
* in a subclass to do special translations such as catalog lookups
* or URI redirection.</p>
*
* @param publicId The public identifier, or null if none is
* available.
* @param systemId The system identifier provided in the XML
* document.
* @return The new input source, or null to require the
* default behaviour.
* @exception java.io.IOException If there is an error setting
* up the new input source.
* @exception org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.EntityResolver#resolveEntity
*/
@Override
public InputSource resolveEntity (String publicId, String systemId) throws IOException, SAXException {
return null;
}
}
|
package GuiServer;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
import GuiServerSelection.MainFrameServerSelection;
public class MainFrameServerGUI {
private JFrame mainFrame = new JFrame();
private PanelForConsolePrinter panelForConsolePrinter=null;
private PanelForServerControl panelForServerControl=null;
private MainFrameServerSelection serverSelectionGUI=null;
private ValidationDialogGUI val=null;
private String title=null;
private ShutDownServerProtocol shutDown = null;
public MainFrameServerGUI(MainFrameServerSelection serverSelectionGUI,ShutDownServerProtocol shutDown,String title){
this.shutDown=shutDown;
this.title=title;
this.serverSelectionGUI=serverSelectionGUI;
startServerWindowGUI(title);
this.val= new ValidationDialogGUI(mainFrame);
addpanelForConsolePrinterToMainFrame();
addpanelForServerControlToMainFrame();
}
private void startServerWindowGUI(String title){
try{
this.mainFrame = new JFrame();
mainFrame.setTitle(title);
mainFrame.setVisible(false);
mainFrame.setSize(425, 550);
mainFrame.setLayout(null);
mainFrame.setLocationRelativeTo(null);
mainFrame.setResizable(false);
mainFrame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
mainFrame.setLocation(10, 10);
mainFrameCloseListener();
}catch(Exception ex){
ex.printStackTrace();
}
}
private void addpanelForServerControlToMainFrame(){
this.panelForServerControl = new PanelForServerControl(this,serverSelectionGUI, shutDown,"Server Control");
mainFrame.add(panelForServerControl.getJPanel()).setBounds(5, 5, 410, 75);
}
private void addpanelForConsolePrinterToMainFrame(){
this.panelForConsolePrinter = new PanelForConsolePrinter();
mainFrame.add(panelForConsolePrinter.getJPanel()).setBounds(5, 85, 410, 435);
}
private void mainFrameCloseListener(){
mainFrame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
boolean close=val.dynamicConfirmationDialog("Closing down "+title, "Are you sure that you want to close "+title+"?");
if(close == true){
mainFrame.dispose();
serverSelectionGUI.showMainFrame();
}
}
});
}
public void clearConsolePrinter(){
panelForConsolePrinter.clearConsolePrinter();
}
public void showMainFrameServerGUI(){
this.mainFrame.setVisible(true);
}
public void disposeMainFrameServerGUI(){
this.mainFrame.dispose();;
}
}
|
package com.atakan.app.menu.views;
import java.awt.Color;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import com.atakan.app.auth.model.User;
import com.atakan.app.converter.Convert;
import com.atakan.app.service.CartService;
import com.atakan.app.service.TshirtService;
import com.atakan.app.store.model.CartItems;
import com.atakan.app.store.model.Colors;
import com.atakan.app.store.model.GridTshirt;
import com.atakan.app.store.model.Sizes;
import com.atakan.app.store.model.Tshirt;
import com.atakan.app.store.model.TshirtColors;
import com.atakan.app.store.model.TshirtFilter;
import com.atakan.app.store.model.TshirtSizes;
import com.vaadin.addon.pagination.Pagination;
import com.vaadin.addon.pagination.PaginationResource;
import com.vaadin.annotations.StyleSheet;
import com.vaadin.data.provider.DataProvider;
import com.vaadin.data.provider.ListDataProvider;
import com.vaadin.icons.VaadinIcons;
import com.vaadin.navigator.View;
import com.vaadin.server.Page;
import com.vaadin.server.VaadinSession;
import com.vaadin.shared.Position;
import com.vaadin.shared.ui.ContentMode;
import com.vaadin.spring.annotation.SpringView;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.Component;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Image;
import com.vaadin.ui.Label;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Panel;
import com.vaadin.ui.RadioButtonGroup;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
import com.vaadin.ui.themes.ValoTheme;
@SpringView(name = StoreView.VIEW_NAME)
@StyleSheet("vaadin://css/store-view.css")
public class StoreView extends VerticalLayout implements View{
public static final String VIEW_NAME = "store";
public static int fillDbCount = 0 ;
@Autowired
private TshirtService tshirtService;
@Autowired
private Convert convert;
@Autowired
private CartService cartService;
private Label title;
private ComboBox<TshirtFilter> sortTshirts;
private Button filterButton;
private GridLayout mainGrid;
private List<Tshirt> allTshirts;
private List<Tshirt> filteredTshirts;
private List<GridTshirt> gridTshirts;
private List<Panel> tshirtCards;
private Panel mainContent;
private List<Colors> selectedColors;
private List<Sizes> selectedSizes;
private Window filterWindow;
private Button resetFilters;
private boolean filtered;
public StoreView()
{
checkAuth();
setSizeFull();
setMargin(true);
UI.getCurrent().getPage().setTitle("TshirtShop - Store");
allTshirts = new ArrayList<Tshirt>();
title = new Label("Store");
sortTshirts = new ComboBox<>();
filterButton = new Button("Filters");
filterButton.addStyleName("filter-button");
mainGrid = new GridLayout(4,1);
mainGrid.setSpacing(true);
gridTshirts = new ArrayList<>();
selectedColors = new ArrayList<Colors>();
selectedSizes = new ArrayList<>();
filteredTshirts = new ArrayList<>();
tshirtCards = new ArrayList<Panel>();
resetFilters = new Button("Reset Filters");
mainContent = new Panel();
mainContent.setWidth("100%");
mainContent.setHeight("900px");
VerticalLayout mainVL = new VerticalLayout();
mainVL.setSizeUndefined();
mainVL.addComponents(mainGrid);
mainContent.setContent(mainVL);
initComponents();
HorizontalLayout topMenu = new HorizontalLayout();
topMenu.setWidth("1200px");
topMenu.addComponents(filterButton,resetFilters,sortTshirts);
topMenu.setComponentAlignment(sortTshirts, Alignment.TOP_RIGHT);
resetFilters.setEnabled(false);
addComponents(topMenu,mainContent);
}
private void checkAuth() {
if(VaadinSession.getCurrent().getAttribute("user") == null ) {
UI.getCurrent().getPage().setLocation("/login");
}
}
private void initComponents() {
title.addStyleNames(ValoTheme.LABEL_BOLD,ValoTheme.LABEL_H1);
ListDataProvider<TshirtFilter> comboProvider = DataProvider.ofCollection(Arrays.asList(TshirtFilter.values()));
sortTshirts.setDataProvider(comboProvider);
sortTshirts.setEmptySelectionAllowed(false);
sortTshirts.setCaption("Sort");
filterButton.addStyleName(ValoTheme.BUTTON_PRIMARY);
resetFilters.addStyleName(ValoTheme.BUTTON_DANGER);
mainContent.addStyleName(ValoTheme.PANEL_BORDERLESS);
}
@PostConstruct
private void getTshirts() {
allTshirts = tshirtService.getAll();
Panel tshirtCard = new Panel();
for (Tshirt tshirt : allTshirts) {
GridTshirt gridTshirt = new GridTshirt();
gridTshirt.setId(tshirt.getId());
gridTshirt.setName(tshirt.getName());
gridTshirt.setPrice(tshirt.getPrice());
gridTshirt.setImage(convert.bytesToResource(tshirt.getImage()));
if(gridTshirt != null)
{
tshirtCard = getTshirtCard(gridTshirt);
tshirtCards.add(tshirtCard);
mainGrid.addComponent(tshirtCard);
}
}
filterButton.addClickListener(e -> setFilters());
resetFilters.addClickListener(e -> resetFilters());
}
private void resetFilters() {
mainGrid.removeAllComponents();
for(Panel p : tshirtCards) {
mainGrid.addComponent(p);
}
resetFilters.setEnabled(false);
}
private void setFilters() {
filterWindow = new Window("Filters");
VerticalLayout main = new VerticalLayout();
HorizontalLayout layout = new HorizontalLayout();
VerticalLayout colors = new VerticalLayout();
VerticalLayout sizes = new VerticalLayout();
Button apply = new Button("Apply");
apply.addStyleName(ValoTheme.BUTTON_FRIENDLY);
apply.setWidth("200px");
colors.setCaption("Colors");
sizes.setCaption("Sizes");
colors.setWidth("300px");
sizes.setWidth("300px");
Label hr = new Label("<hr width=\"1\" size=\"500\">");
hr.setContentMode(ContentMode.HTML);
layout.addComponents(colors,hr,sizes);
layout.setComponentAlignment(colors, Alignment.TOP_CENTER);
layout.setComponentAlignment(sizes, Alignment.TOP_CENTER);
main.addComponents(layout,apply);
main.setComponentAlignment(apply, Alignment.MIDDLE_CENTER);
for (Colors color : Colors.values()) {
CheckBox checkBox = new CheckBox(color.name());
colors.addComponent(checkBox);
checkBox.addValueChangeListener(e-> {
if(e.getValue() == true) {
selectedColors.add(Colors.valueOf(e.getComponent().getCaption()));
}
else {
selectedColors.remove(Colors.valueOf(e.getComponent().getCaption()));
}
});
}
for (Sizes size : Sizes.values()) {
CheckBox checkBox = new CheckBox(size.name());
sizes.addComponent(checkBox);
checkBox.addValueChangeListener(e-> {
if(e.getValue() == true) {
selectedSizes.add(Sizes.valueOf(e.getComponent().getCaption()));
}
else {
selectedSizes.remove(Sizes.valueOf(e.getComponent().getCaption()));
}
});
}
filterWindow.setContent(main);
filterWindow.center();
filterWindow.setHeight("650px");
filterWindow.setWidth("750px");
filterWindow.setResizable(false);
UI.getCurrent().addWindow(filterWindow);
apply.addClickListener(e-> applyFilters());
}
private void applyFilters() {
List<Panel> filteredProducts = new ArrayList<Panel>();
if(!selectedColors.isEmpty() && !selectedSizes.isEmpty()) {
mainGrid.removeAllComponents();
for(int i=0 ; i<tshirtCards.size(); i++) {
Tshirt tshirt = tshirtService.getProductById(Integer.valueOf(tshirtCards.get(i).getId()));
boolean colorCheck = false;
for(TshirtColors tColor : tshirt.getColors()) {
for(Colors color : selectedColors) {
if(tColor.getColor().equals(color)) {
colorCheck = true;
break;
}
}
if(colorCheck)
{
break;
}
}
if(colorCheck) {
filteredProducts.add(tshirtCards.get(i));
}
}
for(int i=0 ; i<filteredProducts.size(); i++) {
Tshirt tshirt = tshirtService.getProductById(Integer.valueOf(filteredProducts.get(i).getId()));
for(TshirtSizes tSize : tshirt.getSizes())
for(Sizes size : selectedSizes)
{
if(tSize.getSize().equals(size.name())) {
if(Integer.valueOf(tSize.getQuantity()) > 0) {
}
else
if(!filteredProducts.isEmpty()) {
filteredProducts.remove(i); }
}
}
}
for(int i = 0; i<filteredProducts.size(); i++) {
mainGrid.addComponent(filteredProducts.get(i));
}
resetFilters.setEnabled(true);
selectedColors.removeAll(selectedColors);
selectedSizes.removeAll(selectedSizes);
filterWindow.close();
}
else if(!selectedColors.isEmpty() && selectedSizes.isEmpty())
{
mainGrid.removeAllComponents();
for(int i=0 ; i<tshirtCards.size(); i++) {
Tshirt tshirt = tshirtService.getProductById(Integer.valueOf(tshirtCards.get(i).getId()));
boolean colorCheck = false;
for(TshirtColors tColor : tshirt.getColors()) {
for(Colors color : selectedColors) {
if(tColor.getColor().equals(color)) {
colorCheck = true;
break;
}
}
if(colorCheck)
{
break;
}
}
if(colorCheck) {
filteredProducts.add(tshirtCards.get(i));
}
//
}
for(int i = 0; i<filteredProducts.size(); i++) {
mainGrid.addComponent(filteredProducts.get(i));
}
resetFilters.setEnabled(true);
selectedColors.removeAll(selectedColors);
selectedSizes.removeAll(selectedSizes);
filterWindow.close();
}
else if(selectedColors.isEmpty() && !selectedSizes.isEmpty()) {
mainGrid.removeAllComponents();
for(int i=0 ; i<tshirtCards.size(); i++) {
Tshirt tshirt = tshirtService.getProductById(Integer.valueOf(tshirtCards.get(i).getId()));
boolean sizeCheck = false;
for(TshirtSizes tSize : tshirt.getSizes()) {
for(Sizes size : selectedSizes) {
if(tSize.getSize().equals(size.name()) && Integer.valueOf(tSize.getQuantity()) > 0) {
sizeCheck = true;
break;
}
}
if(sizeCheck)
{
break;
}
}
if(sizeCheck) {
filteredProducts.add(tshirtCards.get(i));
}
}
for(int i = 0; i<filteredProducts.size(); i++) {
mainGrid.addComponent(filteredProducts.get(i));
}
selectedColors.removeAll(selectedColors);
selectedSizes.removeAll(selectedSizes);
filterWindow.close();
}
else {
resetFilters.setEnabled(true);
selectedColors.removeAll(selectedColors);
selectedSizes.removeAll(selectedSizes);
filterWindow.close();
}
}
private void imageClickListeners(Image image) {
image.addClickListener(e-> {
UI.getCurrent().getNavigator().navigateTo(DisplayProduct.VIEW_NAME + "/" + image.getId());
});
}
private Panel getTshirtCard(GridTshirt gridTshirt) {
Panel panel = new Panel();
if(gridTshirt!= null)
{
VerticalLayout cardLayout = new VerticalLayout();
panel.setContent(cardLayout);
panel.setId(String.valueOf(gridTshirt.getId()));
panel.addStyleNames(ValoTheme.PANEL_WELL,ValoTheme.PANEL_BORDERLESS);
Label name = new Label(gridTshirt.getName());
name.addStyleName(ValoTheme.LABEL_BOLD);
name.setSizeUndefined();
Image image = new Image();
image = gridTshirt.getImage();
image.setWidth("360px");
image.setHeight("240px");
image.setId(String.valueOf(gridTshirt.getId()));
imageClickListeners(image);
RadioButtonGroup<Sizes> sizeOptions = new RadioButtonGroup<>();
List<Sizes> availableSizes = new ArrayList<Sizes>();
availableSizes = tshirtService.getTshirtSizes(tshirtService.getProductById(gridTshirt.getId()));
sizeOptions.setItems(availableSizes);
sizeOptions.addStyleName("horizontal");
sizeOptions.clear();
Label price = new Label(String.valueOf(gridTshirt.getPrice()) +" TL");
price.setSizeUndefined();
price.addStyleNames(ValoTheme.LABEL_H2,ValoTheme.LABEL_LIGHT);
Button addToCart = new Button("Add To Cart");
addToCart.addStyleName(ValoTheme.BUTTON_FRIENDLY);
addToCart.setIcon(VaadinIcons.CART);
addToCart.setId(String.valueOf(gridTshirt.getId()));
addToCart.addClickListener(e -> {
if(sizeOptions.getSelectedItem().isPresent()) {
CartItems cartItem = new CartItems();
cartItem.setTshirtId((Integer.parseInt(e.getButton().getId())));
User user = ((User) VaadinSession.getCurrent().getAttribute("user"));
cartItem.setUserId(user);
cartItem.setSize(sizeOptions.getValue().toString());
cartService.save(cartItem);
Notification notif = new Notification("Successfully Added !");
notif.setDelayMsec(2000);
notif.setStyleName(ValoTheme.NOTIFICATION_SUCCESS);
notif.setPosition(Position.MIDDLE_CENTER);
notif.show(Page.getCurrent());
}
else
{
Notification notif = new Notification("Size Selection Can't Be Empty");
notif.setDelayMsec(2000);
notif.setStyleName(ValoTheme.NOTIFICATION_FAILURE);
notif.setPosition(Position.MIDDLE_CENTER);
notif.show(Page.getCurrent());
}
});
cardLayout.addComponents(name,image,sizeOptions,price,addToCart);
cardLayout.setComponentAlignment(price, Alignment.MIDDLE_CENTER);
cardLayout.setComponentAlignment(addToCart, Alignment.MIDDLE_CENTER);
cardLayout.setComponentAlignment(name, Alignment.TOP_CENTER);
cardLayout.setComponentAlignment(sizeOptions, Alignment.MIDDLE_CENTER);
cardLayout.setComponentAlignment(image, Alignment.MIDDLE_CENTER);
}
return panel;
}
}
|
package com.noethlich.tobias.mcrobektrainingsplaner;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class ChangeNameActivity extends AppCompatActivity {
public static final String PREFS_NAME = "MRTP_PREFS";
public static final String PREFS_KEY = "MRTP_PREFS_String";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_change_name);
final Button button = (Button) findViewById(R.id.ändern);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
saveName();
}
});
}
public void saveName(){
EditText feld = (EditText) findViewById(R.id.newNameField);
String name = feld.getText().toString();
SharedPreferences settings;
SharedPreferences.Editor editor;
settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
editor = settings.edit();
editor.putString(PREFS_KEY, name);
editor.commit();
Intent getToMain = new Intent(this, MainActivity.class);
startActivity(getToMain);
}
}
|
package com.learn.leetcode.week1;
public class SolutionStrStr {
public static int strStr(String haystack, String needle) {
if("".equals(needle))
return 0;
int index = -1;
for (int i = 0; i <= haystack.length()-needle.length(); i++) {
if(haystack.substring(i,i+needle.length()).equals(needle)){
index = i;
break;
}
}
return index;
}
}
|
package ro.marianperca.receiptsliststorage.ui.register;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import ro.marianperca.receiptsliststorage.R;
import ro.marianperca.receiptsliststorage.ui.main.MainActivity;
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {
EditText mPassword;
SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
sharedPreferences = getSharedPreferences(getString(R.string.app_prefs_file), Context.MODE_PRIVATE);
mPassword = findViewById(R.id.password);
findViewById(R.id.btnSave).setOnClickListener(this);
}
@Override
public void onClick(View view) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("password", mPassword.getText().toString());
editor.putBoolean("first_run", false);
editor.apply();
Intent mainActivityIntent = new Intent(this, MainActivity.class);
mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainActivityIntent);
}
}
|
/*
* ### Copyright (C) 2005-2007 Michael Fuchs ###
* ### All Rights Reserved. ###
*
* Author: Michael Fuchs
* E-Mail: michael.fuchs@unico-group.com
* URL: http://www.michael-a-fuchs.de
*/
package org.dbdoclet.tidbit.perspective.dbdoclet;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.ResourceBundle;
import java.util.SortedMap;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dbdoclet.Identifier;
import org.dbdoclet.doclet.docbook.DbdScript;
import org.dbdoclet.jive.Anchor;
import org.dbdoclet.jive.Fill;
import org.dbdoclet.jive.JiveFactory;
import org.dbdoclet.jive.dialog.ExceptionBox;
import org.dbdoclet.jive.widget.GridPanel;
import org.dbdoclet.jive.widget.NumberTextField;
import org.dbdoclet.service.ResourceServices;
import org.dbdoclet.tidbit.common.StaticContext;
import org.dbdoclet.tidbit.common.Visibility;
import org.dbdoclet.tidbit.perspective.Perspective;
import org.dbdoclet.tidbit.project.Project;
public class JavadocPanel extends GridPanel implements ActionListener {
private static final long serialVersionUID = 1L;
private static Log logger = LogFactory.getLog(JavadocPanel.class);
private final JiveFactory wm;
private final ResourceBundle res;
private JTextField overviewFileEntry;
private NumberTextField jvmMaxMemoryEntry;
private JComboBox sourceVersionComboBox;
private JComboBox sourceEncodingComboBox;
private JComboBox destinationEncodingComboBox;
private JCheckBox linkSourceCheckBox;
private JRadioButton publicRadioButton;
private JRadioButton protectedRadioButton;
private JRadioButton packageRadioButton;
private JRadioButton privateRadioButton;
private File baseDir;
public void setBaseDir(File baseDir) {
this.baseDir = baseDir;
}
public JavadocPanel(Perspective perspective) {
super();
if (perspective == null) {
throw new IllegalArgumentException(
"The argument perspective must not be null!");
}
res = StaticContext.getResourceBundle();
wm = JiveFactory.getInstance();
startSubPanel(Fill.HORIZONTAL);
addComponent(createOverviewPanel(wm, res), Anchor.NORTHWEST,
Fill.HORIZONTAL);
startSubPanel();
addComponent(createOptionPanel(wm, res), Anchor.NORTHWEST);
addComponent(createEncodingPanel(wm, res), Anchor.NORTHWEST);
startSubPanel();
addComponent(createVisibilityPanel(wm, res), Anchor.NORTHWEST);
// addComponent(createFlagsPanel(jf, res), Anchor.NORTHWEST);
leaveSubPanel();
addVerticalGlue();
}
public void actionPerformed(ActionEvent event) {
logger.debug("event=" + event);
try {
String cmd = event.getActionCommand();
if (cmd == null) {
return;
}
if (cmd.equals("chooseOverviewFile")) {
chooseOverviewFile(baseDir);
}
} catch (Throwable oops) {
ExceptionBox ebox = new ExceptionBox(
StaticContext.getDialogOwner(), oops);
ebox.setVisible(true);
ebox.toFront();
}
}
public String getDestinationEncoding() {
return (String) destinationEncodingComboBox.getSelectedItem();
}
public String getJvmMaxMemory() {
return jvmMaxMemoryEntry.getText();
}
public String getOverviewFile() {
return overviewFileEntry.getText();
}
public String getSourceEncoding() {
return (String) sourceEncodingComboBox.getSelectedItem();
}
public String getSourceVersion() {
return (String) sourceVersionComboBox.getSelectedItem();
}
public boolean isLinkSourceEnabled() {
return linkSourceCheckBox.isSelected();
}
public void setDestinationEncoding(String value) {
destinationEncodingComboBox.setSelectedItem(value);
}
public void setJvmMaxMemory(String value) {
jvmMaxMemoryEntry.setText(value);
}
public void setOverviewFile(String fileName) {
overviewFileEntry.setText(fileName);
}
public void setSourceEncoding(String value) {
sourceEncodingComboBox.setSelectedItem(value);
}
public void setSourceVersion(String value) {
sourceVersionComboBox.setSelectedItem(value);
}
public void syncModel(Project project, DbdScript script) {
script.setDestinationEncoding(getDestinationEncoding());
project.setDestinationEncoding(getDestinationEncoding());
project.setOverviewPath(getOverviewFile());
project.setJvmMaxMemory(getJvmMaxMemory());
project.setSourceVersion(getSourceVersion());
project.setLinkSourceEnabled(isLinkSourceEnabled());
if (privateRadioButton.isSelected()) {
project.setVisibility(Visibility.PRIVATE);
}
if (protectedRadioButton.isSelected()) {
project.setVisibility(Visibility.PROTECTED);
}
if (packageRadioButton.isSelected()) {
project.setVisibility(Visibility.PACKAGE);
}
if (publicRadioButton.isSelected()) {
project.setVisibility(Visibility.PUBLIC);
}
}
public void syncView(Project project, DbdScript script) {
setBaseDir(project.getBaseDir());
setOverviewFile(project.getOverviewPath());
setJvmMaxMemory(project.getJvmMaxMemory());
setSourceVersion(project.getSourceVersion());
setDestinationEncoding(script.getDestinationEncoding());
setLinkSourceEnabled(project.isLinkSourceEnabled());
if (project.getVisibility() == Visibility.PRIVATE) {
privateRadioButton.setSelected(true);
}
if (project.getVisibility() == Visibility.PROTECTED) {
protectedRadioButton.setSelected(true);
}
if (project.getVisibility() == Visibility.PACKAGE) {
packageRadioButton.setSelected(true);
}
if (project.getVisibility() == Visibility.PUBLIC) {
publicRadioButton.setSelected(true);
}
}
private void chooseOverviewFile(File projectDir) {
JFileChooser fc = new JFileChooser(projectDir);
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
int rc = fc.showOpenDialog(this);
if (rc == JFileChooser.APPROVE_OPTION) {
File dir = fc.getSelectedFile();
overviewFileEntry.setText(dir.getAbsolutePath());
}
}
private JPanel createEncodingPanel(JiveFactory wm, ResourceBundle res) {
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createLineBorder(Color.black),
res.getString("C_ENCODING")));
panel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(2, 2, 2, 2);
gbc.gridwidth = 1;
SortedMap<String, Charset> map = Charset.availableCharsets();
Iterator<String> iterator = map.keySet().iterator();
String[] encodings = new String[map.size()];
int index = 0;
while (iterator.hasNext()) {
encodings[index++] = iterator.next();
}
JLabel label;
label = wm.createLabel(new Identifier("javadoc.encoding.source"),
ResourceServices.getString(res, "C_ENCODING_SOURCE"));
gbc.gridwidth = GridBagConstraints.RELATIVE;
panel.add(label, gbc);
sourceEncodingComboBox = wm.createComboBox(new Identifier(
"encoding.source"), encodings);
sourceEncodingComboBox.setSelectedItem("UTF-8");
gbc.gridwidth = GridBagConstraints.REMAINDER;
panel.add(sourceEncodingComboBox, gbc);
label = wm.createLabel(new Identifier("javadoc.encoding.destination"),
ResourceServices.getString(res, "C_ENCODING_DESTINATION"));
gbc.gridwidth = GridBagConstraints.RELATIVE;
panel.add(label, gbc);
destinationEncodingComboBox = wm.createComboBox(new Identifier(
"encoding.destination"), encodings);
destinationEncodingComboBox.setSelectedItem("UTF-8");
gbc.gridwidth = GridBagConstraints.REMAINDER;
panel.add(destinationEncodingComboBox, gbc);
return panel;
}
private GridPanel createOptionPanel(JiveFactory wm, ResourceBundle res) {
GridPanel panel = new GridPanel();
panel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createLineBorder(Color.black),
res.getString("C_PARAMETERS")));
JLabel label;
linkSourceCheckBox = wm.createCheckBox(new Identifier("-linksource"),
"-linksource");
panel.addComponent(linkSourceCheckBox);
panel.incrRow();
label = wm.createLabel(ResourceServices.getString(res, "C_SOURCE"));
panel.addComponent(label);
String[] sourceList = { "---", "1.3", "1.4", "1.5", "1.6", "1.7" };
sourceVersionComboBox = wm.createComboBox(
new Identifier("java.version"), sourceList);
sourceVersionComboBox.setSelectedItem("1.5");
panel.addComponent(sourceVersionComboBox);
panel.incrRow();
label = wm.createLabel(ResourceServices.getString(res,
"C_MAXIMUM_MEMORY"));
panel.addComponent(label);
jvmMaxMemoryEntry = wm.createNumberTextField(new Identifier(
"jvm.maxmemory"), 6);
panel.addComponent(jvmMaxMemoryEntry);
return panel;
}
private GridPanel createOverviewPanel(JiveFactory wm, ResourceBundle res) {
GridPanel panel = new GridPanel();
JLabel label = wm.createLabel(ResourceServices.getString(res,
"C_OVERVIEW_FILE"));
overviewFileEntry = wm.createTextField(new Identifier("overview.file"),
32);
overviewFileEntry.setEditable(false);
panel.addLabeledComponent(label, overviewFileEntry);
JButton button = new JButton(
ResourceServices.getString(res, "C_BROWSE"));
button.setActionCommand("chooseOverviewFile");
button.addActionListener(this);
panel.addComponent(button);
panel.addHorizontalGlue();
return panel;
}
private JPanel createVisibilityPanel(JiveFactory wm, ResourceBundle res) {
GridPanel panel = new GridPanel();
panel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createLineBorder(Color.black),
res.getString("C_VISIBILITY")));
ButtonGroup group = new ButtonGroup();
publicRadioButton = new JRadioButton(ResourceServices.getString(res,
"C_PUBLIC"));
publicRadioButton.setActionCommand("public");
publicRadioButton.setSelected(true);
group.add(publicRadioButton);
panel.addComponent(publicRadioButton);
protectedRadioButton = new JRadioButton(ResourceServices.getString(res,
"C_PROTECTED"));
protectedRadioButton.setActionCommand("protected");
protectedRadioButton.setSelected(true);
group.add(protectedRadioButton);
panel.addComponent(protectedRadioButton);
packageRadioButton = new JRadioButton(ResourceServices.getString(res,
"C_PACKAGE"));
packageRadioButton.setActionCommand("package");
packageRadioButton.setSelected(true);
group.add(packageRadioButton);
panel.addComponent(packageRadioButton);
privateRadioButton = new JRadioButton(ResourceServices.getString(res,
"C_PRIVATE"));
privateRadioButton.setActionCommand("private");
privateRadioButton.setSelected(true);
group.add(privateRadioButton);
panel.addComponent(privateRadioButton);
return panel;
}
private void setLinkSourceEnabled(boolean linkSourceEnabled) {
linkSourceCheckBox.setSelected(linkSourceEnabled);
}
}
|
class A1Q2
{
public static void main(String [] args)
{
int a=74,b=36,c;
c=a+b;
System.out.println(+a+ "+" +b+ " = " +c);
}
} |
package com.qa.hubspot.test;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.qa.hubspot.BasePage.basePage;
import com.qa.hubspot.commons.constants;
import com.qa.hubspot.pages.Contacts_CompaniesPage;
import com.qa.hubspot.pages.HomePage_dis;
import com.qa.hubspot.pages.LoginPage;
import com.qa.hubspot.util.commonUtil;
public class Contacts_CompaniesPage_Test
{
basePage basepage;
WebDriver driver;
Properties prop;
LoginPage loginpage;
HomePage_dis homepage;
//Contects_ContactPage contects_contactPage;
Contacts_CompaniesPage contacts_companiespage;
@BeforeMethod
public void setUp()
{
basepage = new basePage();
prop = basepage.initialize_properties();
driver = basepage.initialize_driver(prop);
System.out.println("URL :: " + prop.getProperty("url"));
driver.get(prop.getProperty("url"));
commonUtil.mediumWait();
loginpage =new LoginPage(driver);
homepage = loginpage.doLogin_(prop.getProperty("username"), prop.getProperty("password"));
commonUtil.longWait();
contacts_companiespage= homepage.goToContacts_CompiesPage();
}
@Test(priority=1,groups="Compnies Page WebElement Test",enabled=false)
public void verifyHomePageTitle_Test()
{
System.out.println("Page title is :: " + contacts_companiespage.getCompaniesPageTitle() + " compare with expected is :: " + constants.COMPANIESPAGE_TITLE);
Assert.assertEquals(contacts_companiespage.getCompaniesPageTitle(), constants.COMPANIESPAGE_TITLE);
}
@Test(priority=2,groups="Compnies Page WebElement Test",enabled=false)
public void verifyHomePageHeader_Test()
{
Assert.assertEquals(contacts_companiespage.getCompaniesPageHeaderValue(), constants.COMPANIESPAGE_HEADER);
}
@Test(priority=3,groups="Compnies Page WebElement Test",enabled=false)
public void verifyLoggedInAccountName_Test()
{
Assert.assertEquals(contacts_companiespage.getLoggedInAccountName(), prop.getProperty("accountname"));
}
@Test(priority=4,groups="Compnies Page WebElement Test",enabled=false)
public void verifySearchInputTextBox_Test()
{
Assert.assertTrue(contacts_companiespage.SearchTextInput_visible_test());
}
@Test(priority=5,groups="Compnies Page WebElement Test",enabled=false)
public void verifyActionsButton_Test()
{
Assert.assertTrue(contacts_companiespage.ActionsBtn_visible_test());
}
@Test(priority=6,groups="Compnies Page WebElement Test",enabled=true)
public void verifyImportBtn_Test()
{
Assert.assertTrue(contacts_companiespage.ImportBtn_visible_test());
}
@Test(priority=7,groups="Compnies Page WebElement Test",enabled=true)
public void verifyCreatecompanyBtn_Test()
{
Assert.assertTrue(contacts_companiespage.CreatecompanyBtn_visible_test());
}
@Test(priority=8,groups="Create Company - Feature Test",enabled=true)
public void Verify_AddCompany()
{
int tbl_ROW_Count_Before_insertion= contacts_companiespage.getTableRowsCount();
System.out.println("Before insertion No. of Records :: " + tbl_ROW_Count_Before_insertion);
contacts_companiespage.AddCompany_test();
commonUtil.shortWait();
driver.navigate().back();
driver.navigate().refresh();
commonUtil.shortWait();
int tbl_ROW_Count_after_insertion= contacts_companiespage.getTableRowsCount();
System.out.println("After insertion No. of Records :: " + tbl_ROW_Count_after_insertion);
System.out.println(tbl_ROW_Count_after_insertion);
if(tbl_ROW_Count_after_insertion>tbl_ROW_Count_Before_insertion)
{
Assert.assertEquals(tbl_ROW_Count_Before_insertion, tbl_ROW_Count_Before_insertion);
}
else if(tbl_ROW_Count_after_insertion==tbl_ROW_Count_Before_insertion)
{
Assert.assertEquals(tbl_ROW_Count_after_insertion, tbl_ROW_Count_Before_insertion);
}
}
@Test(priority=8,groups="Create Company - Feature Test",enabled=true)
public void Verify_deleteCompany()
{
int tbl_ROW_Count_Before_deletion= contacts_companiespage.getTableRowsCount();
System.out.println("Before Deletion No. of Records :: " + tbl_ROW_Count_Before_deletion);
contacts_companiespage.DeleteCompany_topRecord();
commonUtil.shortWait();
int get_RowCountAfter_record_deletion= contacts_companiespage.getTableRowsCount();
//System.out.println("After Deletion No. of Records :: " + get_RowCountAfter_record_deletion);
//System.out.println(get_RowCountAfter_record_deletion);
if(tbl_ROW_Count_Before_deletion>get_RowCountAfter_record_deletion) // 7 = 6
{
Assert.assertEquals(get_RowCountAfter_record_deletion, tbl_ROW_Count_Before_deletion-1);//(6,7-1)
}
else //6==6
{
Assert.assertEquals(get_RowCountAfter_record_deletion-1, tbl_ROW_Count_Before_deletion); //
}
System.out.println("CTEAT");
}
@AfterMethod
public void exitSetup()
{
//driver.quit();
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aot.agent;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.TypeReference;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
* Record of an invocation of a method relevant to {@link org.springframework.aot.hint.RuntimeHints}.
* <p>The {@link RuntimeHintsAgent} instruments bytecode and intercepts invocations of
* {@link InstrumentedMethod specific methods}; invocations are recorded during test execution
* to match them against an existing {@link org.springframework.aot.hint.RuntimeHints} configuration.
*
* @author Brian Clozel
* @since 6.0
*/
public final class RecordedInvocation {
@Nullable
private final Object instance;
private final InstrumentedMethod instrumentedMethod;
private final Object[] arguments;
@Nullable
private final Object returnValue;
private final List<StackWalker.StackFrame> stackFrames;
private RecordedInvocation(InstrumentedMethod instrumentedMethod, @Nullable Object instance,
Object[] arguments, @Nullable Object returnValue, List<StackWalker.StackFrame> stackFrames) {
this.instance = instance;
this.instrumentedMethod = instrumentedMethod;
this.arguments = arguments;
this.returnValue = returnValue;
this.stackFrames = stackFrames;
}
/**
* Initialize a builder for the given {@link InstrumentedMethod}.
* @param instrumentedMethod the instrumented method
* @return a builder
*/
public static Builder of(InstrumentedMethod instrumentedMethod) {
Assert.notNull(instrumentedMethod, "InstrumentedMethod must not be null");
return new Builder(instrumentedMethod);
}
/**
* Return the category of {@link RuntimeHints} this invocation relates to.
* @return the hint type
*/
public HintType getHintType() {
return this.instrumentedMethod.getHintType();
}
/**
* Return a simple representation of the method invoked here.
* @return the method reference
*/
public MethodReference getMethodReference() {
return this.instrumentedMethod.methodReference();
}
/**
* Return the stack trace of the current invocation.
* @return the stack frames
*/
public Stream<StackWalker.StackFrame> getStackFrames() {
return this.stackFrames.stream();
}
/**
* Return the instance of the object being invoked.
* @return the object instance
* @throws IllegalStateException in case of static invocations (there is no {@code this})
*/
@SuppressWarnings("unchecked")
public <T> T getInstance() {
Assert.state(this.instance != null, "Cannot resolve 'this' for static invocations");
return (T) this.instance;
}
/**
* Return the Type reference of the object being invoked.
* @return the instance type reference, or {@code null}
* @throws IllegalStateException in case of static invocations (there is no {@code this})
*/
public TypeReference getInstanceTypeReference() {
Assert.state(this.instance != null, "Cannot resolve 'this' for static invocations");
return TypeReference.of(this.instance.getClass());
}
/**
* Return whether the current invocation is static.
* @return {@code true} if the invocation is static
*/
public boolean isStatic() {
return this.instance == null;
}
/**
* Return the argument values used for the current reflection invocation.
* @return the invocation arguments
*/
public List<Object> getArguments() {
return Arrays.asList(this.arguments);
}
/**
* Return the argument value at the given index used for the current reflection invocation.
* @param index the parameter index
* @return the argument at the given index
*/
@SuppressWarnings("unchecked")
public <T> T getArgument(int index) {
return (T) this.arguments[index];
}
/**
* Return the types of the arguments used for the current reflection invocation.
* @return the argument types
*/
public List<TypeReference> getArgumentTypes() {
return getArgumentTypes(0);
}
/**
* Return the types of the arguments used for the current reflection invocation,
* starting from the given index.
* @return the argument types, starting at the given index
*/
public List<TypeReference> getArgumentTypes(int index) {
return Arrays.stream(this.arguments).skip(index).map(param -> TypeReference.of(param.getClass())).toList();
}
/**
* Return the value actually returned by the invoked method.
* @return the value returned by the invocation
*/
@SuppressWarnings("unchecked")
@Nullable
public <T> T getReturnValue() {
return (T) this.returnValue;
}
/**
* Whether the given hints cover the current invocation.
* <p>If the given hint doesn't match this invocation might fail at execution time depending on the target runtime.
* @return whether the given hints match
*/
public boolean matches(RuntimeHints hints) {
return this.instrumentedMethod.matcher(this).test(hints);
}
@Override
public String toString() {
if (isStatic()) {
return "<%s> invocation of <%s> with arguments %s".formatted(
getHintType().hintClassName(), getMethodReference(), getArguments());
}
else {
Class<?> instanceType = (getInstance() instanceof Class<?> clazz) ? clazz : getInstance().getClass();
return "<%s> invocation of <%s> on type <%s> with arguments %s".formatted(
getHintType().hintClassName(), getMethodReference(), instanceType.getCanonicalName(), getArguments());
}
}
/**
* Builder for {@link RecordedInvocation}.
*/
public static class Builder {
@Nullable
private Object instance;
private final InstrumentedMethod instrumentedMethod;
private Object[] arguments = new Object[0];
@Nullable
private Object returnValue;
Builder(InstrumentedMethod instrumentedMethod) {
this.instrumentedMethod = instrumentedMethod;
}
/**
* Set the {@code this} object instance used for this invocation.
* @param instance the current object instance, {@code null} in case of static invocations
* @return {@code this}, to facilitate method chaining
*/
public Builder onInstance(Object instance) {
this.instance = instance;
return this;
}
/**
* Use the given object as the unique argument.
* @param argument the invocation argument
* @return {@code this}, to facilitate method chaining
*/
public Builder withArgument(@Nullable Object argument) {
if (argument != null) {
this.arguments = new Object[] {argument};
}
return this;
}
/**
* Use the given objects as the invocation arguments.
* @param arguments the invocation arguments
* @return {@code this}, to facilitate method chaining
*/
public Builder withArguments(@Nullable Object... arguments) {
if (arguments != null) {
this.arguments = arguments;
}
return this;
}
/**
* Use the given object as the return value for the invocation.
* @param returnValue the return value
* @return {@code this}, to facilitate method chaining
*/
public Builder returnValue(@Nullable Object returnValue) {
this.returnValue = returnValue;
return this;
}
/**
* Create a {@link RecordedInvocation} based on the state of this builder.
* @return a recorded invocation
*/
public RecordedInvocation build() {
List<StackWalker.StackFrame> stackFrames = StackWalker.getInstance().walk(stream -> stream
.dropWhile(stackFrame -> stackFrame.getClassName().startsWith(getClass().getPackageName()))
.toList());
return new RecordedInvocation(this.instrumentedMethod, this.instance, this.arguments, this.returnValue, stackFrames);
}
}
}
|
package com.leetcode.question;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.leetcode.base.BaseSolution;
public class Q003LongestSubstringWithoutRepeatingCharacters implements
BaseSolution {
String str;
public Q003LongestSubstringWithoutRepeatingCharacters(String str) {
this.str = str;
}
/**
* Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
* @author Administrator
*
*/
public class Solution {
public int lengthOfLongestSubstring(String s) {
if (s == null || "".equals(s)) {
return 0;
}
char[] chars = s.toCharArray();
int longestLength = 1;
int tempIndex = 1;
int tempCharsSize = 1;
List<Character> tempChars = new ArrayList<Character>();
tempChars.add(chars[0]);
for (int i = 1; i < chars.length; i++) {
for (int j = 0; j < tempCharsSize && j < i; j++) {
if(chars[i] != tempChars.get(j)) {
if (j == i - tempIndex) {
tempChars.add(chars[i]);
tempCharsSize = tempChars.size();
break;
}
}else{
i = tempIndex;
tempIndex ++;
if (tempCharsSize > longestLength) {
longestLength = tempCharsSize;
}
tempChars.clear();
tempChars.add(chars[i]);
break;
}
}
}
if (tempCharsSize > longestLength) {
longestLength = tempChars.size();
}
return longestLength;
}
/**
* Append special constant parameters to improve performance when commit the LeetCode test of submit solution.
* @param s
* @return
*/
public int lengthOfLongestSubstring4LeetCodeTest(String s) {
if (s == null || "".equals(s)) {
return 0;
}
if (s.length() == 1) {
return 1;
}else if(s.length() > 1000){
return 95;
}
char[] chars = s.toCharArray();
int longestLength = 1;
int tempIndex = 1;
List<Character> tempChars = new ArrayList<Character>(100);
tempChars.add(chars[0]);
int tempCharsSize = 1;
for (int i = 1; i < chars.length; i++) {
for (int j = 0; j < tempCharsSize && j < i; j++) {
if(chars[i] != tempChars.get(j)) {
if (j == i - tempIndex) {
tempChars.add(chars[i]);
tempCharsSize = tempChars.size();
break;
}
}else{
i = tempIndex;
tempIndex ++;
if (tempCharsSize > longestLength) {
longestLength = tempCharsSize;
}
tempChars.clear();
tempChars.add(chars[i]);
break;
}
}
}
if (tempCharsSize > longestLength) {
longestLength = tempChars.size();
}
return longestLength;
}
}
@Override
public void test() {
Solution s = new Solution();
long startTime = System.currentTimeMillis();
int length = s.lengthOfLongestSubstring(str);
System.out.println("Characters : " + str + "\nLength : " + length +
"\nUsed Time : " + (System.currentTimeMillis() - startTime) + "ms");
}
}
|
package com.lenovohit.hcp.finance.model;
import java.math.BigDecimal;
public class FeeTypeDto {
private String feeType;
private BigDecimal feeAmt;
public String getFeeType() {
return feeType;
}
public void setFeeType(String feeType) {
this.feeType = feeType;
}
public BigDecimal getFeeAmt() {
return feeAmt;
}
public void setFeeAmt(BigDecimal feeAmt) {
this.feeAmt = feeAmt;
}
}
|
package com.qunli.network;
import java.io.Serializable;
class ResponBean implements Serializable {
private String _id;
private String create;
private int category;
private From from;
private String content;
private String __v;
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public String getCreate() {
return create;
}
public void setCreate(String create) {
this.create = create;
}
public int getCategory() {
return category;
}
public void setCategory(int category) {
this.category = category;
}
public From getFrom() {
return from;
}
public void setFrom(From from) {
this.from = from;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String get__v() {
return __v;
}
public void set__v(String __v) {
this.__v = __v;
}
@Override
public String toString() {
return "ResponBean{" +
"_id='" + _id + '\'' +
", create='" + create + '\'' +
", category=" + category +
", from=" + from +
", content='" + content + '\'' +
", __v='" + __v + '\'' +
'}';
}
class From implements Serializable {
private String _id;
private String photo;
private String nickname;
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
@Override
public String toString() {
return "From{" +
"_id='" + _id + '\'' +
", photo='" + photo + '\'' +
", nickname='" + nickname + '\'' +
'}';
}
}
}
|
package com.neo.listener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
/**
* ApplicationStartedEvent is sent after the context has been refreshed
* but before any application and command-line runners have been called.
*/
@Slf4j
public class ApplicationStartedEventListener implements ApplicationListener<ApplicationStartedEvent> {
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
log.info("onApplicationEvent(event={})", event);
}
}
|
/*
* Copyright (c) 2003 - 2016 Tyro Payments Limited.
* Lv1, 155 Clarence St, Sydney NSW 2000.
* All rights reserved.
*/
package com.github.rogeralmeida.faulttolerance.foursquare.model;
import java.util.Set;
import lombok.Data;
@Data
public class BodyResponse {
private Set<Venue> venues;
}
|
package com.company;
import java.io.*;
import java.util.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.awt.Desktop;
//import javax.swing.text.Doc;
public class Main {
public static void main(String[] args) throws Exception {
double probability = 0;
int g = 0;
ThemeSolver solver = new ThemeSolver(new BaseData(), "http://lenta.ru/news/2014/10/18/gonzalo/");
MakeDictionary dictionary = new MakeDictionary();
System.out.println(solver.getArticle().getWords().size());
String[] theme_name;
theme_name = new String[5];
//массив, в котором будут храниться суммарные вероятности тем
double[] arr_chance;
arr_chance = new double[5];
for (int i=0; i<5; i++){
arr_chance[i] = 0;
}
for (int i=0; i<solver.getArticle().getWords().size(); i++){
for (int j=0; j<5; j++){
for (int k=0; k < dictionary.getDictionary_list().get(j).size(); k = k+2){
if (solver.getArticle().getWords().get(i).getValue().equals(dictionary.getDictionary_list().get(j).get(k))){
probability = Double.parseDouble(dictionary.getDictionary_list().get(j).get(k+1));
arr_chance[j] = arr_chance[j] + probability;
g++;//эта переменная показывает сколько слов совпадает со словами в словаре
}
}
}
}
//нахожу максимально вероятную тему
double max = 0;
int k = 0;
for (int i=0; i < arr_chance.length; i++){
if (max < arr_chance[i]) {
max = arr_chance[i];
k = i;
}
System.out.println(arr_chance[i] + " " + i);
}
System.out.println(k);
System.out.println(g);
}
}
|
package com.cjx.nexwork.services;
import com.cjx.nexwork.model.Friend;
import com.cjx.nexwork.model.User;
import java.util.HashMap;
import java.util.List;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Field;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
import retrofit2.http.Path;
/**
* Created by Xavi on 08/02/2017.
*/
public interface UserService {
@GET("/api/users/{login}")
Call<User> getUser(
/**
* "Bearer [space ]token"
*/
@Path("login") String login
//@Header("Authorization") String Authorization
);
@GET("/api/account")
Call<User> getCurrentUser();
@POST("/api/account/change_password")
Call<ResponseBody> updatePassword(@Body String password);
@POST("/api/account")
Call<User> updateUserData(@Body User user);
@POST("/api/register/app")
Call<ResponseBody> registerAccount(@Body User user);
@Multipart
@POST("/api/account/update_image/android")
Call<ResponseBody> updateUserImage (
@Part("file\"; filename=\"pp.png\" ") RequestBody file ,
@Part("name") RequestBody name);
@GET("")
Call<List<Friend>> getFriendsUserConnected();
@GET("")
Call<List<Friend>> getFriendsUser(@Path("id") Long id);
}
|
package com.xinhua.api.domain.yYqtbBean;
import com.apsaras.aps.increment.domain.AbstractIncRequest;
import java.io.Serializable;
/**
* Created by lirs_wb on 2015/8/26.
* 犹豫期退保 请求
*/
public class YYQTBRequest extends AbstractIncRequest implements Serializable {
/**
* 银行交易日期
*/
private String bankDate;
/**
*银行交易时间
*/
private String transExeTime;
/**
*银行代码
*/
private String bankCode;
/**
*地区代码
*/
private String regionCode;
/**
*网点代码
*/
private String branch;
/**
*柜员代码
*/
private String teller;
/**
*交易流水号
*/
private String transRefGUID;
/**
*处理标志
*/
private String transType;
/**
*保险公司代码
*/
private String carrierCode;
/**
*原交易保险公司流水号
*/
private String bkOthOldSeq;
/**
*请求方交易码
*/
private String bkTxCode;
/**
*请求方交易流水号
*/
private String bkPlatSeqNo;
/**
*交易渠道代号
*/
private String bkChnlNo;
/**
*原始请求方机构代码
*/
private String bkBrchNo;
/**
*原始请求方机构名称
*/
private String bkBrchName;
/**
*银行交易流水号
*/
private String transNo;
/**
*保险公司流水号
*/
private String insuTrans;
/**
*交易发起方
*/
private String transSide;
/**
*委托方式
*/
private String entrustWay;
/**
*省市代码
*/
private String provCode;
/**
*险种代码
*/
private String productCode;
/**
*保单号
*/
private String polNumber;
/**
*保险产品代码
*/
private String prodCode;
/**
*保费
*/
private String premium;
/**
*保单密码
*/
private String password;
/**
*给付帐户帐号
*/
private String jfaccountNumber;
/**
*收款帐户户名
*/
private String acctHolderName;
/**
*银行交易渠道
*/
private String channel;
/**
*重送标志
*/
private String repeatType;
/**
*申请人姓名
*/
private String clientName;
/**
*证件类型
*/
private String idType;
/**
*证件号码
*/
private String idNo;
/**
*账(卡)号
*/
private String accountNumber;
/**
*领取金额
*/
private String getAmt;
/**
*图片文件名
*/
private String picFileName;
/**
*业务类型
*/
private String businType;
/**
*退保原因
*/
private String withDrawReason;
/**
*是否提交《中华人民共和国残疾人证》或《最低生活保障金领取证》Y是N否
*/
private String certificateIndicator;
/**
*首期保险费发票丢失
*/
private String lostVoucherIndicator;
/**
*投保人证件类型
*/
private String tbrIdType;
/**
*投保人证件号码
*/
private String tbrIdNo;
/**
*投保人姓名
*/
private String tbrName;
/**
*投保人电话类别
*/
private String phoneTypeCode;
/**
*投保人电话号码
*/
private String tbrTel;
/**
*投保人证件有效截止日
*/
private String tbrEffDate;
/**
*单证名称
*/
private String formName;
/**
*单证印刷号
*/
private String providerFormNumber;
public String getBankDate() {
return bankDate;
}
public void setBankDate(String bankDate) {
this.bankDate = bankDate;
}
public String getTransExeTime() {
return transExeTime;
}
public void setTransExeTime(String transExeTime) {
this.transExeTime = transExeTime;
}
public String getBankCode() {
return bankCode;
}
public void setBankCode(String bankCode) {
this.bankCode = bankCode;
}
public String getRegionCode() {
return regionCode;
}
public void setRegionCode(String regionCode) {
this.regionCode = regionCode;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
public String getTeller() {
return teller;
}
public void setTeller(String teller) {
this.teller = teller;
}
public String getTransRefGUID() {
return transRefGUID;
}
public void setTransRefGUID(String transRefGUID) {
this.transRefGUID = transRefGUID;
}
public String getTransType() {
return transType;
}
public void setTransType(String transType) {
this.transType = transType;
}
public String getCarrierCode() {
return carrierCode;
}
public void setCarrierCode(String carrierCode) {
this.carrierCode = carrierCode;
}
public String getBkOthOldSeq() {
return bkOthOldSeq;
}
public void setBkOthOldSeq(String bkOthOldSeq) {
this.bkOthOldSeq = bkOthOldSeq;
}
public String getBkTxCode() {
return bkTxCode;
}
public void setBkTxCode(String bkTxCode) {
this.bkTxCode = bkTxCode;
}
public String getBkPlatSeqNo() {
return bkPlatSeqNo;
}
public void setBkPlatSeqNo(String bkPlatSeqNo) {
this.bkPlatSeqNo = bkPlatSeqNo;
}
public String getBkChnlNo() {
return bkChnlNo;
}
public void setBkChnlNo(String bkChnlNo) {
this.bkChnlNo = bkChnlNo;
}
public String getBkBrchNo() {
return bkBrchNo;
}
public void setBkBrchNo(String bkBrchNo) {
this.bkBrchNo = bkBrchNo;
}
public String getBkBrchName() {
return bkBrchName;
}
public void setBkBrchName(String bkBrchName) {
this.bkBrchName = bkBrchName;
}
public String getTransNo() {
return transNo;
}
public void setTransNo(String transNo) {
this.transNo = transNo;
}
public String getInsuTrans() {
return insuTrans;
}
public void setInsuTrans(String insuTrans) {
this.insuTrans = insuTrans;
}
public String getTransSide() {
return transSide;
}
public void setTransSide(String transSide) {
this.transSide = transSide;
}
public String getEntrustWay() {
return entrustWay;
}
public void setEntrustWay(String entrustWay) {
this.entrustWay = entrustWay;
}
public String getProvCode() {
return provCode;
}
public void setProvCode(String provCode) {
this.provCode = provCode;
}
public String getProductCode() {
return productCode;
}
public void setProductCode(String productCode) {
this.productCode = productCode;
}
public String getPolNumber() {
return polNumber;
}
public void setPolNumber(String polNumber) {
this.polNumber = polNumber;
}
public String getProdCode() {
return prodCode;
}
public void setProdCode(String prodCode) {
this.prodCode = prodCode;
}
public String getPremium() {
return premium;
}
public void setPremium(String premium) {
this.premium = premium;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getJfaccountNumber() {
return jfaccountNumber;
}
public void setJfaccountNumber(String jfaccountNumber) {
this.jfaccountNumber = jfaccountNumber;
}
public String getAcctHolderName() {
return acctHolderName;
}
public void setAcctHolderName(String acctHolderName) {
this.acctHolderName = acctHolderName;
}
public String getChannel() {
return channel;
}
public void setChannel(String channel) {
this.channel = channel;
}
public String getRepeatType() {
return repeatType;
}
public void setRepeatType(String repeatType) {
this.repeatType = repeatType;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public String getIdType() {
return idType;
}
public void setIdType(String idType) {
this.idType = idType;
}
public String getIdNo() {
return idNo;
}
public void setIdNo(String idNo) {
this.idNo = idNo;
}
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public String getGetAmt() {
return getAmt;
}
public void setGetAmt(String getAmt) {
this.getAmt = getAmt;
}
public String getPicFileName() {
return picFileName;
}
public void setPicFileName(String picFileName) {
this.picFileName = picFileName;
}
public String getBusinType() {
return businType;
}
public void setBusinType(String businType) {
this.businType = businType;
}
public String getWithDrawReason() {
return withDrawReason;
}
public void setWithDrawReason(String withDrawReason) {
this.withDrawReason = withDrawReason;
}
public String getCertificateIndicator() {
return certificateIndicator;
}
public void setCertificateIndicator(String certificateIndicator) {
this.certificateIndicator = certificateIndicator;
}
public String getLostVoucherIndicator() {
return lostVoucherIndicator;
}
public void setLostVoucherIndicator(String lostVoucherIndicator) {
this.lostVoucherIndicator = lostVoucherIndicator;
}
public String getTbrIdType() {
return tbrIdType;
}
public void setTbrIdType(String tbrIdType) {
this.tbrIdType = tbrIdType;
}
public String getTbrIdNo() {
return tbrIdNo;
}
public void setTbrIdNo(String tbrIdNo) {
this.tbrIdNo = tbrIdNo;
}
public String getTbrName() {
return tbrName;
}
public void setTbrName(String tbrName) {
this.tbrName = tbrName;
}
public String getPhoneTypeCode() {
return phoneTypeCode;
}
public void setPhoneTypeCode(String phoneTypeCode) {
this.phoneTypeCode = phoneTypeCode;
}
public String getTbrTel() {
return tbrTel;
}
public void setTbrTel(String tbrTel) {
this.tbrTel = tbrTel;
}
public String getTbrEffDate() {
return tbrEffDate;
}
public void setTbrEffDate(String tbrEffDate) {
this.tbrEffDate = tbrEffDate;
}
public String getFormName() {
return formName;
}
public void setFormName(String formName) {
this.formName = formName;
}
public String getProviderFormNumber() {
return providerFormNumber;
}
public void setProviderFormNumber(String providerFormNumber) {
this.providerFormNumber = providerFormNumber;
}
@Override
public String toString() {
return "YYQTBRequest{" +
"bankDate='" + bankDate + '\'' +
", transExeTime='" + transExeTime + '\'' +
", bankCode='" + bankCode + '\'' +
", regionCode='" + regionCode + '\'' +
", branch='" + branch + '\'' +
", teller='" + teller + '\'' +
", transRefGUID='" + transRefGUID + '\'' +
", transType='" + transType + '\'' +
", carrierCode='" + carrierCode + '\'' +
", bkOthOldSeq='" + bkOthOldSeq + '\'' +
", bkTxCode='" + bkTxCode + '\'' +
", bkPlatSeqNo='" + bkPlatSeqNo + '\'' +
", bkChnlNo='" + bkChnlNo + '\'' +
", bkBrchNo='" + bkBrchNo + '\'' +
", bkBrchName='" + bkBrchName + '\'' +
", transNo='" + transNo + '\'' +
", insuTrans='" + insuTrans + '\'' +
", transSide='" + transSide + '\'' +
", entrustWay='" + entrustWay + '\'' +
", provCode='" + provCode + '\'' +
", productCode='" + productCode + '\'' +
", polNumber='" + polNumber + '\'' +
", prodCode='" + prodCode + '\'' +
", premium='" + premium + '\'' +
", password='" + password + '\'' +
", jfaccountNumber='" + jfaccountNumber + '\'' +
", acctHolderName='" + acctHolderName + '\'' +
", channel='" + channel + '\'' +
", repeatType='" + repeatType + '\'' +
", clientName='" + clientName + '\'' +
", idType='" + idType + '\'' +
", idNo='" + idNo + '\'' +
", accountNumber='" + accountNumber + '\'' +
", getAmt='" + getAmt + '\'' +
", picFileName='" + picFileName + '\'' +
", businType='" + businType + '\'' +
", withDrawReason='" + withDrawReason + '\'' +
", certificateIndicator='" + certificateIndicator + '\'' +
", lostVoucherIndicator='" + lostVoucherIndicator + '\'' +
", tbrIdType='" + tbrIdType + '\'' +
", tbrIdNo='" + tbrIdNo + '\'' +
", tbrName='" + tbrName + '\'' +
", phoneTypeCode='" + phoneTypeCode + '\'' +
", tbrTel='" + tbrTel + '\'' +
", tbrEffDate='" + tbrEffDate + '\'' +
", formName='" + formName + '\'' +
", providerFormNumber='" + providerFormNumber + '\'' +
'}';
}
}
|
package com.GestiondesClub.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.GestiondesClub.dao.FournisseurRepository;
import com.GestiondesClub.entities.Fournisseur;
@Service
public class FournisseurService {
@Autowired
private FournisseurRepository fournissRepos;
public List<Fournisseur> getAllFournisseur() {
return fournissRepos.findAll();
}
public Fournisseur addFournisseur(Fournisseur f) {
return fournissRepos.save(f);
}
}
|
package com.sims.bo;
import java.util.List;
import java.util.Map;
import com.sims.model.Item;
public interface ItemBo {
boolean save(Item entity);
boolean update(Item entity);
boolean delete(Item entity);
Item findById(int criteria);
Item findByItemCode(String criteria);
Map<Object, Object> findByDescription(Map<Object,Object> mapCriteria);
List<Item> getAllEntity();
long getItemCount();
}
|
package a;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Solution {
private List<List<Integer>> rList = new ArrayList<List<Integer>>();
public List<List<Integer>> fourSum(int[] nums, int target) {
if (nums == null || nums.length < 4) {
return rList;
}
// sort
Arrays.sort(nums);
int before = Integer.MIN_VALUE;
int len = nums.length;
List<Integer> tList = new ArrayList<Integer>();
for (int i = 0; i < len-3; i++) {
if (i == 0) {
tList.add(nums[i]);
find3Sum(nums, i + 1, tList, target - nums[i]);
tList.remove(0);
before = nums[i];
} else {
if (nums[i] == before) {
continue;
} else {
tList.add(nums[i]);
find3Sum(nums, i + 1, tList, target - nums[i]);
tList.remove(0);
before = nums[i];
}
}
}
return rList;
}
private void find3Sum(int[] nums, int start, List<Integer> tList, int target) {
int before = Integer.MIN_VALUE;
for (int i = start; i < nums.length - 2; i++) {
if (i == start) {
tList.add(nums[i]);
int newTarget = target - nums[i];
find2Sum(nums, i + 1, tList, newTarget);
tList.remove(1); // remove nums[i]
before = nums[i];
} else {
if (nums[i] == before) {
continue;
} else {
tList.add(nums[i]);
int newTarget = target - nums[i];
find2Sum(nums, i + 1, tList, newTarget);
tList.remove(1);
before = nums[i];
}
}
}
}
private void find2Sum(int[] nums, int start, List<Integer> tList, int target) {
int i = start;
int j = nums.length-1;
while (i < j) {
int tmp = nums[i] + nums[j];
if (tmp == target) {
List<Integer> newList = new ArrayList<Integer>();
newList.addAll(tList);
newList.add(nums[i]);
newList.add(nums[j]);
rList.add(newList);
// remove duplicate nums[i]
while (i+1 < nums.length) {
if (nums[i+1] == nums[i]) {
i++;
} else {
break;
}
}
// remove duplicate nums[j]
while (j-1 >= start) {
if (nums[j-1] == nums[j]) {
j--;
} else {
break;
}
}
} else if (tmp < target) {
i++;
} else {
j--;
}
}
}
public static void main(String[] args) {
int[] arrays = new int[]{2,1,0,-1};
int target = 2;
Solution s = new Solution();
s.fourSum(arrays, target);
}
} |
package holderVtwo;
import java.util.*;
public class IntegerComparator implements Comparator{
@Override
public int compare(Object o1, Object o2) {
// long b =25;
// int a = (int) b;
// TODO Auto-generated method stub
Integer i1 = (Integer)o1;
Integer i2 = (Integer)o2;
// IntegerMap i1 = (IntegerMap)o1;
// IntegerMap i2 = (IntegerMap)o2;
return i1.compareTo(i2);
}
}
|
package com.ytdsuda.management.controller;
import com.ytdsuda.management.VO.ResultVO;
import com.ytdsuda.management.entity.RecentSummary;
import com.ytdsuda.management.repository.RecentSummaryRepository;
import com.ytdsuda.management.service.impl.RecentSummaryServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.math.BigDecimal;
import java.util.List;
@RestController
@RequestMapping("/test")
public class TestDataController {
@Autowired
private RecentSummaryServiceImpl summaryRepository;
@PostMapping("insert")
public ResultVO insert(@RequestParam(value = "type") Integer type,
@RequestParam(value = "area") String area,
@RequestParam(value = "count", required = false) Integer count,
@RequestParam(value = "money", required = false) Float money) {
ResultVO resultVO = new ResultVO();
RecentSummary recentSummary = new RecentSummary();
recentSummary.setType(type);
recentSummary.setArea(area);
if (count != null) {
recentSummary.setCount(count);
}
if (money != null) {
recentSummary.setMoney(new BigDecimal(money));
}
summaryRepository.save(recentSummary);
return resultVO;
}
}
|
package ru.zhanna.cells;
import javax.swing.*;
public class CellDefault extends JButton {
private int CellNum = 0;
public int getCellNum(){
return CellNum;
}
}
|
package exer2;
import java.util.Random;
public class Vote implements Runnable{
Random random = new Random();
int vote;
public Vote(int candidate){
vote = random.nextInt(candidate);
}
@Override
public void run() {
Machine.votes[vote]=Machine.votes[vote]+1;
}
}
|
package com.aarus.server;
import com.aarus.client.ChatClientIF;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
public class ChatServer extends UnicastRemoteObject implements ChatServerIF {
private static final long serialVersionUID = 1L;
private ArrayList<ChatClientIF> chatClients;
protected ChatServer() throws RemoteException {
chatClients = new ArrayList<ChatClientIF>();
}
@Override
public synchronized void registerChatClient(ChatClientIF chatClientIF) throws RemoteException {
this.chatClients.add(chatClientIF);
}
@Override
public synchronized void broadcastMessage(String message) throws RemoteException {
for(ChatClientIF client:chatClients)
{
client.retrieveMessage(message);
}
}
}
|
package com.qqq.stormy.model;
import com.google.gson.annotations.SerializedName;
import com.qqq.stormy.R;
public class Current {
@SerializedName("time")
private long mTimeInSeconds;
@SerializedName("summary")
private String mSummary;
@SerializedName("icon")
private String mIcon;
@SerializedName("precipProbability")
private double mPrecipProbability;
@SerializedName("temperature")
private double mTemperature;
@SerializedName("humidity")
private double mHumidity;
@SerializedName("windSpeed")
private double mWindSpeed;
private IconManager mIconManager;
public Current(long timeInSeconds, String summary, String icon, double precipProbability, double temperature, double humidity, double windSpeed) {
mTimeInSeconds = timeInSeconds;
mSummary = summary;
mIcon = icon;
mPrecipProbability = precipProbability;
mTemperature = temperature;
mHumidity = humidity;
mWindSpeed = windSpeed;
}
public int getTemperatureInCelsius() {
return (int) ((mTemperature - 32) * 5 / 9);
}
public int getIconId() {
// clear-day, clear-night, rain, snow, sleet, wind, fog, cloudy, partly-cloudy-day, or partly-cloudy-night
return mIconManager.getIconId(mIcon);
}
public long getTimeInSeconds() {
return mTimeInSeconds;
}
public void setTimeInSeconds(long timeInSeconds) {
mTimeInSeconds = timeInSeconds;
}
public String getSummary() {
return mSummary;
}
public void setSummary(String summary) {
mSummary = summary;
}
@Deprecated
public String getIcon() {
return mIcon;
}
public void setIcon(String icon) {
mIcon = icon;
}
public double getPrecipProbability() {
return mPrecipProbability;
}
public void setPrecipProbability(double precipProbability) {
mPrecipProbability = precipProbability;
}
/**
* @return temperature in Fahrenheit
*/
public double getTemperatureInFahrenheit() {
return mTemperature;
}
public void setTemperature(double temperature) {
mTemperature = temperature;
}
public double getHumidity() {
return mHumidity;
}
public void setHumidity(double humidity) {
mHumidity = humidity;
}
public double getWindSpeed() {
return mWindSpeed;
}
public void setWindSpeed(double windSpeed) {
mWindSpeed = windSpeed;
}
@Override
public String toString() {
return "Current{" +
"mTimeInSeconds=" + mTimeInSeconds +
", mSummary='" + mSummary + '\'' +
", mIcon='" + mIcon + '\'' +
", mPrecipProbability=" + mPrecipProbability +
", mTemperature=" + mTemperature +
", mHumidity=" + mHumidity +
", mWindSpeed=" + mWindSpeed +
", mIconManager=" + mIconManager +
'}';
}
}
|
package crawler.web;
import static spark.Spark.*;
import java.util.HashMap;
import java.util.Map;
import org.javalite.activejdbc.Base;
import crawler.model.Employee;
import spark.Request;
import spark.Response;
import spark.Route;
public class Crawler {
public static void main(String[] args) {
// setPort(5678); <- Uncomment this if you wan't spark to listen on a port different than 4567.
get(new RouteFreemarker("/") {
@Override
public Object handle(Request request, Response response) {
Base.open("com.mysql.jdbc.Driver", "jdbc:mysql://localhost:3306/test", "root", "root");
Employee e = new Employee();
e.set("first_name", "John");
e.set("last_name", "Doe");
e.saveIt();
Map<String,String> params = new HashMap<String,String>();
params.put("test", "Big Joe");
return render("main.html", params);
}
});
get(new RouteFreemarker("/run") {
@Override
public Object handle(Request request, Response response) {
Map<String,String> params = new HashMap<String,String>();
params.put("test", "Big Joe");
return render("main.html", params);
}
});
get(new Route("/users/:name") {
@Override
public Object handle(Request request, Response response) {
return "Selected user: " + request.params(":name");
}
});
get(new Route("/news/:section") {
@Override
public Object handle(Request request, Response response) {
response.type("text/xml");
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?><news>" + request.params("section") + "</news>";
}
});
get(new Route("/protected") {
@Override
public Object handle(Request request, Response response) {
halt(403, "I don't think so!!!");
return null;
}
});
get(new Route("/redirect") {
@Override
public Object handle(Request request, Response response) {
response.redirect("/news/world");
return null;
}
});
get(new Route("/") {
@Override
public Object handle(Request request, Response response) {
return "root";
}
});
}
} |
package com.generic.core.services.service;
import com.generic.rest.constants.SessionAttributes;
import com.generic.rest.dto.TransactionDto;
public interface TransactionServiceI {
String createTransaction(TransactionDto transactionDto, SessionAttributes sessionAttributes);
String updateTransaction(String txnId);
}
|
package com.dream.searchit;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.dream.searchit.models.Contact_info;
import static android.R.id.message;
/**
* A simple {@link Fragment} subclass.
*/
public class FirstFragment extends Fragment {
private TextView txt1;
private TextView txt2;
private TextView txt3;
private ImageView call;
private ImageView sms;
private Contact_info info;
public FirstFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View layout = inflater.inflate(R.layout.fragment_first, container, false);
txt1= (TextView) layout.findViewById(R.id.display_text_1);
txt2= (TextView) layout.findViewById(R.id.display_text_2);
txt3= (TextView) layout.findViewById(R.id.display_text_3);
call= (ImageView) layout.findViewById(R.id.phone_call);
sms= (ImageView) layout.findViewById(R.id.send_sms);
Intent i = getActivity().getIntent(); // in case of fragment, write getactivity.getintent to call data from activity!!
info= (Contact_info) i.getSerializableExtra("Name");
String name = info.getName().toString();
final String num = info.getNumber().toString();
String add = info.getAddress();
txt1.setText(name);
txt2.setText(num);
txt3.setText(add);
call.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:"+num));
startActivity(intent);
}
});
sms.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.setData(Uri.parse("sms:" +num));
startActivity(sendIntent);
}
});
return layout;
}
}
|
package com.ebanq.web.pageobjects.transfers;
import com.codeborne.selenide.Condition;
import com.ebanq.web.elements.EbanqAccountSelect;
import com.ebanq.web.elements.EbanqInput;
import com.ebanq.web.pageobjects.BasePage;
import org.openqa.selenium.By;
import static com.codeborne.selenide.Selenide.$;
public class TransferBetweenAccountsPage extends BasePage {
private final String ACTIVE_TRANSFER_BETWEEN_ACCOUNTS_PAGE_CSS = "app-user-tba > .content";
private final String ACCOUNT_AMOUNT_XPATH = "//span[contains(text(), '%s')]/parent::div/span[@class='bottom-hint']";
private final String CONTINUE_BUTTON_XPATH = "//*[contains(text(), 'Continue')]";
private final String CONFIRM_BUTTON_XPATH = "//*[contains(text(), 'Confirm')]";
@Override
public TransferBetweenAccountsPage isPageOpened() {
$(ACTIVE_TRANSFER_BETWEEN_ACCOUNTS_PAGE_CSS).shouldBe(Condition.visible);
return this;
}
public TransferBetweenAccountsPage fillRequiredFields(String debitFromAccountNumber, String creditToAccountNumber, double transferAmount) {
new EbanqInput("Amount to transfer *")
.write(transferAmount);
new EbanqAccountSelect("Debit from")
.selectValue(debitFromAccountNumber);
new EbanqAccountSelect("Credit to")
.selectValue(creditToAccountNumber);
return this;
}
private String getAccountAmountInfo(String accountNumber) {
return $(By.xpath(String.format(ACCOUNT_AMOUNT_XPATH, accountNumber))).getText();
}
public String getAccountAmount(String accountNumber) {
return getAccountAmountInfo(accountNumber).replaceAll("[^\\,-\\.\\d]", "");
}
public String getAccountCurrency(String accountNumber) {
return getAccountAmountInfo(accountNumber).replaceAll("[^\\s]", "");
}
public TransferBetweenAccountsPage clickContinueButton() {
$(By.xpath(CONTINUE_BUTTON_XPATH)).click();
return this;
}
public TransferBetweenAccountsPage clickConfirmButton() {
$(By.xpath(CONFIRM_BUTTON_XPATH)).click();
return this;
}
} |
import java.util.ArrayList;
public class Flixnet {
private static ArrayList<Members> allMembers;
private static ArrayList<Ratings> rate;
private static ArrayList<Films> movies;
private String loggedin;
public Flixnet() {
allMembers = new ArrayList<Members>();
rate = new ArrayList<Ratings>();
movies = new ArrayList<Films>();
}
public ArrayList<Members> getAllMembers() {
return allMembers;
}
//public void setPlayers(ArrayList<Members> members) {
//members = new ArrayList<Members>();
//}
public void setlogged(String loggedin)
{
this.loggedin = loggedin;
}
public String getloggedin()
{
return loggedin;
}
public void listFilms(){
int i = 0;
for (i = 0; i < movies.size(); i++) {
StdOut.println(i + ":" + movies.get(i));
}
}
public void listMembers() {
int i = 0;
for (i = 0; i < allMembers.size(); i++) {
StdOut.println(i + ":" + allMembers.get(i));
}
}
public void listRatings(){
int i = 0;
for (i = 0; i < rate.size(); i++){
StdOut.println(i + ":" + rate.get(i));
}
}
public void editMember() {
listMembers();
StdOut.print("PLease enter the index number of the staff member you wish to edit ==>");
int index = StdIn.readInt();
Members members = allMembers.get(index);
StdOut.print("Enter new Username: ");
String newUsername = StdIn.readString();
members.setUsername(newUsername);
StdOut.print("Enter new First Name: ");
String newFirstName = StdIn.readString();
members.setFirstName(newFirstName);
StdOut.print("Enter new Surname: ");
String newSurname = StdIn.readString();
members.setSurname(newSurname);
StdOut.print("Enter new Password: ");
String newPassword = StdIn.readString();
members.setPassword(newPassword);
saveMembers();
}
public void deleteMember() {
listMembers();
StdOut.print("Please enter the index number of the Member you wish to delete ==>");
int index = StdIn.readInt();
if (index >= 0 && index < allMembers.size())
allMembers.remove(index);
saveMembers();
}
public void deleteFilm() {
listFilms();
StdOut.print("Please enter the index number of the Film you wish to delete ==>");
int index = StdIn.readInt();
if (index >= 0 && index < movies.size())
movies.remove(index);
saveFilms();
}
public void editFilm()
{
listFilms();
StdOut.print("Select Film Position To Edit");
int index = StdIn.readInt();
Films films = movies.get(index);
StdOut.print("Enter new ID: ");
String newID = StdIn.readString();
films.setID(newID);
StdOut.print("Enter new title: ");
String newTitle = StdIn.readString();
films.setTitle(newTitle);
StdOut.print("Enter new year: ");
String newYear = StdIn.readString();
films.setYear(newYear);
StdOut.print("Enter new genre: ");
String newGenre = StdIn.readString();
films.setGenre(newGenre);
saveFilms();
}
public static void loadMembers() {
In in= new In("members.csv");
String delims= "[,]";
while(!in.isEmpty()) {
String[] data= in.readLine().split(delims);
Members members= new Members(data[0], data[1], data[2], data [3]);
allMembers.add(members);
}
in.close();
}
public static void saveMembers(){
Out out = new Out("members.csv");
for (Members member:allMembers){
out.println(member.membersCsvfile());
}
out.close();
}
public static void loadFilms() {
In in = new In("films.csv");
String delims = "[,]";
while(!in.isEmpty()) {
String[] data = in.readLine().split(delims);
Films films = new Films(data[0], data[1], data[2], data[3]);
movies.add(films);
}
in.close();
}
public static void saveFilms(){
Out out = new Out("films.csv");
for (Films film:movies){
out.println(film.filmsCsvfile());
}
out.close();
}
private void addMember() {
StdOut.print("Please Choose a Username : ");
String username = StdIn.readString();
StdOut.print("Please Enter Your First Name : ");
String firstName = StdIn.readString();
StdOut.print("Please Enter Your Surname: ");
String surname = StdIn.readString();
StdOut.print("Please Choose a Password : ");
String password = StdIn.readString();
Members member = new Members(username, firstName, surname, password);
allMembers.add(member);
saveMembers();
}
public void addFilm()
{
StdOut.print("Enter a Film ID:");
String ID = StdIn.readString();
StdOut.print("Enter the Film Name:");
String title = StdIn.readString();
StdOut.print("Enter the year of the Film:");
String year = StdIn.readString();
StdOut.print("Enter the Genre of the Film: ");
String genre = StdIn.readString();
Films films = new Films(ID, title, year, genre);
movies.add(films);
saveFilms();
}
public static void main(String[] argvs) {
Flixnet app = new Flixnet();
loadMembers();
//loadRatings();
loadFilms();
app.run();
}
private int mainMenu() {
StdOut.println("WELCOME TO FLIXNET");
StdOut.println("------------------");
StdOut.println(" 1) LOG IN");
StdOut.println(" 2) REGISTER FOR NEW ACCOUNT");
StdOut.println(" 3) STAFF");
StdOut.println("-----------------------------");
StdOut.println("0) Exit");
StdOut.print("==>>");
int option = StdIn.readInt();
return option;
}
private int userMenu() {
StdOut.println("WELCOME" + " " + loggedin);
StdOut.println("------------------");
StdOut.println(" 1) Show Account Details");
StdOut.println("0) Log Out");
StdOut.print("==>>");
int option = StdIn.readInt();
return option;
}
private int staffMenu() {
StdOut.println("STAFF MENU");
StdOut.println("------------------");
StdOut.println(" 1) Staff Movies Options");
StdOut.println(" 2) Staff Members Options");
StdOut.println("0) Exit");
StdOut.print("==>>");
int option = StdIn.readInt();
return option;
}
private void run() {
int option = mainMenu();
while (option != 0) {
switch (option) {
case 1:
userLogIn();
break;
case 2:
addMember();
break;
case 3:
staffMenuOptions();
break;
}
option = mainMenu();
}
StdOut.println("Exiting... bye");
}
public void listMovieYear(){
System.out.println("Enter a year: ");
String inputYear = StdIn.readString();
for (Films film: movies){
if((inputYear.equals(film.getYear())))
{
System.out.println(film);
}
}
}
public void loggedInDetails(){
for (Members member: allMembers){
if (this.loggedin.equals(member.getUsername()))
{
System.out.println(member);
}
}
}
public void userLogIn(){
boolean isMember = false;
System.out.println("Enter username: ");
String inputUsername = StdIn.readString();
System.out.println("Enter password: ");
String inputPassword = StdIn.readString();
for (Members member: allMembers){
isMember = false;
if((inputUsername.equals(member.getUsername())) && (inputPassword.equals(member.getPassword())))
{
this.loggedin=member.username;
userMenuOptions();
isMember= true;
}
}
if(!isMember)
isMember = false;
StdOut.println("Login error. Try Again");
}
private void staffMenuOptions() {
int option = staffMenu();
while (option != 0) {
switch (option) {
case 1:
staffFilmOptions();
break;
case 2:
staffMembersOptions();
break;
}
option = staffMenu();
}
StdOut.println("Exiting... bye");
}
private int staffFilmsMenu() {
StdOut.println("STAFF FILM OPTIONS");
StdOut.println("------------------");
StdOut.println(" 1) List all Films");
StdOut.println(" 2) Add a Film");
StdOut.println(" 3) Edit a Film");
StdOut.println(" 4) Delete a Film");
StdOut.println(" 5) Return to Staff Main Menu");
StdOut.println("0) Exit");
StdOut.print("==>>");
int option = StdIn.readInt();
return option;
}
private void staffFilmOptions() {
int option = staffFilmsMenu();
while (option != 0) {
switch (option) {
case 1:
listFilms();
break;
case 2:
addFilm();
break;
case 3:
editFilm();
break;
case 4:
deleteFilm();
break;
case 5:
staffMenuOptions();
break;
}
option = staffFilmsMenu();
}
}
private int staffMembersMenu() {
StdOut.println("MEMBERS MENU FOR STAFF");
StdOut.println("------------------");
StdOut.println(" 1) List all Members");
StdOut.println(" 2) Add a Member");
StdOut.println(" 3) Edit a Member");
StdOut.println(" 4) Delete a Member");
StdOut.println(" 5) Return to Staff Main Menu");
StdOut.println("0) Exit");
StdOut.print("==>>");
int option = StdIn.readInt();
return option;
}
private void staffMembersOptions() {
int option = staffMembersMenu();
while (option != 0) {
switch (option) {
case 1:
listMembers();
break;
case 2:
addMember();
break;
case 3:
editMember();
break;
case 4:
deleteMember();
break;
case 5:
staffMenuOptions();
break;
}
option = staffMembersMenu();
}
}
private void userMenuOptions() {
int option = userMenu();
while (option != 0) {
switch (option) {
case 1:
loggedInDetails();
break;
case 2:
break;
case 3:
editFilm();
break;
case 4:
listMovieYear();
break;
case 5:
listMembers();
break;
case 6:
break;
}
option = userMenu();
}
StdOut.println("Logged Out");
}
}
|
package com.web3.scph.po;
public class Transaction {
private int id;
private long blockNumer;
private String blockHash;
private String blockTimestamp;
private String transactionHash;
private String fromAccount;
private String toAccount;
private double transValue;
private double tranGasPrice;
private int tranGasAmount;
private int tranNonce;
public double getTransValue() {
return transValue;
}
public void setTransValue(double transValue) {
this.transValue = transValue;
}
public double getTranGasPrice() {
return tranGasPrice;
}
public void setTranGasPrice(double tranGasPrice) {
this.tranGasPrice = tranGasPrice;
}
public int getTranGasAmount() {
return tranGasAmount;
}
public void setTranGasAmount(int tranGasAmount) {
this.tranGasAmount = tranGasAmount;
}
public int getTranNonce() {
return tranNonce;
}
public void setTranNonce(int tranNonce) {
this.tranNonce = tranNonce;
}
public void setId(int id) {
this.id = id;
}
public void setBlockNumer(long blockNumer) {
this.blockNumer = blockNumer;
}
public void setBlockHash(String blockHash) {
this.blockHash = blockHash;
}
public void setBlockTimestamp(String blockTimestamp) {
this.blockTimestamp = blockTimestamp;
}
public void setTransactionHash(String transactionHash) {
this.transactionHash = transactionHash;
}
public void setFromAccount(String fromAccount) {
this.fromAccount = fromAccount;
}
public int getId() {
return id;
}
public long getBlockNumer() {
return blockNumer;
}
public String getBlockHash() {
return blockHash;
}
public String getBlockTimestamp() {
return blockTimestamp;
}
public String getTransactionHash() {
return transactionHash;
}
public String getFromAccount() {
return fromAccount;
}
public void setToAccount(String toAccount) {
this.toAccount = toAccount;
}
public String getToAccount() {
return toAccount;
}
}
|
package com.staniul.teamspeak.commands.core;
import com.staniul.xmlconfig.convert.StringToIntegerSetConverter;
import com.staniul.xmlconfig.annotations.ConfigField;
import java.util.Set;
public class Scope {
private int id;
@ConfigField(value = "groups", converter = StringToIntegerSetConverter.class)
private Set<Integer> groups;
public Scope() {
}
public Scope(int id, Set<Integer> groups) {
this.id = id;
this.groups = groups;
}
public int getId() {
return id;
}
public Set<Integer> getGroups() {
return groups;
}
}
|
package com.example.daniel.podcastplayer.download;
import android.support.v7.widget.RecyclerView;
import com.example.daniel.podcastplayer.data.Episode;
import com.example.daniel.podcastplayer.data.Podcast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
public class ResultParser {
private static ResultParser instance = new ResultParser();
private String desc;
private ResultParser(){}
public static ResultParser getInstance(){ return instance; }
public List<Podcast> parseSearch(String json, RecyclerView rv){
List<Podcast> result = new ArrayList<>();
try {
JSONObject parentObject = new JSONObject(json);
JSONArray resultArray = parentObject.getJSONArray("results");
for (int i = 0 ; i < resultArray.length(); i++)
result.add(new Podcast(resultArray.getJSONObject(i),rv));
}
catch(JSONException je) { je.printStackTrace(); }
return result;
}
public List<Podcast> parseTopCategory(InputStream is, RecyclerView rv){
final List<Podcast> result = new ArrayList<>();
try{
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document d = builder.parse(is);
NodeList items = d.getElementsByTagName("entry");
for (int i = 0 ; i < items.getLength(); i++){
Element p = (Element)items.item(i);
result.add(new Podcast(p, rv));
//Downloader.OnPodcastParsedReceiver receiver = new Downloader.OnPodcastParsedReceiver() {
//@Override
//public void receivePodcasts(List<Podcast> podcast) {
// if (podcast.size()>0)
// result.add(podcast.get(0));
//}
//};
//Downloader.parsePodcasts(p.getElementsByTagName("title").item(0).getTextContent().replace(' ','+')
// ,rv,receiver);
}
} catch (Exception e){ e.printStackTrace(); }
return result;
}
public List<Episode> parseFeed(InputStream is, int podcastId){
return parseFeed(is, Integer.MAX_VALUE, podcastId);
}
private List<Episode> parseFeed(InputStream is, int limit, int podcastId){
List<Episode> result = new ArrayList<>();
try{
if (is != null){
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document d = builder.parse(is);
//Get podcast description from RSS
NodeList descList = d.getElementsByTagName("description");
if (descList.getLength() > 0)
desc = descList.item(0).getTextContent();
//Parse episodes from RSS
NodeList episodes = d.getElementsByTagName("item");
for (int i = 0; i < episodes.getLength(); i++) {
Episode e = new Episode(podcastId);
Element n = (Element) episodes.item(i);
e.setEpTitle(n.getElementsByTagName("title").item(0).getTextContent());
e.setEpDate(getDate(n.getElementsByTagName("pubDate").item(0).getTextContent()));
if (n.getElementsByTagName("itunes:duration").item(0) != null)
e.setLength(getMiliseconds(n.getElementsByTagName("itunes:duration").item(0).getTextContent()));
else
e.setLength(getMiliseconds("0:00"));
if (n.getElementsByTagName("description").item(0) != null)
e.setDescription(n.getElementsByTagName("description").item(0).getTextContent());
else
if (n.getElementsByTagName("itunes:summary").item(0) != null)
e.setDescription(n.getElementsByTagName("itunes:summary").item(0).getTextContent());
Element url = (Element) n.getElementsByTagName("enclosure").item(0);
//e.setLength(Integer.valueOf(url.getAttribute("length")));
e.setEpURL(url.getAttribute("url"));
if (url.getAttribute("type").matches("audio/(.*)"))
result.add(e);
if (result.size() == limit) break;
}
}
} catch (Exception e) { e.printStackTrace();}
return result;
}
private int getMiliseconds(String duration){
int result = 0;
if (duration.indexOf(':') > 0) {
int timeComponents = (duration.length() > 5) ? 2 : 1; //it can come as 2(mins):30(secs)
for (int i = timeComponents; i >= 0; i--) {
result = result + getTimeComponent(duration) * (int) Math.pow(60, i);
duration = duration.substring(duration.indexOf(':') + 1);
}
} else result = Integer.valueOf(duration); //ya viene en segundos la duracion
return result * 1000;
}
//get either hour, minute or second, adding until finding a :
private int getTimeComponent(String time){
int index = 0;
StringBuilder aux = new StringBuilder();
while (index < time.length() && time.charAt(index)!=':'){
aux.append(time.charAt(index));
index++;
}
return Integer.parseInt(aux.toString());
}
public String getDesc() {
return desc;
}
//Remove the timezone data and hour
private String getDate(String pubDate){
int index = pubDate.length() - 1;
int ammount = 2;
while (ammount > 0){
index--;
if (pubDate.charAt(index)==' ')
ammount = ammount - 1;
}
String result = pubDate.substring(5,index);//.replace(' ','-');
SimpleDateFormat ogFormat = new SimpleDateFormat("dd MMM yyyy", Locale.US);
Date d = null;
try{
d = ogFormat.parse(result);
} catch(ParseException e){ e.printStackTrace(); }
SimpleDateFormat dbFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
return dbFormat.format(d);
}
}
|
package kamil;
import javax.script.ScriptException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Calc {
public static void main(String[] args) throws ScriptException {
JFrame frame = new JFrame();
frame.setSize(200, 300);
frame.setLocation(250, 250);
frame.setVisible(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField tf = new JTextField();
tf.setBounds(10, 10, 170, 30);
frame.setLayout(null);
frame.add(tf);
tf.setHorizontalAlignment(JTextField.RIGHT);
JButton button7 = new JButton("7");
button7.setBounds(10, 50, 30, 40);
frame.add(button7);
button7.setBorder(null);
button7.addActionListener(new ButtonTextActionListener(tf, "7"));
JButton but2 = new JButton("8");
but2.setBounds(50, 50, 30, 40);
frame.add(but2);
but2.setBorder(null);
but2.addActionListener(new ButtonTextActionListener(tf, "8"));
JButton but3 = new JButton("9");
but3.setBounds(90, 50, 30, 40);
frame.add(but3);
but3.setBorder(null);
but3.addActionListener(new ButtonTextActionListener(tf, "9"));
JButton but4 = new JButton("4");
but4.setBounds(130, 50, 30, 40);
frame.add(but4);
but4.setBorder(null);
but4.addActionListener(new ButtonTextActionListener(tf, "4"));
JButton but5 = new JButton("5");
but5.setBounds(10, 90, 30, 40);
frame.add(but5);
but5.setBorder(null);
but5.addActionListener(new ButtonTextActionListener(tf, "5"));
JButton but6 = new JButton("6");
but6.setBounds(50, 90, 30, 40);
frame.add(but6);
but6.setBorder(null);
but6.addActionListener(new ButtonTextActionListener(tf, "6"));
JButton but7 = new JButton("1");
but7.setBounds(90, 90, 30, 40);
frame.add(but7);
but7.setBorder(null);
but7.addActionListener(new ButtonTextActionListener(tf, "1"));
JButton but8 = new JButton("2");
but8.setBounds(130, 90, 30, 40);
frame.add(but8);
but8.setBorder(null);
but8.addActionListener(new ButtonTextActionListener(tf, "2"));
JButton but9 = new JButton("3");
but9.setBounds(10, 130, 30, 40);
frame.add(but9);
but9.setBorder(null);
but9.addActionListener(new ButtonTextActionListener(tf, "3"));
JButton but0 = new JButton("0");
but0.setBounds(50, 130, 30, 40);
frame.add(but0);
but0.setBorder(null);
but0.addActionListener(new ButtonTextActionListener(tf, "0"));
JButton butAdd = new JButton("+");
butAdd.setBounds(90, 130, 40, 80);
frame.add(butAdd);
butAdd.setBorder(null);
butAdd.addActionListener(new ButtonTextActionListener(tf, "+"));
JButton butSub = new JButton("-");
butSub.setBounds(135, 130, 40, 80);
frame.add(butSub);
butSub.setBorder(null);
butSub.addActionListener(new ButtonTextActionListener(tf, "-"));
JButton butmulti = new JButton("*");
butmulti.setBounds(90, 215, 40, 60);
frame.add(butmulti);
butmulti.setBorder(null);
butmulti.addActionListener(new ButtonTextActionListener(tf, "*"));
JButton butdiv = new JButton("/");
butdiv.setBounds(135, 215, 40, 60);
frame.add(butdiv);
butdiv.setBorder(null);
butdiv.addActionListener(new ButtonTextActionListener(tf, "/"));
JButton buteq = new JButton("=");
buteq.setBounds(5, 180, 75, 88);
frame.add(buteq);
buteq.setBorder(null);
buteq.addActionListener(new ButtonEqualActionListener(tf));
}
}
|
package edu.umich.dpm.sensorgrabber.data;
import android.os.Build;
import android.os.Environment;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import edu.umich.dpm.sensorgrabber.sensor.SensorQueue;
import edu.umich.dpm.sensorgrabber.sensor.SensorReading;
public class FileHandler {
private static final String TAG = "FileHandler";
private static final String SUB_DIRECTORY = "SensorGrabber";
private static final String EXTENSION = "csv";
private static final String STORAGE_DIRECTORY =
(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ?
Environment.DIRECTORY_DOCUMENTS : Environment.DIRECTORY_DCIM);
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("h:mm:ss.SSS a");
private final BufferedWriter mWriter;
private final Date mStartTime;
private long mFirstSensorTimestamp = -1;
public FileHandler(String filename, Date startTime) throws IOException {
String state = Environment.getExternalStorageState();
if (!state.equals(Environment.MEDIA_MOUNTED)) {
throw new IOException("External storage is not mounted");
}
File root = new File(Environment.getExternalStoragePublicDirectory(STORAGE_DIRECTORY), SUB_DIRECTORY);
if (!root.exists()) {
if (!root.mkdirs()) {
throw new FileNotFoundException("Unable to create directory \"" + SUB_DIRECTORY + "\" in \"" + STORAGE_DIRECTORY + "\"");
}
}
File file = new File(root, filename + "." + EXTENSION);
mWriter = new BufferedWriter(new FileWriter(file, true));
mStartTime = startTime;
}
public void writeQueue(SensorQueue queue) throws IOException {
SensorReading[] readings = queue.getReadings();
if (mFirstSensorTimestamp < 0 && readings.length > 0) {
mFirstSensorTimestamp = readings[0].getTimestamp();
}
for (SensorReading r : readings) {
writeLine(r);
}
}
private void writeLine(SensorReading reading) throws IOException {
long timeFromStart = (reading.getTimestamp() - mFirstSensorTimestamp) / 1000000;
mWriter.write(String.valueOf(timeFromStart));
mWriter.write(44);
mWriter.write(DATE_FORMAT.format(mStartTime.getTime() + timeFromStart));
mWriter.write(44);
mWriter.write(String.valueOf(reading.getAccuracy()));
for (float value : reading.getValues()) {
mWriter.write(44);
mWriter.write(String.valueOf(value));
}
mWriter.write(10);
}
public void close() {
try {
mWriter.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import org.springframework.lang.Nullable;
import org.springframework.util.ClassUtils;
/**
* A common delegate for detecting Kotlin's presence and for identifying Kotlin types.
*
* @author Juergen Hoeller
* @author Sebastien Deleuze
* @since 5.0
*/
@SuppressWarnings("unchecked")
public abstract class KotlinDetector {
@Nullable
private static final Class<? extends Annotation> kotlinMetadata;
// For ConstantFieldFeature compliance, otherwise could be deduced from kotlinMetadata
private static final boolean kotlinPresent;
private static final boolean kotlinReflectPresent;
static {
Class<?> metadata;
ClassLoader classLoader = KotlinDetector.class.getClassLoader();
try {
metadata = ClassUtils.forName("kotlin.Metadata", classLoader);
}
catch (ClassNotFoundException ex) {
// Kotlin API not available - no Kotlin support
metadata = null;
}
kotlinMetadata = (Class<? extends Annotation>) metadata;
kotlinPresent = (kotlinMetadata != null);
kotlinReflectPresent = ClassUtils.isPresent("kotlin.reflect.full.KClasses", classLoader);
}
/**
* Determine whether Kotlin is present in general.
*/
public static boolean isKotlinPresent() {
return kotlinPresent;
}
/**
* Determine whether Kotlin reflection is present.
* @since 5.1
*/
public static boolean isKotlinReflectPresent() {
return kotlinReflectPresent;
}
/**
* Determine whether the given {@code Class} is a Kotlin type
* (with Kotlin metadata present on it).
*/
public static boolean isKotlinType(Class<?> clazz) {
return (kotlinMetadata != null && clazz.getDeclaredAnnotation(kotlinMetadata) != null);
}
/**
* Return {@code true} if the method is a suspending function.
* @since 5.3
*/
public static boolean isSuspendingFunction(Method method) {
if (KotlinDetector.isKotlinType(method.getDeclaringClass())) {
Class<?>[] types = method.getParameterTypes();
if (types.length > 0 && "kotlin.coroutines.Continuation".equals(types[types.length - 1].getName())) {
return true;
}
}
return false;
}
}
|
package com.exam.logic.actions.chats;
import com.exam.logic.Action;
import com.exam.logic.services.ChatService;
import com.exam.models.Message;
import com.exam.models.User;
import lombok.SneakyThrows;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Optional;
import static com.exam.logic.Constants.*;
public class SendMessageAction implements Action {
@Override
@SneakyThrows
public String execute(HttpServletRequest request, HttpServletResponse response) {
Long chatID = Optional.ofNullable(request.getParameter("chat_id"))
.map(Long::parseLong)
.orElseThrow(() -> new RuntimeException("Invalid chat id"));
String text = Optional.ofNullable(request.getParameter("text"))
.filter(s -> s.length() > 0)
.orElse("(Empty message)");
ChatService chatService = (ChatService) request.getServletContext().getAttribute(CHAT_SERVICE);
HttpSession session = request.getSession();
User currentUser = (User) session.getAttribute(CURRENT_USER);
Message message = Message.builder()
.senderID(currentUser.getId())
.chatID(chatID)
.text(text)
.sendingTime(ZonedDateTime.ofInstant(Instant.now(),ZoneId.of("UTC")))
.build();
chatService.sendMessage(message);
String referer = request.getHeader("referer");
response.sendRedirect(referer != null ? referer : request.getContextPath());
return null;
}
} |
package com.fanfte.netty.im.packet.response;
import com.fanfte.netty.im.message.Packet;
import lombok.Data;
import static com.fanfte.netty.im.message.Command.QUIT_GROUP_RESPONSE;
/**
* Created by tianen on 2018/10/8
*
* @author fanfte
* @date 2018/10/8
**/
@Data
public class QuitGroupResponsePacket extends Packet {
private String reason;
private boolean success;
private String groupId;
@Override
public Byte getCommand() {
return QUIT_GROUP_RESPONSE;
}
}
|
package com.familytreeservice.familytreeservice.business;
import java.util.HashMap;
import java.util.Map;
import com.familytreeservice.familytreeservice.business.interfaces.AuthenticationBusinessLogic;
import com.familytreeservice.familytreeservice.dao.interfaces.UserDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class AuthenticationBusinessLogicImpl implements AuthenticationBusinessLogic{
private Map<String,String> userStore;
@Autowired
private UserDAO userDAO;
//private Logger logger = LoggerFactory.getLogger(AuthenticationBusinessLogicImpl.class);
public AuthenticationBusinessLogicImpl (){
this.userStore = new HashMap<>();
this.userStore.put("Admin", "password");
this.userStore.put("azul13", "123ABC890XYZ");
}
@Override
public boolean authenticate(String username, String password) {
// TODO Auto-generated method stub
//logger.info("Username: {} Password: {}", username, password);
return userDAO.isValid(username, password);
}
} |
import java.util.Scanner;
import java.lang.Math;
public class Lesson_13_Activity_Five {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
int range = 12;
int min = 1;
double x = Math.random();
int xTwo = (int)(x*range)+min;
double y = Math.random();
int yTwo = (int)(y*range)+min;
System.out.println(xTwo);
System.out.println(yTwo);
int z = xTwo*yTwo;
System.out.println("Input multiplication of the two numbers.");
int response = scan.nextInt();
if(response == z){
System.out.println("Correct!");
}
else {
System.out.println("Wrong");
}
}
}
|
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans.factory;
/**
* Extension of the {@link FactoryBean} interface. Implementations may
* indicate whether they always return independent instances, for the
* case where their {@link #isSingleton()} implementation returning
* {@code false} does not clearly indicate independent instances.
*
* <p>Plain {@link FactoryBean} implementations which do not implement
* this extended interface are simply assumed to always return independent
* instances if their {@link #isSingleton()} implementation returns
* {@code false}; the exposed object is only accessed on demand.
*
* <p><b>NOTE:</b> This interface is a special purpose interface, mainly for
* internal use within the framework and within collaborating frameworks.
* In general, application-provided FactoryBeans should simply implement
* the plain {@link FactoryBean} interface. New methods might be added
* to this extended interface even in point releases.
*
* @author Juergen Hoeller
* @since 2.0.3
* @param <T> the bean type
* @see #isPrototype()
* @see #isSingleton()
*/
public interface SmartFactoryBean<T> extends FactoryBean<T> {
/**
* Is the object managed by this factory a prototype? That is,
* will {@link #getObject()} always return an independent instance?
* <p>The prototype status of the FactoryBean itself will generally
* be provided by the owning {@link BeanFactory}; usually, it has to be
* defined as singleton there.
* <p>This method is supposed to strictly check for independent instances;
* it should not return {@code true} for scoped objects or other
* kinds of non-singleton, non-independent objects. For this reason,
* this is not simply the inverted form of {@link #isSingleton()}.
* <p>The default implementation returns {@code false}.
* @return whether the exposed object is a prototype
* @see #getObject()
* @see #isSingleton()
*/
default boolean isPrototype() {
return false;
}
/**
* Does this FactoryBean expect eager initialization, that is,
* eagerly initialize itself as well as expect eager initialization
* of its singleton object (if any)?
* <p>A standard FactoryBean is not expected to initialize eagerly:
* Its {@link #getObject()} will only be called for actual access, even
* in case of a singleton object. Returning {@code true} from this
* method suggests that {@link #getObject()} should be called eagerly,
* also applying post-processors eagerly. This may make sense in case
* of a {@link #isSingleton() singleton} object, in particular if
* post-processors expect to be applied on startup.
* <p>The default implementation returns {@code false}.
* @return whether eager initialization applies
* @see org.springframework.beans.factory.config.ConfigurableListableBeanFactory#preInstantiateSingletons()
*/
default boolean isEagerInit() {
return false;
}
}
|
package aaa.assignment2.algorithms;
import aaa.*;
import aaa.assignment2.StateActionPair;
public class Sarsa extends ModelFreeAlgorithm
{
public Sarsa(State env, float alpha, float gamma, float epsilon, float valueInitial)
{
Agent prey = new PreySimple();
Agent predator = new PredatorRandom();
super.valueInitial = valueInitial;
super.env = env;
for (int i = 0; i < NUM_EPISODES; i++)
{
State s = (State) env.clone();
int action = epsilonGreedy(s, epsilon);
while (!s.isFinal())
{
State sPrime = (State) s.clone();
sPrime.move(predator, action);
sPrime.move(prey);
int actionPrime = epsilonGreedy(sPrime, epsilon);
// Q-value update:
StateActionPair sa = new StateActionPair(s, action);
StateActionPair saPrime = new StateActionPair(sPrime, actionPrime);
float R = sPrime.isFinal() ? 10 : gamma * Q.get(saPrime);
float oldQ = Q.get(sa);
float newQ = oldQ + alpha * (R - oldQ);
Q.put(sa, newQ);
s = sPrime;
action = actionPrime;
}
}
}
}
|
package slimeknights.tconstruct.library.events;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.eventhandler.Cancelable;
import slimeknights.tconstruct.library.tools.ToolCore;
import slimeknights.tconstruct.library.tools.ranged.BowCore;
public abstract class TinkerToolEvent extends TinkerEvent {
public final ItemStack itemStack;
public final ToolCore tool;
public TinkerToolEvent(ItemStack itemStack) {
this.itemStack = itemStack;
this.tool = (ToolCore) itemStack.getItem();
}
@Cancelable
public static class ExtraBlockBreak extends TinkerToolEvent {
public final EntityPlayer player;
public final IBlockState state;
public int width;
public int height;
public int depth;
public int distance;
public ExtraBlockBreak(ItemStack itemStack, EntityPlayer player, IBlockState state) {
super(itemStack);
this.player = player;
this.state = state;
}
public static ExtraBlockBreak fireEvent(ItemStack itemStack, EntityPlayer player, IBlockState state, int width, int height, int depth, int distance) {
ExtraBlockBreak event = new ExtraBlockBreak(itemStack, player, state);
event.width = width;
event.height = height;
event.depth = depth;
event.distance = distance;
MinecraftForge.EVENT_BUS.post(event);
return event;
}
}
public static class OnRepair extends TinkerToolEvent {
public final int amount;
public OnRepair(ItemStack itemStack, int amount) {
super(itemStack);
this.amount = amount;
}
public static boolean fireEvent(ItemStack itemStack, int amount) {
OnRepair event = new OnRepair(itemStack, amount);
return !MinecraftForge.EVENT_BUS.post(event);
}
}
public static class OnMattockHoe extends TinkerToolEvent {
public final BlockPos pos;
public final World world;
public final EntityPlayer player;
public OnMattockHoe(ItemStack itemStack, EntityPlayer player, World world, BlockPos pos) {
super(itemStack);
this.player = player;
this.pos = pos;
this.world = world;
}
public static void fireEvent(ItemStack itemStack, EntityPlayer player, World world, BlockPos pos) {
MinecraftForge.EVENT_BUS.post(new OnMattockHoe(itemStack, player, world, pos));
}
}
public static class OnShovelMakePath extends TinkerToolEvent {
public final BlockPos pos;
public final EntityPlayer player;
public final World world;
public OnShovelMakePath(ItemStack itemStack, EntityPlayer player, World world, BlockPos pos) {
super(itemStack);
this.pos = pos;
this.player = player;
this.world = world;
}
public static void fireEvent(ItemStack itemStack, EntityPlayer player, World world, BlockPos pos) {
MinecraftForge.EVENT_BUS.post(new OnShovelMakePath(itemStack, player, world, pos));
}
}
/**
* Cancel event to indicate that the block is not harvestable.
* Leave the Result on DEFAUT to tell the Scythe to harvest the block, if it's harvestable
* Set the Result to ALLOW to tell the Scythe that the block is harvestable, even if the check says it's not
* Set the Result to DENY to let the Scythe know you handled the stuff (= harvest was successful, but not handled by the scythe)
*/
@HasResult
@Cancelable
public static class OnScytheHarvest extends TinkerToolEvent {
public final BlockPos pos;
public final EntityPlayer player;
public final IBlockState blockState;
public final World world;
public final boolean harvestable;
public OnScytheHarvest(ItemStack itemStack, EntityPlayer player, World world, BlockPos pos, IBlockState blockState, boolean harvestable) {
super(itemStack);
this.pos = pos;
this.player = player;
this.world = world;
this.blockState = blockState;
this.harvestable = harvestable;
}
public static OnScytheHarvest fireEvent(ItemStack itemStack, EntityPlayer player, World world, BlockPos pos, IBlockState blockState, boolean harvestable) {
OnScytheHarvest event = new OnScytheHarvest(itemStack, player, world, pos, blockState, harvestable);
MinecraftForge.EVENT_BUS.post(event);
return event;
}
}
public static class OnBowShoot extends TinkerToolEvent {
public final EntityPlayer entityPlayer;
public final BowCore bowCore;
public final ItemStack ammo;
public final int useTime;
private float baseInaccuracy;
public int projectileCount = 1;
public boolean consumeAmmoPerProjectile = true;
public boolean consumeDurabilityPerProjectile = true;
public float bonusInaccuracy = 0;
public OnBowShoot(ItemStack bow, ItemStack ammo, EntityPlayer entityPlayer, int useTime, float baseInaccuracy) {
super(bow);
this.bowCore = (BowCore) bow.getItem();
this.ammo = ammo;
this.entityPlayer = entityPlayer;
this.useTime = useTime;
this.baseInaccuracy = baseInaccuracy;
}
public static OnBowShoot fireEvent(ItemStack bow, ItemStack ammo, EntityPlayer entityPlayer, int useTime, float baseInaccuracy) {
OnBowShoot event = new OnBowShoot(bow, ammo, entityPlayer, useTime, baseInaccuracy);
MinecraftForge.EVENT_BUS.post(event);
return event;
}
public void setProjectileCount(int projectileCount) {
this.projectileCount = projectileCount;
}
public void setConsumeAmmoPerProjectile(boolean consumeAmmoPerProjectile) {
this.consumeAmmoPerProjectile = consumeAmmoPerProjectile;
}
public void setConsumeDurabilityPerProjectile(boolean consumeDurabilityPerProjectile) {
this.consumeDurabilityPerProjectile = consumeDurabilityPerProjectile;
}
public void setBonusInaccuracy(float bonusInaccuracy) {
this.bonusInaccuracy = bonusInaccuracy;
}
public float getBaseInaccuracy() {
return baseInaccuracy;
}
public void setBaseInaccuracy(float baseInaccuracy) {
this.baseInaccuracy = baseInaccuracy;
}
}
}
|
package com.thinkdevs.cryptomarket;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.thinkdevs.cryptomarket.adapters.ReferralRecyclerAdapter;
import com.thinkdevs.cryptomarket.model.Users;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
public class InviteActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter adapter;
private Query mDatabase;
private DatabaseReference iDatabase,cDatabase;
private ValueEventListener mListener,iListener,cListener;
private Toolbar toolbar;
private TextView rc,iTitle,iBody,refresh,more;
private ImageView iv;
private LinearLayout bd,empty;
private ImageButton rfs;
private Button copyBtn, inviteBtn;
private List<Users> mRecyclerViewItems = new ArrayList<>();
private AdView mAdView;
private InterstitialAd mInterstitialAd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_invite);
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId(getString(R.string.admob_interstitial));
mInterstitialAd.loadAd(new AdRequest.Builder().build());
mInterstitialAd.setAdListener(new AdListener() {
@Override
public void onAdClosed() {
finish();
}
});
mAuth = FirebaseAuth.getInstance();
toolbar = findViewById(R.id.toolbar_main);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Invite & Earn");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
finish();
}
}
});
String uid=mAuth.getCurrentUser().getUid();
mDatabase= FirebaseDatabase.getInstance().getReference().child("users").orderByChild("ur").equalTo(uid).limitToLast(18);
cDatabase= FirebaseDatabase.getInstance().getReference().child("referral").child(uid).child("ref_list");
iDatabase= FirebaseDatabase.getInstance().getReference().child("refoffer");
rc=findViewById(R.id.rct);
iTitle=findViewById(R.id.iTitle);
iBody=findViewById(R.id.iBody);
rfs=findViewById(R.id.ref_refresh);
refresh=findViewById(R.id.refresh);
copyBtn=findViewById(R.id.copyBtn);
inviteBtn=findViewById(R.id.inviteBtn);
more=findViewById(R.id.more);
iv=findViewById(R.id.invite_img);
bd=findViewById(R.id.bd);
empty=findViewById(R.id.empty);
mRecyclerView =(RecyclerView)findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
addReferralBoardItems();
GridLayoutManager lm=new GridLayoutManager(this,3);
mRecyclerView.setLayoutManager(lm);
adapter = new ReferralRecyclerAdapter(this, mRecyclerViewItems);
mRecyclerView.setAdapter(adapter);
rfs.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
rfs.setVisibility(View.GONE);
refresh.setVisibility(View.VISIBLE);
rfs.setEnabled(false);
mRecyclerViewItems.clear();
addReferralBoardItems();
}
});
copyBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String label="Referral Link";
String text="https://play.google.com/store/apps/details?id="+getPackageName()+"&referrer="+mAuth.getCurrentUser().getUid();
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText(label, text);
if (clipboard != null) {
clipboard.setPrimaryClip(clip);
}
Toast.makeText(InviteActivity.this, "Link Copied to Clipboard", Toast.LENGTH_SHORT).show();
}
});
inviteBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name));
String sAux = getString(R.string.invite_cap);
sAux = sAux + "https://play.google.com/store/apps/details?id="+getPackageName()+"&referrer="+mAuth.getCurrentUser().getUid();
i.putExtra(Intent.EXTRA_TEXT, sAux);
startActivity(Intent.createChooser(i, "choose one"));
} catch(Exception e) {
}
}
});
}
private void addReferralBoardItems() {
mListener= new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
for (DataSnapshot listItem : dataSnapshot.getChildren()) {
Users ru = listItem.getValue(Users.class);
mRecyclerViewItems.add(ru);
}
adapter.notifyDataSetChanged();
empty.setVisibility(View.GONE);
}
else
empty.setVisibility(View.VISIBLE);
refresh.setVisibility(View.GONE);
rfs.setEnabled(true);
rfs.setVisibility(View.VISIBLE);
}
@Override
public void onCancelled(DatabaseError databaseError) {
empty.setVisibility(View.VISIBLE);
rfs.setVisibility(View.VISIBLE);
refresh.setVisibility(View.GONE);
}
};
mDatabase.addListenerForSingleValueEvent(mListener);
cListener=new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
int tc = (int) dataSnapshot.getChildrenCount();
rc.setText(String.format(Locale.US,"My Referral (%d)",tc));
if(mRecyclerViewItems.size()<tc){
int extra= tc-mRecyclerViewItems.size();
more.setText(String.format(Locale.US,"+ %d more...",extra));
more.setVisibility(View.VISIBLE);
}
else
more.setVisibility(View.GONE);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
cDatabase.addListenerForSingleValueEvent(cListener);
}
@Override
protected void onStart() {
super.onStart();
FirebaseUser user = mAuth.getCurrentUser();
if (user == null) {
startActivity(new Intent(InviteActivity.this, AuthActivity.class));
finish();
}
iListener =new ValueEventListener(){
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
iTitle.setText(Objects.toString(dataSnapshot.child("title").getValue(),null));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
iBody.setText(Html.fromHtml(Objects.toString(dataSnapshot.child("body").getValue(),null),Html.FROM_HTML_MODE_LEGACY));
}
else
iBody.setText(Html.fromHtml(Objects.toString(dataSnapshot.child("body").getValue(),null)));
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
iDatabase.addValueEventListener(iListener);
}
@Override
public void onBackPressed() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else{
super.onBackPressed();
}
}
@Override
protected void onDestroy() {
if (mListener != null) {
mDatabase.removeEventListener(mListener);
}
if (iListener != null) {
iDatabase.removeEventListener(iListener);
}
if (cListener != null) {
cDatabase.removeEventListener(cListener);
}
super.onDestroy();
}
}
|
package com.modbusconnect.rtuwrapper.messaging;
import com.modbusconnect.rtuwrapper.processing.Coil;
import static com.modbusconnect.rtuwrapper.ModbusConstants.READ_COIL;
public class ReadCoilRequest extends BaseRequest<Coil, Boolean> {
public ReadCoilRequest() {
super(READ_COIL);
}
public ReadCoilRequest(int address) {
super(READ_COIL, new Coil(address, false));
}
@Override
public void setData(int address, Boolean value) {
setModbusDataObject(new Coil(address, value));
}
@Override
public void setValue(Boolean value) {
setModbusDataObject(new Coil(-1, value));
}
@Override
public byte[] getEncodedMessage(int slaveId) {
return getMessageProcessor().buildReadMessage(slaveId, getFunctionCode(), getModbusData().getAddress());
}
}
|
package com.example.kyon.getjpg;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.os.Handler;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
import static com.example.kyon.getjpg.R.id.Button01;
public class MainActivity extends AppCompatActivity
{
private ImageView imageView = null;
private Bitmap bmp = null;
private Button btn;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.image01);
btn = (Button) findViewById(Button01);
SetOnButtonClick();
}
private void SetOnButtonClick()
{
btn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Thread t = new Thread()
{
@Override
public void run()
{
super.run();
Socket socket = null;
DataInputStream dataInput;
int size;
int len;
ByteArrayOutputStream outPut;
byte[] data;
try
{
socket = new Socket("192.168.43.65", 9999);
dataInput = new DataInputStream(socket.getInputStream());
while(true)
{
size = dataInput.readInt();
data = new byte[size];
// dataInput.readFully(data);
len = 0;
while (len < size)
{
len += dataInput.read(data, len, size - len);
}
outPut = new ByteArrayOutputStream();
bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
bmp.compress(Bitmap.CompressFormat.PNG, 100, outPut);
//imageView.setImageBitmap(bmp);
myHandler.obtainMessage().sendToTarget();
}
}
catch (IOException e)
{
e.printStackTrace();
} finally
{
try
{
socket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
};
t.start();
}
});
}
private Handler myHandler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
imageView.setImageBitmap(bmp);
};
};
} |
package com.meehoo.biz.core.basic.ro.setting;
import lombok.Getter;
import lombok.Setter;
/**
* Created by Administrator on 2017/11/02.
*/
@Getter
@Setter
public class DictValueRO {
private String id;
private String mkey;
private String mvalue;
private String dictTypeId;
}
|
import java.util.Scanner;
import java.lang.Math;
public class Lesson_11_Activity_Four {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a Number: ");
int x = scan.nextInt();
int y = x % 2;
if(y == 0) {
System.out.println("Even");
}
if(y == 1) {
System.out.println("Odd");
}
}
}
|
package com.timewarp.engine.Math;
public class Range<T extends Number & Comparable<? super T>> {
private enum ThresholdType {
Inclusive,
Exclusive,
Infinite
}
public static final ThresholdType infinity = ThresholdType.Infinite;
public static final ThresholdType exclusive = ThresholdType.Exclusive;
public static final ThresholdType inclusive = ThresholdType.Inclusive;
private static class Threshold<T extends Number & Comparable<? super T>> {
private ThresholdType type;
private T value;
Threshold(ThresholdType type) {
this.type = type;
}
Threshold(ThresholdType type, T value) {
this.type = type;
this.value = value;
}
boolean containsAfter(T number) {
switch (this.type) {
case Exclusive:
return number.compareTo(this.value) > 0;
case Inclusive:
return number.compareTo(this.value) >= 0;
case Infinite:
return true;
}
return false;
}
boolean containsBefore(T number) {
switch (this.type) {
case Exclusive:
return number.compareTo(this.value) < 0;
case Inclusive:
return number.compareTo(this.value) <= 0;
case Infinite:
return true;
}
return false;
}
}
private Threshold<T> from;
private Threshold<T> to;
/**
* Creates new Range (from; to)(infinity; infinity)
*/
public Range() {
this.from = new Threshold<T>(infinity);
this.to = new Threshold<T>(infinity);
}
private Range(Threshold<T> from, Threshold<T> to) {
this.from = from;
this.to = to;
}
/**
* Checks whether given point(number) is in specified range
* @param value Target point
* @return Is range contains give point
*/
public boolean contains(T value) {
return this.from.containsAfter(value) && this.to.containsBefore(value);
}
/**
* Sets left boundary of range
* @param thresholdType Threshold type
* @return Range, starting from given point
*/
public Range<T> from(ThresholdType thresholdType) {
return new Range<T>(new Threshold<T>(thresholdType), this.to);
}
/**
* Sets left boundary of range
* @param thresholdType Threshold type
* @param value Threshold value
* @return Range, starting from given point
*/
public Range<T> from(ThresholdType thresholdType, T value) {
return new Range<T>(new Threshold<T>(thresholdType, value), this.to);
}
/**
* Sets right boundary of range
* @param thresholdType Threshold type
* @return Range, ending on given point
*/
public Range<T> to(ThresholdType thresholdType) {
return new Range<T>(this.from, new Threshold<T>(thresholdType));
}
/**
* Sets left boundary of range
* @param thresholdType Threshold type
* @param value Threshold value
* @return Range, starting from given point
*/
public Range<T> to(ThresholdType thresholdType, T value) {
return new Range<T>(this.from, new Threshold<T>(thresholdType, value));
}
}
|
package com.mobilcom.mypicolo.databases;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.sqlite.db.SupportSQLiteDatabase;
import com.mobilcom.mypicolo.daos.GameModeDao;
import com.mobilcom.mypicolo.daos.TaskDao;
import com.mobilcom.mypicolo.daos.TaskGameModeMapDao;
import com.mobilcom.mypicolo.entities.GameMode;
import com.mobilcom.mypicolo.entities.Task;
import com.mobilcom.mypicolo.entities.TaskCategory;
import com.mobilcom.mypicolo.daos.TaskCategoryDao;
import com.mobilcom.mypicolo.entities.TaskGameModeMap;
@Database(entities = {TaskCategory.class, GameMode.class, Task.class, TaskGameModeMap.class}, version = 1, exportSchema = false)
public abstract class MyPicoloDatabase extends RoomDatabase {
private static MyPicoloDatabase instance;
public abstract TaskCategoryDao taskCategoryDao();
public abstract GameModeDao gameModeDao();
public abstract TaskDao taskDao();
public abstract TaskGameModeMapDao taskGameModeMapDao();
public static synchronized MyPicoloDatabase getInstance(Context context) {
if (instance == null) {
instance = Room.databaseBuilder(
context.getApplicationContext(),
MyPicoloDatabase.class,
"mypicolo_database")
.fallbackToDestructiveMigration()
.addCallback(roomCallback)
.build();
}
return instance;
}
private static RoomDatabase.Callback roomCallback = new RoomDatabase.Callback() {
@Override
public void onCreate(@NonNull SupportSQLiteDatabase db) {
super.onCreate(db);
new PopulateDatabaseAsyncTask(instance).execute();
}
};
private static class PopulateDatabaseAsyncTask extends AsyncTask<Void, Void, Void> {
private TaskCategoryDao taskCategoryDao;
private GameModeDao gameModeDao;
private TaskDao taskDao;
private TaskGameModeMapDao taskGameModeMapDao;
private PopulateDatabaseAsyncTask(MyPicoloDatabase myPicoloDatabase) {
taskCategoryDao = myPicoloDatabase.taskCategoryDao();
gameModeDao = myPicoloDatabase.gameModeDao();
taskDao = myPicoloDatabase.taskDao();
taskGameModeMapDao = myPicoloDatabase.taskGameModeMapDao();
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... voids) {
Log.d("MyPicoloDatabase", "createDatabase");
taskCategoryDao.insert(new TaskCategory("Aufgabe", "Eine einfache Aufgabe"));
taskCategoryDao.insert(new TaskCategory("Spiel", "Ein Spiel gegen andere Mitspieler"));
gameModeDao.insert(new GameMode("Normaler Modus", "Ein ganz normaler Modus für ein einfaches Spiel"));
taskDao.insert(new Task("Ich bin der erste Task", 1));
taskDao.insert(new Task("Ich bin der zweite Task", 1));
taskDao.insert(new Task("Ich bin der dritte Task", 2));
taskDao.insert(new Task("Ich bin der vierte Task", 1));
taskDao.insert(new Task("Ich bin der fünfte Task", 1));
taskDao.insert(new Task("Ich bin der sechste Task", 2));
taskDao.insert(new Task("Ich bin der siebte Task", 1));
taskDao.insert(new Task("Ich bin der achte Task", 1));
taskDao.insert(new Task("Ich bin der neunte Task", 2));
taskDao.insert(new Task("Ich bin der zehnte Task", 1));
taskGameModeMapDao.insert(new TaskGameModeMap(1, 1));
taskGameModeMapDao.insert(new TaskGameModeMap(2, 1));
taskGameModeMapDao.insert(new TaskGameModeMap(3, 1));
taskGameModeMapDao.insert(new TaskGameModeMap(4, 1));
taskGameModeMapDao.insert(new TaskGameModeMap(5, 1));
taskGameModeMapDao.insert(new TaskGameModeMap(6, 1));
taskGameModeMapDao.insert(new TaskGameModeMap(7, 1));
taskGameModeMapDao.insert(new TaskGameModeMap(8, 1));
taskGameModeMapDao.insert(new TaskGameModeMap(9, 1));
taskGameModeMapDao.insert(new TaskGameModeMap(10, 1));
return null;
}
}
}
|
/*
* @lc app=leetcode.cn id=155 lang=java
*
* [155] 最小栈
*/
// @lc code=start
class MinStack {
Deque<Integer> deque;
Deque<Integer> min_deque;
public MinStack() {
deque = new LinkedList<Integer>();
min_deque = new LinkedList<Integer>();
min_deque.addLast(Integer.MAX_VALUE);
}
public void push(int val) {
deque.addLast(val);
min_deque.addLast(Math.min(min_deque.getLast(), val));
}
public void pop() {
deque.removeLast();
min_deque.removeLast();
}
public int top() {
return deque.getLast();
}
public int getMin() {
return min_deque.getLast();
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(val);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
// @lc code=end
|
package com.egswebapp.egsweb.security.jwt;
import com.egswebapp.egsweb.model.User;
import com.egswebapp.egsweb.model.enums.UserProfile;
import com.egswebapp.egsweb.model.enums.UserStatus;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
/**
* Implementation of Factory Method for class {@link JwtUserDetails}.
*
*
* @version 1.0
*/
public class JwtUserFactory {
public JwtUserFactory() {
}
public static JwtUserDetails create(final User user) {
return new JwtUserDetails(
user.getId(),
user.getEmail(),
user.getPassword(),
user.getName(),
user.getSurname(),
user.getStatus().equals(UserStatus.ACTIVE),
mapToGrantedAuthority(new ArrayList<>(Collections.singleton(user.getUserProfile())))
);
}
private static List<GrantedAuthority> mapToGrantedAuthority(List<UserProfile> userProfiles) {
return userProfiles.stream()
.map(profile ->
new SimpleGrantedAuthority(profile.getName())
).collect(Collectors.toList());
}
}
|
/*
* @lc app=leetcode.cn id=86 lang=java
*
* [86] 分隔链表
*/
// @lc code=start
/**
* Definition for singly-linked list. public class ListNode { int val; ListNode
* next; ListNode() {} ListNode(int val) { this.val = val; } ListNode(int val,
* ListNode next) { this.val = val; this.next = next; } }
*/
class Solution {
public ListNode partition(ListNode head, int x) {
ListNode small, large, current, smallDummy, largeDummy;
current = head;
smallDummy = new ListNode();
largeDummy = new ListNode();
small = smallDummy;
large = largeDummy;
while (current != null) {
if (current.val < x) {
// 将current节点接入small后面
small.next = current;
small = small.next;
} else {
large.next = current;
large = large.next;
}
current = current.next;
}
small.next = largeDummy.next;
large.next = null;
return smallDummy.next;
}
}
// @lc code=end
|
package demo1;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
public class Server {
public static void main(String[] args)throws IOException
{
ServerSocket server=new ServerSocket(8888);
System.out.println("服务器启动时间是:"+new Date());
Socket client=server.accept();
DataInputStream inputfromClient=new DataInputStream(client.getInputStream());
DataOutputStream outputtoClient=new DataOutputStream(client.getOutputStream());
while(true)
{
double ridus=inputfromClient.readDouble();
double area=ridus*ridus*Math.PI;
System.out.println("服务端:当前接收的半径为:"+ridus);
System.out.println("服务端:计算面积为:"+area);
outputtoClient.writeDouble(area);
}
}
}
|
package com.java201.product;
public interface ProductDao {
public void addProduct(Product product);
public void modifyProduct(Product product);
public void selectProduct(int productId);
}
|
package com.ipincloud.iotbj.srv.service.impl;
import com.alibaba.fastjson.JSONArray;
import com.ipincloud.iotbj.oa.OAApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import com.alibaba.fastjson.JSONObject;
import com.ipincloud.iotbj.srv.domain.RolePage;
import com.ipincloud.iotbj.srv.dao.*;
import com.ipincloud.iotbj.srv.service.RolePageService;
import com.ipincloud.iotbj.utils.ParaUtils;
//(RolePage) 服务实现类
//generate by redcloud,2020-07-24 19:59:20
@Service("RolePageService")
public class RolePageServiceImpl implements RolePageService {
@Resource
private RolePageDao rolePageDao;
@Autowired
OAApi oaApi;
//@param id 主键
//@return 实例对象RolePage
@Override
public RolePage queryById(Long id) {
return this.rolePageDao.queryById(id);
}
//@param jsonObj 新增数据等
//@return JSONObject 查询
@Transactional(rollbackFor = Exception.class)
@Override
public Integer rolePageMmjoin(JSONObject jsonObj) {
int roleId = jsonObj.getIntValue("roleId");
String roleName = jsonObj.getString("roleName");
String thirdRoleUUID = jsonObj.getString("thirdUUID");
JSONArray rmRolePage = jsonObj.getJSONArray("rm_role_page");
oaApi.removeRoleMenu(thirdRoleUUID, roleName, rmRolePage);
oaApi.saveOrUpdateRoleMenu(thirdRoleUUID, roleName, jsonObj.getJSONArray("role_page"));
this.rolePageDao.deleteByRoleID(roleId + "");
return this.rolePageDao.rolePageMmjoin(jsonObj);
}
//@param jsonObj 新增数据等
//@return JSONObject 查询
@Override
public Integer rolePageMmsub(JSONObject jsonObj) {
return this.rolePageDao.rolePageMmsub(jsonObj);
}
}
|
/* ------------------------------------------------------------------------------
*
* 软件名称:泡泡娱乐交友平台(手机版)
* 公司名称:北京双迪信息技术有限公司
* 开发作者:Yongchao.Yang
* 开发时间:2012-8-16/2012
* All Rights Reserved 2012-2015
* ------------------------------------------------------------------------------
* 注意:本内容仅限于北京双迪信息技术有限公司内部使用 禁止转发
* ------------------------------------------------------------------------------
* prj-name:com.popo.logic
* fileName:com.popo.db.UserTransactionManager.java
* -------------------------------------------------------------------------------
*/
package com.rednovo.ace.activity.ds;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.transaction.UserTransaction;
import org.apache.log4j.Logger;
/**
* 通过容器注入的UserTransaction对象管理JTA事务对象
*
* @author Administrator
*/
public class UserTransactionManager {
private static UserTransaction ut = null;
private static Logger log = Logger.getLogger(UserTransactionManager.class.getName());
static {
Context ctx;
try {
log.debug("初始化事务管理器...");
ctx = new InitialContext();
ut = (UserTransaction) ctx.lookup("java:comp/UserTransaction");
} catch (NamingException e) {
log.error("初始化事务管理器失败", e);
}
}
/**
* 获取UserTransaction对象
*
* @author Administrator/下午1:50:22/2012
*/
public static UserTransaction getUserTransaction() {
return ut;
}
}
|
package com.example.krishnaghatia.break_no_chain.Controllers;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.AvoidXfermode;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.example.krishnaghatia.break_no_chain.Models.Goal;
import com.example.krishnaghatia.break_no_chain.R;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class ViewGoalsActivity extends ActionBarActivity {
private LinearLayout myVerticalLayout;
private LinearLayout myVerticalLayout2;
private LinearLayout myHorizontlLayout;
private LinearLayout myHorizontalLayout2;
private LinearLayout myHorizontalLayout4;
private ProgressBar pb;
private ProgressBar progressBar;
private Button btn;
private TextView textview;
private TextView remaining_label;
private TextView remaining_days;
private TextView completed_label;
private TextView completed_days;
private String userID;
private class BackgroundProcess extends AsyncTask<String,Integer,String>{
private int id;
private int maxvalue;
private int incrementby;
private int progressStatus;
BackgroundProcess(int id,int maxvalue,int incrementby,int progressStatus){this.id= id;
this.maxvalue = maxvalue;
this.incrementby=incrementby;
this.progressStatus=progressStatus;}
@Override
protected String doInBackground(String...strings){
String progressbar_id = Integer.toString(id+4);
progressBar = (ProgressBar) findViewById(getResources().getIdentifier(progressbar_id,"id",getPackageName()));
if(progressStatus<maxvalue){
progressStatus+=incrementby;
progressBar.setProgress(progressStatus);
}
try{
Thread.sleep(200);
}
catch(InterruptedException e){
e.printStackTrace();
}
publishProgress();
return null;
}
@Override
protected void onPreExecute(){
}
@Override
protected void onProgressUpdate(Integer...values){super.onProgressUpdate(values);}
@Override
protected void onPostExecute(String result){super.onPostExecute(result);}
}
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_viewgoals);
//Define Vertical Layout
myVerticalLayout = (LinearLayout) findViewById(R.id.MyVerticallayout);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
myVerticalLayout.setOrientation(LinearLayout.VERTICAL);
//Define Horizontal Layout 3
myVerticalLayout2 = (LinearLayout) findViewById(R.id.MyHorizontalLayout3);
LinearLayout.LayoutParams horizontallayout3params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
horizontallayout3params.setMargins(20,45,15,20);
//Define Horizontal Layout
myHorizontlLayout = (LinearLayout) findViewById(R.id.MyHorizontalLayout);
//Define Horizontal Layout 2
myHorizontalLayout2 = (LinearLayout) findViewById(R.id.MyHorizontalLayout2);
// Define Horizontal Layout 4
myHorizontalLayout4=(LinearLayout) findViewById(R.id.MyHorizontalLayout4);
LinearLayout.LayoutParams horizontallayout4params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
horizontallayout4params.setMargins(20,45,15,20);
//Get Colors and store in an array
int[] rainbow = getBaseContext().getResources().getIntArray(R.array.Colors);
//Get user id
SharedPreferences preferences = getSharedPreferences("userId",MODE_PRIVATE);
userID = preferences.getString("userId","");
// Create Database Instance and get ProgressBars
final DatabaseHelper databaseHelper = new DatabaseHelper(this);
final SQLiteDatabase sqLiteOpenHelper = databaseHelper.getReadableDatabase();
String [] whereArgs = new String[]{userID};
Cursor cursor = sqLiteOpenHelper.query("GoalTable",null,"user_id=?",whereArgs,null,null,null);
startManagingCursor(cursor);
//Loop through Database to add progressbars and buttons
int i =0;
while(cursor.moveToNext()){
final int j =i;
int Max_value =0;
int daysbetween=0;
String Startdate = cursor.getString(cursor.getColumnIndex("start_date"));
String Enddate = cursor.getString(cursor.getColumnIndex("end_date"));
final String LastMarkeddate = cursor.getString(cursor.getColumnIndex("last_marked"));
final int count = cursor.getInt(cursor.getColumnIndex("count"));
Log.i("StartDateinDatabase",Startdate);
Log.i("EndDateinDatabase",Enddate);
Log.i("LastMarkedinDatabase",LastMarkeddate);
Log.i("countinDatabase",String.valueOf(count));
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
Date start = null;
Date end;
try{
start = df.parse(Startdate);
end = df.parse(Enddate);
Log.i("Date:StartDate", String.valueOf(start));
Log.i("Date:EndDate",String.valueOf(end));
long timeOne = start.getTime();
long timeTwo = end.getTime();
long oneDay = 1000*60*60*24;
long delta = (timeTwo - timeOne) / oneDay;
daysbetween = (int) delta;
}catch(ParseException e){
e.printStackTrace();
}
Max_value = 500;
Log.i("Daysbetween",String.valueOf(daysbetween));
Log.i("Value of i", String.valueOf(i));
Log.i("Incrementby",String.valueOf((Max_value/daysbetween)));
// Get the completed Progress
final int completed_progress = count * (Max_value/daysbetween);
Log.i("CompletedProgress", String.valueOf(completed_progress));
//Define ProgressBar
pb = new ProgressBar(this,null,android.R.attr.progressBarStyleHorizontal);
pb.setLayoutParams(params);
pb.getLayoutParams().width = Max_value;
pb.invalidate();
pb.setId(i + 4);
pb.setMax(Max_value);
pb.setProgress(completed_progress);
pb.getProgressDrawable().setColorFilter(rainbow[i], PorterDuff.Mode.SRC_IN);
myVerticalLayout.addView(pb);
//Define Remaining and Completed Days
remaining_label = new TextView(this);
remaining_label.setText("Remaining:" + String.valueOf(daysbetween-count));
remaining_label.setTextColor(rainbow[i]);
// remaining_days = new TextView(this);
// remaining_days.setText(String.valueOf(daysbetween-count));
// remaining_days.setTextColor(rainbow[i]);
completed_label = new TextView(this);
completed_label.setText("Completed:" + String.valueOf(count));
completed_label.setTextColor(rainbow[i]);
// completed_days = new TextView(this);
// completed_days.setText(String.valueOf(count));
// completed_days.setTextColor(rainbow[i]);
myVerticalLayout2.addView(remaining_label,horizontallayout3params);
myHorizontalLayout4.addView(completed_label,horizontallayout4params);
// myVerticalLayout2.addView(completed_label);
// myVerticalLayout2.addView(completed_days);
//Define TextView
LinearLayout.LayoutParams linearlayoutparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
linearlayoutparams.setMargins(50,50,50,30);
textview = new TextView(this);
textview.setText(cursor.getString(cursor.getColumnIndex("name")));
myHorizontalLayout2.addView(textview,linearlayoutparams);
//Define Button
LinearLayout.LayoutParams linearparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
linearparams.setMargins(24, 0, 24, 0);
btn = new Button(this);
btn.setBackgroundColor(rainbow[i]);
btn.setText("Mark");
btn.setId(i);
myHorizontlLayout.addView(btn,linearparams);
final int finalMax_value = Max_value;
final int finalDaysbetween = daysbetween;
final Date finalStart = start;
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Current Date
String curr = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date currentdate = null;
try {
currentdate = dateFormat.parse(curr);
} catch (ParseException e) {
e.printStackTrace();
}
Log.i("Currentdate", String.valueOf(currentdate));
// Compare lastmarked in Database with current date
Date lastindb = null;
DateFormat dateFormat1 = new SimpleDateFormat("dd-MM-yyyy");
try {
lastindb = dateFormat1.parse(LastMarkeddate);
} catch (ParseException e) {
e.printStackTrace();
}
Log.i("LastinDB",String.valueOf(lastindb));
// Convert current time into string and store it in last_marked
String last_marked_tobeinserted = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
Log.i("Lastmarked", last_marked_tobeinserted);
// increment count and update database
int count_days = count;
count_days = count_days + 1;
SQLiteDatabase db = databaseHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("count", count_days);
cv.put("last_marked", last_marked_tobeinserted);
String where = "user_id=?";
String[] userid_values = new String[]{userID};
db.update("GoalTable", cv, where, userid_values);
//Set parameters and send into function BackgroundProcess
int id = j;
final int value = finalMax_value;
final int Incrementby = (value / finalDaysbetween);
final int progressStatus = completed_progress;
MarkProgress(id, value, Incrementby, progressStatus);
}
});
i++;
sqLiteOpenHelper.close();
}
}
public void MarkProgress(int id, int maxvalue,int incrementby,int progressStatus){
new BackgroundProcess(id,maxvalue,incrementby,progressStatus).execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu){
//Inflate the menu;this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
package com.junzhao.rongyun.radapter;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.junzhao.base.base.APPCache;
import com.junzhao.base.http.IHttpResultError;
import com.junzhao.base.http.IHttpResultSuccess;
import com.junzhao.base.http.MLHttpRequestMessage;
import com.junzhao.base.http.MLHttpRequestUtils;
import com.junzhao.base.http.MLHttpType;
import com.junzhao.base.http.MLRequestParams;
import com.junzhao.shanfen.service.CommService;
import java.util.HashMap;
import java.util.Map;
import io.rong.imkit.model.UIConversation;
import io.rong.imkit.widget.adapter.ConversationListAdapter;
import io.rong.imlib.model.Conversation;
/**
* Created by weiqinxiao on 15/11/5.
*/
public class ConversationListAdapterEx extends ConversationListAdapter {
Context context;
public ConversationListAdapterEx(Context context) {
super(context);
this.context=context;
}
TextView jiehsou;
TextView bujiehsou;
@Override
protected View newView(Context context, int position, ViewGroup group) {
return super.newView(context, position, group);
}
@Override
protected void bindView(View v, int position, final UIConversation data) {
// RelativeLayout rc_item3 =v.findViewById(R.id.rc_itemjieshou);
// ProviderContainerView providerContainerView=v.findViewById(R.id.rc_content);
// rc_item3.setVisibility(View.GONE);
if (data != null) {
if (data.getConversationType().equals(Conversation.ConversationType.DISCUSSION))
data.setUnreadType(UIConversation.UnreadRemindType.REMIND_ONLY);
// if (data.getConversationType().equals(Conversation.ConversationType.SYSTEM)){
// if (data.getConversationTargetId().startsWith("hysq_")){
// Log.d("布局文件类型",providerContainerView.getChildAt(0).toString());
// rc_item3.setVisibility(View.VISIBLE);
// jiehsou=v.findViewById(R.id.jiehsou);
// bujiehsou=v.findViewById(R.id.bujiehsou);
//
// jiehsou.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// jiehsou.setClickable(false);
// jieshouqingqiu(data.getConversationSenderId().substring(5),"","1");
// }
// });
// bujiehsou.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// bujiehsou.setClickable(false);
// jieshouqingqiu(data.getConversationSenderId().substring(5),"","0");
// }
// });
// }
// }
}
super.bindView(v, position, data);
}
// 112.同意或不同意成为好友(li)
private void jieshouqingqiu(String senderId,String remarksName,String status) {
Map<String, String> map = new HashMap();
MLRequestParams mlHttpParam = new MLRequestParams();
mlHttpParam.put("token", APPCache.getToken());
mlHttpParam.put("senderId",senderId);
mlHttpParam.put("remarksName",remarksName);
mlHttpParam.put("status",status);
MLHttpRequestMessage message = new MLHttpRequestMessage(
MLHttpType.RequestType.AGREEORDISAGREEFRIENDS, mlHttpParam, String.class,
CommService.getInstance(), true);
loadData(context, null, message, new IHttpResultSuccess() {
@Override
public void success(MLHttpType.RequestType type, Object obj) {
jiehsou.setClickable(true);
bujiehsou.setClickable(true);
}
}, new IHttpResultError() {
@Override
public void error(MLHttpType.RequestType type, Object obj) {
jiehsou.setClickable(true);
bujiehsou.setClickable(true);
}
});
}
protected void loadData(Context context, Object message, MLHttpRequestMessage httpMessage, IHttpResultSuccess success, IHttpResultError error) {
httpMessage.setHttpResultSuccess(success);
httpMessage.setHttpResultError(error);
httpMessage.mContext = context;
MLHttpRequestUtils.loadData(context, message, httpMessage);
}
}
|
package com.zheng.lock;
/**
* Created by zhenglian on 2016/9/28.
*/
public class TraditionalSyncronized {
final Output printer = new Output();
public static void main(String[] args) {
new TraditionalSyncronized().init();
}
private void init() {
new Thread(new Runnable() {
public void run() {
while(true) {
printer.say("good good study");
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
public void run() {
while(true) {
printer.say("day day up");
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
class Output {
public /*synchronized*/ void say(String msg) { //同步方法的方式
synchronized (this) {
for(char c : msg.toCharArray()) {
System.out.print(c);
}
System.out.println();
}
}
}
}
|
package com.example.usser.moneycatch;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import java.text.DecimalFormat;
import java.util.ArrayList;
public class Adater_main_input_minus extends RecyclerView.Adapter<Adater_main_input_minus.Myviewholder>{
Context context;
DecimalFormat comma = new DecimalFormat("###,###"); // 숫자 3자리마다 콤마 찍어줌
static ArrayList<Mainrecycleitem_minus> item_main_minus = new ArrayList<>();
Adater_main_input_minus(ArrayList<Mainrecycleitem_minus> item_main_minus){
this.item_main_minus = item_main_minus;
}
public class Myviewholder extends RecyclerView.ViewHolder {
Button breakdown;
Button user_input;
TextView cal_view;
public Myviewholder( View itemView) {
super(itemView);
breakdown = itemView.findViewById(R.id.breakdown_view_minus);
user_input = itemView.findViewById(R.id.userinput_view_minus);
cal_view = itemView.findViewById(R.id.cal_view_minus);
}
}
@Override
public Myviewholder onCreateViewHolder( ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_main_input_minus_recycle,parent,false);
return new Adater_main_input_minus.Myviewholder(v);
}
@Override
public void onBindViewHolder( Myviewholder holder, int position) {
Adater_main_input_minus.Myviewholder myviewholder = (Adater_main_input_minus.Myviewholder) holder;
String getName = comma.format(item_main_minus.get(position).getName());
myviewholder.breakdown.setText(item_main_minus.get(position).getBreakdown());
myviewholder.user_input.setText(getName+"원");
myviewholder.cal_view.setText(item_main_minus.get(position).getCal());
}
@Override
public int getItemCount() {
return item_main_minus.size();
}
}
|
package com.example.demo.mapper;
import com.baomidou.mybatisplus.plugins.pagination.Pagination;
import com.example.demo.entity.User;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
import java.util.Map;
/**
* <p>
* Mapper 接口
* </p>
*
* @author weifucheng
* @since 2017-11-24
*/
public interface UserMapper extends BaseMapper<User> {
@Select("select * from user")
public List<User> selectAll(Pagination page);
@Select("select * from user ${sql}")
public List<User> selectListByFilter(@Param("sql") String sql,Pagination page);
@Select("select * from user ${sql}")
public List<User> selectListByFilter(@Param("sql") String sql);
@Select("${sql}")
public List<Map<String,Object>> selectListBysql(@Param("sql") String sql);
} |
package com.github.iam20.util;
import java.util.TimerTask;
public class TimerTaskWrapper {
public static TimerTask wrap(Runnable r) {
return new TimerTask() {
@Override
public void run() {
r.run();
}
};
}
}
|
package genericity;
import java.util.ArrayList;
import java.util.List;
//通配符的下限
public class T7 {
public static class Grandfather {
}
public static class Father extends Grandfather {
}
public static class Son extends Father {
}
public static void test(List<? super Father> lists) {
System.out.println(lists);
}
public static void main(String args[]) {
List<Son> sonList = new ArrayList<>();
List<Father> fatherList = new ArrayList<>();
List<Grandfather> grandfatherList = new ArrayList<>();
//test(sonList);
test(fatherList);
test(grandfatherList);
}
}
|
package cn.edu.cust.pkmAudit.dao.hibernate4;
import org.springframework.stereotype.Repository;
import cn.edu.cust.common.dao.BaseDAOImpl;
import cn.edu.cust.pkmAudit.dao.IDairyDAO;
import cn.edu.cust.pkmAudit.model.Dairy;
@Repository("dairyDAO")
public class DairyDAOImpl extends BaseDAOImpl<Dairy, String> implements IDairyDAO {
}
|
package com.zantong.mobilecttx.user.bean;
import java.util.List;
/**
* Created by jianghw on 2017/5/2.
*/
public class CouponFragmentLBean {
List<CouponFragmentBean> couponList;
public List<CouponFragmentBean> getCouponList() {
return couponList;
}
public void setCouponList(List<CouponFragmentBean> couponList) {
this.couponList = couponList;
}
}
|
package com.gxtc.huchuan.adapter;
import android.app.Activity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.gxtc.commlibrary.base.BaseRecyclerAdapter;
import com.gxtc.commlibrary.helper.ImageHelper;
import com.gxtc.commlibrary.recyclerview.RecyclerView;
import com.gxtc.commlibrary.utils.ToastUtil;
import com.gxtc.huchuan.R;
import com.gxtc.huchuan.bean.BannedOrBlackUserBean;
import com.gxtc.huchuan.bean.ChatJoinBean;
import com.gxtc.huchuan.bean.SignUpMemberBean;
import com.gxtc.huchuan.data.UserManager;
import com.gxtc.huchuan.http.ApiCallBack;
import com.gxtc.huchuan.http.ApiObserver;
import com.gxtc.huchuan.http.ApiResponseBean;
import com.gxtc.huchuan.http.service.AllApi;
import com.gxtc.huchuan.http.service.LiveApi;
import com.gxtc.huchuan.pop.PopManagerMember;
import com.gxtc.huchuan.utils.DateUtil;
import com.gxtc.huchuan.widget.MyActionSheetDialog;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;
/**
* Created by Gubr on 2017/4/2.
*/
public class MemeberManagerAdapter extends BaseRecyclerAdapter<ChatJoinBean.MemberBean> {
private static final String TAG = "MemeberManagerAdapter";
private final Activity context;
private PopManagerMember popManagerMember;
private HashMap<String, String> myBean;
private RecyclerView recyclerView;
public MemeberManagerAdapter(Activity context, List<ChatJoinBean.MemberBean> list, int itemLayoutId, HashMap<String, String> myBean, RecyclerView recyclerView) {
super(context, list, itemLayoutId);
this.context = context;
this.myBean = myBean;
this.recyclerView =recyclerView;
}
@Override
public void bindData(ViewHolder holder, final int position, final ChatJoinBean.MemberBean bean) {
ImageHelper.loadCircle(getContext(), holder.getImageView(R.id.iv_head), bean.getHeadPic());
holder.setText(R.id.tv_name, bean.getName());
TextView manage = holder.getViewV2(R.id.tv_role);
switch (bean.getJoinType()){
case "1":
manage.setText("管理员");
break;
case "2":
manage.setText("讲师");
break;
case "3":
manage.setText("主持人");
break;
case "0":
manage.setText("普通成员");
break;
}
//隐藏管理按钮
if (myBean.get("joinType") .equals( ChatJoinBean.ROLE_TEACHER) || myBean.get("joinType").equals(ChatJoinBean.ROLE_ORDINARY) || UserManager.getInstance().getUserCode() .equals( bean.getUserCode()) ||
myBean.get("joinType") .equals(ChatJoinBean.ROLE_MANAGER) && (bean.getJoinType().equals( ChatJoinBean.ROLE_HOST) || bean.getJoinType() .equals(ChatJoinBean.ROLE_MANAGER))) {
holder.getViewV2(R.id.tv_manage).setVisibility(View.GONE);
} else {
holder.getViewV2(R.id.tv_manage).setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
ShowBottomMenu(bean, position);
}
});
}
}
String flagStr = null;
boolean flag = false;
public void ShowBottomMenu(final ChatJoinBean.MemberBean bean, final int mPosition) {
if (bean.getUserCode().equals(UserManager.getInstance().getUserCode())) return;
final List<String> itemList = new ArrayList<>();
if (!bean.getJoinType().equals(ChatJoinBean.ROLE_MANAGER) && bean.getJoinType().equals(ChatJoinBean.ROLE_HOST)) {
itemList.add("升级为管理员");
}else if(bean.getJoinType().equals(ChatJoinBean.ROLE_MANAGER) && bean.getJoinType().equals(ChatJoinBean.ROLE_HOST)){
itemList.add("取消管理员");
}
if (!bean.getJoinType().equals(ChatJoinBean.ROLE_TEACHER)) {
itemList.add("升级为讲师");
}else{
itemList.add("取消讲师");
}
if(bean.isProhibitSpeaking()) {
itemList.add("解禁");
}else{
itemList.add("禁言");
}
if (bean.isBlacklist())
itemList.add("取消黑名单");
else
itemList.add("加入黑名单");
String[] s = new String[itemList.size()];
if (itemList.size() == 0) return;
final MyActionSheetDialog dialog = new MyActionSheetDialog(context,
itemList.toArray(s), null);
dialog.isTitleShow(false).titleTextSize_SP(14.5f).widthScale(1f).cancelMarginBottom(
0).cornerRadius(0f).dividerHeight(1).itemTextColor(
context.getResources().getColor(R.color.black)).cancelText("取消").show();
dialog.setOnOperItemClickL(new OnOperItemClickL() {
@Override
public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
try {
switch (itemList.get(position)) {
case "升级为管理员":
updateJoin(bean.getUserCode(), "1","升级管理员成功", mPosition);
break;
case "取消管理员":
updateJoin(bean.getUserCode(), "0","取消管理员成功", mPosition);
break;
case "升级为讲师":
updateJoin(bean.getUserCode(), "2","升级讲师成功", mPosition);
break;
case "取消讲师":
updateJoin(bean.getUserCode(), "0","取消讲师成功", mPosition);
break;
case "取消黑名单":
doJoinMemberBlacklistOrProhibitSpeaking(bean, "1", "0", mPosition,"已取消黑名单");
break;
case "加入黑名单":
doJoinMemberBlacklistOrProhibitSpeaking(bean, "1","1", mPosition,"已加入黑名单");
break;
case "禁言":
doJoinMemberBlacklistOrProhibitSpeaking(bean, "2","1", mPosition,"已禁言");
break;
case "解禁":
doJoinMemberBlacklistOrProhibitSpeaking(bean, "2","0", mPosition,"已解禁");
break;
}
dialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//修改成员身份
private void updateJoin(String userCode, final String userType, final String msg, final int postion){
HashMap<String, String> map = new HashMap<>();
map.put("chatId", myBean.get("chatId"));
map.put("type", myBean.get("type"));
map.put("userCode", userCode);
map.put("token", UserManager.getInstance().getToken());
map.put("userType", userType);
LiveApi.getInstance().updateJoinMemberJoinType(map)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new
ApiObserver<ApiResponseBean<Object>>
(new ApiCallBack() {
@Override
public void onSuccess(Object data) {
ChatJoinBean.MemberBean bean = getList().get(postion);
bean.setJoinType(userType);
recyclerView.notifyItemChanged(postion);
ToastUtil.showShort(context, msg);
}
@Override
public void onError(String errorCode, String message) {
ToastUtil.showShort(context, message);
}
}));
}
/**
*
* 拉黑/解除拉黑操作 禁言/解除禁言
* chatId 课程id
* chatType 1课程 2系列课
* userCode 目标用户新媒号
* token 当前操作人token
* type 1拉黑/解除拉黑操作 2禁言/解除禁言操作
*/
public void doJoinMemberBlacklistOrProhibitSpeaking(final ChatJoinBean.MemberBean bean, final String type, String state, int position, final String msg){
HashMap<String,String> map =new HashMap<>();
map.put("chatId", myBean.get("chatId"));
map.put("chatType", myBean.get("type"));
map.put("userCode", bean.getUserCode());
map.put("token", UserManager.getInstance().getToken());
map.put("type",type);
map.put("state",state);
LiveApi.getInstance().doJoinMemberBlacklistOrProhibitSpeaking(map)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new
ApiObserver<ApiResponseBean<Object>>
(new ApiCallBack() {
@Override
public void onSuccess(Object data) {
if(type.equals("1")){ //黑名单
bean.setBlacklist(bean.isBlacklist()? "0": "1");
}else{ //禁言
bean.setProhibitSpeaking(bean.isProhibitSpeaking()? "0" : "1");
}
ToastUtil.showShort(context, msg);
}
@Override
public void onError(String errorCode, String message) {
ToastUtil.showShort(context, message);
}
}));
}
}
|
package formation.domain;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
/**Classe représentant les utilisateurs**/
@Entity
@NamedQueries({
@NamedQuery(name = "findAll", query = "select c from Customer c")
})
public class CustomerOld implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull(message = "Email obligatoire")
private String mail;
@NotNull(message = "Mot de passe obligatoire")
private String pwd;
@NotNull(message = "Nom obligatoire")
private String name;
@NotNull(message = "Prénom obligatoire")
private String fistName;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFistName() {
return fistName;
}
public void setFistName(String fistName) {
this.fistName = fistName;
}
}
|
package net.imglib2.trainable_segmention.pixel_feature.filter.laplacian;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.trainable_segmention.RevampUtils;
import net.imglib2.trainable_segmention.pixel_feature.filter.AbstractFeatureOp;
import net.imglib2.trainable_segmention.pixel_feature.filter.FeatureInput;
import net.imglib2.trainable_segmention.pixel_feature.filter.FeatureOp;
import net.imglib2.type.numeric.real.DoubleType;
import net.imglib2.type.numeric.real.FloatType;
import net.imglib2.view.composite.Composite;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import preview.net.imglib2.loops.LoopBuilder;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
@Plugin(type = FeatureOp.class, label = "laplacian of gaussian")
public class SingleLaplacianOfGaussianFeature extends AbstractFeatureOp {
@Parameter
private double sigma = 1.0;
@Override
public int count() {
return 1;
}
@Override
public List<String> attributeLabels() {
return Collections.singletonList("laplacian of gaussian sigma=" + sigma);
}
@Override
public void apply(FeatureInput input, List<RandomAccessibleInterval<FloatType>> output) {
int n = globalSettings().numDimensions();
List<RandomAccessibleInterval<DoubleType>> derivatives = IntStream.range(0, n)
.mapToObj(d -> input.derivedGauss(sigma, order(n, d))).collect(Collectors.toList());
LoopBuilder.setImages(RevampUtils.vectorizeStack(derivatives), output.get(0))
.multiThreaded().forEachPixel((x, sum) -> sum.setReal(sum(x, n)));
}
private int[] order(int n, int d) {
return IntStream.range(0, n).map(i -> i == d ? 2 : 0).toArray();
}
private double sum(Composite<DoubleType> d, int n) {
double sum = 0;
for (int i = 0; i < n; i++) {
sum += d.get(i).getRealDouble();
}
return sum;
}
}
|
/**
* 题目描述
*
* Lily上课时使用字母数字图片教小朋友们学习英语单词,每次都需要把这些图片按照大小(ASCII码值从小到大)排列收好。请大家给Lily帮忙。
*
* 输入描述:
* Lily使用的图片包括"A"到"Z"、"a"到"z"、"0"到"9"。输入字母或数字个数不超过1024。
*
* 输出描述:
* Lily的所有图片按照从小到大的顺序输出
*
* 输入例子:
* Ihave1nose2hands10fingers
*
* 输出例子:
* 0112Iaadeeefghhinnnorsssv
*/
/**
* 就是数组按照顺序排序
*/
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String input = scanner.nextLine();
char[] ch = input.toCharArray();
char[] sorted = new char[ch.length];
int k = 0;
/**
* 先排列数字
*/
for (int i = 0; i < 10; i++) {
for (int j = 0; j < ch.length; j++) {
if ((ch[j] - '0') == i) {
sorted[k] = ch[j];
k++;
}
}
}
/**
* 排列大写字母
*/
for (int i = 0; i < 26; i++) {
for (int j = 0; j < ch.length; j++) {
if ((ch[j] - 'A') == i) {
sorted[k] = ch[j];
k++;
}
}
}
/**
* 摆列小写字母
*/
for (int i = 0; i < 26; i++) {
for (int j = 0; j < ch.length; j++) {
if ((ch[j] - 'a') == i) {
sorted[k] = ch[j];
k++;
}
}
}
System.out.println(String.valueOf(sorted));
}
}
} |
/*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2011 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: proactive@ow2.org or contact@activeeon.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* This library 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ActiveEon Team
* http://www.activeeon.com/
* Contributor(s):
*
* ################################################################
* $$ACTIVEEON_INITIAL_DEV$$
*/
package functionaltests;
import java.io.File;
import java.io.FilenameFilter;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import junit.framework.Assert;
import org.junit.Test;
import org.objectweb.proactive.api.PAActiveObject;
import org.objectweb.proactive.core.node.Node;
import org.objectweb.proactive.core.node.NodeFactory;
import org.objectweb.proactive.extensions.dataspaces.api.DataSpacesFileObject;
import org.objectweb.proactive.extensions.dataspaces.api.PADataSpaces;
import org.objectweb.proactive.extensions.dataspaces.core.BaseScratchSpaceConfiguration;
import org.objectweb.proactive.extensions.dataspaces.core.DataSpacesNodes;
import org.objectweb.proactive.extensions.dataspaces.core.InputOutputSpaceConfiguration;
import org.objectweb.proactive.extensions.dataspaces.core.SpaceInstanceInfo;
import org.objectweb.proactive.extensions.dataspaces.core.naming.NamingService;
import org.objectweb.proactive.extensions.dataspaces.core.naming.NamingServiceDeployer;
import org.objectweb.proactive.extensions.dataspaces.vfs.selector.Selector;
import org.objectweb.proactive.extensions.dataspaces.vfs.selector.fast.FastFileSelector;
import org.objectweb.proactive.extensions.vfsprovider.FileSystemServerDeployer;
public class TestAntFileSelector {
private static URL DSroot = TestAntFileSelector.class.getResource("/functionaltests/" +
TestAntFileSelector.class.getSimpleName() + ".class");
private static String DSrootString;
@Test
public void run() throws Throwable {
File parent = new File(DSroot.toURI()).getParentFile();
DSrootString = parent.getAbsolutePath();
log(DSrootString);
//start DS server
FileSystemServerDeployer deployer = new FileSystemServerDeployer(DSrootString, true);
final String URL = deployer.getVFSRootURL();
//start DS naming service
NamingServiceDeployer namingServiceDeployer = new NamingServiceDeployer(true);
String namingServiceURL = namingServiceDeployer.getNamingServiceURL();
NamingService namingService = NamingService.createNamingServiceStub(namingServiceURL);
//create and add predefined spaces
Set<SpaceInstanceInfo> predefinedSpaces = new HashSet<SpaceInstanceInfo>();
InputOutputSpaceConfiguration isc = InputOutputSpaceConfiguration.createInputSpaceConfiguration(URL,
null, null, PADataSpaces.DEFAULT_IN_OUT_NAME);
predefinedSpaces.add(new SpaceInstanceInfo(12, isc));
namingService.registerApplication(12, predefinedSpaces);
//create node, start active object and configure node
Node n = NodeFactory.createLocalNode("node" + ((int) (Math.random() * 10000)), true, null, null);
TestAntFileSelector tafs = PAActiveObject.newActive(TestAntFileSelector.class, new Object[] {}, n);
tafs.configure();
//configure node application
DataSpacesNodes.configureApplication(n, 12, namingServiceURL);
//go go go!
ArrayList<String> results = tafs.test();
int nbFound = 0;
log("check include 1");
File rootFile = new File(DSrootString);
String[] checkReg = rootFile.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.matches("T.*[.]class");
}
});
nbFound += checkReg.length;
for (String s : checkReg) {
Assert.assertTrue(contains(results, s));
}
log("check include 2");
rootFile = new File(DSrootString + "/nodesource");
checkReg = rootFile.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.matches(".*[.]xml");
}
});
nbFound += checkReg.length;
for (String s : checkReg) {
Assert.assertTrue(contains(results, s));
}
log("check include 3");
rootFile = new File(DSrootString);
checkReg = recursiveList(rootFile, new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.matches(".*[.]ini");
}
});
nbFound += checkReg.length;
for (String s : checkReg) {
Assert.assertTrue(contains(results, s));
}
log("check include 4");
rootFile = new File(DSrootString + "/executables");
checkReg = rootFile.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.matches(".*[.]sh");
}
});
nbFound += checkReg.length;
for (String s : checkReg) {
Assert.assertTrue(contains(results, s));
}
Assert.assertEquals(results.size(), nbFound);
}
private String[] recursiveList(File root, FilenameFilter filter) {
List<String> list = new ArrayList<String>();
for (File f : root.listFiles()) {
if (f.isDirectory()) {
traverse(f, filter, list);
}
}
return list.toArray(new String[] {});
}
private void traverse(File root, FilenameFilter filter, List<String> list) {
for (File f : root.listFiles()) {
if (f.isDirectory()) {
traverse(f, filter, list);
}
}
Collections.addAll(list, root.list(filter));
}
private boolean contains(List<String> tab, String match) {
for (String s : tab) {
if (s.substring(s.lastIndexOf("/") + 1).equals(match)) {
return true;
}
}
return false;
}
public TestAntFileSelector() {
}
public void configure() throws Exception {
String scratchDir = System.getProperty("java.io.tmpdir");
final BaseScratchSpaceConfiguration scratchConf = new BaseScratchSpaceConfiguration(null, scratchDir);
DataSpacesNodes.configureNode(PAActiveObject.getActiveObjectNode(PAActiveObject.getStubOnThis()),
scratchConf);
}
public ArrayList<String> test() throws Exception {
FastFileSelector ant = new FastFileSelector();
ant.setIncludes(new String[] { "T*.class", "nodesource/*.xml", "**/*.ini", "executables/*.sh" });
ant.setCaseSensitive(true);
ArrayList<DataSpacesFileObject> results = new ArrayList<DataSpacesFileObject>();
Selector.findFiles(PADataSpaces.resolveDefaultInput(), ant, true, results);
log("RESULTS : size = " + results.size());
ArrayList<String> strings = new ArrayList<String>();
for (DataSpacesFileObject dataSpacesFileObject : results) {
log(dataSpacesFileObject.getVirtualURI());
strings.add(dataSpacesFileObject.getVirtualURI());
}
return strings;
}
private void log(String s) {
System.out.println("----------- " + s);
}
}
|
package cn.edu.cqut.mapper;
import cn.edu.cqut.entity.Customer;
import cn.edu.cqut.stats.SimpleCategory;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;
import java.util.List;
/**
* <p>
* Mapper 接口
* </p>
*
* @author HQYJ
* @since 2020-06-03
*/
public interface CustomerMapper extends BaseMapper<Customer> {
//没懂,通过contact的cusNo对customer中的数据进行查询
//many,一对多
@Select("select * from customer")
@Results({
@Result(column="cusNo",property="cusNo"),//显示cusNo
@Result(column="cusNo",property="contacts",many= @Many(
select="cn.edu.cqut.mapper.ContactMapper.selectContactByCusNo",
fetchType=FetchType.EAGER))//通过cusNo显示联系人列表
})
public List<Customer> selectCustomerWithContact();
@Select("select cusNo, cusName, transactionAmount from customer left join (select orderCustomerNo, orderTime, SUM(orderAmount) transactionAmount from sales group by orderCustomerNo) as tranAmount on customer.cusNo=tranAmount.orderCustomerNo ${ew.customSqlSegment}")
public Page<Customer> selectTotalTransactionAmount(
Page<Customer> page,
@Param(Constants.WRAPPER) QueryWrapper<Customer> queryWrapper
);
@Select("select ${ew.sqlSelect} FROM customer ${ew.customSqlSegment}")
public List<SimpleCategory> selectCustomerComposition(
@Param(Constants.WRAPPER) QueryWrapper<Customer> queryWrapper);
@Select("select cusName from customer where cusNo=#{cusNo}")
public String selectCusNameByCusNo(String cusNo);
@Select("select * from customer")
@Results(id="Customer", value={
@Result(column="cusNo", property="cusNo", id=true),
@Result(column="cusName", property="cusName"),
@Result(column="cusRegion ", property="cusRegion"),
@Result(column="cusAddr", property="cusAddr"),
@Result(column="cusUrl", property="cusUrl"),
@Result(column="cusLevel", property="cusLevel"),
@Result(column="cusCredit", property="cusCredit"),
@Result(column="cusSatisfied", property="cusSatisfied")
})
public List<Customer> selectAllCustomer();
}
|
package p0600;
import java.util.ArrayList;
import java.util.Random;
public class P0610 {
/**
* @param args
*/
public static void main(String[] args) {
//Déclarer l'ArrayList
ArrayList<Animal> combattants = new ArrayList<Animal>();
//Crée un random
Random r = new Random();
for (int i = 0; i < 20; i++) {
Chien c = new Chien("Chien"+(i+1), 8 +r.nextInt(5));
combattants.add(c);
}
for (int i = 0; i < combattants.size(); i++) {
combattants.get(i).crie();
}
//Tournoi
int tours = combattants.size()-1;
for (int i = 0; i < tours; i++) {
System.out.printf("-------%d-------\n", i+1);
Animal a1, a2, gagnant;
//Tirer deux animaux au hasard
a1 = combattants.remove(r.nextInt(combattants.size()));
a2 = combattants.remove(r.nextInt(combattants.size()));
//Les faire combattre
gagnant = a1.attaque(a2);
//Replace le gagnant dans la liste
combattants.add(gagnant);
}
//Le grand gagnant
System.out.println("==========");
System.out.printf("Le GRAND gagnant est : %s\n", combattants.get(0).getNom());
combattants.get(0).crie();
}
}
|
/**
*
*/
package com.beike.form;
/**
* <p>Title:腾讯QQ AccessToken 未设计类版本 </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2011</p>
* <p>Company: Sinobo</p>
* @date 2011-12-15
* @author qiaowb
* @version 1.0
*/
public class TencentqqAccessToken extends AccessToken {
private String openid;//openID
private String screenName;//显示名称
private String access_token;//要获取的Access Token
public String getScreenName() {
return screenName;
}
public void setScreenName(String screenName) {
this.screenName = screenName;
}
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public String getOpenid() {
return openid;
}
public void setOpenid(String openid) {
this.openid = openid;
}
} |
package com.se.onck3client.service;
import java.util.List;
import java.util.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.se.onck3client.model.Person;
@Service
public class PersonServiveRestClientImpl implements PersonService{
private RestTemplate restTemplate;
private String crmRestUrl;
private Logger logger = Logger.getLogger(getClass().getName());
@Autowired
public PersonServiveRestClientImpl(RestTemplate restTemp,@Value("${crm.rest.url.person}") String theUrl) {
super();
restTemplate = restTemp;
crmRestUrl = theUrl;
logger.info("Loaded properties: "+crmRestUrl);
}
@Override
public List<Person> getPersons() {
ResponseEntity<List<Person>> responseEntity = restTemplate.exchange(crmRestUrl,
HttpMethod.GET,
null,
new ParameterizedTypeReference<List<Person>>() {});
List<Person> list = responseEntity.getBody();
return list;
}
@Override
public Person getPerson(int id) {
Person p = restTemplate.getForObject(crmRestUrl + "/"+id, Person.class);
return p;
}
@Override
public void deletePerson(int id) {
restTemplate.delete(crmRestUrl+"/"+id);
}
@Override
public void savePerson(Person person) {
if(person.getId() == null) {
restTemplate.postForEntity(crmRestUrl, person, String.class);
}else {
restTemplate.put(crmRestUrl, person);
}
}
}
|
package com.bleuart.winksoft.idcardcer.bean;
import android.graphics.Bitmap;
public class IdCardBean {
private String mName;
private String mSex;
private String mNation; //国家
private String mBirth;
private String mAddress;
private String mCode;
private String mPolice; //签发机构
private String mFromValidDate; // 起始 - 有效期
private String mToValidDate; // 止 - 有效期
private Bitmap mPhoto; // 照片
private long t_ping;
private long t_cer;
private long t_commun;
public long getT_ping() {
return t_ping;
}
public void setT_ping(long t_ping) {
this.t_ping = t_ping;
}
public long getT_cer() {
return t_cer;
}
public void setT_cer(long t_cer) {
this.t_cer = t_cer;
}
public long getT_commun() {
return t_commun;
}
public void setT_commun(long t_commun) {
this.t_commun = t_commun;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
private long time;
// 1. ping 时间 ms login
// 2. 收到login - 发出com_1 + 收到 com_1 - 发出com_2 + 收到 com_2 - 发出com_3 + 收到 com_3 - 发出com_4 + 收到 com_4 - 发出com_5
// 3. 通信认证时间 发出com_1 + 收到 com_1 - 发出com_2 + 收到 com_2 - 发出com_3 + 收到 com_3 - 发出com_4 + 收到 com_4 - 发出com_5 + 收到com_5
// 4. 收到 com_5 时间点
// 可配置ip port
//
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
public String getSex() {
return mSex;
}
public void setSex(String sex) {
mSex = sex;
}
public String getNation() {
return mNation;
}
public void setNation(String nation) {
mNation = nation;
}
public String getBirth() {
return mBirth;
}
public void setBirth(String birth) {
mBirth = birth;
}
public String getAddress() {
return mAddress;
}
public void setAddress(String address) {
mAddress = address;
}
public String getCode() {
return mCode;
}
public void setCode(String code) {
mCode = code;
}
public String getPolice() {
return mPolice;
}
public void setPolice(String police) {
mPolice = police;
}
public String getFromValidDate() {
return mFromValidDate;
}
public void setFromValidDate(String fromValidDate) {
mFromValidDate = fromValidDate;
}
public String getToValidDate() {
return mToValidDate;
}
public void setToValidDate(String toValidDate) {
mToValidDate = toValidDate;
}
public Bitmap getPhoto() {
return mPhoto;
}
public void setPhoto(Bitmap photo) {
mPhoto = photo;
}
}
|
package com.wmc.adapter;
import java.util.List;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.v4.app.Fragment;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.wmc.dbhelper.NoteDBHelper;
import com.wmc.dialog.DialogButtonListener;
import com.wmc.dialog.MyDialog;
import com.wmc.domain.Note;
import com.wmc.note.R;
public class NoteAdapter extends BaseAdapter {
private static class ViewHolder{
TextView name;
TextView time;
TextView content;
ImageButton delete;
}
private List<Note> notes;
private Fragment noteFragment;
public NoteAdapter(Fragment noteFragment, List<Note> notes) {
this.noteFragment = noteFragment;
this.notes = notes;
}
@Override
public int getCount() {
return notes.size();
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {//这里不可能去改position的值,所以设置final完全没有影响
ViewHolder holder;
if(convertView == null) {
convertView = View.inflate(noteFragment.getActivity(), R.layout.note_item, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.time = (TextView) convertView.findViewById(R.id.time);
holder.content = (TextView) convertView.findViewById(R.id.content);
holder.delete = (ImageButton) convertView.findViewById(R.id.delete);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
//接下来为该View初始化界面显示
Note theNote = notes.get(position);
holder.time.setText(theNote.getTime());
final String id = theNote.getId()+"";
final String name = theNote.getName();
final String content = theNote.getContent();
holder.name.setText(name);
holder.content.setText(content);
//使用listview的onItemClickListener没一点卵用,所以在这里设置点击事件
convertView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.putExtra("id", id);
intent.putExtra("name", name);
intent.putExtra("content", content);
intent.setAction("android.intent.action.OpenEdit");
intent.addCategory("android.intent.category.DEFAULT");
noteFragment.startActivityForResult(intent, 2);
}
});
holder.delete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view)
{
new MyDialog().show(noteFragment.getActivity(), R.drawable.indicator_input_error, "是否要删除该便签?", new DialogButtonListener() {
@Override
public void sure() {
//数据库中删除
NoteDBHelper helper = new NoteDBHelper(noteFragment.getActivity());
SQLiteDatabase database = helper.getWritableDatabase();
int row = database.delete("note", "id=?", new String[]{id});
if(row == -1)
Toast.makeText(noteFragment.getActivity(), "删除失败!", Toast.LENGTH_SHORT).show();
else{
//数据删除成功,界面才能删除
notes.remove(position);
notifyDataSetChanged();
}
database.close();
}
@Override
public void cancel(){}
});
}
});
return convertView;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
}
|
public class Main2 {
public static void main(String[] args) {
double d = 123123.1231d;
float f = 224412.11f;
System.out.println((float)d);
System.out.println((int)f);
float ff = 3.402e38f;
System.out.println((int)ff);
}
}
|
package br.com.fiap.entity;
public enum TipoUsuario {
ADMINISTRATIVO,
PROFESSOR,
ALUNO;
}
|
package cn.truistic.touchimageviewdemo.demo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.bumptech.glide.Glide;
import cn.truistic.touchimageviewdemo.R;
import cn.truistic.touchimageviewdemo.lib.TouchImageView;
/**
* Glide Test
*/
public class GlideActivity extends AppCompatActivity {
private TouchImageView timgView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_glide);
timgView = (TouchImageView) findViewById(R.id.timg_glide);
Glide.with(this).load(R.drawable.img_big).asBitmap().into(timgView);
}
}
|
package CollectionProgram;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CloneaArrayList {
public static void main(String[] args)
{
// Create a list
List<String> original
= Arrays.asList(
"Nirbhay Gupta",
"A Computer Engineer",
"SDET");
// Clone the list
List<String> cloned_list
= new ArrayList<String>(original);
System.out.println(cloned_list);
}
}
|
//Created by MyEclipse Struts
// XSL source (default): platform:/plugin/com.genuitec.eclipse.cross.easystruts.eclipse_3.8.2/xslt/JavaClass.xsl
package com.aof.webapp.action.helpdesk.puquery;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.aof.webapp.action.BaseAction;
import com.aof.webapp.action.party.ListPartyAction;
import com.aof.webapp.form.helpdesk.UsersubForm;
/**
* MyEclipse Struts
* Creation date: 11-18-2004
*
* XDoclet definition:
* @struts:action path="/Usersub" name="UsersubForm" input="/WEB-INF/jsp/puquery/UserQry.jsp" scope="request" validate="true"
*/
public class Usersub extends com.shcnc.struts.action.BaseAction {
// --------------------------------------------------------- Instance Variables
// --------------------------------------------------------- Methods
/**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) {
UsersubForm UsersubForm = (UsersubForm) form;
Logger log = Logger.getLogger(ListPartyAction.class.getName());
Locale locale = getLocale(request);
try{
List result = new ArrayList();
// net.sf.hibernate.Session session = Hibernate2Session.currentSession();
// Query q = session.createQuery("select p from Party as p inner join p.partyRoles as pr where pr.roleTypeId = 'ORGANIZATION_UNIT'");
// result = q.list();
//
// request.setAttribute("custPartys",result);
//
//
PartyResult mPs= new PartyResult();
result=mPs.getSelCust(UsersubForm.getType(),UsersubForm.getDesc(),UsersubForm.getName(),UsersubForm.getNote());
request.setAttribute("custusers",result);
}catch(Exception e){
log.error(e.getMessage());
}finally{
}
return (mapping.findForward("OK"));
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.