text
stringlengths 10
2.72M
|
|---|
package com.ibeiliao.trade.api.dto;
import java.io.Serializable;
import java.util.Date;
import com.ibeiliao.trade.api.enums.ItemType;
/**
* 订单项详细信息VO类
* @author jingyesi
* @date 2016年7月15日 下午3:51:17
*
*/
public class OrderItemVO implements Serializable{
/**
*
*/
private static final long serialVersionUID = 8432592716426160911L;
private long orderItemId;
private String outerOrderId;
private String outerItemid;
private String cateId;
private String itemName;
private int itemCnt;
private long itemPrice;
private long itemAmount;
private long paymentAmount;
private ItemType itemType;
private Date createTime;
private Date cancelTime;
public long getOrderItemId() {
return orderItemId;
}
public void setOrderItemId(long orderItemId) {
this.orderItemId = orderItemId;
}
public String getOuterOrderId() {
return outerOrderId;
}
public void setOuterOrderId(String outerOrderId) {
this.outerOrderId = outerOrderId;
}
public String getOuterItemid() {
return outerItemid;
}
public void setOuterItemid(String outerItemid) {
this.outerItemid = outerItemid;
}
public String getCateId() {
return cateId;
}
public void setCateId(String cateId) {
this.cateId = cateId;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public int getItemCnt() {
return itemCnt;
}
public void setItemCnt(int itemCnt) {
this.itemCnt = itemCnt;
}
public long getItemPrice() {
return itemPrice;
}
public void setItemPrice(long itemPrice) {
this.itemPrice = itemPrice;
}
public long getItemAmount() {
return itemAmount;
}
public void setItemAmount(long itemAmount) {
this.itemAmount = itemAmount;
}
public long getPaymentAmount() {
return paymentAmount;
}
public void setPaymentAmount(long paymentAmount) {
this.paymentAmount = paymentAmount;
}
public ItemType getItemType() {
return itemType;
}
public void setItemType(ItemType itemType) {
this.itemType = itemType;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getCancelTime() {
return cancelTime;
}
public void setCancelTime(Date cancelTime) {
this.cancelTime = cancelTime;
}
}
|
package org.bokontep.wavesynth;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
public class WaveDisplay extends View {
public WaveDisplay(Context context, AttributeSet attrs) {
super(context,attrs);
setFocusable(true);
setFocusableInTouchMode(true);
setupPaint();
}
public void setupPaint()
{
drawPaintForeground = new Paint();
drawPaintForeground.setColor(foregroundColor);
drawPaintForeground.setAntiAlias(true);
drawPaintForeground.setStrokeWidth(4);
drawPaintForeground.setStyle(Paint.Style.FILL_AND_STROKE);
drawPaintForeground.setTextSize(44);
drawPaintBackground = new Paint();
drawPaintBackground.setColor(backgroundColor);
drawPaintBackground.setAntiAlias(true);
drawPaintBackground.setStrokeWidth(4);
drawPaintBackground.setStyle(Paint.Style.FILL_AND_STROKE);
drawPaintBackground.setTextSize(44);
}
public void setData(float[] newData)
{
data = newData;
}
@Override
protected void onDraw(Canvas canvas) {
// canvas.drawRect(0,0,w,h,this.drawPaintForeground);
if(data == null)
{
return;
}
for(int i=0;i<data.length-1;i++)
{
canvas.drawLine(xstart + i*xstep,ystart-ystep*data[i],xstart+((i+1)*xstep),ystart-ystep*data[i+1], drawPaintForeground);
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
this.w = w;
this.h = h;
if(data!=null) {
xstep = (int)(w / data.length);
ystep = (int)(h/2.0f);
xstart = (int)0;
ystart = (int)(h/2.0f);
}
else
{
xstep = (int)(w / 256.0f);
ystep = (int)(h/2.0f);
xstart = (int)0f;
ystart = (int)(h/2.0f);
}
//Log.d("INFO","ViewSize=("+w+","+h+") xstep="+xstep+" ystep="+ystep+" xstart="+xstart+"ystart="+ystart);
}
public void setRed(boolean flag)
{
if(flag)
{
this.foregroundColor = Color.RED;
}
else
{
this.foregroundColor = Color.GREEN;
}
this.drawPaintForeground.setColor(this.foregroundColor);
this.invalidate();
}
float[] data;
int w;
int h;
int xstep;
int ystep;
int xstart;
int ystart;
private int foregroundColor = Color.GREEN;
private final int backgroundColor = Color.BLACK;
private Paint drawPaintForeground;
private Paint drawPaintBackground;
}
|
package JavaSE.OO.IO;
import java.io.FileNotFoundException;
import java.io.*;
/*
* 文件复制,只能复制纯文本文件
*/
public class copy02 {
public static void main(String[] args) throws Exception {
FileReader fr=new FileReader("E:\\test03.txt");
FileWriter fw=new FileWriter("D:\\test03.txt");
char[] chars=new char[512];
int temp = 0;
while((temp=fr.read(chars))!=-1) {
//写
fw.write(chars,0,temp);
}
fw.flush();
fr.close();
fw.close();
}
}
|
package sbnz.integracija.example.models;
import java.util.ArrayList;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import sbnz.integracija.example.enums.Equipment;
import sbnz.integracija.example.enums.PhysicalLevel;
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
//private String username;
//private String password;
@Column(name = "weight")
private double weight;
@Column(name = "height")
private double height;
@Column(name = "pl")
private PhysicalLevel pl;
@Column(name = "equipment")
private ArrayList<Equipment> equipment;
public User(long id, String username, String password, double weight, double height, PhysicalLevel pl,
ArrayList<Equipment> equipment) {
super();
this.id = id;
this.weight = weight;
this.height = height;
this.pl = pl;
this.equipment = equipment;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public PhysicalLevel getPl() {
return pl;
}
public void setPl(PhysicalLevel pl) {
this.pl = pl;
}
public ArrayList<Equipment> getEquipment() {
return equipment;
}
public void setEquipment(ArrayList<Equipment> equipment) {
this.equipment = equipment;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Modelos;
/**
*
* @author Administrator
*/
public class CategoriaTipoCalzados {
private int id_categoriatipocalzado;
private String nombre_categoriatipocalzado;
public CategoriaTipoCalzados() {
}
public CategoriaTipoCalzados(int id_categoriatipocalzado, String nombre_categoriatipocalzado) {
this.id_categoriatipocalzado = id_categoriatipocalzado;
this.nombre_categoriatipocalzado = nombre_categoriatipocalzado;
}
public int getId_categoriatipocalzado() {
return id_categoriatipocalzado;
}
public void setId_categoriatipocalzado(int id_categoriatipocalzado) {
this.id_categoriatipocalzado = id_categoriatipocalzado;
}
public String getNombre_categoriatipocalzado() {
return nombre_categoriatipocalzado;
}
public void setNombre_categoriatipocalzado(String nombre_categoriatipocalzado) {
this.nombre_categoriatipocalzado = nombre_categoriatipocalzado;
}
}
|
package com.github.limboc.refresh;
public interface SwipeRefreshTrigger {
void onRefresh();
}
|
package saif.com.vaadin.ui.GridPanel;
import java.util.Map;
/**
*
* @author Saiful Islam<saifislam2167@gmail.com>
*/
public interface NotificationMsgProvider {
public static final String KEY_EXPORT_MSG="ui.msg.export";
public static final String KEY_REFRESH_MSG="ui.msg.refresh";
public static final String KEY_FIRST_MSG="ui.msg.first";
public static final String KEY_LAST_MSG="ui.msg.last";
public static final String KEY_FORWARD_MSG="ui.msg.forward";
public static final String KEY_BACKWARD_MSG="ui.msg.backward";
public static final String GRID_EXPORT_HEADER="ui.msg.backward";
String getInvalidPageNumberMsg();
String getInvalidNumberFormatMsg();
String getMaxPageReachedMsg();
String getInvalidDateFormatMsg();
Map<String,String> getCommonLocaleMgs();
}
|
package edu.sit.erro.venda;
public enum EErrosVenda {
BUSCA_LISTA_PRODUTO("Erro ao buscar os produtos "),
BUSCA_LISTA_CLIENTE("Erro ao buscar os clientes");
private String mensagem;
public String getMensagem() {
return mensagem;
}
private EErrosVenda(String mensagem) {
this.mensagem = mensagem;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.printcalculator.enums;
/**
*
* @author LiH
*/
public enum PrintJobName {
Unknown("Unknown"),
A4SingleSide("A4 Single Sided Print Job"),
A4DoubleSide("A4 Double Sided Print Job");
PrintJobName(String name) {
this.name = name;
}
private final String name;
public String getName() {
return name;
}
}
|
package com.xu.easyweb.util.annotation;
/**
* 在从属对象(表)中标识主对象(表)的set函数
* User: zht
* Date: 12-8-30
* Time: 上午8:26
* To change this template use File | Settings | File Templates.
*/
@java.lang.annotation.Target({java.lang.annotation.ElementType.METHOD})
@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
public @interface Master {
}
|
package com.tencent.mm.plugin.nearby.ui;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import com.tencent.mm.R;
import com.tencent.mm.ui.MMActivity;
import com.tencent.mm.ui.widget.a.c;
public class NearbyFriendsIntroUI extends MMActivity {
private Button eGn;
private View lBE;
private CheckBox lBF;
private c lBH = null;
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setMMTitle(R.l.nearby_friend_title);
initView();
}
protected final int getLayoutId() {
return R.i.nearby_friend_intro;
}
protected final void initView() {
this.lBE = View.inflate(this, R.i.lbs_open_dialog_view, null);
this.lBF = (CheckBox) this.lBE.findViewById(R.h.lbs_open_dialog_cb);
this.lBF.setChecked(false);
this.eGn = (Button) findViewById(R.h.nearby_friend_intro_start_btn);
this.eGn.setOnClickListener(new 1(this));
setBackBtn(new 2(this));
}
}
|
package prototype.design.pattern.example;
public interface Animal extends Cloneable{
Animal createClone();
}
|
package removeadjcent;
public class Solutiontest {
public static void main(String [] args){
Solution s = new Solution();
System.out.println(s.deDup("abc"));
}
}
|
package ru.aahzbrut.reciperestapi.dto.responses.note;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import java.time.LocalDateTime;
import static ru.aahzbrut.reciperestapi.utils.Constants.ISO_DATE_TIME_PATTERN;
@Setter
@Getter
@NoArgsConstructor
@Accessors(chain = true)
public class NoteResponse {
private Long id;
private Long recipeId;
private String noteText;
@JsonFormat(pattern = ISO_DATE_TIME_PATTERN)
private LocalDateTime createdDateTime;
@JsonFormat(pattern = ISO_DATE_TIME_PATTERN)
private LocalDateTime updatedDateTime;
}
|
import java.util.Scanner;
public class Example2_10
{
public static void main(String[] args)// calculating energy
{
//create a scanner object
Scanner input = new Scanner(System.in);
//prompt to enter the amount of water in kilograms
System.out.print(" Enter the amount of water in kilograms: ");
// m is the weight of water in kilograms
double M = input.nextDouble();
//prompt the user to enter the intial temperature
System.out.print(" Enter the intial temperature : ");
double intialTemperature = input.nextDouble();
//prompt the user to enter the final temperature
System.out.print(" Enter the final temperature : ");
double finalTemperature = input.nextDouble();
//compute the energy
double Q = M *(finalTemperature - intialTemperature)* 4184;
System.out.println(" The energy needed is " +Q);
}
}
|
package com.liu.Class;
import java.io.Serializable;
public class joinresponse implements Serializable{
private Boolean status;
private Boolean changeheading;
private String formationid;
private String prevehid;//前车的id
private String behvehid;//后车的ID
private int membernum;
public void setStatus(Boolean status) {
this.status = status;
}
public void setChangeheading(Boolean changeheading) {
this.changeheading = changeheading;
}
public void setFormationid(String formationid) {
this.formationid = formationid;
}
public void setPrevehid(String prevehid) {
this.prevehid = prevehid;
}
public void setBehvehid(String behvehid) {
this.behvehid = behvehid;
}
public void setMembernum(int membernum) {
this.membernum = membernum;
}
public Boolean getStatus() {
return status;
}
public Boolean getChangeheading() {
return changeheading;
}
public String getFormationid() {
return formationid;
}
public String getPrevehid() {
return prevehid;
}
public String getBehvehid() {
return behvehid;
}
public int getMembernum() {
return membernum;
}
}
|
package com.cnk.travelogix.custom.zif.erp.ws.opportunity;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
/**
* <p>Java class for ZifProdCatAircraft complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ZifProdCatAircraft">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="DepartureDate" type="{urn:sap-com:document:sap:rfc:functions}date10"/>
* <element name="DepartureTime" type="{urn:sap-com:document:sap:rfc:functions}time"/>
* <element name="ReturnDate" type="{urn:sap-com:document:sap:rfc:functions}date10"/>
* <element name="ReturnTime" type="{urn:sap-com:document:sap:rfc:functions}time"/>
* <element name="NoOfPassangers" type="{urn:sap-com:document:sap:rfc:functions}numeric2"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ZifProdCatAircraft", propOrder = {
"departureDate",
"departureTime",
"returnDate",
"returnTime",
"noOfPassangers"
})
public class ZifProdCatAircraft {
@XmlElement(name = "DepartureDate", required = true)
protected String departureDate;
@XmlElement(name = "DepartureTime", required = true)
@XmlSchemaType(name = "time")
protected XMLGregorianCalendar departureTime;
@XmlElement(name = "ReturnDate", required = true)
protected String returnDate;
@XmlElement(name = "ReturnTime", required = true)
@XmlSchemaType(name = "time")
protected XMLGregorianCalendar returnTime;
@XmlElement(name = "NoOfPassangers", required = true)
protected String noOfPassangers;
/**
* Gets the value of the departureDate property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDepartureDate() {
return departureDate;
}
/**
* Sets the value of the departureDate property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDepartureDate(String value) {
this.departureDate = value;
}
/**
* Gets the value of the departureTime property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getDepartureTime() {
return departureTime;
}
/**
* Sets the value of the departureTime property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setDepartureTime(XMLGregorianCalendar value) {
this.departureTime = value;
}
/**
* Gets the value of the returnDate property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getReturnDate() {
return returnDate;
}
/**
* Sets the value of the returnDate property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setReturnDate(String value) {
this.returnDate = value;
}
/**
* Gets the value of the returnTime property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getReturnTime() {
return returnTime;
}
/**
* Sets the value of the returnTime property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setReturnTime(XMLGregorianCalendar value) {
this.returnTime = value;
}
/**
* Gets the value of the noOfPassangers property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNoOfPassangers() {
return noOfPassangers;
}
/**
* Sets the value of the noOfPassangers property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNoOfPassangers(String value) {
this.noOfPassangers = value;
}
}
|
/**
*
*/
package presentacion.controlador.command.CommandLibro;
import negocio.factorias.FactorySA;
import negocio.libro.SALibro;
import presentacion.contexto.Contexto;
import presentacion.controlador.command.Command;
import presentacion.eventos.EventosLibro;
/**
* The Class BajaLibro.
*/
public class BajaLibro implements Command {
/*
* (non-Javadoc)
*
* @see presentacion.controlador.command.Command#execute(java.lang.Object)
*/
@Override
public Contexto execute(final Object objeto) {
final Integer idLibro = (Integer) objeto;
final SALibro sa = FactorySA.getInstance().createLibro();
String mensaje;
Contexto contexto;
try {
sa.bajaLibro(idLibro);
mensaje = "Libro dado de baja corretamente. Su ID es: " + idLibro + ". ";
contexto = new Contexto(EventosLibro.BAJA_LIBRO_OK, mensaje);
} catch (final Exception e) {
mensaje = e.getMessage();
contexto = new Contexto(EventosLibro.BAJA_LIBRO_KO, mensaje);
}
return contexto;
}
}
|
package Tree.BinaryTree.Traversal.BFS;
public class Traversal {
static class Node {
int key;
Node left;
Node right;
Node(int key) {
this.key = key;
this.left = this.right = null;
}
}
static class BinaryTree {
Node root;
BinaryTree() {
root = null;
}
BinaryTree(int key) {
root = new Node(key);
}
// Pre-Order traversal follows:
// (ROOT-LEFT-RIGHT)
void preOrderTraversal(Node temp) {
if (temp == null)
return;
System.out.print(temp.key + " ");
preOrderTraversal(temp.left);
preOrderTraversal(temp.right);
}
// In-Order Traversal follows:
// (LEFT-ROOT-RIGHT)
void inOrderTraversal(Node temp) {
if (temp == null)
return;
inOrderTraversal(temp.left);
System.out.print(temp.key + " ");
inOrderTraversal(temp.right);
}
// Post-Order Traversal follows:
// (LEFT-RIGHT-ROOT)
void postOrderTraversal(Node temp) {
if (temp == null)
return;
postOrderTraversal(temp.left);
postOrderTraversal(temp.right);
System.out.print(temp.key + " ");
}
public static void main(String[] args) {
BinaryTree tree = new BinaryTree(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
System.out.println("Pre-Order Traversal: ");
tree.preOrderTraversal(tree.root);
System.out.println("\n");
System.out.println("In-Order Traversal: ");
tree.inOrderTraversal(tree.root);
System.out.println("\n");
System.out.println("Post-Order Traversal: ");
tree.postOrderTraversal(tree.root);
System.out.println("\n");
}
}
}
|
package kyle.game.besiege;
public interface Value {
public float getValue();
}
|
package com.e6soft.bpm.dao.impl;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.e6soft.core.mybatis.BaseEntityDao;
import com.e6soft.bpm.dao.FlowAgencyWorkflowDao;
import com.e6soft.bpm.model.FlowAgencyWorkflow;
@Transactional
@Repository("flowAgencyWorkflowDao")
public class FlowAgencyWorkflowDaoImpl extends BaseEntityDao<FlowAgencyWorkflow,String> implements FlowAgencyWorkflowDao {
public FlowAgencyWorkflowDaoImpl() {
super(FlowAgencyWorkflow.class);
}
}
|
package application;
import java.util.ArrayList;
import java.util.HashMap;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
public class LEDHandler {
private ArrayList<LED> leds;
public LEDHandler() {
this.leds = new ArrayList<LED>();
}
public void addLED(String label, Color cond1Color, Color cond2Color, Color elseColor, String cond1, String cond2, boolean has2Clause, Rectangle gui_Rect) {
LED led = new LED(label, cond1Color, cond2Color, elseColor, cond1, cond2, has2Clause, gui_Rect);
leds.add(led);
}
public void updateLEDs(HashMap<String, Boolean> virtualRelays) {
for(LED led: leds) {
boolean cond1 = virtualRelays.get(led.getCond1());
if(led.has2clause()) {
boolean cond2 = virtualRelays.get(led.getCond2());
led.update(cond1, cond2);
} else {
led.update(cond1, false);
}
}
}
public ArrayList<LED> getLEDs() {
return leds;
}
}
|
package com.brd.brdtools.parser;
import com.brd.brdtools.SqlBaseListener;
import com.brd.brdtools.SqlParser;
import com.brd.brdtools.model.sql.Column;
import com.brd.brdtools.model.sql.Database;
import com.brd.brdtools.model.sql.ForeignKey;
import com.brd.brdtools.model.sql.Table;
import com.brd.brdtools.SqlParser.Alter_table_add_constraintContext;
import com.brd.brdtools.SqlParser.Alter_table_stmtContext;
import com.brd.brdtools.SqlParser.Any_nameContext;
import com.brd.brdtools.SqlParser.Fk_origin_column_nameContext;
import com.brd.brdtools.SqlParser.Fk_target_column_nameContext;
import com.brd.brdtools.SqlParser.Foreign_tableContext;
import com.brd.brdtools.SqlParser.Indexed_columnContext;
import com.brd.brdtools.SqlParser.Source_table_nameContext;
import com.brd.brdtools.SqlParser.Table_constraint_foreign_keyContext;
import com.brd.brdtools.SqlParser.Table_constraint_primary_keyContext;
import com.brd.brdtools.util.Util;
/**
* Parse Listener only for ALTER TABLE statements parsing.
*/
public class AlterTableParseListener extends SqlBaseListener {
/**
* Debug mode to display ANTLR v4 contexts.
*/
private static boolean DEBUG = false;
/**
* ANTLR Parser
*/
private final SqlParser sqlParser;
/**
* Database schema
*/
private final Database database;
Table table;
Column column;
ForeignKey foreignKey;
boolean inAlter_table_stmt = false; // ALTER TABLE
boolean inAlter_table_add_constraint = false; // ALTER TABLE with ADD CONSTRAINT
boolean inTable_constraint_primary_key = false; // PRIMARY KEY in ALTER TABLE
boolean inTable_constraint_foreign_key = false; // FOREIGN KEY in ALTER TABLE
/**
* Utils methods.
*/
Util util = new Util();
/**
* Constructor.
* @param sqlParser SQL parser
* @param database Database
*/
public AlterTableParseListener(final SqlParser sqlParser, final Database database) {
this.sqlParser = sqlParser;
this.database = database;
}
/**
* Used only for debug, its called for each token based on the token "name".
*/
@Override
public void exitAny_name(final Any_nameContext ctx) {
if(DEBUG) {
System.out.println(ctx.getText() + " - ctx : " + ctx.toInfoString(sqlParser));
}
}
//--- ALTER TABLE
@Override
public void enterAlter_table_stmt(final Alter_table_stmtContext ctx) {
inAlter_table_stmt = true;
}
@Override
public void exitAlter_table_stmt(final Alter_table_stmtContext ctx) {
inAlter_table_stmt = false;
}
@Override
public void exitSource_table_name(final Source_table_nameContext ctx) {
if(inAlter_table_stmt) {
table = database.getTableForName(util.unformatSqlName(ctx.getText()));
}
}
//--- Add constraint
@Override
public void enterAlter_table_add_constraint(
final Alter_table_add_constraintContext ctx) {
inAlter_table_add_constraint = true;
}
@Override
public void exitAlter_table_add_constraint(
final Alter_table_add_constraintContext ctx) {
inAlter_table_add_constraint = false;
}
//--- Constraints
//--- Primary Key in ALTER TABLE
@Override
public void enterTable_constraint_primary_key(
final Table_constraint_primary_keyContext ctx) {
inTable_constraint_primary_key = true;
}
@Override
public void exitTable_constraint_primary_key(
final Table_constraint_primary_keyContext ctx) {
inTable_constraint_primary_key = false;
}
@Override
public void exitIndexed_column(final Indexed_columnContext ctx) {
if(inAlter_table_stmt && inTable_constraint_primary_key) {
final String columnName = util.unformatSqlName(ctx.getText());
table.getPrimaryKey().getColumnNames().add(columnName);
}
}
//--- Foreign Key in CREATE TABLE or in ALTER TABLE
@Override
public void enterTable_constraint_foreign_key(
final Table_constraint_foreign_keyContext ctx) {
inTable_constraint_foreign_key = true;
if(inAlter_table_stmt) {
foreignKey = new ForeignKey();
foreignKey.setTableNameOrigin(table.getName());
}
}
@Override
public void exitTable_constraint_foreign_key(
final Table_constraint_foreign_keyContext ctx) {
if(inAlter_table_stmt) {
foreignKey.setTableNameOrigin(table.getName());
table.getForeignKeys().add(foreignKey);
foreignKey = null;
}
inTable_constraint_foreign_key = false;
}
@Override
public void exitForeign_table(final Foreign_tableContext ctx) {
if(inTable_constraint_foreign_key) {
foreignKey.setTableNameTarget(util.unformatSqlName(ctx.getText()));
}
}
@Override
public void exitFk_origin_column_name(
final Fk_origin_column_nameContext ctx) {
if(inTable_constraint_foreign_key) {
foreignKey.getColumnNameOrigins().add(util.unformatSqlName(ctx.getText()));
}
}
@Override
public void exitFk_target_column_name(
final Fk_target_column_nameContext ctx) {
if(inTable_constraint_foreign_key) {
foreignKey.getColumnNameTargets().add(util.unformatSqlName(ctx.getText()));
}
}
}
|
import java.util.*;
import java.io.*;
import java.io.FileNotFoundException;
public class Naloga6 {
public static PrintWriter izhod;
public static Scanner in;
public static ArrayList<String> fst = new ArrayList<String>();
public static ArrayList<String> scnd = new ArrayList<String>();
public static void main(String[] args) throws FileNotFoundException, IOException {
File file = new File(args[0]);
izhod = new PrintWriter(new FileWriter(args[1]));
in = new Scanner(file);
int stZapisov = in.nextInt();
for (int i = 0; i < stZapisov; i++) {
String[] car_driver = in.next().split("-");
String one = car_driver[0];
String two = car_driver[1];
int one_in = find(one);
int two_in = find(two);
if (one_in == two_in && one_in > -1) {
System.out.printf("NAPAKA!: one: %s .. one_in: %d, two: %s ..two_in: %d\n", one, one_in, two, two_in);
return;
}
if (one_in <= -1) {
if (two_in <= -1) {
fst.add(one);
scnd.add(two);
} else {
// Prvi ni nikjer, daj ga drugam kot je drugi
if (two_in == 0) {
// Drugi je v fst, dodaj prvega v scnd
scnd.add(one);
} else {
// Obratno
fst.add(one);
}
}
} else {
// Prvega smo nasli v fst
if (one_in == 0) {
if (two_in <= -1) {
scnd.add(two);
}
} else {
// Prvega smo nasli v scnd
if (two_in <= -1) {
fst.add(two);
}
}
}
System.out.println("Prvi");
printList(fst);
System.out.println("Drugi");
printList(scnd);
//System.out.printf("1st found in %d .. 2nd found in %d\n", one_in, two_in);
// Prvega vedno isci, ce ga najdes poglej ce je drugi slucajno v istem arraylistu, ce je potem je napaka
}
if (fst.size() == scnd.size()) {
System.out.println("-1");
} else {
if (fst.size() > scnd.size()) {
printList(fst);
} else {
printList(scnd);
}
}
}
public static int find(String value) {
/*
- If value is found in 1st return 0
- If value is found in 2nd return 1
- If value isn't found in any return -1
*/
// First search in fst
ListIterator it = fst.listIterator();
while (it.hasNext()) {
if (it.next().equals(value)) {
return 0;
}
}
it = scnd.listIterator();
while (it.hasNext()) {
if (it.next().equals(value)) {
return 1;
}
}
return -1;
}
public static void insertUnique(ArrayList list, String value) {
ListIterator<String> it = list.listIterator();
while (it.hasNext()) {
if (it.next().equals(value)) {
return;
}
}
list.add(value);
return;
}
public static void printList(ArrayList l) {
ListIterator it = l.listIterator();
while (it.hasNext()) {
System.out.printf("%s, ", it.next());
}
System.out.println();
}
}
|
package com.designPattern.com.imooc.strategy;
/**
* @Author : Admin
* @Description :
* @Date : 2018/6/28 11:18
*/
/*
* 策略接口,实现鸭子的飞行行为
*/
public interface FlyingStragety {
void performFly();
}
|
package page;
import java.util.Random;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
public class BasePage {
public void dropdown(WebElement element, String abc)
{ Select sel= new Select (element);
sel.selectByVisibleText(abc);
}
public int randomnumber (int boundary) {
Random rnd= new Random();
int randomn=rnd.nextInt(boundary);
return randomn;
}
}
|
package com.movieapi.movieapi.exception;
public class MissingServletRequestParameterException extends Exception {
public MissingServletRequestParameterException(String msg) {
super(msg);
}
}
|
public class logInService {
// line1 added
// added god words to Login Service
}
|
package com.uinsk.mobileppkapps;
public class LoginViewModel {
}
|
package com.yourtravel.entity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import javax.persistence.*;
@Entity
@Data
@Table(name = "CITY")
@ToString(exclude = {"country"})
@EqualsAndHashCode(exclude = {"country"})
public class City {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "country_id", nullable = false)
private Country country;
}
|
package com.noteshare.solr.utils;
import java.util.HashMap;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import com.noteshare.common.utils.resources.Configuration;
public class SolrUtil {
private static HashMap<String, HttpSolrClient> solrMap = new HashMap<String, HttpSolrClient>();
/**
* @Title : getSolrClient
* @Description : 根据core的类型来获取solr客户端对象
* @param coreName : core名称,如果为null则去默认名称
* @return : SolrClient
* @author : xingchen
* @date : 2016年8月6日 上午11:12:15
* @throws
*/
public static HttpSolrClient getSolrClient(String coreName){
if(null == coreName || "".equals(coreName)){
coreName = SolrConstant.DEFAULTCORENAME;
}
if (solrMap.containsKey(coreName) && null != solrMap.get(coreName)) {
return solrMap.get(coreName);
}else{
String corepath = Configuration.getProperty(SolrConstant.COREPATH, "http://localhost/solr/");
HttpSolrClient.Builder solrBuilder = new HttpSolrClient.Builder(corepath + coreName);
HttpSolrClient solrClient = solrBuilder.build();
solrMap.put(coreName, solrClient);
return solrClient;
}
}
/**
* @Title : escapeQueryChars
* @Description : 对特殊字符进行替换
* @param condition : 查询条件
* @return : String
* @author : xingchen
* @date : 2016年8月28日 上午8:26:24
* @throws
*/
public static String escapeQueryChars(String condition) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < condition.length(); i++) {
char c = condition.charAt(i);
// These characters are part of the query syntax and must be escaped
if (c == '\\' || c == '+' || c == '-' || c == '!' || c == '(' || c == ')' || c == ':'
|| c == '^' || c == '[' || c == ']' || c == '\"' || c == '{' || c == '}' || c == '~'
|| c == '*' || c == '?' || c == '|' || c == '&' || c == ';' || c == '/'
|| Character.isWhitespace(c)) {
sb.append('\\');
}
sb.append(c);
}
return sb.toString();
}
}
|
package exceleg.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import exceleg.repository.ExcelRepository;
import exceleg.entities.TestDataBean;
public class ExcelController {
public static void main(String[] args) {
ExcelRepository excelRepo = new ExcelRepository();
try {
//Reading the file
String fileName = "testData.xlsx";
FileInputStream dataStream = new FileInputStream(new File(fileName));
XSSFWorkbook xwb = new XSSFWorkbook(dataStream);
XSSFSheet xSheet = xwb.getSheetAt(0);
ArrayList<TestDataBean> dataList = excelRepo.readExcel(xSheet);
System.out.println(Arrays.toString(dataList.toArray()));
//Writing to a new file
excelRepo.writeExcel(dataList);
//Creating a pivot with multiple column labels
excelRepo.createPivot();
xwb.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package net.sf.ardengine.renderer.opengl.modern;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.nio.FloatBuffer;
import javafx.scene.paint.Color;
import net.sf.ardengine.ASprite;
import net.sf.ardengine.renderer.opengl.lib.textures.Texture;
import net.sf.ardengine.renderer.opengl.lib.textures.TextureManager;
import net.sf.ardengine.renderer.ISpriteImpl;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL20;
public class ModernOpenGLSpriteImpl extends ModernOpenGLRenderable implements ISpriteImpl{
protected static int genericSprites = 0;
protected ASprite parentSprite;
protected Texture spriteTexture;
private final String textureName;
private boolean requiresInit = true;
protected final static float[] textureUVCoordinates = {
0f, 0f,
0f, 1f,
1f, 0f,
1f, 1f
};
protected final static FloatBuffer textureUVCoordinatesBuffer = BufferUtils.createFloatBuffer(textureUVCoordinates.length);
static{
textureUVCoordinatesBuffer.put(textureUVCoordinates);
textureUVCoordinatesBuffer.flip();
}
public ModernOpenGLSpriteImpl(InputStream is, ASprite parentSprite){
this.textureName = "genericSprite"+genericSprites;
genericSprites++;
TextureManager.getInstance().loadTexture(textureName, is);
this.spriteTexture = TextureManager.getInstance().getTexture(textureName);
this.parentSprite = parentSprite;
}
public ModernOpenGLSpriteImpl(BufferedImage buf, ASprite parentSprite){
this.textureName = "genericSprite"+genericSprites;
genericSprites++;
TextureManager.getInstance().loadTexture(textureName, buf);
this.spriteTexture = TextureManager.getInstance().getTexture(textureName);
this.parentSprite = parentSprite;
}
public ModernOpenGLSpriteImpl(String url, ASprite parentSprite){
this.textureName = url;
TextureManager.getInstance().loadTexture(url);
this.spriteTexture = TextureManager.getInstance().getTexture(textureName);
this.parentSprite = parentSprite;
}
public ModernOpenGLSpriteImpl(Texture spriteTexture, ASprite parentSprite) {
this.textureName = spriteTexture.getKey();
this.spriteTexture = spriteTexture;
spriteTexture.increaseUsage();
this.parentSprite = parentSprite;
}
@Override
public void draw() {
if(spriteTexture == null){
return; //TODO substitute, exception?
}
if(requiresInit){
init(2);
requiresInit = false;
}
render(ModernOpenGLRenderer.SPRITE_SHADER);
}
@Override
public void update() {
//nothing special + ModernOpenGLRenderable updates everything
}
@Override
public void free() {
freeBuffers();
spriteTexture.delete();
}
@Override
protected void customBufferInit() {
float hWidth = (float)getRenderWidth()/2f;
float hHeight = (float)getRenderHeight()/2f;
float[] vertexPositions = new float[]{
-hWidth, -hHeight, 0f, 1f,
-hWidth, hHeight, 0f, 1f,
hWidth, -hHeight, 0f, 1f,
hWidth, hHeight, 0f, 1f
};
FloatBuffer vertexPositionsBuffer = BufferUtils.createFloatBuffer(vertexPositions.length);
vertexPositionsBuffer.put(vertexPositions);
vertexPositionsBuffer.flip();
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vertexBuffers.get(0));
GL15.glBufferData(GL15.GL_ARRAY_BUFFER, vertexPositionsBuffer, GL15.GL_STATIC_DRAW);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vertexBuffers.get(1));
GL15.glBufferData(GL15.GL_ARRAY_BUFFER, textureUVCoordinatesBuffer, GL15.GL_STATIC_DRAW);
}
@Override
protected void customBind() {
GL20.glEnableVertexAttribArray(0);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vertexBuffers.get(0));
GL20.glVertexAttribPointer(
0, //must match the layout in the shader!
4, // size
GL11.GL_FLOAT, // type
false, // normalized?
0, // stride
0 // array buffer offset
);
GL20.glEnableVertexAttribArray(1);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vertexBuffers.get(1));
GL20.glVertexAttribPointer(1, 2, GL11.GL_FLOAT, false, 0, 0);
spriteTexture.bind();
}
@Override
protected float getRenderAngle() {
return parentSprite.getAngle();
}
@Override
protected float getRenderOpacity() {
return parentSprite.getOpacity();
}
@Override
protected float getRenderScale() {
return parentSprite.getScale();
}
@Override
protected Color getRenderColor() {
return parentSprite.getColor();
}
@Override
protected float getRenderWidth() {
return parentSprite.getWidth();
}
@Override
protected float getRenderHeight() {
return parentSprite.getHeight();
}
@Override
protected float getRenderX() {
return parentSprite.getX();
}
@Override
protected float getRenderY() {
return parentSprite.getY();
}
@Override
public float getWidth() {
if(spriteTexture == null) return -1;
return spriteTexture.getWidth();
}
@Override
public float getHeight() {
if(spriteTexture == null) return -1;
return spriteTexture.getHeight();
}
@Override
protected boolean isRenderStatic() {
return parentSprite.isStatic();
}
}
|
package Behaviors;
import Entities.Person;
import java.util.ArrayList;
public class PersonManagement {
ArrayList<Person> personArrayList = new ArrayList<>();
public void addPerson(Person person){
personArrayList.add(person);
}
public void updatePerson(Person person){
for (Person ePerson:personArrayList) {
if(ePerson.getIdentity() == person.getIdentity()){
ePerson.setName(person.getName());
ePerson.setDOB(person.getDOB());
ePerson.setJob(person.getJob());
}
}
}
public void removePerson(int identity){
for (int i = 0; i < personArrayList.size(); i++) {
if(personArrayList.get(i).getIdentity() == identity){
personArrayList.remove(personArrayList.get(i));
}
}
}
public void showPersonInfo(){
for (Person ePerson:personArrayList) {
System.out.println(ePerson.toString());
}
}
public Person getPersonByIdentity(int identity){
Person person = new Person();
for (Person ePerson: personArrayList) {
if(ePerson.getIdentity() == identity){
person = ePerson;
}
}
return person;
}
}
|
/**
*
*/
package org.rebioma.client.services;
import java.util.List;
import org.rebioma.client.OccurrenceQuery;
import org.rebioma.client.bean.SearchFieldNameValuePair;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
/**
* @author Mikajy
*/
@RemoteServiceRelativePath("occurrenceSearchService")
public interface OccurrenceSearchService extends RemoteService{
/**
* Provides a singleton proxy to {@link OccurrenceSearchService}. Clients typically
* use the proxy as follows:
*
* OccurrenceSearchService.Proxy.get();
*/
public static class Proxy {
/**
* The singleton proxy instance.
*/
private static OccurrenceSearchServiceAsync service;
/**
* Returns the singleton proxy instance and creates it if needed.
*/
public static synchronized OccurrenceSearchServiceAsync get() {
if (service == null) {
service = GWT.create(OccurrenceSearchService.class);
}
return service;
}
}
/**
*
* @param sessionId
* @param query
* @return
*/
List<SearchFieldNameValuePair> getSearchFieldNameValuePair(String sessionId, OccurrenceQuery query) throws Exception;
}
|
package ru.otus.l111.dataset;
/*
* Created by VSkurikhin at winter 2018.
*/
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Entity
public class UserDataSet extends DataSet {
@Column(name = "name")
private String name;
@OneToOne(targetEntity = AddressDataSet.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private AddressDataSet address;
@OneToMany(mappedBy = "userDataSet", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set<PhoneDataSet> phones = new HashSet<>();
//Important for Hibernate
public UserDataSet() {
super(-1);
}
public UserDataSet(long id) {
super(id);
}
public UserDataSet(long id, String name, AddressDataSet address) {
this(id);
this.name = name;
this.address = address;
}
public UserDataSet(String name, AddressDataSet address) {
this(-1, name, address);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public AddressDataSet getAddress() {
return address;
}
public void setAddress(AddressDataSet address) {
this.address = address;
}
public void setPhones(Set<PhoneDataSet> phones) {
this.phones = phones;
}
public void addPhone(PhoneDataSet phone) {
phone.setUserDataSet(this);
phones.add(phone);
}
@Override
public String toString() {
return "UserDataSet{" +
" id'" + getId() + "'" +
", name='" + name + "'" +
", address=" + address +
", phones=" + phones +
" }";
}
@Override
public int hashCode() {
return name.hashCode() + 13 * address.hashCode() + 31 * phones.hashCode();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserDataSet that = (UserDataSet) o;
return name.equals(that.name) &&
address.equals(that.address) &&
phones.equals(that.phones);
}
}
/* vim: syntax=java:fileencoding=utf-8:fileformat=unix:tw=78:ts=4:sw=4:sts=4:et
*/
//EOF
|
package com.vilio.custom.service;
import com.vilio.comm.exception.ErrorException;
import com.vilio.comm.service.BaseService;
import com.vilio.custom.dao.CustomUserDao;
import com.vilio.custom.pojo.CustomUser;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
/**
* 类名: C200016<br>
* 功能:验证手机号是否存在用户表中<br>
* 版本: 1.0<br>
* 日期: 2017年7月22日<br>
* 作者: wangxf<br>
* 版权:vilio<br>
* 说明:<br>
*/
@Service
public class C200016 extends BaseService {
private static final Logger logger = Logger.getLogger(C200016.class);
@Resource
private CustomUserDao customUserDao;
/**
* 参数校验
*
* @param body
*/
public void checkParam(Map<String, Object> body) throws ErrorException {
//手机号
checkField(ObjectUtils.toString(body.get("mobileNo")), "手机号", null, 18);
}
/**
* 交易密码验证接口
*
* @param head
* @param body
* @param resultMap
*/
public void busiService(Map<String, Object> head, Map<String, Object> body, Map<String, Object> resultMap) throws ErrorException, IllegalAccessException, IntrospectionException, InvocationTargetException {
CustomUser customUserParam = new CustomUser();
customUserParam.setMobile(ObjectUtils.toString(body.get("mobileNo")));
int count = customUserDao.checkMobile(customUserParam);
if (count == 0) {
throw new ErrorException("0106","");
}
}
}
|
package com.ibm.ive.tools.japt.reduction.xta;
import com.ibm.ive.tools.japt.JaptRepository;
import com.ibm.ive.tools.japt.reduction.ClassSet;
import com.ibm.ive.tools.japt.reduction.EntryPointLister;
import com.ibm.jikesbt.BT_Class;
import com.ibm.jikesbt.BT_ClassReferenceSiteVector;
import com.ibm.jikesbt.BT_ClassVector;
import com.ibm.jikesbt.BT_CodeAttribute;
import com.ibm.jikesbt.BT_CreationSiteVector;
import com.ibm.jikesbt.BT_ExceptionTableEntry;
import com.ibm.jikesbt.BT_ExceptionTableEntryVector;
import com.ibm.jikesbt.BT_HashedClassVector;
import com.ibm.jikesbt.BT_Ins;
import com.ibm.jikesbt.BT_InsVector;
import com.ibm.jikesbt.BT_Method;
import com.ibm.jikesbt.BT_MethodSignature;
/**
* Represents a method declared in an interface or class. A method propagates objects from one place
* to another through the parameters (which includes the class itself in a non-static method call). An
* object may be propagated to the method through the parameters and then propagated elsehwere by a field write
* or another method call or from a thrown exception.<p>
* For example, when calling threadx.equals(objectx) in a method x(),
* the thread object threadx and the object objectx is propagated from the
* stack of method x to the stack of java.lang.Object.equals(). From there, the two
* objects may be propagated elsewhere. Note that the methods Object.equals() as listed as
* a method call from the body of x() can only be called if an object of type thread has
* previously been propagated to x() or has been created inside the body of x(). Once this
* has been proven true, then it is possible that any other object propagated to x() or created
* within the body of x() might be passed as the sole argument to the method call threadx.equals(objectx)
* and propagated to Object.equals().
* <p>
* This class uses these principles, propagating objects from methods to other methods and fields
* when it is known that such propagations are possible.
* @author sfoley
*
*/
public class Method extends MethodPropagator {
public BT_Method underlyingMethod;
private static final short scanned = 0x20;
private static final short storesIntoArrays = 0x40;
private static final short loadsFromArrays = 0x80;
private static final short canThrow = 0x100;
private static final short verified = 0x200;
/**
* The types that this method accepts as arguments, including the declaring class
* if this method is non-static
*/
private BT_Class typesPropagatable[];
static final BT_Class noTypesPropagatable[] = new BT_Class[0];
public Method(Repository repository, BT_Method method, BT_HashedClassVector propagatedObjects, ClassSet allPropagatedObjects) {
super(repository.getClazz(method.getDeclaringClass()), propagatedObjects, allPropagatedObjects);
this.underlyingMethod = method;
initialize();
}
/**
* Constructor for Method.
* @param member
*/
public Method(Repository repository, BT_Method method) {
super(repository.getClazz(method.getDeclaringClass()));
this.underlyingMethod = method;
initialize();
}
// public void tracex(String msg) {
// if( false
// //|| toString().startsWith("java.util.Map.containsKey")
// //|| toString().startsWith("java.lang.reflect.Proxy.")
// || toString().startsWith("java.lang.String.valueOf(java")
// || toString().startsWith("java.lang.Object.toString()")
// //|| toString().startsWith("java.lang.reflect.String.valueOf")
////|| toString().startsWith("java.lang.Byte.int")
//// || toString().startsWith("java.lang.Byte.short")
//// || toString().startsWith("java.lang.Byte.byte")
//// || toString().startsWith("java.lang.Number.byte")
//// || toString().startsWith("java.lang.Byte(")
//
// //|| toString().startsWith("java.util.Vector(java.util.Collection)") //(Ljava/util/Collection;)
// //|| underlyingMethod.fullName().equals("com.oti.bb.automatedtests.Test_java_io_BufferedOutputStream.suite")
// //|| underlyingMethod.fullName().equals("junit.framework.TestSuite.addTest")
// //|| msg.indexOf("Test_java_io_BufferedOutputStream") != -1
// //|| msg.indexOf("test.framework.TestCase") != -1
// //|| underlyingMethod.fullName().equals("test.framework.TestSuite.run")
// //|| underlyingMethod.fullName().equals("test.textui.TestRunner.doRun")
// //|| underlyingMethod.fullName().equals("test.textui.TestRunner.run")
// //|| underlyingMethod.fullName().equals("java.util.Vector$1.nextElement")
// //|| underlyingMethod.fullName().equals("java.util.Enumeration.nextElement")
// //|| underlyingMethod.fullName().equals("junit.framework.TestSuite.tests")
// //|| underlyingMethod.fullName().equals("test.framework.TestSuite")
// //|| underlyingMethod.fullName().equals("com.oti.bb.automatedtests.Test_java_io_BufferedOutputStream.main")
// ) {
// System.out.println(getState());
// }
//
// }
void initialize() {
boolean isNotStatic = !underlyingMethod.isStatic();
BT_ClassVector paramTypes = underlyingMethod.getSignature().types;
BT_ClassVector alreadyFound = new BT_ClassVector(paramTypes.size() + (isNotStatic ? 1 : 0));
for (int x = 0; x < paramTypes.size(); x++) {
BT_Class param = paramTypes.elementAt(x);
if(param.isBasicTypeClass) {
continue;
}
if(alreadyFound.contains(param)) {
continue;
}
alreadyFound.addElement(param);
}
if (isNotStatic && !alreadyFound.contains(underlyingMethod.getDeclaringClass())) {
alreadyFound.addElement(underlyingMethod.getDeclaringClass());
}
if(alreadyFound.size() == 0) {
typesPropagatable = noTypesPropagatable;
}
else {
alreadyFound.trimToSize();
typesPropagatable = alreadyFound.getBackingArray();
}
}
BT_Class getReturnType() {
return underlyingMethod.getSignature().returnType;
}
BT_Class[] getDeclaredExceptions() {
return underlyingMethod.getDeclaredExceptions();
}
public void setRequired() {
if(isRequired()) {
return;
}
super.setRequired();
//tracex("set required method");
Repository rep = getRepository();
JaptRepository japtRepository = rep.repository;
EntryPointLister lister = rep.entryPointLister;
boolean checkEntryPoints = (lister != null) && !japtRepository.isInternalClass(getBTClass());
if(checkEntryPoints) {
BT_MethodSignature sig = underlyingMethod.getSignature();
BT_Class returnType = sig.returnType;
BT_ClassVector types = sig.types;
for(int i=0; i<types.size(); i++) {
BT_Class type = types.elementAt(i);
if(!type.isBasicTypeClass && japtRepository.isInternalClass(type)) {
lister.foundEntryTo(type, underlyingMethod);
}
}
if(!returnType.isBasicTypeClass && japtRepository.isInternalClass(returnType)) {
lister.foundEntryTo(returnType, underlyingMethod);
}
}
//The following stuff is actually not mandatory, it is possible to have
//elements in the method signature that are not needed whatsoever
BT_Class declaredExceptions []= getDeclaredExceptions();
//if a method declares that that it can throw something, it must be included
for(int i=0; i<declaredExceptions.length; i++) {
getRepository().getClazz(declaredExceptions[i]).setRequired();
}
if(returnsObjects()) {
getRepository().getClazz(getReturnType()).setRequired();
}
BT_MethodSignature sig = underlyingMethod.getSignature();
BT_ClassVector types = sig.types;
for(int i=0; i<types.size(); i++) {
BT_Class type = types.elementAt(i);
if(type.isBasicTypeClass) {
continue;
}
getRepository().getClazz(type).setRequired();
}
}
public void setAccessed() {
if(isAccessed()) {
return;
}
super.setAccessed();
if(underlyingMethod.isStatic()) {
declaringClass.setInitialized();
}
}
boolean isThrowableObject(BT_Class objectType) {
return getRepository().properties.isThrowableObject(objectType);
}
boolean hasObjectParameters() {
return typesPropagatable.length > 0;
}
/**
* @return whether the method can accept an object of the given type during a method invocation
*/
boolean acceptsArgument(BT_Class type) {
return getRepository().isCompatibleType(typesPropagatable, type);
}
/**
* @see com.ibm.ive.tools.japt.reduction.xta.Member#propagateFromUnknownSource()
*/
// void propagateFromUnknownSource() {
// if(underlyingMethod.isAbstract()) {
// setRequired();
// return;
// }
// super.propagateFromUnknownSource();
// BT_ClassVector unknowns = new BT_HashedClassVector();
// for(int i=0; i<typesPropagatable.length; i++) {
// unknowns.addUnique(typesPropagatable[i]);
// }
// for(int i=0; i<unknowns.size(); i++) {
// BT_Class creation = unknowns.elementAt(i);
// Clazz clazz = addCreatedObject(creation);
// clazz.includeAllConstructors();
// }
// Clazz clazz = getDeclaringClass();
// if(underlyingMethod.isStatic()) {
// clazz.setInitialized();
// }
// }
void propagateFromUnknownSource() {
if(underlyingMethod.isAbstract()) {
setRequired();
return;
}
super.propagateFromUnknownSource();
BT_ClassVector unknowns = new BT_HashedClassVector();
for(int i=0; i<typesPropagatable.length; i++) {
unknowns.addUnique(typesPropagatable[i]);
}
for(int i=0; i<unknowns.size(); i++) {
BT_Class creation = unknowns.elementAt(i);
addCreatedObject(creation);
}
Clazz clazz = getDeclaringClass();
if(!underlyingMethod.isStatic()) {
addCreatedObject(clazz.getBTClass());
clazz.setInstantiated();
clazz.includeConstructors();
}
}
/**
* The current method has been accessed, so it can now propagate objects elsewhere.
* Find all possible targets and determine what objects are created within the body
* of this method.
* <p>
* @see com.ibm.ive.tools.japt.reduction.xta.Propagator#initializePropagation()
*/
void initializePropagation() {
if(underlyingMethod.isAbstract()) {
potentialTargets = noPotentialTargets;
return;
}
if(underlyingMethod.isNative()) {
addCreatedObjectsUnknown();
potentialTargets = getPotentialNativeTargets();
return;
}
BT_CodeAttribute code = underlyingMethod.getCode();
if(code != null) {
addCreatedObjects(code);
findReferences(code);
potentialTargets = getPotentialTargets(code);
potentialTargets.findTargets(code);
}
else { //really we should never arrive here, presumably this method can be
//executed but for some reason there is no code, so we treat it like a native method
addCreatedObjectsUnknown();
potentialTargets = noPotentialTargets;
}
}
protected MethodPotentialTargets getPotentialNativeTargets() {
return new MethodPotentialArrayTargets(this);
}
protected MethodPotentialTargets getPotentialTargets(BT_CodeAttribute code) {
int accessedFields = code.accessedFields.size();
int calledMethods = code.calledMethods.size();
boolean hasArraySources = storesIntoArrays() || loadsFromArrays();
if(accessedFields == 0 && calledMethods == 0) {
if(hasArraySources) {
return new MethodPotentialArrayTargets(this);
}
return noPotentialTargets;
}
final MethodPotentialCodeTargets codeTargets =
new MethodPotentialCodeTargets(this);
if(hasArraySources) {
return new MethodPotentialTargets() {
MethodPotentialArrayTargets arrayTargets =
new MethodPotentialArrayTargets(Method.this);
public void findTargets(BT_CodeAttribute code) {
codeTargets.findTargets(code);
arrayTargets.findTargets(code);
}
public void findNewTargets(BT_Class objectType) {
arrayTargets.findNewTargets(objectType);
codeTargets.findNewTargets(objectType);
if(codeTargets.hasNoPotentialTargets()) {
potentialTargets = arrayTargets;
}
}
};
}
return new MethodPotentialTargets() {
public void findTargets(BT_CodeAttribute code) {
codeTargets.findTargets(code);
}
public void findNewTargets(BT_Class objectType) {
codeTargets.findNewTargets(objectType);
if(codeTargets.hasNoPotentialTargets()) {
potentialTargets = noPotentialTargets;
}
}
};
}
void findVerifierRequiredClasses(BT_CodeAttribute code) {
if((flags & verified) != 0) {
return;
}
flags |= verified;
Repository rep = getRepository();
JaptRepository japtRepository = rep.repository;
EntryPointLister lister = rep.entryPointLister;
boolean checkEntryPoints = (lister != null) && !japtRepository.isInternalClass(getBTClass());
BT_ClassVector referencedClses = code.getVerifierRequiredClasses(getRepository().pool);
for(int i=0; i<referencedClses.size(); i++) {
BT_Class referencedClass = referencedClses.elementAt(i);
if(checkEntryPoints && !referencedClass.isBasicTypeClass && japtRepository.isInternalClass(referencedClass)) {
lister.foundEntryTo(referencedClass, underlyingMethod);
}
Clazz clazz = rep.getClazz(referencedClass);
clazz.setRequired();
}
}
/**
* This method finds classes that are required by the method body and marks them as being
* required. This is done when the method is accessed. This could be changed so that it is
* done when the method is marked required for more stringent VM's
*/
private void findReferences(BT_CodeAttribute code) {
//TODO reduction fix involving not targetting explicitly removed items
Repository rep = getRepository();
JaptRepository japtRepository = rep.repository;
EntryPointLister lister = rep.entryPointLister;
boolean checkEntryPoints = (lister != null) && !japtRepository.isInternalClass(getBTClass());
//determine which classes are required by the method body
BT_ClassReferenceSiteVector referencedClasses = code.referencedClasses;
for(int i=0; i<referencedClasses.size(); i++) {
BT_Class referencedClass = referencedClasses.elementAt(i).getTarget();
if(checkEntryPoints && !referencedClass.isBasicTypeClass && japtRepository.isInternalClass(referencedClass)) {
lister.foundEntryTo(referencedClass, underlyingMethod);
}
Clazz clazz = rep.getClazz(referencedClass);
clazz.setRequired();
}
findVerifierRequiredClasses(code);
//if a method is included, then anything that it explicitly declares that it can catch is required
BT_ExceptionTableEntryVector exceptions = code.getExceptionTableEntries();
for (int t=0; t < exceptions.size(); t++) {
BT_ExceptionTableEntry e = exceptions.elementAt(t);
BT_Class catchType = e.catchType;
if (catchType == null)
continue;
if(checkEntryPoints && !catchType.isBasicTypeClass && japtRepository.isInternalClass(catchType)) {
lister.foundEntryTo(catchType, underlyingMethod);
}
rep.getClazz(catchType).setRequired();
}
}
protected void addCreatedObjects(BT_CodeAttribute code) {
/*
* Determine which classes have instances created
* Note that this includes all new, anewarray, multianewarray instructions as well
* as ldc and ldc_w instructions that reference strings
*/
BT_CreationSiteVector createdClasses = code.createdClasses;
for(int i=0; i<createdClasses.size(); i++) {
BT_Class creation = createdClasses.elementAt(i).getCreation();
//TODO this does not populate arrays created by multianewarray - we need to get the array element of each creation and add the element Clazz to it,
//recursively through the array dimensions
//trace("Creating " + creation);
addCreatedObject(creation);
}
addConditionallyCreatedObjects(underlyingMethod);
}
protected void addCreatedObjectsUnknown() {
/*
* We must assume that the return type and any subclass or implementing type
* is being created within the method body and can be propagated.
* In other words, since there is no method body to scan we must assume the worst,
* that anything that can be created by this method will be created.
*/
BT_Class returnType = getReturnType();
if(!returnType.isBasicTypeClass) {
addCreatedObject(returnType);
//addCreatedObjectAndAllSubtypes(returnType);
}
/*
* We can say the same as abovefor thrown exceptions, so we must assume
* that all subtypes of declared exceptions as well as all RuntimeExceptions are propagated
*/
//addCreatedObjectAndAllSubtypes(getRepository().properties.javaLangRuntimeException);
addCreatedObject(getRepository().properties.javaLangRuntimeException);
BT_Class declaredExceptions[] = getDeclaredExceptions();
for(int i=0; i<declaredExceptions.length; i++) {
addCreatedObject(declaredExceptions[i]);
}
addConditionallyCreatedObjects(underlyingMethod);
}
boolean returnsObjects() {
return !getReturnType().isBasicTypeClass;
}
boolean returns(BT_Class objectType) {
BT_Class returnType = getReturnType();
return objectType.equals(returnType) || objectType.isDescendentOf(returnType);
}
/**
* returns true if the method declares the throwable type in its list of checked exceptions
*/
boolean canThrow(BT_Class objectType) {
return canThrow() && canPassThrown(objectType);
}
boolean canPassThrown(BT_Class objectType) {
if(getRepository().properties.isRuntimeThrowableObject(objectType)) {
return true;
}
BT_Class declaredExceptions[] = getDeclaredExceptions();
for(int i=0; i<declaredExceptions.length; i++) {
BT_Class throwable = declaredExceptions[i];
if(objectType.equals(throwable) || objectType.isDescendentOf(throwable)) {
return true;
}
}
return false;
}
/**
Returns true if there is no athrow instruction.
**/
private void scanCode() {
if((flags & scanned) != 0) {
return;
}
flags |= scanned;
BT_CodeAttribute code = underlyingMethod.getCode();
if(underlyingMethod.isNative() || code == null) {
//for natives we assume the worst to try to be safe, although there is no guarantee
//this will help
flags |= canThrow;
flags |= storesIntoArrays;
flags |= loadsFromArrays;
return;
}
else if(underlyingMethod.isAbstract()) {
return;
}
boolean foundCanThrow = false;
boolean foundStoresIntoArrays = false;
boolean foundLoadsFromArrays = false;
BT_InsVector ins = code.getInstructions();
if(ins != null) {
for (int k = 0; k < ins.size(); k++) {
BT_Ins instruction = ins.elementAt(k);
if(foundCanThrow && foundStoresIntoArrays && foundLoadsFromArrays) {
return;
}
else {
switch(instruction.opcode) {
case BT_Ins.opc_athrow:
flags |= canThrow;
foundCanThrow = true;
continue;
case BT_Ins.opc_aastore:
flags |= storesIntoArrays;
foundStoresIntoArrays = true;
continue;
case BT_Ins.opc_aaload:
flags |= loadsFromArrays;
foundLoadsFromArrays = true;
default:
continue;
}
}
}
}
}
/**
* returns true if the method contains an aastore instruction
*/
public boolean storesIntoArrays() {
scanCode();
return (flags & storesIntoArrays) != 0;
}
/**
* returns true if the method contains an aaload instruction
*/
public boolean loadsFromArrays() {
scanCode();
return (flags & loadsFromArrays) != 0;
}
/**
* returns true if the method contains an athrow instruction
*/
boolean canThrow() {
scanCode();
return (flags & canThrow) != 0;
}
/**
* returns true if the method has an exception handler for the given type,
* not including finally clauses (ie even if there is a finally clause, this method
* will return false if there is not explicit handler)
*/
boolean catches(BT_Class throwableType) {
BT_ExceptionTableEntryVector exceptions = underlyingMethod.getCode().getExceptionTableEntries();
for(int i=0; i<exceptions.size(); i++) {
BT_ExceptionTableEntry entry = exceptions.elementAt(i);
BT_Class catchable = entry.catchType;
if(catchable == null) {
continue;
//technically, the exception object is placed on the operand
//stack, so it is propagated, but the finally clause does not allow
//the programmer to access any thrown exception objects, so we can
//assume that the object is not propagated to the method
}
if(throwableType.equals(catchable) || throwableType.isDescendentOf(catchable)) {
return true;
}
}
return false;
}
public String toString() {
return getName();
}
public String getName() {
return underlyingMethod.toString();
}
}
|
package com.szcinda.express.controller;
import com.szcinda.express.controller.dto.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
@Slf4j
public class GlobalExceptionAdvice {
@ExceptionHandler(Exception.class)
public Result handleException(Exception ex) {
log.error("应用程序错误", ex);
return Result.fail(ex.getMessage());
}
}
|
package br.com.fiap.singleton;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class EntityManagerFactorySingleton {
//1- atributo estático que sera unico
private static EntityManagerFactory factory;
//2- construtror vazio e privado
private EntityManagerFactorySingleton() {}
//3- Método estático que retorna a unica instancia
public static EntityManagerFactory getInstance() {
if(factory == null) {
factory = Persistence
.createEntityManagerFactory("CLIENTE_ORACLE");
}
return factory;
}
}
|
package com.tencent.mm.plugin.appbrand.widget.input.autofill;
import android.database.DataSetObserver;
class AutoFillListPopupWindowBase$c extends DataSetObserver {
final /* synthetic */ AutoFillListPopupWindowBase gKu;
private AutoFillListPopupWindowBase$c(AutoFillListPopupWindowBase autoFillListPopupWindowBase) {
this.gKu = autoFillListPopupWindowBase;
}
/* synthetic */ AutoFillListPopupWindowBase$c(AutoFillListPopupWindowBase autoFillListPopupWindowBase, byte b) {
this(autoFillListPopupWindowBase);
}
public final void onChanged() {
if (this.gKu.eZB.isShowing()) {
this.gKu.show();
}
}
public final void onInvalidated() {
this.gKu.dismiss();
}
}
|
package com.woncheol.restapi.model;
public class Company {
int companyNo;
String companyName;
String address;
//String endDate;
//List <Department> departmentList;
public int getCompanyNo() {
return companyNo;
}
public void setCompanyNo(int companyNo) {
this.companyNo = companyNo;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
// public String getEndDate() {
// return endDate;
// }
//
// public void setEndDate(String endDate) {
// this.endDate = endDate;
// }
// public List<Department> getDepartmentList() {
// return departmentList;
// }
//
// public void setDepartmentList(List<Department> departmentList) {
// this.departmentList = departmentList;
// }
}
|
package com.tencent.mm.plugin.location.ui;
import com.tencent.mm.sdk.platformtools.x;
class h$2 implements Runnable {
final /* synthetic */ h kFD;
final /* synthetic */ int kFE;
h$2(h hVar, int i) {
this.kFD = hVar;
this.kFE = i;
}
public final void run() {
x.d("MicroMsg.ShareHeaderAvatarViewMgr", "scrollToTalker pos=%d", new Object[]{Integer.valueOf(this.kFE)});
this.kFD.kFz.En(this.kFE);
}
}
|
package com.github.sixro.minihabits.core;
import java.util.Date;
import com.badlogic.gdx.*;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.utils.*;
import com.badlogic.gdx.utils.Json.Serializer;
import com.github.sixro.minihabits.core.domain.*;
import com.github.sixro.minihabits.core.infrastructure.domain.*;
import com.github.sixro.minihabits.core.ui.MainView;
import com.github.sixro.minihabits.core.util.libgdx.PreferencesBasedStorage;
import com.github.sixro.minihabits.core.util.libgdx.text.DateTimeFormatter;
public class MiniHabits extends Game {
private static final String TAG = MiniHabits.class.getSimpleName();
private final DateTimeFormatter dateTimeFormatter;
private AllMiniHabits miniHabits;
private Skin skin;
public MiniHabits(DateTimeFormatter dateTimeFormatter) {
super();
this.dateTimeFormatter = dateTimeFormatter;
}
@Override
public void create () {
Preferences preferences = Gdx.app.getPreferences(MiniHabits.class.getSimpleName());
final PreferencesBasedStorage<MiniHabit> storage = new PreferencesBasedStorage<MiniHabit>(preferences, "minihabits", newJsonForPersistence(), MiniHabit.class);
miniHabits = new AllMiniHabits(storage.findAll());
miniHabits.addListener(new AllMiniHabits.Listener() {
@Override
public void onAdd(AllMiniHabits all) {
storage.saveAll(all.all());
}
});
skin = new Skin(Gdx.files.internal("uiskin.json"));
Calendar calendar = new JavaBasedCalendar();
MainScreen mainScreen = new MainScreen(
skin,
miniHabits,
calendar,
new PreferencesBasedFeedbacksStorage(
preferences,
calendar
)
);
setScreen(mainScreen);
}
private Json newJsonForPersistence() {
Json json = new Json();
json.setSerializer(MiniHabit.class, new MiniHabitSerializer(dateTimeFormatter));
return json;
}
public static class MiniHabitSerializer implements Serializer<MiniHabit> {
private static final String ISO8601_PATTERN = "yyyy-MM-dd HH:mm:ss,SSS";
private final DateTimeFormatter dateTimeFormatter;
public MiniHabitSerializer(DateTimeFormatter dateTimeFormatter) {
super();
this.dateTimeFormatter = dateTimeFormatter;
}
@SuppressWarnings("rawtypes")
@Override
public void write(Json json, MiniHabit o, Class knownType) {
json.writeObjectStart();
json.writeValue("label", o.label());
json.writeValue("start-date", dateTimeFormatter.format(o.startDate(), ISO8601_PATTERN));
json.writeObjectEnd();
}
@SuppressWarnings("rawtypes")
@Override
public MiniHabit read(Json json, JsonValue jsonData, Class type) {
Gdx.app.log(TAG, "jsonData:" + jsonData.toString());
String label = jsonData.getString("label");
String startDateAsText = jsonData.getString("start-date");
Date startDate = dateTimeFormatter.parse(startDateAsText, ISO8601_PATTERN);
return new MiniHabit(label, startDate);
}
}
}
|
package com.tree.binary;
public class TreeDiameter {
int diameter;
public static void main(String[] args) {
TreeDiameter treeDiameter = new TreeDiameter();
BinaryTree tree = BinaryTree.buildTestTree();
tree.levelOrder();
treeDiameter.diameter(tree.getRoot(), treeDiameter);
System.out.println();
System.out.println("Diameter of tree: " + treeDiameter.diameter);
}
private int diameter(Node node, TreeDiameter treeDiameter) {
if (node == null) {
return 0;
}
int left = diameter(node.getLeft(), treeDiameter);
int right = diameter(node.getRight(), treeDiameter);
if(left + right > treeDiameter.diameter){
treeDiameter.diameter = left + right;
}
return Math.max(left,right) + 1;
}
}
|
package com.cdeid.io;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;
import gate.creole.ResourceInstantiationException;
public class Input {
/**
* Get the list of files from a given input directory.
*
* @param input_dir
* @return
*/
public static Collection<File> readFolder(File input_dir){
Collection<File> fileList = FileUtils.listFiles(new File(input_dir.getAbsolutePath()), TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
return fileList;
}
/**
* Read given file format.
*
* @param f file
* @return gate.Document
* @throws IOException
* @throws ResourceInstantiationException
*
* TODO: expand input formats ...
*/
public static gate.Document getGateDocument(File f) {
PDFTextStripper stripper;
gate.Document gateDoc = null;
try {
stripper = new PDFTextStripper();
if(f.getName().endsWith(".txt")){
gateDoc = gate.Factory.newDocument(FileUtils.readFileToString(f, "UTF-8"));
}else if(f.getName().endsWith(".pdf")){
PDDocument d = PDDocument.load(f);
gateDoc = gate.Factory.newDocument(stripper.getText(d));
}else{
System.err.println("ChristieDEID can only process plain text (.txt) and searchable portable document format (.pdf) documents.\n"
+ "Amend the filename extension accordingly.");
System.err.println("Document err: " + f.getName());
}
} catch (IOException e) {
e.printStackTrace();
} catch (ResourceInstantiationException e) {
e.printStackTrace();
}
return gateDoc;
}
}
|
public class LinkedListNode {
Object element;
LinkedListNode next;
public LinkedListNode(Object o) {
element = o;
}
}
|
package Concrete;
import Entities.Campaign;
import Entities.Game;
public class CampaignCalculatorHelper
{
public static double calculate(Game game, Campaign campaign)
{
var result = (game.getPrice() * campaign.getDiscountAmount()) / 100;
return game.getPrice() - result;
};
}
|
/*
* Copyright 2011 frdfsnlght <frdfsnlght@gmail.com>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.frdfsnlght.transporter;
import com.frdfsnlght.transporter.api.GateException;
import com.frdfsnlght.transporter.api.GateType;
import com.frdfsnlght.transporter.api.RemoteGate;
import com.frdfsnlght.transporter.api.RemoteServer;
import com.frdfsnlght.transporter.api.RemoteWorld;
/**
*
* @author frdfsnlght <frdfsnlght@gmail.com>
*/
public abstract class RemoteGateImpl extends GateImpl implements RemoteGate {
public static RemoteGateImpl create(Server server, GateType type, String name, boolean hidden) throws GateException {
switch (type) {
case BLOCK:
return new RemoteBlockGateImpl(server, name, hidden);
case AREA:
return new RemoteAreaGateImpl(server, name, hidden);
case SERVER:
return new RemoteServerGateImpl(server, name, hidden);
}
throw new GateException("unknown gate type '%s'", type.toString());
}
protected Server server;
protected String worldName;
protected boolean hidden;
protected RemoteGateImpl(Server server, String name, boolean hidden) {
this.server = server;
if (name == null) throw new IllegalArgumentException("name is required");
String[] parts = name.split("\\.", 2);
worldName = parts[0];
this.name = parts[1];
this.hidden = hidden;
}
@Override
public abstract GateType getType();
@Override
public String getLocalName() {
return worldName + "." + getName();
}
@Override
public String getFullName() {
return server.getName() + "." + getLocalName();
}
@Override
public String getGlobalName() {
return getFullName();
}
@Override
public String getName(Context ctx) {
return getFullName();
}
@Override
public RemoteWorld getRemoteWorld() {
return server.getRemoteWorld(worldName);
}
@Override
public RemoteServer getRemoteServer() {
return server;
}
@Override
public boolean isSameServer() {
return false;
}
@Override
protected void attach(GateImpl origin) {
if (! (origin instanceof LocalGateImpl)) return;
server.sendGateAttach(this, (LocalGateImpl)origin);
}
@Override
protected void detach(GateImpl origin) {
if (! (origin instanceof LocalGateImpl)) return;
server.sendGateDetach(this, (LocalGateImpl)origin);
}
@Override
public boolean getHidden() {
return hidden;
}
}
|
import java.util.PriorityQueue;
public class MinimumMovesForStringConversion {
static int [][] dp;
static String src;
static String dest;
public static void main(String[] args) {
src = args[0];
dest = args[1];
int n = src.length();
dp = new int [n][n];
for(int m=0;m<n;m++){
for(int i=0;i<n-m;i++){
if(m==0){
if(src.charAt(i) != dest.charAt(i))
dp[i][i] = 1;
} else {
int j = i+m;
dp[i][j] = rec(i, j, dest.charAt(i));
}
}
}
log(dp[0][n-1]);
}
private static int rec(int i, int j, char c) {
PriorityQueue<Integer> sums;
if(i==j){
return dp[i][i];
} else{
sums = new PriorityQueue<Integer>();
for(int k=i;k<j;k++){
sums.add(rec(i,k, dest.charAt(i)) + rec(k+1,j, dest.charAt(k+1)));
}
}
return Math.min(sums.peek(),
1 + rec(i+1,j,dest.charAt(i)));
}
static void log(Object o) {
System.out.println(o.toString());
}
}
|
package jpabook.jpashop.api;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jpabook.jpashop.domain.Member;
import jpabook.jpashop.service.MemberService;
import lombok.*;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;
@RestController
@RequiredArgsConstructor
public class MemberApiController {
private final MemberService memberService;
// 회원 조회 api
/**
* 화면을 뿌려주기 위한 로직이 추가될 것이다. @JsonIgnore
* api 로직이 바뀌면 api 스펙도 의도치 않게 바뀌기 쉬어진다. -> 장애 발생 가능
* 유연하지도 유지보수하기도 어려운 구조이다.
**/
@GetMapping("/api/v1/members")
public List<Member> membersV1() { return memberService.findMembers(); }
@GetMapping("/api/v2/members")
public Result memberV2() {
List<Member> findMembers = memberService.findMembers();
List<MemberDto> collect = findMembers.stream()
.map(m -> new MemberDto(m.getName()))
.collect(Collectors.toList());
// return new Result(collect);
return new Result(collect.size(), collect);
}
@Data
@AllArgsConstructor
// []이 아닌 {}로 감싸서 (유지보수, 유연성)
// {count: 2, data: [{},{}]}
// 엔티티 그대로가 아닌, 원하는 일부만 보여줄 수 있고, 추가도 가능하다 (유연성)
static class Result<T> {
private int count;
private T data;
}
@Data
@AllArgsConstructor
static class MemberDto {
private String name;
}
// 회원 등록 api
@PostMapping("/api/v1/members")
public CreateMemberResponse saveMemberV1(@RequestBody @Valid Member member) { // api 만들 때는 엔티티를 파라메터로 이렇게 받으면 안된다. mapping 문제 때문. -> v2 권장
Long id = memberService.join(member);
return new CreateMemberResponse(id);
}
@PostMapping("/api/v2/members")
public CreateMemberResponse saveMemberV2(@RequestBody @Valid CreateMemberRequest request) { // 별도의 DTO 받는 방법
Member member = new Member();
member.setName(request.getName());
Long id = memberService.join(member);
return new CreateMemberResponse(id);
}
// 회원 수정 api
@PutMapping("/api/v2/members/{id}")
public UpdateMemberResponse updateMemberV2(
@PathVariable("id") Long id,
@RequestBody @Valid UpdateMemberRequest request) {
memberService.update(id, request.getName());
Member findMember = memberService.findOne(id);
return new UpdateMemberResponse(findMember.getId(), findMember.getName());
}
// 안에서만 쓸꺼니까 Inner class
@Data
static class UpdateMemberRequest {
private String name;
}
@Data
@AllArgsConstructor
static class UpdateMemberResponse {
private Long id;
private String name;
}
// ? 왜 static일까?
@Data
static class CreateMemberRequest {
private String name;
}
@Data
static class CreateMemberResponse {
private Long id;
public CreateMemberResponse(Long id) {
this.id = id;
}
}
}
|
// Will Westrich and Seth Hunter
class AdaptableBinarySearchTree extends BinarySearchTree{
public AdaptableBinarySearchTree(){
super();
}
public KeyedItem retrieve(Comparable searchKey){
try{
return (KeyedItem)retrieveItemAdapt(getRootNode(), searchKey);
}catch(TreeException e){
return null;
}
}
private TreeNode retrieveItemAdapt(TreeNode tNode, Comparable searchKey) throws TreeException{
KeyedItem treeItem;
if (tNode == null)
{
throw new TreeException("Item not found.");
}
else
{
KeyedItem nodeItem = (KeyedItem) tNode.getItem();
int comparison = searchKey.compareTo(nodeItem.getKey());
getRootNode() = tNode;
if (comparison == 0)
{
// item is in the root of some subtree
treeItem = nodeItem;
}
else if (comparison < 0)
{
// search the left subtree
treeItem = retrieveItem(tNode.getLeft(), searchKey);
rotateRight(tNode);
}
else
{
// search the right subtree
treeItem = retrieveItem(tNode.getRight(), searchKey);
rotateLeft(tNode);
}
}
return tNode;
}
}
|
package edu.mum.cs.cs544.exercises.a;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String firstName;
private String lastName;
@OneToMany(mappedBy="owner", cascade = CascadeType.PERSIST)
private Set<Laptop> laptops = new HashSet<Laptop>();
public Employee() {
}
public Employee(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String toString() {
return "Employee Number: " + this.getId() + ", Name: " + this.getFirstName() + " " + this.getLastName();
}
public void addLaptop(Laptop laptop) {
laptop.setOwner(this);
this.laptops.add(laptop);
}
public Set<Laptop> getLaptops() {
return laptops;
}
public void setLaptops(Set<Laptop> laptops) {
this.laptops = laptops;
}
}
|
/*
* Copyright (C) 2019-2023 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hedera.mirror.common.domain.token;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.google.common.collect.Range;
import com.hedera.mirror.common.converter.ObjectToStringSerializer;
import com.hedera.mirror.common.domain.History;
import com.hedera.mirror.common.domain.Upsertable;
import io.hypersistence.utils.hibernate.type.json.JsonBinaryType;
import jakarta.persistence.Id;
import jakarta.persistence.MappedSuperclass;
import java.util.ArrayList;
import java.util.List;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.experimental.SuperBuilder;
import org.hibernate.annotations.Type;
import org.springframework.util.CollectionUtils;
@Data
@MappedSuperclass
@NoArgsConstructor
@SuperBuilder(toBuilder = true)
@Upsertable(history = true)
public abstract class AbstractCustomFee implements History {
@JsonSerialize(using = ObjectToStringSerializer.class)
@Type(JsonBinaryType.class)
private List<FixedFee> fixedFees;
@JsonSerialize(using = ObjectToStringSerializer.class)
@Type(JsonBinaryType.class)
private List<FractionalFee> fractionalFees;
@JsonSerialize(using = ObjectToStringSerializer.class)
@Type(JsonBinaryType.class)
private List<RoyaltyFee> royaltyFees;
private Range<Long> timestampRange;
@Id
private Long tokenId;
public void addFixedFee(@NonNull FixedFee fixedFee) {
if (this.fixedFees == null) {
this.fixedFees = new ArrayList<>();
}
this.fixedFees.add(fixedFee);
}
public void addFractionalFee(@NonNull FractionalFee fractionalFee) {
if (this.fractionalFees == null) {
this.fractionalFees = new ArrayList<>();
}
this.fractionalFees.add(fractionalFee);
}
public void addRoyaltyFee(@NonNull RoyaltyFee royaltyFee) {
if (this.royaltyFees == null) {
this.royaltyFees = new ArrayList<>();
}
this.royaltyFees.add(royaltyFee);
}
@JsonIgnore
public boolean isEmptyFee() {
return CollectionUtils.isEmpty(this.fixedFees)
&& CollectionUtils.isEmpty(this.fractionalFees)
&& CollectionUtils.isEmpty(this.royaltyFees);
}
}
|
package jwscert.rest.services;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import jwscert.rest.services.annotations.HelloWorld;
import jwscert.rest.services.annotations.PathAnnotation;
import jwscert.rest.services.annotations.QueryParamAnnotation;
import jwscert.rest.services.book.JsonResources;
import jwscert.rest.services.book.SearchBooks;
import jwscert.rest.services.ejb.MyEjbResource1;
import jwscert.rest.services.ejb.MyEjbResource2;
import jwscert.rest.services.mediatypes.MediaTypeAnnotation;
@ApplicationPath("/rest1")
public class MyApplication extends Application {
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> s = new HashSet<Class<?>>();
s.add(MyEjbResource1.class);
s.add(MyEjbResource2.class);
s.add(HelloWorld.class);
s.add(QueryParamAnnotation.class);
s.add(PathAnnotation.class);
s.add(MediaTypeAnnotation.class);
s.add(JsonResources.class);
s.add(SearchBooks.class);
return s;
}
}
|
package com.tencent.mm.pluginsdk.ui;
import android.text.Editable;
import android.text.TextWatcher;
class MultiSelectContactView$1 implements TextWatcher {
final /* synthetic */ MultiSelectContactView qGe;
MultiSelectContactView$1(MultiSelectContactView multiSelectContactView) {
this.qGe = multiSelectContactView;
}
public final void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
MultiSelectContactView.a(this.qGe);
if (MultiSelectContactView.b(this.qGe) != null) {
MultiSelectContactView.b(this.qGe).FW(charSequence.toString());
}
}
public final void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
public final void afterTextChanged(Editable editable) {
}
}
|
package com.dais.mapper;
import com.dais.model.WalletUnlockInfo;
import com.dais.model.WalletUnlockInfoExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface WalletUnlockInfoMapper {
int countByExample(WalletUnlockInfoExample example);
int deleteByExample(WalletUnlockInfoExample example);
int deleteByPrimaryKey(Integer id);
int insert(WalletUnlockInfo record);
int insertSelective(WalletUnlockInfo record);
List<WalletUnlockInfo> selectByExample(WalletUnlockInfoExample example);
WalletUnlockInfo selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") WalletUnlockInfo record, @Param("example") WalletUnlockInfoExample example);
int updateByExample(@Param("record") WalletUnlockInfo record, @Param("example") WalletUnlockInfoExample example);
int updateByPrimaryKeySelective(WalletUnlockInfo record);
int updateByPrimaryKey(WalletUnlockInfo record);
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.cmsfacades.cmsitems;
import de.hybris.platform.cms2.model.contents.CMSItemModel;
import de.hybris.platform.converters.Populator;
import java.util.List;
import java.util.Map;
/**
* Interface to provide a list of custom {@link Populator} populators for a given {@link CMSItemModel}.
*/
public interface ItemDataPopulatorProvider
{
/**
* Interface method to return a list of {@link Populator} populators given the {@link CMSItemModel}.
* @param itemModel the CMSItemModel
* @return the list of Populators registered for the {@link CMSItemModel}.
*/
List<Populator<CMSItemModel, Map<String, Object>>> getItemDataPopulators(final CMSItemModel itemModel);
}
|
package com.tencent.tencentmap.mapsdk.a;
public interface ac$i {
void a();
}
|
package com.nju.cyt.handler;
import com.nju.cyt.server.ReSendServer;
import com.nju.cyt.util.AddressParser;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.apache.log4j.Logger;
/**
* @author Cyt
*
* Created on 2017年12月29日下午3:17:33
*/
/**
* A---->Server A发送给服务器,主要是身份识别和注册
包头字符+客户端类型+客户端编号+附加内容(例如指令等)+包尾字符
B---->Server B发送给服务器,身份识别注册以及数据包
包头字符+客户端类型+客户端编号+日期(时间)+2/4小时标志位+数据+附加内容(例如指令等)+包尾字符
* */
public class ClientHandler extends SimpleChannelInboundHandler<String> {
private static Logger Log = Logger.getLogger(ClientHandler.class);
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg)
throws Exception {
if(identify(ctx, msg)==1){
ctx.fireChannelRead(msg);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
ctx.channel().close();
Log.error("unexpected exception: "+cause.getMessage()+",close channel ["+AddressParser.IpParser(ctx)+"]");
}
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
Log.info(AddressParser.IpParser(ctx)+":"+AddressParser.portParser(ctx)+" is unregistered!");
ctx.fireChannelUnregistered();
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
Log.info(AddressParser.IpParser(ctx)+":"+AddressParser.portParser(ctx)+" is inactive, should be closed");
ctx.fireChannelInactive();
}
private int identify(ChannelHandlerContext ctx,String msg){
if (!msg.startsWith("A")) {
ctx.channel().close();
return -1;
}
if (msg.substring(1, 3).equals("01")) {
// center client
if (ReSendServer.getInstance().getCenterSet().contains(ctx.channel())) {
return 1;
}
Log.info("接入一个A客户端");
ReSendServer.getInstance().addCenterChannel(ctx.channel());
}else if (msg.substring(1, 3).equals("02")) {
//station client
String stationId = msg.substring(3,6);
Channel ch = ReSendServer.getInstance().getStationMap().get(stationId);
if (ch!=null&&ch.isActive()&&ch.isOpen()) {
return 1;
}
Log.info("接入一个B客户端,编号为"+stationId);
ReSendServer.getInstance().getStationMap().put(stationId, ctx.channel());
return 1;
}
return 0;
}
}
|
package com.tencent.mm.plugin.sns.ui;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import com.tencent.mm.plugin.sns.ui.SnsUploadBrowseUI.3;
class SnsUploadBrowseUI$3$2 implements OnClickListener {
final /* synthetic */ 3 ogq;
SnsUploadBrowseUI$3$2(3 3) {
this.ogq = 3;
}
public final void onClick(DialogInterface dialogInterface, int i) {
}
}
|
package entities;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity
@Table(name = "articles")
public class Article {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "article_id", nullable = false, columnDefinition = "INT UNSIGNED")
private long id;
@Column(name = "article_title", length = 300, nullable = false)
private String title;
@Column(name = "article_text")
private String text;
@Column(name = "article_date")
private Date date;
@Column(name = "article_source", length = 50)
private String source;
@Column(name = "article_image_path", length = 300)
private String image;
@ManyToMany
@JoinTable(name = "articles_categories", joinColumns = {@JoinColumn(name = "article_id", columnDefinition = "ON DELETE SET NULL ON UPDATE CASCADE")}, inverseJoinColumns = {@JoinColumn(name = "category_id", columnDefinition = "ON DELETE SET NULL ON UPDATE CASCADE")})
private Collection<Category> categories = new ArrayList<Category>();
public Article() {
}
public Article(long id, String title, String text, Date date, String source, String image) {
this.id = id;
this.title = title;
this.text = text;
this.date = date;
this.source = source;
this.image = image;
}
public Article(String title, String text, Date date, String source, String image) {
this.title = title;
this.text = text;
this.date = date;
this.source = source;
this.image = image;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public Collection<Category> getCategories() {
return categories;
}
public void setCategories(ArrayList<Category> categories) {
this.categories = categories;
}
public String getCategoryList() {
String list = "";
for (Category c : getCategories())
list += ", " + c.getName();
if (getCategories().size() == 0)
return "";
list = list.substring(2);
return list;
}
}
|
public class Pants extends Cloths{
public Pants(String color, double size, double price, boolean isOnSale) {
super(color, size, price, isOnSale);
}
public void printInfo(Cloths item) {
if(item.isOnSale()== true){
System.out.println("The "+item.getColor()+" pant size "+item.getSize()+" is on sale. The original price is "
+item.getPrice()+" SEK, now it is "+item.discount(item));
}
else{
System.out.println("The "+item.getColor()+" pant size "+item.getSize()+" is not on sale. its price is "
+item.getPrice()+" SEK.");
}
}
@Override
public double discount(Cloths item) {
double promotion = item.getPrice()- item.getPrice()*0.50;
return promotion;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.insat.gl5.crm_pfa.service.security;
import com.insat.gl5.crm_pfa.model.Contact;
import com.insat.gl5.crm_pfa.model.BackendUser;
import com.insat.gl5.crm_pfa.model.security.IdentityObject;
import com.insat.gl5.crm_pfa.model.security.IdentityRoleName;
import java.io.Serializable;
import java.util.Collection;
import javax.ejb.TransactionAttribute;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import javax.interceptor.Interceptors;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.jboss.seam.security.GroupImpl;
import org.jboss.seam.security.Identity;
import org.jboss.solder.logging.Logger;
import org.picketlink.idm.api.Group;
import org.picketlink.idm.api.IdentitySession;
import org.picketlink.idm.api.Role;
import org.picketlink.idm.api.User;
import org.picketlink.idm.common.exception.FeatureNotSupportedException;
import org.picketlink.idm.common.exception.IdentityException;
/**
*
* @author Mounir Messelmeni, contact: messelmeni.mounir@gmail.com
*/
@TransactionAttribute
@Interceptors(org.jboss.seam.transaction.TransactionInterceptor.class)
public class UserProfileService implements Serializable {
@Inject
private EntityManager em;
@Inject
private Identity ident;
@Inject
private IdentitySession identitySession;
@Inject
private Logger log;
@Inject
private Event<Contact> uDetailsEvent;
private final static String INFORMATION_USER = "informationUser";
public boolean updatePassword(String password, String email, String oldPassword) {
if (ident.getUser() != null) {
this.log.info("Update password for user '" + email + "'. Done by " + ident.getUser().getId());
} else {
this.log.info("Update password for user '" + email + "'.");
}
User u = searchUser(email);
try {
if (!this.identitySession.getAttributesManager().validatePassword(u, oldPassword)) {
return false;
}
this.identitySession.getAttributesManager().updatePassword(u, password);
return true;
} catch (IdentityException ex) {
this.log.error("", ex);
return false;
}
}
public Contact saveNewUser(Contact contact, String password, Collection<Role> roles) throws FeatureNotSupportedException, IdentityException {
if (this.ident.getUser() != null) {
this.log.info("Save a new user '" + contact.getLogin() + "'. Done by " + ident.getUser().getId());
}
User user = null;
try {
user = this.identitySession.getPersistenceManager().createUser(contact.getLogin());
this.identitySession.getAttributesManager().updatePassword(user, password);
this.identitySession.getAttributesManager().addAttribute(user.getId(), INFORMATION_USER, contact.getId().toString());
for (Role role : roles) {
try {
identitySession.getRoleManager().createRole(role.getRoleType(), user, role.getGroup());
} catch (FeatureNotSupportedException ex) {
this.log.error("FeatureNotSupportedException :", ex);
throw ex;
}
}
return contact;
} catch (IdentityException ex) {
this.log.error("", ex);
throw ex;
}
}
public BackendUser saveNewUser(BackendUser crmUser, String password, Collection<Role> roles) throws FeatureNotSupportedException, IdentityException {
if (this.ident.getUser() != null) {
this.log.info("Save a new user '" + crmUser.getLogin() + "'. Done by " + ident.getUser().getId());
}
User user = null;
try {
user = this.identitySession.getPersistenceManager().createUser(crmUser.getLogin());
this.identitySession.getAttributesManager().updatePassword(user, password);
this.em.persist(crmUser);
this.identitySession.getAttributesManager().addAttribute(user.getId(), INFORMATION_USER, crmUser.getId().toString());
for (Role role : roles) {
try {
identitySession.getRoleManager().createRole(role.getRoleType(), user, role.getGroup());
} catch (FeatureNotSupportedException ex) {
this.log.error("FeatureNotSupportedException :", ex);
throw ex;
}
}
return crmUser;
} catch (IdentityException ex) {
this.log.error("", ex);
throw ex;
}
}
//* find profiluser by id*/
public Contact getProfilById(int profilId) {
return this.em.find(Contact.class, profilId);
}
/**
* Edit User Profile
* @param Contact
*/
public void editProfiluser(Contact contact) {
this.log.info("Edit a profil '" + contact.getLogin() + "'. Done by " + ident.getUser().getId());
try {
User user = searchUser(contact.getLogin());
String pu = this.identitySession.getAttributesManager().getAttribute(user, INFORMATION_USER).getValue().toString();
contact.setId(Long.parseLong(pu));
this.em.merge(contact);
} catch (IdentityException ex) {
this.log.error("", ex);
}
this.uDetailsEvent.fire(contact);
}
public Contact loadProfilUser(User user) {
try {
if (user != null && this.identitySession.getAttributesManager().getAttribute(user.getId(), INFORMATION_USER) != null) {
Query query = this.em.createQuery("select p from Contact p where p.id = ?1");
Object o = this.identitySession.getAttributesManager().getAttribute(user.getId(), INFORMATION_USER).getValue();
query.setParameter(1, Long.parseLong(o.toString()));
if (!query.getResultList().isEmpty()) {
return (Contact) query.getSingleResult();
}
}
} catch (IdentityException ex) {
this.log.error("", ex);
}
return null;
}
/**
* Load profile by userId
* @param userId
* @return
*/
public Contact loadProfilUser(String userId) {
try {
Query query = this.em.createQuery("select p from Contact p where p.login = ?1");
query.setParameter(1, userId);
if (!query.getResultList().isEmpty()) {
return (Contact) query.getSingleResult();
}
} catch (Exception ex) {
this.log.error("", ex);
}
return null;
}
public BackendUser loadCrmUser(String userId) {
try {
Query query = this.em.createQuery("select p from BackendUser p where p.login = ?1");
query.setParameter(1, userId);
if (!query.getResultList().isEmpty()) {
return (BackendUser) query.getSingleResult();
}
} catch (Exception ex) {
this.log.error("", ex);
}
return null;
}
public User searchUser(String username) {
try {
if (this.identitySession.getPersistenceManager().findUser(username) != null) {
return this.identitySession.getPersistenceManager().findUser(username);
}
} catch (IdentityException ex) {
this.log.error("", ex);
}
return null;
}
public boolean userExists(String username) {
return this.searchUser(username) != null;
}
public Contact verifyExistenceCount(String username) {
Query query = this.em.createQuery("select p from Contact p where p.emailAddress = ?1");
query.setParameter(1, username);
if ((query.getResultList()).isEmpty()) {
return null;
}
return (Contact) query.getSingleResult();
}
public Contact createContact() {
return new Contact();
}
public void deleteGroup(String name, String groupType) throws IdentityException {
Group group = new GroupImpl(name, groupType);
this.identitySession.getPersistenceManager().removeGroup(group, true);
}
public void saveGroup(String groupName, String groupType) throws IdentityException {
this.identitySession.getPersistenceManager().createGroup(groupName, groupType);
}
public void updateGroup(String oldName, String newName) {
Query query = em.createQuery("select i from IdentityObject i where i.name=?1");
query.setParameter(1, oldName);
if ((query.getResultList()).isEmpty()) {
return;
}
IdentityObject identityObject = (IdentityObject) query.getSingleResult();
identityObject.setName(newName);
em.persist(identityObject);
}
public void deleteRoleType(String roleType) throws IdentityException, FeatureNotSupportedException {
this.identitySession.getRoleManager().removeRoleType(roleType);
}
public void saveRoleType(String roleType) throws IdentityException, FeatureNotSupportedException {
this.identitySession.getRoleManager().createRoleType(roleType);
}
public void updateRoleType(String oldName, String newName) {
Query query = em.createQuery("select i from IdentityRoleName i where i.name=?1");
query.setParameter(1, oldName);
if ((query.getResultList()).isEmpty()) {
return;
}
IdentityRoleName identityRoleName = (IdentityRoleName) query.getSingleResult();
identityRoleName.setName(newName);
em.persist(identityRoleName);
}
}
|
package com.zhowin.miyou.recommend.callback;
/**
* author : zho
* date :2020/10/26
* desc :房间设置
*/
public interface OnLiveRoomSettingItemListener {
void onLiveRoomItemClick(int itemID,String itemText);
}
|
package com.tencent.mm.wallet_core.ui;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
class WalletBaseUI$3 implements OnMenuItemClickListener {
final /* synthetic */ WalletBaseUI uYT;
WalletBaseUI$3(WalletBaseUI walletBaseUI) {
this.uYT = walletBaseUI;
}
public final boolean onMenuItemClick(MenuItem menuItem) {
if (this.uYT.bND()) {
this.uYT.YC();
this.uYT.showDialog(1000);
} else {
this.uYT.finish();
}
return true;
}
}
|
package com.tencent.mm.plugin.game;
import com.tencent.mm.bt.h.d;
import com.tencent.mm.plugin.game.wepkg.a.b;
class e$6 implements d {
final /* synthetic */ e jFV;
e$6(e eVar) {
this.jFV = eVar;
}
public final String[] xb() {
return b.diD;
}
}
|
package com.agenin.report.Model.API;
import com.agenin.report.Model.MyOrderItemModel;
import com.agenin.report.Model.NotaItemModel;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class OrderDetailsModel {
@SerializedName("message")
private MyOrderItemModel message;
@SerializedName("nota")
private List<NotaItemModel> nota;
public MyOrderItemModel getMessage() {
return message;
}
public List<NotaItemModel> getNota() {
return nota;
}
}
|
package com.hqhcn.android.service;
import com.hqh.android.entity.Log;
import com.hqh.android.entity.LogExample;
import com.hqh.android.tool.LogType;
import java.util.List;
public interface LogService {
void add(Log entity) throws Exception;
List<Log> query(LogExample example);
/**
* 添加到操作日志记录
*
* @param cz 操作类型
* @param czip 操作员电脑IP
* @param jmw 加密位
* @param logtype 1:系统日志 2:业务日志 3:非常规操作
* @param program 模块代码
* @param usercode 操作员账号
* @param xxsm 详细说明
* @throws Exception
*/
void info(LogType cz, String czip, String jmw, String logtype,
String program, String usercode, String xxsm);
/**
* 添加到操作日志记录
*
* @param cz 操作类型
* @param czip 操作员电脑IP
* @param jmw 加密位
* @param logtype 1:系统日志 2:业务日志 3:非常规操作
* @param program 模块代码
* @param usercode 操作员账号
* @param xxsm 详细说明
* @param resultCode 操作结果 0:失败 1:成功
* @throws Exception
*/
void info(LogType cz, String czip, String jmw, String logtype,
String program, String usercode, String xxsm, String resultCode);
/**
* 只查询今天的数据
*
* @param example
* @return
* @throws Exception
*/
List<Log> queryToday(LogExample example);
}
|
package com.example.a51700.demo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private SurfaceView mSurfaceView;//前面的surfaceview
private SurfaceHolder mSurfaceHolder;//
private Camera mCamera;//相机对象
private ImageView iv_show;//图片
private int viewWidth, viewHeight;//mSurfaceView的宽和高
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
@Override
public void onRequestPermissionsResult(int permsRequestCode, @NonNull String[] permissions, @NonNull int[] grantResults){
switch(permsRequestCode){
case 200:
boolean cameraAccepted = grantResults[0]==PackageManager.PERMISSION_GRANTED;
if(cameraAccepted){
//授权成功之后,调用系统相机进行拍照操作等
}else{
//用户授权拒绝之后,友情提示一下就可以了
Toast.makeText(this,"权限被拒绝",Toast.LENGTH_SHORT).show();
}
break;
}
}
/**
* 初始化控件
*/
private void initView() {
iv_show = (ImageView) findViewById(R.id.iv_show_camera2_activity);
//mSurfaceView
mSurfaceView = (SurfaceView) findViewById(R.id.surface_view_camera2_activity);
mSurfaceHolder = mSurfaceView.getHolder();
// mSurfaceView 不需要自己的缓冲区
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
// mSurfaceView添加回调
mSurfaceHolder.addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) { //SurfaceView创建
// 初始化Camera
initCamera();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) { //SurfaceView销毁
// 释放Camera资源
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
}
}
});
//设置点击监听
iv_show.setOnClickListener(this);
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (mSurfaceView != null) {
viewWidth = mSurfaceView.getWidth();
viewHeight = mSurfaceView.getHeight();
}
}
/**
* SurfaceHolder 回调接口方法
*/
private void initCamera() {
mCamera = Camera.open();//默认开启后置
mCamera.setDisplayOrientation(90);//摄像头进行旋转90°
if (mCamera != null) {
try {
Camera.Parameters parameters = mCamera.getParameters();
//设置预览照片的大小
parameters.setPreviewFpsRange(viewWidth, viewHeight);
//设置相机预览照片帧数
parameters.setPreviewFpsRange(4, 10);
//设置图片格式
parameters.setPictureFormat(ImageFormat.JPEG);
//设置图片的质量
parameters.set("jpeg-quality", 90);
//设置照片的大小
parameters.setPictureSize(viewWidth, viewHeight);
//通过SurfaceView显示预览
mCamera.setPreviewDisplay(mSurfaceHolder);
//开始预览
mCamera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 点击回调方法
*/
@Override
public void onClick(View v) {
if (mCamera == null) return;
//自动对焦后拍照
mCamera.autoFocus(autoFocusCallback);
}
/**
* 自动对焦 对焦成功后 就进行拍照
*/
Camera.AutoFocusCallback autoFocusCallback = new Camera.AutoFocusCallback() {
@Override
public void onAutoFocus(boolean success, Camera camera) {
if (success) {//对焦成功
camera.takePicture(new Camera.ShutterCallback() {//按下快门
@Override
public void onShutter() {
//按下快门瞬间的操作
Toast.makeText(MainActivity.this,"拍照!",Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this,Environment.getExternalStorageDirectory().toString(),Toast.LENGTH_LONG).show();
}
}, new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {//是否保存原始图片的信息
}
}, pictureCallback);
}
}
};
/**
* 获取图片
*/
Camera.PictureCallback pictureCallback = new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
final Matrix matrix = new Matrix();
matrix.setRotate(90);
final Bitmap bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
Toast.makeText(MainActivity.this,"正在保存照片",Toast.LENGTH_SHORT).show();
SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String datetime = tempDate.format(new java.util.Date());
saveBitmapFile(bitmap,datetime);
}
};
//检查系统6.0权限
private boolean canMakeSmores(){
return(Build.VERSION.SDK_INT> Build.VERSION_CODES.LOLLIPOP_MR1);
}
public void saveBitmapFile(Bitmap bitmap,String bitName){
File sdDir=null;
boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
if(sdCardExist)
{
sdDir = Environment.getExternalStorageDirectory();//获取根目录
}else {
Toast.makeText(this,"未发现存储卡",Toast.LENGTH_SHORT).show();
return;
}
File file=new File(sdDir.toString()+"/"+bitName+".jpg");//将要保存图片的路径
try {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
Toast.makeText(this,"存储成功",Toast.LENGTH_SHORT).show();
bos.flush();
bos.close();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this,"存储失败",Toast.LENGTH_SHORT).show();
}
initCamera();
}
}
|
package com.pangpang6.hadoop.flink.apps;
import com.pangpang6.hadoop.flink.source.TradeSource;
import org.apache.flink.api.common.functions.FoldFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
//使用AggregateFunction 重新实现
public class TradeMain {
private static Logger logger = LoggerFactory.getLogger(TradeMain.class);
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(2);
DataStream<Tuple2<String, Integer>> ds = env.addSource(new TradeSource());
KeyedStream<Tuple2<String, Integer>, Tuple> keyedStream = ds.keyBy(0);
keyedStream.sum(1).keyBy(new KeySelector<Tuple2<String, Integer>, Object>() {
@Override
public Object getKey(Tuple2<String, Integer> value) throws Exception {
//为了统计全局信息我们通过在getKey()方法里返回常数“欺骗”flink将所有数据分成一组
return "";
}
}).fold(new HashMap<String, Integer>(), new FoldFunction<Tuple2<String, Integer>, HashMap<String, Integer>>() {
@Override
public HashMap<String, Integer> fold(HashMap<String, Integer> accumulator, Tuple2<String, Integer> value) throws Exception {
accumulator.put(value.f0, value.f1);
return accumulator;
}
}).addSink(new SinkFunction<HashMap<String, Integer>>() {
@Override
public void invoke(HashMap<String, Integer> value, Context context) throws Exception {
Integer sum = value.values().stream().mapToInt(v -> v).sum();
logger.info("TradeMain: {}", sum);
System.out.println(sum);
}
});
//AggregateFunction
//ds.addSink(new TradeSink());
env.execute();
}
}
|
//city-be átpakolva Person-t Car-t megváltozik az osztály neve
//city.Person city.Car VAGY import city.Car; import city.Person;
import city.*;
class Main {
public static void main(String[] args) {
//Person p = new Person("Roger", "Federer", 1980);
//Person q = new Person("Rafael", "Nadal", 1980);
Person p = new Person.makePerson("Roger", "Federer", 1980);
Person q = new Person.makePerson("Rafael", "Nadal", 1980);
Car c = new Car("ABC-242", 5, p);
Car c2 = new Car("CDE-424", 3, null); // null -> q
//Person.isUpperCase() = true;
System.out.println(p);
System.out.println(q);
System.out.println(c);
System.out.println(c2);
}
}
|
package com.tencent.mm.pluginsdk.f;
final class b {
b() {
}
}
|
package rontikeky.beraspakone.cart;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Created by Acer on 2/16/2018.
*/
public class ListCart {
@SerializedName("cart")
@Expose
private List<CartRes> cartList = null;
public List<CartRes> getCart() {
return cartList;
}
public void setCart(List<CartRes> cart) {
this.cartList = cart;
}
}
|
package com.example.restauth.domain;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Domain Service to manage the authentication operations
*/
@Service
public class UserService {
private UserRepository repository;
@Autowired
public UserService(UserRepository repository) {
this.repository = repository;
}
/**
* Registers a user and stores it in the repository
*/
public void registerUser(UserRegistrationRequest request) throws NoSuchAlgorithmException, InvalidKeySpecException, UserAlreadyExistsException {
User user = new User(request.getUsername(), request.getPassword());
repository.storeUser(user);
}
/**
* AUthenticate a user against stored information
*/
public String authenticateUser(String username, UserAuthenticationRequest request) throws InvalidKeySpecException, NoSuchAlgorithmException {
User user = repository.findByUsername(username);
if (user == null || !user.doesPasswordMatch(request.getPassword())) {
return null;
}
return UUID.randomUUID().toString();
}
/**
* Resets the user password
* Executes first an authentication on the fly with the old password
*/
public boolean resetPassword(String username, PasswordResetRequest request) throws InvalidKeySpecException, NoSuchAlgorithmException {
User user = repository.findByUsername(username);
if (user == null || !user.doesPasswordMatch(request.getOldPassword())) {
return false;
}
user.resetPassword(request.getNewPassword());
return true;
}
}
|
package com.twitter.graphjet.demo;
import SprESRepo.HashTag;
import SprESRepo.Message;
import SprESRepo.ProfileUser;
import com.google.gson.reflect.TypeToken;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
* Created by saurav on 21/03/17.
*/
public class InsertEdge extends AbstractServlet {
public InsertEdge(Map<String, SprGraph> graphs) {
super(graphs);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
if (checkIdentifier(req, resp)) {
return;
}
StringBuffer jb = new StringBuffer();
String line;
try {
BufferedReader reader = req.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) {
}
if (jb != null) {
final TypeToken<List<Map<String, Object>>> typeToken = new TypeToken<List<Map<String, Object>>>() {
};
final List<Map<String, Object>> messages = GSON_INSTANCE.fromJson(jb.toString(), typeToken.getType());
for (Map<String, Object> message : messages) {
try {
Message msg = convertToMessage(message);
sprGraph.indexMessage(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
}
} finally {
// do nothing for now
}
}
private Message convertToMessage(Map<String, Object> sourceMap) {
Message message = new Message();
message.setId(Long.valueOf((String) sourceMap.get("snMsgId")));
message.setMessage((String) sourceMap.get("message"));
ProfileUser profile = new ProfileUser();
Map user = (Map) sourceMap.get("fromSnUser");
profile.setId(Long.valueOf((String) user.get("userId")));
profile.setName((String) user.get("screenName"));
message.setUser(profile);
List<String> hTs = (List<String>) sourceMap.get("hashTags");
HashTag[] hashTags = new HashTag[hTs.size()];
for (int i = 0; i < hTs.size(); i++) {
hashTags[i] = new HashTag(hTs.get(i));
}
message.setHashTags(hashTags);
if (sourceMap.get("msgType").equals(8)) {
message.setRetweet(true);
message.setRetweetId(Long.valueOf((String) ((Map) sourceMap.get("additional")).get("quotedStatusId")));
} else {
message.setRetweet(false);
}
return message;
}
}
|
/* Michael Cisternino
* PS#2
* September 16, 2015
*/
package mainPackage;
// class MyInteger contains all methods, objects, and constructors for MyInteger
public class MyInteger {
public static void main(String[] args) {
// created this class to test MyInteger class and methods
char[] numbers = { '1', '2', '3', '4', '9' };
MyInteger newInt = new MyInteger(6);
System.out.println(newInt.isEven());
System.out.println(newInt.isOdd());
System.out.println(newInt.equals(9));
System.out.println(newInt.isPrime());
System.out.println(parseInt("1234"));
System.out.println(parseInt(numbers));
}
// an int data field named value that stores the int value represented by
// this object
private int value;
// a constructor that creates a MyInteger object for specified int value
public MyInteger(int num) {
value = num;
}
// getMyInteger returns int value
public int getMyInteger() {
return value;
}
// isEven returns true if given value is even
public boolean isEven() {
if (this.getMyInteger() % 2 == 0) {
return true;
} else {
return false;
}
}
// isOdd returns true if given value is odd
public boolean isOdd() {
if (this.getMyInteger() % 2 != 0) {
return true;
} else {
return false;
}
}
// is prime returns true if given value is prime
public boolean isPrime() {
int num = 0;
for (num = 2; num <= Math.sqrt(value); num++) {
if (value % num == 0) {
return false;
}
}
{
return true;
}
}
// returns true if specified value is even
public static boolean isEven(int value) {
if (value % 2 == 0) {
return true;
} else {
return false;
}
}
// returns true if specified value is odd
public static boolean isOdd(int value) {
if (value % 2 != 0) {
return true;
} else {
return false;
}
}
// returns true if specified value is prime
public static boolean isPrime(int value) {
int num;
for (num = 0; num <= Math.sqrt(value); num++) {
if (value % 2 == 0) {
return false;
}
}
{
return true;
}
}
// returns true if specified value is even
public static boolean isEven(MyInteger myInt) {
if (myInt.getMyInteger() % 2 == 0) {
return true;
} else {
return false;
}
}
// returns true if specified value is odd
public static boolean isOdd(MyInteger myInt) {
if (myInt.getMyInteger() % 2 != 0) {
return true;
}
else
{
return false;
}
}
// returns true if specified value is prime
public static boolean isPrime(MyInteger myInt) {
int num;
for (num = 0; num <= Math.sqrt(myInt.getMyInteger()); num++) {
if (myInt.getMyInteger() % 2 == 0) {
return false;
}
}
{
return true;
}
}
// returns true if value in the object is equal to specified value
public boolean equals(int aValue) {
if (value == aValue) {
return true;
} else {
return false;
}
}
// returns true if value in the object is equal to specified value
public boolean equals(MyInteger myInt, int someValue) {
if (someValue == myInt.getMyInteger()) {
return true;
} else {
return false;
}
}
// parseInt converts a string into an int value
public static int parseInt(String x) {
int i;
int sum = 0;
for (i = 0; i <= x.length(); i++) {
sum += i;
}
return sum;
}
// uses parseInt to convert an array of numeric characters into an int value
public static int parseInt(char[] anArray) {
int i;
int sum = 0;
for (i = 0; i <= anArray.length; i++) {
sum += i;
}
return sum;
}
}
|
import java.util.LinkedHashMap;
import java.util.Map;
public class uniquevalues {
public static void main(String[] args) {
String s="civic";
char[] ch = s.toCharArray();
Map<Character,Integer> lhm = new LinkedHashMap<>();
for(char c:ch)
{
if(lhm.containsKey(c))
{
lhm.put(c,lhm.get(c)+1);
}
else
{
lhm.put(c,1);
}
}
for(Map.Entry<Character,Integer> me:lhm.entrySet())
{
if(me.getValue()>1)
{
System.out.println(me.getKey()+"-"+me.getValue());
break;
}
}
}
}
|
package cmm04.array;
public class No02_StringArrayDemo {
public static void main(String[] args) {
new No02_StringArrayVO().execute();
}
}
|
package com.ling.mybatis.begin.bean.common;
import io.swagger.annotations.ApiModel;
@ApiModel(description = "请求参数(无额外参数)")
public class DglgRequest extends DglgRequestBase {
}
|
package graph.upload.storage;
import java.nio.file.Path;
import java.util.stream.Stream;
import org.springframework.core.io.Resource;
import org.springframework.web.multipart.MultipartFile;
/**
* ControllerからStorageにアクセスするためのインターフェース
*
*/
public interface StorageService {
/**
* Storageの初期化を行います。
*/
void init();
/**
* uploadfileをStorageに保存します。
* @param uploadfile
*/
void store(MultipartFile uploadfile);
/**
* Storageに保存されいている全てのファイルパスをStreamとして返す。
* @return
*/
Stream<Path> loadAll();
/**
* 指定したfilenameのパスを返す。
* @param filename
* @return Path
*/
Path load(String filename);
/**
* 指定したfilenameのResourceを返す。
* @param filename
* @return Resource
*/
Resource loadAsResource(String filename);
/**
* Storageを全て削除する。
*/
void deleteAll();
}
|
package com.github.emailtohl.integration.core.auth;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.List;
import java.util.Random;
import javax.inject.Inject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.github.emailtohl.integration.core.ExecResult;
import com.github.emailtohl.integration.core.coreTestConfig.CoreTestData;
import com.github.emailtohl.integration.core.role.Role;
import com.github.emailtohl.integration.core.role.RoleAuditedService;
import com.github.emailtohl.integration.core.role.RoleService;
import com.github.emailtohl.integration.core.role.RoleType;
import com.github.emailtohl.integration.core.user.customer.CustomerAuditedService;
import com.github.emailtohl.integration.core.user.customer.CustomerService;
import com.github.emailtohl.integration.core.user.employee.EmployeeAuditedService;
import com.github.emailtohl.integration.core.user.employee.EmployeeService;
import com.github.emailtohl.integration.core.user.entities.Customer;
import com.github.emailtohl.integration.core.user.entities.Employee;
import com.github.emailtohl.lib.jpa.AuditedRepository.RevTuple;
/**
* 在接口处声明了权限,对这些声明进行测试
* @author HeLei
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SecurityConfiguration.class)
public class GlobalMethodSecurityTest {
@Inject
CoreTestData td;
@Inject
SecurityContextManager scm;
@Inject
RoleService roleService;
@Inject
EmployeeService employeeService;
@Inject
CustomerService customerService;
@Inject
CustomerAuditedService customerAuditedService;
@Inject
EmployeeAuditedService employeeAuditedService;
@Inject
RoleAuditedService roleAuditedService;
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test(expected = AccessDeniedException.class)
public void testRoleService() {
scm.clearContext();
try {
// 未登录时不能访问被权限包含的方法
roleService.getAuthorities();
} catch (Exception e) {
assertTrue(e instanceof AuthenticationCredentialsNotFoundException);
}
scm.setEmailtohl();
// 登录的用户可以调用该方法
roleService.getAuthorities();
Role r = new Role("test", RoleType.EMPLOYEE, "test");
r = roleService.create(r);
roleService.update(r.getId(), new Role("test", RoleType.CUSTOMER, "for update"));
// 只要登录,即可查询角色列表
scm.setBar();
roleService.getAuthorities();
// bar没有role权限,故会抛出AccessDeniedException
roleService.update(r.getId(), new Role("test", RoleType.EMPLOYEE, "for update again"));
}
@Test
public void testEmployeeService() {
Integer empNum = 1002;
Employee bar = null;
ExecResult r = null;
scm.clearContext();
try {
employeeService.create(new Employee());
} catch (Exception e) {
assertTrue(e instanceof AuthenticationCredentialsNotFoundException);
}
try {
bar = employeeService.get(td.bar.getId());
} catch (Exception e) {
assertTrue(e instanceof AuthenticationCredentialsNotFoundException);
}
assertNull(bar);
try {
// 传入参数是否正确并不重要,关键是测试被权限包含的方法是否能被调用
bar = employeeService.grandRoles(td.bar.getId(), "a", "b", "c");
} catch (Exception e) {
assertTrue(e instanceof AuthenticationCredentialsNotFoundException);
}
assertNull(bar);
try {
r = employeeService.resetPassword(td.bar.getId());
} catch (Exception e) {
assertTrue(e instanceof AuthenticationCredentialsNotFoundException);
}
assertNull(r);
try {
bar = employeeService.enabled(td.bar.getId(), true);
} catch (Exception e) {
assertTrue(e instanceof AuthenticationCredentialsNotFoundException);
}
assertNull(bar);
try {
r = employeeService.updatePassword(empNum, "678901", "token");
} catch (Exception e) {
assertTrue(e instanceof AuthenticationCredentialsNotFoundException);
}
scm.setEmailtohl();
employeeService.create(new Employee());
bar = employeeService.get(td.bar.getId());
assertNotNull(bar);
bar = employeeService.grandRoles(td.bar.getId(), "a", "b", "c");
assertNotNull(bar);
r = employeeService.resetPassword(td.bar.getId());
assertTrue(r.ok);
bar = employeeService.enabled(td.bar.getId(), false);
bar = employeeService.enabled(td.bar.getId(), true);
try {
r = employeeService.updatePassword(empNum, "678901", "token");
} catch (Exception e) {
assertTrue(e instanceof AccessDeniedException);
}
scm.setBar();
try {
employeeService.create(new Employee());
} catch (Exception e) {
assertTrue(e instanceof AccessDeniedException);
}
bar = employeeService.get(td.bar.getId());
assertNotNull(bar);
try {
bar = employeeService.grandRoles(td.bar.getId(), "a", "b", "c");
} catch (Exception e) {
assertTrue(e instanceof AccessDeniedException);
}
try {
r = employeeService.resetPassword(td.bar.getId());
} catch (Exception e) {
assertTrue(e instanceof AccessDeniedException);
}
try {
bar = employeeService.enabled(td.bar.getId(), false);
} catch (Exception e) {
assertTrue(e instanceof AccessDeniedException);
}
System.out.println(SecurityContextHolder.getContext().getAuthentication().getName());
r = employeeService.updatePassword(empNum, "678901", "token");
assertTrue(r.ok);
}
@Test
public void testCustomerService() {
Customer baz = null;
ExecResult r = null;
scm.clearContext();
try {
baz = customerService.get(td.baz.getId());
} catch (Exception e) {
assertTrue(e instanceof AuthenticationCredentialsNotFoundException);
}
assertNull(baz);
try {
baz = customerService.getByUsername(randomCellPhoneOrEmail(td.baz));
} catch (Exception e) {
assertTrue(e instanceof AuthenticationCredentialsNotFoundException);
}
assertNull(baz);
try {
baz = customerService.update(td.baz.getId(), new Customer());
} catch (Exception e) {
assertTrue(e instanceof AuthenticationCredentialsNotFoundException);
}
// assertNull(baz);
try {
baz = customerService.grandRoles(td.baz.getId(), "a", "b", "c");
} catch (Exception e) {
assertTrue(e instanceof AuthenticationCredentialsNotFoundException);
}
assertNull(baz);
try {
baz = customerService.grandLevel(td.baz.getId(), Customer.Level.VIP);
} catch (Exception e) {
assertTrue(e instanceof AuthenticationCredentialsNotFoundException);
}
assertNull(baz);
try {
r = customerService.resetPassword(td.baz.getId());
} catch (Exception e) {
assertTrue(e instanceof AuthenticationCredentialsNotFoundException);
}
assertNull(r);
try {
baz = customerService.enabled(td.baz.getId(), true);
} catch (Exception e) {
assertTrue(e instanceof AuthenticationCredentialsNotFoundException);
}
assertNull(baz);
try {
r = customerService.updatePassword(td.baz.getEmail(), "678901", "token");
} catch (Exception e) {
assertTrue(e instanceof AuthenticationCredentialsNotFoundException);
}
scm.setEmailtohl();
baz = customerService.get(td.baz.getId());
assertNotNull(baz);
baz = customerService.getByUsername(randomCellPhoneOrEmail(td.baz));
assertNotNull(baz);
td.baz.setName("_baz");
baz = customerService.update(td.baz.getId(), td.baz);
td.baz.setName("baz");
baz = customerService.update(td.baz.getId(), td.baz);
// assertNotNull(baz);
baz = customerService.grandRoles(td.baz.getId(), "a", "b", "c");
assertNotNull(baz);
baz = customerService.grandLevel(td.baz.getId(), Customer.Level.VIP);
assertNotNull(baz);
r = employeeService.resetPassword(td.baz.getId());
assertTrue(r.ok);
baz = customerService.enabled(td.baz.getId(), false);
baz = customerService.enabled(td.baz.getId(), true);
try {
r = customerService.updatePassword(td.baz.getEmail(), "678901", "token");
} catch (Exception e) {
assertTrue(e instanceof AccessDeniedException);
}
scm.setBaz();
baz = customerService.get(td.baz.getId());
assertNotNull(baz);
baz = customerService.getByUsername(randomCellPhoneOrEmail(td.baz));
assertNotNull(baz);
baz = customerService.update(td.baz.getId(), new Customer());
// assertNotNull(baz);
try {
baz = customerService.grandRoles(td.baz.getId(), "a", "b", "c");
} catch (Exception e) {
assertTrue(e instanceof AccessDeniedException);
}
try {
baz = customerService.grandLevel(td.baz.getId(), Customer.Level.VIP);
} catch (Exception e) {
assertTrue(e instanceof AccessDeniedException);
}
try {
r = customerService.resetPassword(td.baz.getId());
} catch (Exception e) {
assertTrue(e instanceof AccessDeniedException);
}
try {
baz = customerService.enabled(td.baz.getId(), false);
} catch (Exception e) {
assertTrue(e instanceof AccessDeniedException);
}
System.out.println(SecurityContextHolder.getContext().getAuthentication().getName());
r = customerService.updatePassword(td.baz.getCellPhone(), "678901", "token");
assertTrue(r.ok);
}
@Test
public void testCustomerAuditedService() {
Customer baz = null;
List<RevTuple<Customer>> ls = null;
scm.clearContext();
try {
baz = customerAuditedService.getCustomerAtRevision(1L, 1);
} catch (Exception e) {
assertTrue(e instanceof AuthenticationCredentialsNotFoundException);
}
assertNull(baz);
try {
ls = customerAuditedService.getCustomerRevision(1L);
} catch (Exception e) {
assertTrue(e instanceof AuthenticationCredentialsNotFoundException);
}
assertNull(ls);
scm.setBaz();
try {
baz = customerAuditedService.getCustomerAtRevision(1L, 1);
} catch (Exception e) {
assertTrue(e instanceof AccessDeniedException);
}
assertNull(baz);
try {
ls = customerAuditedService.getCustomerRevision(1L);
} catch (Exception e) {
assertTrue(e instanceof AccessDeniedException);
}
scm.setEmailtohl();
baz = customerAuditedService.getCustomerAtRevision(1L, 1);
assertNotNull(baz);
ls = customerAuditedService.getCustomerRevision(1L);
assertNotNull(ls);
}
@Test
public void testEmployeeAuditedService() {
Employee bar = null;
List<RevTuple<Employee>> ls = null;
scm.clearContext();
try {
bar = employeeAuditedService.getEmployeeAtRevision(1L, 1);
} catch (Exception e) {
assertTrue(e instanceof AuthenticationCredentialsNotFoundException);
}
assertNull(bar);
try {
ls = employeeAuditedService.getEmployeeRevision(1L);
} catch (Exception e) {
assertTrue(e instanceof AuthenticationCredentialsNotFoundException);
}
assertNull(ls);
scm.setBaz();
try {
bar = employeeAuditedService.getEmployeeAtRevision(1L, 1);
} catch (Exception e) {
assertTrue(e instanceof AccessDeniedException);
}
assertNull(bar);
try {
ls = employeeAuditedService.getEmployeeRevision(1L);
} catch (Exception e) {
assertTrue(e instanceof AccessDeniedException);
}
scm.setEmailtohl();
bar = employeeAuditedService.getEmployeeAtRevision(1L, 1);
assertNotNull(bar);
ls = employeeAuditedService.getEmployeeRevision(1L);
assertNotNull(ls);
}
@Test
public void testRoleAuditedService() {
Role role = null;
List<RevTuple<Role>> ls = null;
scm.clearContext();
try {
role = roleAuditedService.getRoleAtRevision(1L, 1);
} catch (Exception e) {
assertTrue(e instanceof AuthenticationCredentialsNotFoundException);
}
assertNull(role);
try {
ls = roleAuditedService.getRoleRevision(1L);
} catch (Exception e) {
assertTrue(e instanceof AuthenticationCredentialsNotFoundException);
}
assertNull(ls);
scm.setBaz();
try {
role = roleAuditedService.getRoleAtRevision(1L, 1);
} catch (Exception e) {
assertTrue(e instanceof AccessDeniedException);
}
assertNull(role);
try {
ls = roleAuditedService.getRoleRevision(1L);
} catch (Exception e) {
assertTrue(e instanceof AccessDeniedException);
}
scm.setEmailtohl();
role = roleAuditedService.getRoleAtRevision(1L, 1);
assertNotNull(role);
ls = roleAuditedService.getRoleRevision(1L);
assertNotNull(ls);
}
Random r = new Random();
String randomCellPhoneOrEmail(Customer c) {
if (r.nextBoolean()) {
return c.getCellPhone();
} else {
return c.getEmail();
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Distributions.MethodOfMoments;
import Distributions.ContinuousDistribution;
import Distributions.ContinuousDistributionError;
import java.util.ArrayList;
/**
*
* @author Will_and_Sara
*/
public class Uniform extends ContinuousDistribution{
private double _Min;
private double _Max;
public double GetMin(){return _Min;}
public double GetMax(){return _Max;}
public Uniform(){
//for reflection
_Min = 0;
_Max = 0;
}
public Uniform(double min, double max){
_Min = min;
_Max = max;
}
public Uniform(double[] data){
MomentFunctions.BasicProductMoments BPM = new MomentFunctions.BasicProductMoments(data);
_Min = BPM.GetMin();
_Max = BPM.GetMax();
SetPeriodOfRecord(BPM.GetSampleSize());
//alternative method
//double dist = java.lang.Math.sqrt(3*BPM.GetSampleVariance());
//_Min = BPM.GetMean() - dist;
//_Max = BPM.GetMean() + dist;
}
@Override
public double GetInvCDF(double probability) {
return _Min + ((_Max - _Min)* probability);
}
@Override
public double GetCDF(double value) {
if(value<_Min){
return 0;
}else if(value <=_Max){
return (value - _Min)/(_Min - _Max);
}else{
return 1;
}
}
@Override
public double GetPDF(double value) {
if(value < _Min){
return 0;
}else if(value <= _Max){
return 1/(_Max-_Min);
}else{
return 0;
}
}
@Override
public ArrayList<ContinuousDistributionError> Validate() {
ArrayList<ContinuousDistributionError> errs = new ArrayList<>();
if(_Min>_Max){errs.add(new ContinuousDistributionError("The min cannot be greater than the max in the uniform distribuiton."));}
return errs;
}
}
|
package com.example.demo.dao;
import com.example.demo.entity.Customer;
import com.example.demo.utils.GenericDaoHibernateImpl;
import com.example.demo.utils.SearchCriteria;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;
import java.io.Serializable;
import java.util.List;
@Repository
public class CustomerDao extends GenericDaoHibernateImpl<Customer, Serializable> {
public List<Customer> getSearchedCustomer(SearchCriteria searchCriteria) {
String hql = "from Customer customer where 1=1";
if (searchCriteria != null) {
if(searchCriteria.getId()!=null) {
hql+= " and customer.id=:customerId";
}
if(searchCriteria.getName()!=null && !searchCriteria.getName().isEmpty()) {
hql+= " and customer.name like :customerName";
}
if(searchCriteria.getEmail()!=null && !searchCriteria.getEmail().isEmpty()) {
hql+= " and customer.emailId=:customerEmail";
}
if(searchCriteria.getPassword()!=null && !searchCriteria.getPassword().toString().isEmpty()) {
hql+= " and customer.password=:customerPassword";
}
if(searchCriteria.getContactNo()!=null && !searchCriteria.getContactNo().isEmpty()) {
hql+= " and customer.contactNo like :customerContact";
}
if(searchCriteria.getActive()!=null) {
hql+= " and customer.active=:customerActive";
}
if(searchCriteria.getPasswordToken()!=null && !searchCriteria.getPasswordToken().isEmpty()) {
hql+= " and customer.passwordToken=:passwordToken";
}
}
hql += " order by customer.name";
Query query = currentSession().createQuery(hql);
if (searchCriteria != null) {
if(searchCriteria.getId()!=null) {
query.setParameter("customerId", searchCriteria.getId());
}
if(searchCriteria.getName()!=null && !searchCriteria.getName().isEmpty()) {
query.setParameter("customerName", searchCriteria.getName() + "%");
}
if(searchCriteria.getEmail()!=null && !searchCriteria.getEmail().isEmpty()) {
query.setParameter("customerEmail", searchCriteria.getEmail());
}
if(searchCriteria.getPassword()!=null && !searchCriteria.getPassword().toString().isEmpty()) {
query.setParameter("customerPassword", searchCriteria.getPassword().toString());
}
if(searchCriteria.getContactNo()!=null && !searchCriteria.getContactNo().isEmpty()) {
query.setParameter("customerContact", searchCriteria.getContactNo() + "%");
}
if(searchCriteria.getActive()!=null) {
query.setParameter("customerActive", searchCriteria.getActive());
}
if(searchCriteria.getPasswordToken()!=null && !searchCriteria.getPasswordToken().isEmpty()) {
query.setParameter("passwordToken", searchCriteria.getPasswordToken());
}
}
return query.getResultList();
}
public int updateCustomerPassword(Customer customer) {
String hql = "update Customer customer set customer.password=:password," +
" customer.passwordToken=NULL" +
" where customer.id=:customerId";
Query query = currentSession().createQuery(hql);
query.setParameter("password", customer.getPassword());
query.setParameter("customerId", customer.getId());
return query.executeUpdate();
}
public int updateCustomerProfile(Customer customer) {
String hql = "update Customer customer set customer.name=:name," +
" customer.emailId=:emailId, customer.contactNo=:contactNo" +
" where customer.id=:customerId";
Query query = currentSession().createQuery(hql);
query.setParameter("name", customer.getName());
query.setParameter("emailId", customer.getEmailId());
query.setParameter("contactNo", customer.getContactNo());
query.setParameter("customerId", customer.getId());
return query.executeUpdate();
}
public int updateCustomerPaswordToken(Customer customer) {
String hql = "update Customer customer set customer.passwordToken=:passwordToken"
+ " where customer.id=:customerId";
Query query = currentSession().createQuery(hql);
query.setParameter("passwordToken", customer.getPasswordToken());
query.setParameter("customerId", customer.getId());
return query.executeUpdate();
}
public int activateCustomer(String activationToken) {
String hql = "update Customer customer set customer.active=true,"
+ " customer.passwordToken=NULL"
+ " where customer.passwordToken=:activationToken";
Query query = currentSession().createQuery(hql);
query.setParameter("activationToken", activationToken);
return query.executeUpdate();
}
}
|
package com.previred.lost.periods.utils;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
/**
* Set of operations to manipulate and format Strings.
*
* @author Carlos Izquierdo
* @author izqunited@gmail.com
*
*/
public final class StringFormatUtils {
private StringFormatUtils() {
}
/**
* Apply a String format mask to a {@link Date}, using the ISO Date Format.
*
* @return String that represents a date into ISO format (i.e. 2020-05-02
* 14:03:47.896Z).
*/
public static String getTodayISODate() {
return LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
}
/**
* Build and return String REST endpoint.
*
* @param protocol Service protocol ("http://" or "://").
* @param host Host name or IP address of service (i.e. "127.0.0.1",
* "localhost").
* @param port Port number of service, recommended value between [1100 -
* 65535].
* @param path API operation context path started with "/" character (i.e.
* "/resource/operation").
* @return String URL with the following structure:
* <b>"<protocol://><host>:<port></path>"</b>
* (i.e. http://127.0.0.1:8080/tickets-api/list).
*/
public static String getUrlService(String protocol, String host, String port, String path) {
return String.format("%s%s%s%s", protocol, host, ":" + port, path);
}
}
|
package com.example.ty_en.ires;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.InputStream;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
public class OrderActivity extends AppCompatActivity implements View.OnClickListener{
private MenuItemAdapter menuItemAdapter ;
private ArrayList<MenuItem> menuItemList ;
private GridView orderGridView ;
private Bundle imageBundle ;
private SaveMenuImageAsyncTask saveMenuImageAsyncTask ;
private ImageFileOutFactory ifof1 ;
private ImageFileOutFactory ifof2 ;
private ImageFileOutFactory ifof3 ;
private ImageFileOutFactory ifof4 ;
private ImageFileOutFactory ifof5 ;
//確認用のmenuItemList
private ArrayList<MenuItem> confirmMenuItemList ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order);
//メニューリストの生成
menuItemList = new ArrayList() ;
//メニューリストにサンプルデータ投入
getMenuData();
//GridView用のAdapter生成
menuItemAdapter = new MenuItemAdapter(getApplicationContext(),R.id.order_list,menuItemList) ;
//Adapter設定
orderGridView = (GridView)findViewById(R.id.order_list) ;
orderGridView.setAdapter(menuItemAdapter);
//Gridビューの編集
//スクロールバーを非表示
orderGridView.setVerticalScrollBarEnabled(false);
//カード部分をselectorにするため、リストのselectorは透明に
orderGridView.setSelector(android.R.color.transparent);
//DoneButton
Button orderDoneButton = (Button)findViewById(R.id.order_done_button) ;
orderDoneButton.setOnClickListener(this) ;
}
@Override
protected void onStop(){
super.onStop();
System.out.println("STOPしたよ") ;
orderGridView.setAdapter(null);
menuItemAdapter = null ;
orderGridView = null ;
imageBundle = null ;
saveMenuImageAsyncTask.cancel(false) ;
saveMenuImageAsyncTask = null ;
ifof1 = null;
ifof2 = null;
ifof3 = null;
ifof4 = null;
ifof5 = null;
}
@Override
public void onClick(View v) {
//オーダーがあるメニューのみ入れ替え
confirmMenuItemList = new ArrayList<>() ;
for(MenuItem item:menuItemList){
if(item.getMenuOrderCount() > 0){
confirmMenuItemList.add(item);
}
}
//Intentにリストを登録
Intent intent = new Intent(getApplicationContext(),OrderDoneActivity.class) ;
intent.putExtra("menuItemList",confirmMenuItemList) ;
startActivity(intent) ;
}
private class MenuItemAdapter extends ArrayAdapter<MenuItem> {
private LayoutInflater inflater;
public MenuItemAdapter(Context context, int resource, List<MenuItem> objects) {
super(context, resource, objects);
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public View getView(int position, View convertView, ViewGroup parent) {
//ビューの取得
View view = inflater.inflate(R.layout.menu_layout, null, false);
//メニュー情報取得
MenuItem menuItem = getItem(position) ;
//メニュー画像
ImageView menuImageView = (ImageView)view.findViewById(R.id.menu_image);
menuImageView.setImageBitmap((Bitmap)imageBundle.getParcelable(menuItem.getMenuImageKey()));
//メニュー名
final TextView menuNameView = (TextView)view.findViewById(R.id.menu_name) ;
menuNameView.setText(menuItem.getMenuName());
//メニューオーダー数
TextView menuOrderCountView = (TextView)view.findViewById(R.id.menu_order_count) ;
menuOrderCountView.setText(String.valueOf(menuItem.getMenuOrderCount()));
//メニュー金額
NumberFormat numberFormat = NumberFormat.getCurrencyInstance() ;
TextView menuPriceView = (TextView)view.findViewById(R.id.menu_price) ;
menuPriceView.setText(numberFormat.format(menuItem.getMenuPrice()));
//追加ボタンにリスナー登録
Button addButton = (Button)view.findViewById(R.id.add_button) ;
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//タグから対象オブジェクトを特定し、オーダー数の加算
MenuItem tempMenuItem = menuItemList.get((Integer) v.getTag()) ;
int menuOrderCount = tempMenuItem.getMenuOrderCount();
//件数が最大値未満であれば追加させる
if(menuOrderCount < Integer.MAX_VALUE){
tempMenuItem.setMenuOrderCount(++menuOrderCount);
}
//親ビューを特定し、加算後のオーダー数で更新
View parentView = (View)v.getParent() ;
TextView menuOrderCountView = (TextView)parentView.findViewById(R.id.menu_order_count) ;
menuOrderCountView.setText(String.valueOf(tempMenuItem.getMenuOrderCount()));
}
});
//減少ボタンにリスナー登録
Button decButton = (Button)view.findViewById(R.id.dec_button) ;
decButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//タグから対象オブジェクトを特定し、オーダー数の減少
MenuItem tempMenuItem = menuItemList.get((Integer) v.getTag()) ;
int menuOrderCount = tempMenuItem.getMenuOrderCount();
//件数が1以上であれば減少させる
if(menuOrderCount > 0){
tempMenuItem.setMenuOrderCount(--menuOrderCount);
}
//親ビューを特定し、減少後のオーダー数で更新
View parentView = (View)v.getParent() ;
TextView menuOrderCountView = (TextView)parentView.findViewById(R.id.menu_order_count) ;
menuOrderCountView.setText(String.valueOf(menuOrderCount));
}
});
//タグの設定(OnClickListener呼び出し時に使う)
addButton.setTag(position);
decButton.setTag(position);
return view;
}
}
private void getMenuData() {
MenuItem item1 = new MenuItem();
MenuItem item2 = new MenuItem();
MenuItem item3 = new MenuItem();
MenuItem item4 = new MenuItem();
MenuItem item5 = new MenuItem();
Bitmap image1;
Bitmap image2;
Bitmap image3;
Bitmap image4;
Bitmap image5;
//設定先のImageViewを取得
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.menu_layout, null, false);
ImageView imageView = (ImageView)view.findViewById(R.id.menu_image) ;
//サンプルサイズを決定
int imageViewWidth = imageView.getLayoutParams().width ;
int imageViewHeight = imageView.getLayoutParams().height ;
//Optionsを用いて画像のメモリ展開を抑制
BitmapFactory.Options options1 = new BitmapFactory.Options() ;
options1.inJustDecodeBounds = true ;
BitmapFactory.Options options2 = new BitmapFactory.Options() ;
options2.inJustDecodeBounds = true ;
BitmapFactory.Options options3 = new BitmapFactory.Options() ;
options3.inJustDecodeBounds = true ;
BitmapFactory.Options options4 = new BitmapFactory.Options() ;
options4.inJustDecodeBounds = true ;
BitmapFactory.Options options5 = new BitmapFactory.Options() ;
options5.inJustDecodeBounds = true ;
//画像を取得
image1 = BitmapFactory.decodeResource(getResources(), R.raw.img_bagna_cauda,options1);
image2 = BitmapFactory.decodeResource(getResources(), R.raw.img_beer,options2);
image3 = BitmapFactory.decodeResource(getResources(), R.raw.img_edamame_web,options3);
image4 = BitmapFactory.decodeResource(getResources(), R.raw.img_dassai_web,options4);
image5 = BitmapFactory.decodeResource(getResources(), R.raw.img_pasta,options5);
//リサイズ
options1.inJustDecodeBounds = false ;
options2.inJustDecodeBounds = false ;
options3.inJustDecodeBounds = false ;
options4.inJustDecodeBounds = false ;
options5.inJustDecodeBounds = false ;
options1.inPreferredConfig = Bitmap.Config.RGB_565 ;
options2.inPreferredConfig = Bitmap.Config.RGB_565 ;
options3.inPreferredConfig = Bitmap.Config.RGB_565 ;
options4.inPreferredConfig = Bitmap.Config.RGB_565 ;
options5.inPreferredConfig = Bitmap.Config.RGB_565 ;
calculateInSampleSize(options1,imageViewWidth,imageViewHeight) ;
image1 = BitmapFactory.decodeResource(getResources(), R.raw.img_bagna_cauda,options1);
calculateInSampleSize(options2,imageViewWidth,imageViewHeight) ;
image2 = BitmapFactory.decodeResource(getResources(), R.raw.img_beer,options2);
calculateInSampleSize(options3,imageViewWidth,imageViewHeight) ;
image3 = BitmapFactory.decodeResource(getResources(), R.raw.img_edamame_web,options3);
calculateInSampleSize(options4,imageViewWidth,imageViewHeight) ;
image4 = BitmapFactory.decodeResource(getResources(), R.raw.img_dassai_web,options4);
calculateInSampleSize(options5,imageViewWidth,imageViewHeight) ;
image5 = BitmapFactory.decodeResource(getResources(), R.raw.img_pasta,options5);
//画像格納用のBundleを生成
imageBundle = new Bundle();
//リソースファイルのインプットストリームを取得し設定
item1.setMenuName("Bagna cauda");
item1.setMenuImageKey("image1");
imageBundle.putParcelable(item1.getMenuImageKey(),image1);
item1.setMenuImageKey("image1");
item1.setSoftMovieKey("soft1");
item1.setHardMovieKey("hard1");
item1.setMenuPrice(1000);
item1.setMenuOrderCount(0);
item2.setMenuName("Japanese Beer");
item2.setMenuImageKey("image2");
imageBundle.putParcelable(item2.getMenuImageKey(),image2);
item2.setMenuImageKey("image2");
item2.setSoftMovieKey("soft2");
item2.setHardMovieKey("hard2");
item2.setMenuOrderCount(0);
item2.setMenuPrice(450);
item3.setMenuName("Edamame");
item3.setMenuImageKey("image3");
imageBundle.putParcelable(item3.getMenuImageKey(),image3);
item3.setMenuImageKey("image3");
item3.setSoftMovieKey("soft3");
item3.setHardMovieKey("hard3");
item3.setMenuOrderCount(0);
item3.setMenuPrice(500);
item4.setMenuName("Nihonshu Dassai");
item4.setMenuImageKey("image4");
imageBundle.putParcelable(item4.getMenuImageKey(),image4);
item4.setMenuImageKey("image4");
item4.setSoftMovieKey("soft4");
item4.setHardMovieKey("hard4");
item4.setMenuOrderCount(0);
item4.setMenuPrice(1200);
item5.setMenuName("Seafood Pasta");
item5.setMenuImageKey("image5");
imageBundle.putParcelable(item5.getMenuImageKey(),image5);
item5.setSoftMovieKey("soft5");
item5.setHardMovieKey("hard5");
item5.setMenuImageKey("image5");
item5.setMenuOrderCount(0);
item5.setMenuPrice(2000);
menuItemList.add(item1);
menuItemList.add(item2);
menuItemList.add(item3);
menuItemList.add(item4);
menuItemList.add(item5);
//画像を他アクティビティで取り出せるように内部ストレージに保存
ifof1 = new ImageFileOutFactory(getApplicationContext(),item1.getMenuImageKey(),image1);
ifof2 = new ImageFileOutFactory(getApplicationContext(),item2.getMenuImageKey(),image2);
ifof3 = new ImageFileOutFactory(getApplicationContext(),item3.getMenuImageKey(),image3);
ifof4 = new ImageFileOutFactory(getApplicationContext(),item4.getMenuImageKey(),image4);
ifof5 = new ImageFileOutFactory(getApplicationContext(),item5.getMenuImageKey(),image5);
saveMenuImageAsyncTask = new SaveMenuImageAsyncTask() ;
saveMenuImageAsyncTask.execute(ifof1,ifof2,ifof3,ifof4,ifof5) ;
}
//画像のサイズ縮小率を計算
public static void calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// 画像の元サイズ
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = (int)Math.floor((double)height / (double)reqHeight);
} else {
inSampleSize = (int)Math.floor((double)width / (double)reqWidth);
}
}
options.inSampleSize = inSampleSize ;
}
//別タスクで画像を保存
public class SaveMenuImageAsyncTask extends AsyncTask<ImageFileOutFactory,Void,Boolean> {
@Override
protected Boolean doInBackground(ImageFileOutFactory... ifofs){
for(ImageFileOutFactory ifof : ifofs){
ifof.saveBitmap() ;
ifof = null ;
}
return true ;
}
@Override
protected void onPostExecute(Boolean result){
cancel(true) ;
}
}
}
|
package com.netease.course;
import java.util.List;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
/**
* @author menglanyingfei
* @date 2017-8-27
*/
public interface MybatisDao {
@Update("UPDATE UserBalance SET balance=balance+#{param2} WHERE userId=#{param1} ")
public void addMoney(Long userId,double count);
@Update("UPDATE UserBalance SET balance=balance-#{param2} WHERE userId=#{param1} ")
public void subMoney(Long userId,double count);
@Select("SELECT * FROM UserBalance")
public List<UserBalance> findAll();
}
|
/*
* To change this li @Override
public int getWidth(ImageObserver observer) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public int getHeight(ImageObserver observer) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public ImageProducer getSource() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Graphics getGraphics() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Object getProperty(String name, ImageObserver observer) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
cense header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package BankSystem;
/**
*
* @author iktakhairul
*/
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.*;
import java.util.Random;
import javax.swing.JOptionPane;
public class ChangePIN extends javax.swing.JFrame {
Connection conn;
ResultSet rs;
PreparedStatement pst;
/**
* Creates new form AccountResister
*/
public ChangePIN() {
super("ChangePIN");
initComponents();
conn=javaconnect.ConnecrDb();
}
/**
* 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() {
jPanel4 = new javax.swing.JPanel();
jTextField10 = new javax.swing.JTextField();
jPanel5 = new javax.swing.JPanel();
jLabel11 = new javax.swing.JLabel();
ChangePassword = new javax.swing.JPanel();
jTextField2 = new javax.swing.JTextField();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jTextField3 = new javax.swing.JTextField();
jTextField1 = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
jTextField6 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
savec = new javax.swing.JButton();
savec1 = new javax.swing.JButton();
jLabel6 = new javax.swing.JLabel();
jTextField5 = new javax.swing.JTextField();
jTextField7 = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
jTextField8 = new javax.swing.JTextField();
jTextField9 = new javax.swing.JTextField();
jPasswordField1 = new javax.swing.JPasswordField();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
jMenuItem3 = new javax.swing.JMenuItem();
jMenuItem4 = new javax.swing.JMenuItem();
jMenuItem5 = new javax.swing.JMenuItem();
jMenuItem7 = new javax.swing.JMenuItem();
jMenuItem8 = new javax.swing.JMenuItem();
jMenuItem18 = new javax.swing.JMenuItem();
jMenuItem9 = new javax.swing.JMenuItem();
jMenuItem11 = new javax.swing.JMenuItem();
jMenuItem10 = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(new java.awt.Color(0, 0, 0));
setMinimumSize(new java.awt.Dimension(1400, 800));
setPreferredSize(new java.awt.Dimension(1400, 800));
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jPanel4.setBackground(new java.awt.Color(0, 0, 0));
jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 153, 102), 3), "Change Password", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Lucida Grande", 0, 24), new java.awt.Color(51, 255, 153))); // NOI18N
jTextField10.setEditable(false);
jTextField10.setBackground(new java.awt.Color(0,0,0,0)
);
jTextField10.setForeground(new java.awt.Color(204, 204, 204));
jTextField10.setHorizontalAlignment(javax.swing.JTextField.CENTER);
jTextField10.setText("@2018Iktakhairul");
jTextField10.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(26, 26, 26)
.addComponent(jTextField10, javax.swing.GroupLayout.PREFERRED_SIZE, 176, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(44, Short.MAX_VALUE))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
.addContainerGap(717, Short.MAX_VALUE)
.addComponent(jTextField10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
getContentPane().add(jPanel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 260, 780));
jPanel5.setBackground(new java.awt.Color(0, 0, 0));
jPanel5.setLayout(null);
jLabel11.setBackground(new java.awt.Color(0, 0, 0));
jLabel11.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/AboutMe.jpg"))); // NOI18N
jLabel11.setText("jLabel11");
jLabel11.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 153, 51), 3, true), "Humpty-Dumpty Bank Limited", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.ABOVE_BOTTOM, new java.awt.Font("Lucida Grande", 1, 60), new java.awt.Color(102, 255, 153))); // NOI18N
jPanel5.add(jLabel11);
jLabel11.setBounds(0, 0, 1140, 150);
getContentPane().add(jPanel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(258, 0, 1145, 150));
ChangePassword.setBackground(new java.awt.Color(0, 0, 0));
ChangePassword.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 153, 51), 3, true), "Change Password", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Lucida Grande", 1, 24), new java.awt.Color(0, 255, 255))); // NOI18N
ChangePassword.setForeground(new java.awt.Color(0, 255, 255));
ChangePassword.setPreferredSize(new java.awt.Dimension(6, 20));
jTextField2.setEditable(false);
jTextField2.setBackground(new java.awt.Color(0,0,0,0));
jTextField2.setFont(new java.awt.Font("Lucida Grande", 0, 18)); // NOI18N
jTextField2.setForeground(new java.awt.Color(51, 255, 102));
jTextField2.setText("Please Give us Account Number and Password");
jTextField2.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
jTextField2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField2ActionPerformed(evt);
}
});
jButton3.setBackground(new java.awt.Color(0, 153, 153));
jButton3.setForeground(new java.awt.Color(0, 204, 204));
jButton4.setBackground(new java.awt.Color(102, 255, 0));
jButton4.setForeground(new java.awt.Color(0, 204, 51));
jLabel2.setBackground(new java.awt.Color(0, 0, 0));
jLabel2.setForeground(new java.awt.Color(255, 255, 255));
jLabel2.setText("Account Number");
jLabel3.setBackground(new java.awt.Color(0, 0, 0));
jLabel3.setForeground(new java.awt.Color(255, 255, 255));
jLabel3.setText("Name");
jLabel4.setBackground(new java.awt.Color(0, 0, 0));
jLabel4.setForeground(new java.awt.Color(255, 255, 255));
jLabel4.setText("Password");
jTextField3.setBackground(new java.awt.Color(0, 0, 0));
jTextField3.setFont(new java.awt.Font("Lucida Grande", 1, 15)); // NOI18N
jTextField3.setForeground(new java.awt.Color(255, 255, 255));
jTextField3.setHorizontalAlignment(javax.swing.JTextField.CENTER);
jTextField3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204)));
jTextField1.setEditable(false);
jTextField1.setBackground(new java.awt.Color(0, 0, 0));
jTextField1.setFont(new java.awt.Font("Lucida Grande", 1, 15)); // NOI18N
jTextField1.setForeground(new java.awt.Color(255, 255, 255));
jTextField1.setHorizontalAlignment(javax.swing.JTextField.CENTER);
jTextField1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204)));
jTextField1.setPreferredSize(new java.awt.Dimension(6, 20));
jLabel5.setBackground(new java.awt.Color(0, 0, 0));
jLabel5.setForeground(new java.awt.Color(255, 255, 255));
jLabel5.setText("NID");
jLabel5.setPreferredSize(new java.awt.Dimension(36, 16));
jTextField6.setEditable(false);
jTextField6.setBackground(new java.awt.Color(0, 0, 0));
jTextField6.setFont(new java.awt.Font("Lucida Grande", 1, 15)); // NOI18N
jTextField6.setForeground(new java.awt.Color(255, 255, 255));
jTextField6.setHorizontalAlignment(javax.swing.JTextField.CENTER);
jTextField6.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204)));
jButton1.setBackground(new java.awt.Color(0, 0, 0));
jButton1.setForeground(new java.awt.Color(0, 255, 255));
jButton1.setText("Back");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setBackground(new java.awt.Color(0, 0, 0));
jButton2.setForeground(new java.awt.Color(0, 255, 255));
jButton2.setText("Clear");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
savec.setBackground(new java.awt.Color(0, 0, 0));
savec.setForeground(new java.awt.Color(0, 255, 255));
savec.setText("Change Password");
savec.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
savecActionPerformed(evt);
}
});
savec1.setBackground(new java.awt.Color(0, 0, 0));
savec1.setForeground(new java.awt.Color(0, 255, 255));
savec1.setText("Find");
savec1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
savec1ActionPerformed(evt);
}
});
jLabel6.setBackground(new java.awt.Color(0, 0, 0));
jLabel6.setForeground(new java.awt.Color(255, 255, 255));
jLabel6.setText("New Password");
jLabel6.setPreferredSize(new java.awt.Dimension(36, 16));
jTextField5.setBackground(new java.awt.Color(0, 0, 0));
jTextField5.setFont(new java.awt.Font("Lucida Grande", 1, 15)); // NOI18N
jTextField5.setForeground(new java.awt.Color(255, 255, 255));
jTextField5.setHorizontalAlignment(javax.swing.JTextField.CENTER);
jTextField5.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204)));
jTextField7.setBackground(new java.awt.Color(0, 0, 0));
jTextField7.setFont(new java.awt.Font("Lucida Grande", 1, 15)); // NOI18N
jTextField7.setForeground(new java.awt.Color(255, 255, 255));
jTextField7.setHorizontalAlignment(javax.swing.JTextField.CENTER);
jTextField7.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204)));
jLabel7.setBackground(new java.awt.Color(0, 0, 0));
jLabel7.setForeground(new java.awt.Color(255, 255, 255));
jLabel7.setText("Retype Password");
jLabel7.setPreferredSize(new java.awt.Dimension(36, 16));
jTextField8.setEditable(false);
jTextField8.setBackground(new java.awt.Color(0,0,0,0)
);
jTextField8.setFont(new java.awt.Font("Lucida Grande", 1, 15)); // NOI18N
jTextField8.setForeground(new java.awt.Color(255, 255, 255));
jTextField8.setHorizontalAlignment(javax.swing.JTextField.CENTER);
jTextField8.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
jTextField8.setPreferredSize(new java.awt.Dimension(6, 20));
jTextField8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField8ActionPerformed(evt);
}
});
jTextField9.setEditable(false);
jTextField9.setBackground(new java.awt.Color(0,0,0,0)
);
jTextField9.setFont(new java.awt.Font("Lucida Grande", 1, 15)); // NOI18N
jTextField9.setForeground(new java.awt.Color(255, 255, 255));
jTextField9.setHorizontalAlignment(javax.swing.JTextField.CENTER);
jTextField9.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
jTextField9.setPreferredSize(new java.awt.Dimension(6, 20));
jPasswordField1.setBackground(new java.awt.Color(0, 0, 0));
jPasswordField1.setFont(new java.awt.Font("Lucida Grande", 1, 18)); // NOI18N
jPasswordField1.setForeground(new java.awt.Color(255, 255, 255));
jPasswordField1.setHorizontalAlignment(javax.swing.JTextField.CENTER);
jPasswordField1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204)));
javax.swing.GroupLayout ChangePasswordLayout = new javax.swing.GroupLayout(ChangePassword);
ChangePassword.setLayout(ChangePasswordLayout);
ChangePasswordLayout.setHorizontalGroup(
ChangePasswordLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(ChangePasswordLayout.createSequentialGroup()
.addGroup(ChangePasswordLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(ChangePasswordLayout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addGroup(ChangePasswordLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(ChangePasswordLayout.createSequentialGroup()
.addGap(121, 121, 121)
.addGroup(ChangePasswordLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(40, 40, 40)
.addGroup(ChangePasswordLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(savec1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(ChangePasswordLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(ChangePasswordLayout.createSequentialGroup()
.addGroup(ChangePasswordLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(ChangePasswordLayout.createSequentialGroup()
.addGroup(ChangePasswordLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, 117, Short.MAX_VALUE)
.addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addGroup(ChangePasswordLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTextField7, javax.swing.GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE)
.addComponent(jTextField5)))
.addGroup(ChangePasswordLayout.createSequentialGroup()
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(199, 199, 199)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(205, 205, 205)
.addComponent(savec, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(ChangePasswordLayout.createSequentialGroup()
.addGroup(ChangePasswordLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTextField3)
.addComponent(jPasswordField1, javax.swing.GroupLayout.DEFAULT_SIZE, 201, Short.MAX_VALUE))
.addGap(130, 130, 130)
.addGroup(ChangePasswordLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(49, 49, 49)
.addGroup(ChangePasswordLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField8, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField9, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE))))))
.addGroup(ChangePasswordLayout.createSequentialGroup()
.addGap(53, 53, 53)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 421, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, ChangePasswordLayout.createSequentialGroup()
.addGap(121, 121, 121)
.addGroup(ChangePasswordLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addGap(104, 104, 104))
);
ChangePasswordLayout.setVerticalGroup(
ChangePasswordLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(ChangePasswordLayout.createSequentialGroup()
.addGap(17, 17, 17)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(40, 40, 40)
.addGroup(ChangePasswordLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(ChangePasswordLayout.createSequentialGroup()
.addGap(4, 4, 4)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(ChangePasswordLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addGroup(ChangePasswordLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(ChangePasswordLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addComponent(savec1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 1, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(41, 41, 41)
.addGroup(ChangePasswordLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField8, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(ChangePasswordLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField7, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField9, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(112, 112, 112)
.addGroup(ChangePasswordLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2)
.addComponent(savec))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 44, Short.MAX_VALUE)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 1, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(38, 38, 38))
);
getContentPane().add(ChangePassword, new org.netbeans.lib.awtextra.AbsoluteConstraints(260, 150, 1140, 630));
jMenuBar1.setBackground(new java.awt.Color(51, 51, 51));
jMenuBar1.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
jMenuBar1.setForeground(new java.awt.Color(204, 204, 204));
jMenu1.setBackground(new java.awt.Color(0,0,0,0));
jMenu1.setText(" Menu ");
jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem1.setBackground(javax.swing.UIManager.getDefaults().getColor("CheckBox.background"));
jMenuItem1.setText(" Create Account");
jMenuItem1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 1, true));
jMenuItem1.setPreferredSize(new java.awt.Dimension(180, 18));
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem1);
jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_W, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem2.setBackground(javax.swing.UIManager.getDefaults().getColor("CheckBox.background"));
jMenuItem2.setText(" WithDraw");
jMenuItem2.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 1, true));
jMenuItem2.setPreferredSize(new java.awt.Dimension(180, 18));
jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem2ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem2);
jMenuItem3.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_D, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem3.setBackground(javax.swing.UIManager.getDefaults().getColor("CheckBox.background"));
jMenuItem3.setText(" Diposite");
jMenuItem3.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 1, true));
jMenuItem3.setPreferredSize(new java.awt.Dimension(180, 18));
jMenu1.add(jMenuItem3);
jMenuItem4.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_B, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem4.setBackground(javax.swing.UIManager.getDefaults().getColor("CheckBox.background"));
jMenuItem4.setText(" Balance");
jMenuItem4.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 1, true));
jMenuItem4.setPreferredSize(new java.awt.Dimension(180, 18));
jMenuItem4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem4ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem4);
jMenuItem5.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_T, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem5.setBackground(javax.swing.UIManager.getDefaults().getColor("CheckBox.background"));
jMenuItem5.setText(" Transfer Money");
jMenuItem5.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 1, true));
jMenuItem5.setPreferredSize(new java.awt.Dimension(180, 18));
jMenuItem5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem5ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem5);
jMenuItem7.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_T, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem7.setBackground(javax.swing.UIManager.getDefaults().getColor("CheckBox.background"));
jMenuItem7.setText(" Home");
jMenuItem7.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 1, true));
jMenuItem7.setPreferredSize(new java.awt.Dimension(180, 18));
jMenuItem7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem7ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem7);
jMenuItem8.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem8.setBackground(javax.swing.UIManager.getDefaults().getColor("CheckBox.background"));
jMenuItem8.setText(" Profile");
jMenuItem8.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 1, true));
jMenuItem8.setPreferredSize(new java.awt.Dimension(180, 18));
jMenuItem8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem8ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem8);
jMenuItem18.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_R, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem18.setBackground(javax.swing.UIManager.getDefaults().getColor("CheckBox.background"));
jMenuItem18.setText(" Delete Account");
jMenuItem18.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 1, true));
jMenuItem18.setPreferredSize(new java.awt.Dimension(180, 18));
jMenuItem18.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem18ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem18);
jMenuItem9.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_TAB, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem9.setBackground(javax.swing.UIManager.getDefaults().getColor("CheckBox.background"));
jMenuItem9.setText(" About Me");
jMenuItem9.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 1, true));
jMenuItem9.setPreferredSize(new java.awt.Dimension(180, 18));
jMenuItem9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem9ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem9);
jMenuItem11.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE, java.awt.event.InputEvent.META_MASK));
jMenuItem11.setBackground(javax.swing.UIManager.getDefaults().getColor("CheckBox.background"));
jMenuItem11.setText(" Help");
jMenuItem11.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 1, true));
jMenuItem11.setPreferredSize(new java.awt.Dimension(180, 18));
jMenuItem11.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem11ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem11);
jMenuItem10.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE, java.awt.event.InputEvent.META_MASK));
jMenuItem10.setBackground(javax.swing.UIManager.getDefaults().getColor("CheckBox.background"));
jMenuItem10.setText(" Exit");
jMenuItem10.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 1, true));
jMenuItem10.setPreferredSize(new java.awt.Dimension(180, 18));
jMenuItem10.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem10ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem10);
jMenuBar1.add(jMenu1);
setJMenuBar(jMenuBar1);
setBounds(0, 0, 1400, 827);
}// </editor-fold>//GEN-END:initComponents
private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField2ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField2ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
jTextField1.setText("");
jTextField3.setText("");
jPasswordField1.setText("");
jTextField5.setText("");
jTextField6.setText("");
jTextField7.setText("");
jTextField8.setText("");
jTextField9.setText("");
}//GEN-LAST:event_jButton2ActionPerformed
private void savec1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_savec1ActionPerformed
String sql = "select * from Account where ID=? and PIN=?";
try{
pst=conn.prepareStatement(sql);
pst.setString(1, jTextField3.getText());
pst.setString(2, jPasswordField1.getText());
rs = pst.executeQuery();
if(rs.next()){
String add1 = rs.getString("Name");
jTextField1.setText(add1);
String add3 = rs.getString("NID");
jTextField6.setText(add3);
pst.close();
rs.close();
}else{
JOptionPane.showMessageDialog(null, "Enter Registerd ID");
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Have some Problem");
}finally{
try{
rs.close();
pst.close();
}catch(Exception e){
}
}
// TODO add your handling code here:
}//GEN-LAST:event_savec1ActionPerformed
private void savecActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_savecActionPerformed
// TODO add your handling code here:
try{
String value1=jTextField5.getText();//new password
String value2=jTextField7.getText();//retype password
String value3=jTextField3.getText();//account no
int NewPassword = Integer.parseInt(value1);
int RetypePassword = Integer.parseInt(value1);
if( (NewPassword == RetypePassword) == true ){//compare password and retype password and assign Int to String
String Password = String.valueOf(RetypePassword);
String sql = "update Account set PIN ='"+Password+"' where ID = '"+value3+"'";
pst = conn.prepareStatement(sql);
pst.execute();
jTextField8.setText("Password Seccessfully Changed");
jTextField9.setText("Your new Password is : "+Password);
pst.close();
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null , e);
}
}//GEN-LAST:event_savecActionPerformed
private void jTextField8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField8ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField8ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
BankMenu ob =new BankMenu();
setVisible(false);
ob.setVisible(true);
}//GEN-LAST:event_jButton1ActionPerformed
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
// TODO add your handling code here:
AccountResister ob = new AccountResister();
setVisible(false);
ob.setVisible(true);
}//GEN-LAST:event_jMenuItem1ActionPerformed
private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
// TODO add your handling code here:
WithDraw ob = new WithDraw();
setVisible(false);
ob.setVisible(true);
}//GEN-LAST:event_jMenuItem2ActionPerformed
private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed
// TODO add your handling code here:
Balance ob = new Balance();
setVisible(false);
ob.setVisible(true);
}//GEN-LAST:event_jMenuItem4ActionPerformed
private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem5ActionPerformed
// TODO add your handling code here:
TransferMoney ob = new TransferMoney();
setVisible(false);
ob.setVisible(true);
}//GEN-LAST:event_jMenuItem5ActionPerformed
private void jMenuItem7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem7ActionPerformed
// TODO add your handling code here:
Home ob = new Home();
setVisible(false);
ob.setVisible(true);
}//GEN-LAST:event_jMenuItem7ActionPerformed
private void jMenuItem8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem8ActionPerformed
// TODO add your handling code here:
Profile ob = new Profile();
setVisible(false);
ob.setVisible(true);
}//GEN-LAST:event_jMenuItem8ActionPerformed
private void jMenuItem9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem9ActionPerformed
// TODO add your handling code here:
AboutMe ob = new AboutMe();
setVisible(false);
ob.setVisible(true);
}//GEN-LAST:event_jMenuItem9ActionPerformed
private void jMenuItem10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem10ActionPerformed
// TODO add your handling code here:
System.exit(0);
}//GEN-LAST:event_jMenuItem10ActionPerformed
private void jMenuItem18ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem18ActionPerformed
// TODO add your handling code here:
DeleteAccount ob = new DeleteAccount();
setVisible(false);
ob.setVisible(true);
}//GEN-LAST:event_jMenuItem18ActionPerformed
private void jMenuItem11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem11ActionPerformed
// TODO add your handling code here:
Help obh1 = new Help();
setVisible(false);
obh1.setVisible(true);
}//GEN-LAST:event_jMenuItem11ActionPerformed
/**
* @param args the command line arguments
*/
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel ChangePassword;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem10;
private javax.swing.JMenuItem jMenuItem11;
private javax.swing.JMenuItem jMenuItem18;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JMenuItem jMenuItem3;
private javax.swing.JMenuItem jMenuItem4;
private javax.swing.JMenuItem jMenuItem5;
private javax.swing.JMenuItem jMenuItem7;
private javax.swing.JMenuItem jMenuItem8;
private javax.swing.JMenuItem jMenuItem9;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPasswordField jPasswordField1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField10;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
private javax.swing.JTextField jTextField5;
private javax.swing.JTextField jTextField6;
private javax.swing.JTextField jTextField7;
private javax.swing.JTextField jTextField8;
private javax.swing.JTextField jTextField9;
private javax.swing.JButton savec;
private javax.swing.JButton savec1;
// End of variables declaration//GEN-END:variables
}
|
package com.outofmemory.entertainment.dissemination.engine;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
public class CollisionDetector {
private final GameObjectRegistry gameObjectRegistry;
private final Canvas canvas;
public CollisionDetector(GameObjectRegistry gameObjectRegistry, Canvas canvas) {
this.gameObjectRegistry = gameObjectRegistry;
this.canvas = canvas;
}
public Collection<Collision> detectCollisions() {
ArrayList<Collision> collisions = new ArrayList<Collision>();
List<GameObject> gameObjects = gameObjectRegistry.getObjects();
for (int i = 0; i < gameObjects.size(); i++) {
GameObject left = gameObjects.get(i);
if (!left.getBody().isCollisionObject || !left.getBody().isCollisionSubject) {
continue;
}
Collider leftCollider = buildCollider(left);
for (GameObject right : gameObjects) {
if (left == right || !right.getBody().isCollisionObject) {
continue;
}
Collider rightCollider = buildCollider(right);
if (leftCollider.intersects(rightCollider)) {
collisions.add(new Collision(left, right));
}
}
}
return collisions;
}
public Collider buildCollider(GameObject gameObject) {
HashSet<Integer> offsets = new HashSet<Integer>();
Position position = gameObject.getPosition();
Frame frame = gameObject.getAnimation().current();
for (int i = 0; i < frame.getSize().getHeight(); i++) {
String frameRow = frame.getRow(i);
for (int j = 0; j < frameRow.length(); j++) {
int x = position.getX() + j;
int y = position.getY() + i;
if (frameRow.charAt(j) != ' ' && x < canvas.getSize().getWidth()) {
int offset = (y * canvas.getSize().getWidth()) + x;
offsets.add(offset);
}
}
}
return new Collider(offsets);
}
}
|
/*
* *********************************************************
* Copyright (c) 2019 @alxgcrz All rights reserved.
* This code is licensed under the MIT license.
* Images, graphics, audio and the rest of the assets be
* outside this license and are copyrighted.
* *********************************************************
*/
package com.codessus.ecnaris.ambar.fragments;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.codessus.ecnaris.ambar.R;
import com.codessus.ecnaris.ambar.activities.MainActivity;
import com.codessus.ecnaris.ambar.helpers.AmbarManager;
import com.codessus.ecnaris.ambar.models.personaje.Personaje;
import com.codessus.ecnaris.ambar.models.personaje.Talento;
import java.util.HashMap;
import java.util.List;
import butterknife.BindView;
import butterknife.BindViews;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import static com.codessus.ecnaris.ambar.helpers.AmbarManager.MODE_CREATE;
import static com.codessus.ecnaris.ambar.helpers.AmbarManager.MODE_READ;
/**
* Talentos del persoanje
*/
public class TalentosFragment extends Fragment {
private static final String ARG_MODE = "mode";
// Navigation (Oculta por defecto)
@BindView(R.id.include_navigation_next)
ImageButton nextImageButton;
@BindView(R.id.include_navigation_back)
ImageButton backImageButton;
@BindView(R.id.include_navigation_cancel)
ImageButton cancelImageButton;
@BindViews({R.id.fragment_talentos_img_1,
R.id.fragment_talentos_img_2,
R.id.fragment_talentos_img_3,
R.id.fragment_talentos_img_4,
R.id.fragment_talentos_img_5,
R.id.fragment_talentos_img_6,
R.id.fragment_talentos_img_7,
R.id.fragment_talentos_img_8})
List<ImageView> runas;
@BindViews({R.id.fragment_talentos_img_grado_1,
R.id.fragment_talentos_img_grado_2,
R.id.fragment_talentos_img_grado_3,
R.id.fragment_talentos_img_grado_4,
R.id.fragment_talentos_img_grado_5,
R.id.fragment_talentos_img_grado_6,
R.id.fragment_talentos_img_grado_7,
R.id.fragment_talentos_img_grado_8})
List<ImageView> grados;
@BindViews({R.id.fragment_talentos_textView_1,
R.id.fragment_talentos_textView_2,
R.id.fragment_talentos_textView_3,
R.id.fragment_talentos_textView_4,
R.id.fragment_talentos_textView_5,
R.id.fragment_talentos_textView_6,
R.id.fragment_talentos_textView_7,
R.id.fragment_talentos_textView_8})
List<TextView> names;
@BindViews({R.id.fragment_talentos_layout_1,
R.id.fragment_talentos_layout_2,
R.id.fragment_talentos_layout_3,
R.id.fragment_talentos_layout_4,
R.id.fragment_talentos_layout_5,
R.id.fragment_talentos_layout_6,
R.id.fragment_talentos_layout_7,
R.id.fragment_talentos_layout_8})
List<RelativeLayout> layout;
// Puntos restantes
@BindView(R.id.fragment_talentos_textView_points)
TextView pointsTextView;
@BindView(R.id.fragment_talentos_textView_points_value)
TextView pointsValueTextView;
// Binder
private Unbinder unbinder;
// Personaje
private Personaje personaje;
// MODE (creación, edición, etc..)
private int mode;
// Talentos seleccionados
private HashMap<Integer, GridTalentElement> talentos;
// Puntos de talento disponibles
private int points;
// --- CONSTRUCTOR --- //
public TalentosFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param mode Parameter 1.
* @return A new instance of fragment AtributosFragment.
*/
public static TalentosFragment newInstance(int mode) {
TalentosFragment fragment = new TalentosFragment();
Bundle args = new Bundle();
args.putInt(ARG_MODE, mode);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if ( getArguments() != null ) {
mode = getArguments().getInt(ARG_MODE);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_talentos, container, false);
// Inyectar las Views
unbinder = ButterKnife.bind(this, rootView);
// Recuperar personaje
personaje = AmbarManager.instance().getPersonaje();
// Inicializar el HashMap que contendrá los talentos seleccionados
talentos = new HashMap<>();
// Puntos disponibles
points = personaje.getGradosxEscoger();
// Rellenar las casillas con el icono de la runa, el nombre del talento y los grados disponibles
int i = 0;
for ( Talento talento : personaje.getClase().getTalentos() ) {
runas.get(i).setImageDrawable(talento.getRune(getActivity().getBaseContext()));
names.get(i).setText(talento.getName());
grados.get(i).setImageDrawable(talento.getRuneGrados());
// Guardamos en un HashMap el ID del layout como clave y un GridElementTalent
talentos.put(layout.get(i).getId(), new GridTalentElement(talento, false, grados.get(i), i % 2 == 0));
i++;
}
if ( mode == MODE_READ ) {
// En modo lectura no se muestra el textView con el valor de los puntos disponibles
pointsValueTextView.setVisibility(View.INVISIBLE);
pointsTextView.setVisibility(View.INVISIBLE);
// Mostrar el botón 'NEXT' y el botón 'CANCEL'
nextImageButton.setVisibility(View.VISIBLE);
cancelImageButton.setVisibility(View.VISIBLE);
backImageButton.setVisibility(View.VISIBLE);
} else if ( points > 0 ) {
// Actualizar y mostrar el número de puntos disponibles
pointsValueTextView.setText(String.valueOf(points));
}
return rootView;
}
/**
* Gestiona la pulsación de un talento
*
* @param button clicked
*/
@OnClick({R.id.fragment_talentos_layout_1, R.id.fragment_talentos_layout_2, R.id.fragment_talentos_layout_3,
R.id.fragment_talentos_layout_4, R.id.fragment_talentos_layout_5, R.id.fragment_talentos_layout_6,
R.id.fragment_talentos_layout_7, R.id.fragment_talentos_layout_8})
public void selectGrade(View button) {
if ( mode != MODE_READ ) {
// Elemento seleccionado
GridTalentElement elem = talentos.get(button.getId());
/* Si el elemento no está selecciondo y aún dispone de puntos por gastar, se selecciona el elemnto y se resta el punto */
if ( !elem.selected && points > 0 ) {
if ( talentos.get(button.getId()).talento.getGrado() < 3 ) {
// Animacion para seleccionar un punto
button.animate().translationX(elem.par ? -60f : 60f).setDuration(300).start();
// Disminuir un punto
points--;
// Actualizar el estado del talento
talentos.get(button.getId()).selected = true;
// Actualizar los grados aumentando en 1
talentos.get(button.getId()).talento.aumentarGrado();
}
} else if ( elem.selected ) {
// Animación para deseleccionar un talento
button.animate().translationX(0f).setDuration(300).start();
// Aumentamos un punto
points++;
// Actualizar el estado del talento
talentos.get(button.getId()).selected = false;
// Actualizar los grados disminuyendo en 1
talentos.get(button.getId()).talento.disminuirGrado();
}
// Actualizar los grados
((ImageView) talentos.get(button.getId()).grados).setImageDrawable(talentos.get(button.getId()).talento.getRuneGrados());
// Actualizar la etiqueta de info
pointsValueTextView.setText(String.valueOf(points));
// Actualizar el botón 'SIGUIENTE'
if ( points == 0 ) {
nextImageButton.setVisibility(View.VISIBLE);
} else {
nextImageButton.setVisibility(View.INVISIBLE);
}
}
}
/**
* Método que se ejecuta al pulsar en el botón 'NEXT'
*
* @param button pulsado
*/
@OnClick(R.id.include_navigation_next)
public void nextFragment(View button) {
// Según el modo, el botón NEXT actua de determinada forma
if ( mode == MODE_READ ) {
// En modo READ cargamos la pantalla de lectura
((MainActivity) getActivity()).loadNextFragment(button, new LecturaFragment());
} else {
// Poner a 0 el número de grados disponibles
personaje.setGradosxEscoger(points);
// Guardar el personaje
AmbarManager.instance().setPersonaje(personaje);
if ( mode == MODE_CREATE ) {
// En modo CREATE se muestra un dialog para pedir la confirmación del usuario
CreacionPersonajeDialogFragment dialogFragment = new CreacionPersonajeDialogFragment();
dialogFragment.show(getFragmentManager(), "");
} else {
// En modo UPDATE cargamos la siguiente página
((MainActivity) getActivity()).loadNextFragment(button, AmbarManager.instance().getNextFragment(personaje));
}
}
}
public static class CreacionPersonajeDialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.creacion_character_dialog_title)
.setPositiveButton(R.string.creacion_character_dialog_button_aceptar, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
((MainActivity) getActivity()).loadNextFragment(null, new LecturaFragment());
}
})
.setNegativeButton(R.string.creacion_character_dialog_button_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
((MainActivity) getActivity()).loadNextFragment(null, new CharacterCreationFragment());
}
});
return builder.create();
}
}
/**
* Método que se ejecuta al pulsar en el botón 'BACK' y el botón 'CANCEL'
*
* @param button pulsado
*/
@OnClick({R.id.include_navigation_back, R.id.include_navigation_cancel})
public void navigation(View button) {
if ( button.getId() == R.id.include_navigation_cancel ) {
// Cargar la pantalla de lectura
((MainActivity) getActivity()).loadNextFragment(button, new LecturaFragment());
} else if ( button.getId() == R.id.include_navigation_back ) {
// Cargar la pantalla de aptitudes indicando el modo en que estamos
((MainActivity) getActivity()).loadNextFragment(button, AptitudesFragment.newInstance(mode));
}
}
/**
* El usuario da su visto bueno al personaje creado.
* Cargamos la pantalla de lectura ya que el personaje ya fue guardado
*/
public void onAcceptedCharacterClickListener() {
((MainActivity) getActivity()).loadNextFragment(null, new LecturaFragment());
}
/**
* El usuario quiere reiniciar el proceso.
* Volvemos a la pantalla de creación de personaje
*/
public void onRestartCharacterCreationClickListener() {
((MainActivity) getActivity()).loadNextFragment(null, new CharacterCreationFragment());
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
/**
* Elemento de la Grid de talentos. Representa un talento, un booleano que nos indicará si el
* usuario ha seleccionado ese talento y una referencia al ImageView de las runas de los grados
* para seleccionar la runa correspondiente
*/
private class GridTalentElement {
// Talento
public Talento talento;
// Indicador de selección
public boolean selected;
public View grados;
public boolean par;
/* Constructor */
public GridTalentElement(Talento talento, boolean selected, View grados, boolean par) {
this.talento = talento;
this.selected = selected;
this.grados = grados;
this.par = par;
}
}
}
|
package cn.edu.zucc.music.service;
import cn.edu.zucc.music.model.DynamicComment;
import java.util.List;
public interface DynamicCommentService {
int addDynamicComment(DynamicComment comment);
int deleteDynamicComment(DynamicComment comment);
int updateDynamicComment(DynamicComment comment);
DynamicComment findById(int id);
List<DynamicComment> findAll();
}
|
package piefarmer.immunology.gui;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.bouncycastle.jcajce.provider.symmetric.Grain128;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.network.PacketDispatcher;
import cpw.mods.fml.relauncher.Side;
import piefarmer.immunology.common.Immunology;
import piefarmer.immunology.disease.Disease;
import piefarmer.immunology.disease.DiseaseEffect;
import piefarmer.immunology.item.ItemMedicalBook;
import piefarmer.immunology.item.Items;
import piefarmer.immunology.network.packet.Packet6Cure;
import piefarmer.immunology.tileentity.TileEntityMedicalResearchTable;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.inventory.Container;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
import net.minecraft.client.gui.*;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
public class GuiMedicalResearchTable extends GuiContainer{
int posX = 0;
int posY = 0;
int currentPage = 1;
int maxPages = 99;
private EntityPlayer entityplayer;
private TileEntityMedicalResearchTable tile;
private ContainerMedicalResearchTable container;
float count;
float count2;
float count3;
float count4;
int counter = 0;
int cureid = 1;
public static final ResourceLocation RESOURCE_GUI_BG = new ResourceLocation("immunology:textures/gui/MedicalResearchTableGUI.png");
public static final ResourceLocation RESOURCE_GUI_FG = new ResourceLocation("immunology:textures/gui/DiagnosticTableGUI.png");
private static TextureManager textureManager;
public GuiMedicalResearchTable(InventoryPlayer player, TileEntityMedicalResearchTable tileentity)
{
super(new ContainerMedicalResearchTable(player, tileentity));
this.container = (ContainerMedicalResearchTable)this.inventorySlots;
entityplayer = player.player;
this.ySize = 220;
tile = tileentity;
textureManager = Minecraft.getMinecraft().func_110434_K();
}
@Override
public void initGui()
{
super.initGui();
posX = (this.width - this.xSize) / 2;
posY = (this.height - this.ySize) / 2;
this.buttonList.add(new GuiButtonNextDisease(0, posX + 150, posY + 70, true));
this.buttonList.add(new GuiButtonNextDisease(1, posX + 88, posY + 70, false));
}
protected void drawGuiContainerForegroundLayer(int par1, int par2)
{
super.drawGuiContainerForegroundLayer(par1, par2);
this.fontRenderer.drawString(StatCollector.translateToLocal("container.medicalresearchtable"), 9, 5, 4210752);
for(int i = 0; i < 4; i++)
{
if(this.isPointInRegion(14 + (i * 18), 25, 10, 22, par1, par2))
{
String cure = "Cure";
if(tile.getItemStack(i) != null && tile.getItemStack(i).hasDisplayName())
{
cure = tile.getItemStack(i).getDisplayName();
}
int time = 100 - tile.brewTime[i] / 10;
if(time == 100)
{
time = 0;
}
this.drawHoveringText(Arrays.asList(cure + " " + (i + 1) + " : " + time + "/100"), par1 - this.posX, par2 - this.posY, fontRenderer);
}
}
}
@Override
protected void drawGuiContainerBackgroundLayer(float var1, int var2,
int var3) {
this.drawDefaultBackground();
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
textureManager.func_110577_a(RESOURCE_GUI_BG);
drawTexturedModalRect(posX, posY, 0, 0, this.xSize, this.ySize);
this.drawpotioncolours();
this.drawbrewing();
textureManager.func_110577_a(RESOURCE_GUI_FG);
drawTexturedModalRect(posX + 85, posY + 80, 0, 139, 70, 33);
drawTexturedModalRect(posX + 85, posY + 113, 0, 211, 70, 14);
drawTexturedModalRect(posX + 155, posY + 113, 140, 211, 10, 14);
drawTexturedModalRect(posX + 155, posY + 80, 140, 139, 55, 33);
this.drawCenteredString(fontRenderer, currentPage + "/" + maxPages, posX + 125, posY + 70, 0xffffff);
GL11.glScalef(0.5F, 0.5F, 1F);
posX *= 2;
posY *= 2;
if(this.tile.itemstacks[12] != null && this.tile.itemstacks[12].getItem() instanceof ItemMedicalBook)
{
ItemStack is = this.tile.itemstacks[12];
ItemMedicalBook it = (ItemMedicalBook) is.getItem();
List dl = it.getDiseasePages(is);
List cl = it.getCurePages(is);
List sl = it.getSidePages(is);
fontRenderer.drawString("Total Known", posX + 259, posY + 52, 0x444444);
fontRenderer.drawString("Diseases: " + dl.size(), posX + 259, posY + 62, 0x444444);
fontRenderer.drawString("Total Found", posX + 259, posY + 76, 0x444444);
fontRenderer.drawString("Cures: " + cl.size(), posX + 259, posY + 86, 0x444444);
fontRenderer.drawString("Total Found", posX + 259, posY + 100, 0x444444);
fontRenderer.drawString("Modifiers: " + sl.size(), posX + 259, posY + 110, 0x444444);
this.maxPages = cl.size() + sl.size();
if(currentPage == 0 && sl.size() > 0 || currentPage == 0 && cl.size() > 0)
{
currentPage = 1;
}
if(this.currentPage > cl.size())
{
int id = (currentPage - cl.size()) - 1;
if(id > 0 || id >= 0 && sl.size() > 0)
{
fontRenderer.drawString(DiseaseEffect.diseaseEffects[(Integer) sl.get(id)].getName() + " Modifier", posX + 185, posY + 171, 0xaaaaaa);
List<ItemStack> l = MedicalResearchTableRecipes.brewing().getIngredients((Integer)sl.get(id) + 1, true);
if(l != null)
{
ItemStack is1 = new ItemStack(Items.cure, 1, cureid);
ItemStack is2 = l.get(1);
fontRenderer.drawString("- " + is1.stackSize + " x " + is1.getDisplayName(), posX + 185, posY + 187, 0xaaaaaa);
fontRenderer.drawString("- " + is2.stackSize + " x " + is2.getDisplayName(), posX + 185, posY + 203, 0xaaaaaa);
this.drawItemStack(is1, posX + 213, posY + 182);
this.drawItemStack(is2, posX + 213, posY + 198);
counter++;
if(counter == 500)
{
if(cureid == Disease.diseaseTypes.length)
{
cureid = 0;
}
this.cureid++;
counter = 0;
}
}
}
else
{
currentPage = 0;
}
}
else
{
if(currentPage == 0 && cl.size() > 0)
{
currentPage = 1;
}
List<ItemStack> l = MedicalResearchTableRecipes.brewing().getIngredients(currentPage, false);
if(l != null)
{
fontRenderer.drawString(Disease.diseaseTypes[currentPage - 1].getName() + " Cure", posX + 185, posY + 171, 0xaaaaaa);
ItemStack is1 = l.get(0);
ItemStack is2 = l.get(1);
fontRenderer.drawString("- " + is1.stackSize + " x " + is1.getDisplayName(), posX + 185, posY + 187, 0xaaaaaa);
fontRenderer.drawString("- " + is2.stackSize + " x " + is2.getDisplayName(), posX + 185, posY + 203, 0xaaaaaa);
this.drawItemStack(is1, posX + 213, posY + 182);
this.drawItemStack(is2, posX + 213, posY + 198);
}
}
}
posX /= 2;
posY /= 2;
GL11.glScalef(2F, 2F, 1F);
}
private void drawbrewing() {
if(tile.brewTime[0] > 0)
{
count += 0.3F;
int intcount = (int)count;
drawTexturedModalRect(posX + 11, posY + 94 - intcount, xSize + 1, 82 - intcount, 16, intcount);
if(intcount == 23)
{
count = 0;
}
}
if(tile.brewTime[1] > 0)
{
count2 += 0.3F;
int intcount2 = (int)count2;
drawTexturedModalRect(posX + 29, posY + 94 - intcount2, xSize + 19, 82 - intcount2, 16, intcount2);
if(intcount2 == 23)
{
count2 = 0;
}
}
if(tile.brewTime[2] > 0)
{
count3 += 0.3F;
int intcount3 = (int)count3;
drawTexturedModalRect(posX + 47, posY + 94 - intcount3, xSize + 37, 82 - intcount3, 16, intcount3);
if(intcount3 == 23)
{
count3 = 0;
}
}
if(tile.brewTime[3] > 0)
{
count4 += 0.3F;
int intcount4 = (int)count4;
drawTexturedModalRect(posX + 65, posY + 94 - intcount4, xSize + 55, 82 - intcount4, 16, intcount4);
if(intcount4 == 23)
{
count4 = 0;
}
}
}
public void actionPerformed(GuiButton button)
{
switch(button.id)
{
case 0:
if(this.currentPage + 1 <= this.maxPages)
this.currentPage++;
break;
case 1:
if(this.currentPage - 1 > 0)
{
this.currentPage--;
}
break;
}
}
public void drawpotioncolours()
{
for(int i = 0; i < 4; i++)
{
int potionsize = 22 - ((tile.brewTime[i] / 10) / 4);
if(potionsize > 21)
{
potionsize = 0;
}
GL11.glColor4f(tile.potioncolours[i][0], tile.potioncolours[i][1], tile.potioncolours[i][2], 0.3F);
drawTexturedModalRect(posX + 16 + (18 * i), posY + 25 + (22 - potionsize), xSize, 22 - potionsize, 6, potionsize);
drawTexturedModalRect(posX + 11 + (18 * i), posY + 50, xSize, 23, 16, 16);
drawTexturedModalRect(posX + 10 + (18 * i), posY + 70, xSize + 18, 0, 18, 58);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
drawTexturedModalRect(posX + 13 + (i * 18), posY + 25, xSize + 6, 0, 12, 23);
}
}
protected void mouseClicked(int par1, int par2, int par3)
{
super.mouseClicked(par1, par2, par3);
/*for(int i = 0; i < 4; i++)
{
if(this.isPointInRegion(14 + (i * 18), 25, 10, 22, par1, par2))
{
this.changeColour(i);
}
}*/
}
private void changeColour(int potion)
{
if(tile.potioncolours[potion][0] == 1F && tile.potioncolours[potion][1] == 1F && tile.potioncolours[potion][2] == 1F)
{
tile.potioncolours[potion][0] = 1.0F;
tile.potioncolours[potion][1] = 0.0F;
tile.potioncolours[potion][2] = 0.0F;
}
else if(tile.potioncolours[potion][0] == 1F)
{
tile.potioncolours[potion][0] = 0.0F;
tile.potioncolours[potion][1] = 1.0F;
tile.potioncolours[potion][2] = 0.0F;
}
else if(tile.potioncolours[potion][1] == 1F)
{
tile.potioncolours[potion][0] = 0.0F;
tile.potioncolours[potion][1] = 0.0F;
tile.potioncolours[potion][2] = 1.0F;
}
else if(tile.potioncolours[potion][2] == 1F)
{
tile.potioncolours[potion][0] = 1.0F;
tile.potioncolours[potion][1] = 1.0F;
tile.potioncolours[potion][2] = 1.0F;
}
}
private void drawItemStack(ItemStack par1ItemStack, int par2, int par3)
{
GL11.glTranslatef(0.0F, 0.0F, 32.0F);
this.zLevel = 200.0F;
itemRenderer.zLevel = 200.0F;
FontRenderer font = par1ItemStack.getItem().getFontRenderer(par1ItemStack);
if (font == null) font = fontRenderer;
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
GL11.glEnable(GL11.GL_COLOR_MATERIAL);
GL11.glEnable(GL11.GL_LIGHTING);
itemRenderer.renderItemAndEffectIntoGUI(font, this.mc.renderEngine, par1ItemStack, par2, par3);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDepthMask(true);
GL11.glEnable(GL11.GL_DEPTH_TEST);
this.zLevel = 0.0F;
itemRenderer.zLevel = 0.0F;
}
}
|
package com.zipcodewilmington.person;
import org.junit.Assert;
import org.junit.Test;
/**
* Created by leon on 2/12/18.
*/
public class TestPerson {
@Test
public void testDefaultConstructor() {
// Given
String expectedName = "";
Integer expectedAge = Integer.MAX_VALUE;
// When
Person person = new Person();
// Then
String actualName = person.getName();
Integer actualAge = person.getAge();
Assert.assertEquals(expectedName, actualName);
Assert.assertEquals(expectedAge, actualAge);
}
@Test
public void testConstructorWithName() {
// Given
String expected = "Leon";
// When
Person person = new Person(expected);
// Then
String actual = person.getName();
Assert.assertEquals(expected, actual);
}
@Test
public void testConstructorWithAge() {
// Given
Integer expected = 5;
// When
Person person = new Person(expected);
// Then
Integer actual = person.getAge();
Assert.assertEquals(expected, actual);
}
@Test
public void testConstructorWithNameAndAge() {
// Given
Integer expectedAge = 5;
String expectedName = "Leon";
// When
Person person = new Person(expectedName, expectedAge);
// Then
Integer actualAge = person.getAge();
String actualName = person.getName();
Assert.assertEquals(expectedAge, actualAge);
Assert.assertEquals(expectedName, actualName);
}
@Test
public void testSetName() {
// Given
Person person = new Person();
String expected = "Leon";
// When
person.setName(expected);
String actual = person.getName();
// Then
Assert.assertEquals(expected, actual);
}
@Test
public void testSetAge() {
// Given
Person person = new Person();
Integer expected = 5;
// When
person.setAge(expected);
// Then
Integer actual = person.getAge();
Assert.assertEquals(expected, actual);
}
@Test
public void testSetANDgetFirstInit(){
Person Person = new Person();
String name = "charlotte";
char expected = 'c';
Person.setFirstInit(name);
char actual = Person.getFirstInit();
Assert.assertEquals(expected, actual);
}
@Test
public void testSetANDgetLikesCoding(){
Person Person = new Person();
boolean preference = true;
boolean expected = preference;
Person.setLikesCoding(preference);
boolean actual = Person.getLikesCoding();
Assert.assertEquals(expected, actual);
}
@Test
public void testSetANDgetIsAlive(){
Person Person = new Person();
boolean state = true;
boolean expected = state;
Person.setIsAlive(state);
boolean actual = Person.getIsAlive();
Assert.assertEquals(expected, actual);
}
@Test
public void testSetANDgetHeight(){
Person Person = new Person();
double height = 6.02;
double expected = height;
Person.setHeight(height);
double actual = Person.getHeight();
Assert.assertEquals(expected, actual,actual);
}
@Test
public void testSetANDgetNationality(){
Person Person = new Person();
String nationality = "American";
String expected = nationality;
Person.setNationality(nationality);
String actual = Person.getNationality();
Assert.assertEquals(expected, actual);
}
}
|
package com.cxjd.nvwabao.adapter;
import android.app.ActivityOptions;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.transition.TransitionInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.cxjd.nvwabao.Activity.PeopleSendTestActivity;
import com.cxjd.nvwabao.R;
import tyrantgit.explosionfield.ExplosionField;
/**
* Created by 白 on 2018/3/29.
*/
public class PeopleSpecialAdapter extends AppCompatActivity implements View.OnClickListener {
private Intent mIntent;
private ImageView imageView;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.specialpeople_flower);
findViewById(R.id.tv_reveal).setOnClickListener(this);
initview();
mIntent = new Intent();
getWindow().setExitTransition(TransitionInflater.from(this).inflateTransition(R.transition.slide));
}
private void initview() {
imageView = (ImageView) findViewById(R.id.flower);
TextView textView = (TextView) findViewById(R.id.fragment_title);
textView.setText("(= ̄ω ̄=)");
com.cxjd.nvwabao.bean.ExplosionField explosionField = new com.cxjd.nvwabao.bean.ExplosionField(this);
explosionField.addListener(findViewById(R.id.root));
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.tv_reveal:
mIntent.setClass(this, PeopleSendTestActivity.class);
ActivityOptions transitionActivityOptions2 = ActivityOptions.makeSceneTransitionAnimation(PeopleSpecialAdapter.this, findViewById(R.id.img_reveal_share), "share");
//5.0以下兼容
//ActivityOptionsCompat activityOptionsCompat2 = ActivityOptionsCompat.makeSceneTransitionAnimation(MainActivity.this, findViewById(R.id.img_reveal_share), "share");
startActivity(mIntent, transitionActivityOptions2.toBundle());
break;
}
}
}
|
package com.quiz.projectWilayah.dto;
import lombok.Data;
@Data
public class DesaDto {
private Integer id;
private String desaCode;
private String desaName;
private String kecamatanCode;
private String kabupatenCode;
private String provinsiCode;
}
|
package com.tt.option.ad;
public enum c {
APP_BANNER("banner"),
APP_EXCITING_VIDEO("banner"),
APP_FEED("banner"),
APP_VIDEO_PATCH_AD_POST("banner"),
APP_VIDEO_PATCH_AD_PRE("banner"),
GAME_BANNER("banner"),
GAME_EXCITING_VIDEO("banner"),
GAME_INTERSTITIAL("banner");
private String a;
static {
APP_EXCITING_VIDEO = new c("APP_EXCITING_VIDEO", 2, "video");
APP_VIDEO_PATCH_AD_PRE = new c("APP_VIDEO_PATCH_AD_PRE", 3, "preRollAd");
APP_VIDEO_PATCH_AD_POST = new c("APP_VIDEO_PATCH_AD_POST", 4, "postRollAd");
GAME_BANNER = new c("GAME_BANNER", 5, "banner");
GAME_EXCITING_VIDEO = new c("GAME_EXCITING_VIDEO", 6, "video");
GAME_INTERSTITIAL = new c("GAME_INTERSTITIAL", 7, "interstitial");
b = new c[] { APP_BANNER, APP_FEED, APP_EXCITING_VIDEO, APP_VIDEO_PATCH_AD_PRE, APP_VIDEO_PATCH_AD_POST, GAME_BANNER, GAME_EXCITING_VIDEO, GAME_INTERSTITIAL };
}
c(String paramString1) {
this.a = paramString1;
}
public final String getStrType() {
return this.a;
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\option\ad\c.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package com.ys.service;
import org.springframework.stereotype.Service;
import java.util.Random;
/**
* Created by yushi on 2017/3/20.
*/
@Service
public class RunnableServiceImpl implements RunnableService, Runnable {
@Override
public void getthread() {
Thread t1 = new Thread(new ThreadServiceImpl(), "thread1");
Thread t2 = new Thread(new ThreadServiceImpl(), "thread2");
//多线程的正确方式
//t1.start();
//t2.start();
//run是主线程中进行调用,没有启动多线程
t1.run();
t2.run();
}
@Override
public void run() {
String tname = Thread.currentThread().getName();
System.out.println(tname + "被调用");
Random random = new Random();
for (int i = 0; i < 20; i++) {
try {
Thread.sleep(random.nextInt(10) * 500);
System.out.println(tname);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
|
package com.example.ahmed.octopusmart.RecyclerAdapter;
/**
* Created by sotra on 12/25/2017.
*/
public interface ChangePriceCallback {
void update();
}
|
public class Geometric extends AbstractSeries {
//instance variables
public int i = 1;
public double count = 0;
public int count2 =0;
//returns the next partial sum where it is the series like 1 + 1/2 + 1/4 + 1/8...
public double next() {
if(count2==0){ //the first time the method is called
count = count/Math.pow(2,i-1) + 1;
count2++;
i++;
return count;
}
else{ //anytime after the first time the method is called
count += count2/Math.pow(2,i-1);
i++;
}
return count;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package obstacles;
import data.Entity;
import data.GameData;
import data.World;
import entityparts.LifePart;
import entityparts.PositionPart;
import services.IEntityProcessingService;
import java.util.Random;
import org.openide.util.lookup.ServiceProvider;
import org.openide.util.lookup.ServiceProviders;
/**
*
* @author oskar
*/
@ServiceProviders(value = {
@ServiceProvider(service = IEntityProcessingService.class),})
public class ObstaclesControlSystem implements IEntityProcessingService{
@Override
public void process(GameData gameData, World world) {
for(Entity obstacle : world.getEntities(Obstacle.class)){
PositionPart positionPart = obstacle.getPart(PositionPart.class);
positionPart.process(gameData, obstacle);
LifePart part = obstacle.getPart(LifePart.class);
part.setLife(Integer.MAX_VALUE);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.