text stringlengths 10 2.72M |
|---|
package com.gamemoim.demo.main;
import com.gamemoim.demo.account.CurrentUser;
import com.gamemoim.demo.domain.Account;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.Objects;
@Controller
@Slf4j
public class MainController {
@GetMapping("/")
public String mainPage(@CurrentUser Account account, Model model) {
try{
if (!Objects.isNull(account)) {
model.addAttribute("account", account);
}
} catch (Exception e){
e.printStackTrace();
}
return "index";
}
@GetMapping("/login")
public String loginPage(){
return "login";
}
}
|
package com.jx.user.impl;
import com.alipay.sofa.runtime.api.annotation.SofaService;
import com.alipay.sofa.runtime.api.annotation.SofaServiceBinding;
import com.jx.user.mapper.UserMapper;
import com.jx.user.model.User;
import com.jx.user.service.UserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
@Service // 标记当前为服务层
// 将服务发布到注册中心进行统一管理
@SofaService(interfaceType = UserService.class,
uniqueId = "${service.unique.id}",
bindings = { @SofaServiceBinding(bindingType = "bolt") })
public class UserServiceImpl implements UserService {
@Resource
private UserMapper userMapper;
@Override
public int register(User user){
if(!exists(user.getUsername())){
return userMapper.register(user);
}
return 0;
}
@Override
public boolean exists(String username){
return userMapper.exists(username) > 0;
}
@Override
public User login(String username, String password) {
return userMapper.login(username, password);
}
@Override
public void updBalance(int id, BigDecimal price) {
userMapper.updBalance(id,price);
}
}
|
package com.hesoyam.pharmacy.appointment.service.impl;
import com.hesoyam.pharmacy.appointment.dto.CounselingIDDTO;
import com.hesoyam.pharmacy.appointment.events.OnCounselingReservationCompletedEvent;
import com.hesoyam.pharmacy.appointment.exceptions.CounselingNotFoundException;
import com.hesoyam.pharmacy.appointment.model.Appointment;
import com.hesoyam.pharmacy.appointment.model.AppointmentStatus;
import com.hesoyam.pharmacy.appointment.model.Counseling;
import com.hesoyam.pharmacy.appointment.repository.CounselingRepository;
import com.hesoyam.pharmacy.appointment.service.ICounselingService;
import com.hesoyam.pharmacy.user.exceptions.PatientNotFoundException;
import com.hesoyam.pharmacy.user.exceptions.UserPenalizedException;
import com.hesoyam.pharmacy.user.model.Patient;
import com.hesoyam.pharmacy.user.model.Pharmacist;
import com.hesoyam.pharmacy.user.model.User;
import com.hesoyam.pharmacy.user.service.ILoyaltyAccountService;
import com.hesoyam.pharmacy.user.service.IPatientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class CounselingService implements ICounselingService {
@Autowired
private CounselingRepository counselingRepository;
@Autowired
private ApplicationEventPublisher applicationEventPublisher;
@Autowired
private ILoyaltyAccountService loyaltyAccountService;
@Autowired
private IPatientService patientService;
@Override
public Counseling updateCounselingAfterAppointment(long patientId, LocalDateTime from, String report, Pharmacist pharmacist)
throws CounselingNotFoundException{
Counseling counseling = counselingRepository
.findByPatient_IdAndDateTimeRange_FromAndPharmacist(patientId, from, pharmacist);
if(counseling != null) {
counseling.setReport(report);
counseling.setAppointmentStatus(AppointmentStatus.COMPLETED);
counselingRepository.save(counseling);
}
else {
throw new CounselingNotFoundException(patientId);
}
return counseling;
}
@Override
public List<Counseling> getAllCounselingsForPatientAndPharmacist(Patient patient, Pharmacist user) {
List<Counseling> allCounselings = counselingRepository.findAllByPatientAndPharmacist(patient, user);
allCounselings = filterByDate(allCounselings);
return allCounselings;
}
@Override
public Counseling cancelCounseling(Patient patient, LocalDateTime from, Pharmacist pharmacist) {
Counseling counseling = counselingRepository.findByPatient_IdAndDateTimeRange_FromAndPharmacist(patient.getId(),
from, pharmacist);
counseling.setAppointmentStatus(AppointmentStatus.ABSENT);
counselingRepository.save(counseling);
return counseling;
}
@Override
public List<Counseling> getAllFreeCounselings() {
List<Counseling> counselings = counselingRepository.findByAppointmentStatus(AppointmentStatus.FREE);
return getUpcomingCounselings(counselings);
}
@Override
public List<Counseling> getFreeCounselingsByPharmacyId(Long id) {
List<Counseling> counselings = counselingRepository.findByPharmacy_IdAndAppointmentStatus(id, AppointmentStatus.FREE);
return getUpcomingCounselings(counselings);
}
@Override
public List<Counseling> getUpcomingCounselingsByPatient(Long id) {
List<Counseling> counselings = counselingRepository.getAllByPatient_Id(id);
return getUpcomingCounselings(counselings);
}
@Override
public List<Counseling> getAllCompletedCounselingsByPatient(Long id) {
return counselingRepository.getAllByPatient_IdAndAppointmentStatus(id, AppointmentStatus.COMPLETED);
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
public Counseling findById(Long id) throws CounselingNotFoundException {
return counselingRepository.findById(id).orElseThrow(() ->new CounselingNotFoundException(id));
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
public Counseling update(Counseling counselingData) throws CounselingNotFoundException {
Counseling counseling = counselingRepository.findById(counselingData.getId()).orElseThrow(() -> new CounselingNotFoundException(counselingData.getId()));
counseling.update(counselingData);
counseling = counselingRepository.save(counseling);
return counseling;
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
public CounselingIDDTO reserve(CounselingIDDTO counselingIDDTO, User user) throws CounselingNotFoundException, PatientNotFoundException {
Counseling counseling = findById(counselingIDDTO.getId());
Patient patient = patientService.getById(user.getId());
if(patient.getPenaltyPoints() >= 3){
throw new UserPenalizedException(patient.getId());
}
if(!counseling.isTakeable()){
throw new IllegalArgumentException();
}
counseling.setAppointmentStatus(AppointmentStatus.TAKEN);
counseling.setPatient(patient);
counseling.update(counseling);
update(counseling);
applicationEventPublisher.publishEvent(new OnCounselingReservationCompletedEvent(user));
return counselingIDDTO;
}
private List<Counseling> filterByDate(List<Counseling> allCounselings) {
List<Counseling> filtered = new ArrayList<>();
for (Counseling counseling : allCounselings) {
if (counseling.getDateTimeRange().getFrom().isAfter(LocalDateTime.now())) {
filtered.add(counseling);
}
}
return filtered;
}
private List<Counseling> getUpcomingCounselings(List<Counseling> counselings){
return counselings.stream().filter(Appointment::isUpcoming).collect(Collectors.toList());
}
}
|
package com.shangcai.entity.common;
import java.util.Date;
import com.irille.core.repository.orm.Column;
import com.irille.core.repository.orm.ColumnBuilder;
import com.irille.core.repository.orm.ColumnFactory;
import com.irille.core.repository.orm.ColumnTemplate;
import com.irille.core.repository.orm.Entity;
import com.irille.core.repository.orm.IColumnField;
import com.irille.core.repository.orm.IColumnTemplate;
import com.irille.core.repository.orm.Table;
import com.irille.core.repository.orm.TableFactory;
public class Comment extends Entity {
public static final Table<Comment> table = TableFactory.entity(Comment.class).column(T.values()).create();
public enum T implements IColumnField {
PKEY(ColumnTemplate.PKEY),
WORKS(ColumnFactory.manyToOne(Works.class).showName("作品")),
REPLY_TO(ColumnFactory.manyToOne(Member.class).nullable(true).showName("被评论人")),
REPLY_TO_NAME(ColumnTemplate.STR.length(25).nullable(true).showName("被评论人名称").comment("被评论人名称 冗余字段")),
MEMBER(ColumnFactory.manyToOne(Member.class).showName("评论人")),
MEMBER_NAME(ColumnTemplate.STR.length(25).showName("评论人名称").comment("评论人名称 冗余字段")),
MEMBER_HEAD_PIC(ColumnTemplate.STR__200.nullable(true).showName("评论人头像").comment("评论人头像 冗余字段")),
CONTENTS(ColumnTemplate.STR__500.showName("评论内容")),
CREATED_TIME(ColumnTemplate.TIME.showName("评论时间")),
;
private Column column;
T(IColumnTemplate template) {
this.column = template.builder().create(this);
}
T(ColumnBuilder builder) {
this.column = builder.create(this);
}
@Override
public Column column() {
return column;
}
}
// >>>以下是自动产生的源代码行--源代码--请保留此行用于识别>>>
// 实例变量定义-----------------------------------------
private Integer pkey; // 主键 INT(11)
private Integer works; // 作品<表主键:Works> INT(11)
private Integer replyTo; // 被评论人<表主键:Member> INT(11)<null>
private String replyToName; // 被评论人名称 VARCHAR(25)<null>
private Integer member; // 评论人<表主键:Member> INT(11)
private String memberName; // 评论人名称 VARCHAR(25)
private String memberHeadPic; // 评论人头像 VARCHAR(200)<null>
private String contents; // 评论内容 VARCHAR(500)
private Date createdTime; // 评论时间 DATETIME(0)
@Override
public Comment init() {
super.init();
works = null; // 作品 INT(11)
replyTo = null; // 被评论人 INT(11)
replyToName = null; // 被评论人名称 VARCHAR(25)
member = null; // 评论人 INT(11)
memberName = null; // 评论人名称 VARCHAR(25)
memberHeadPic = null; // 评论人头像 VARCHAR(200)
contents = null; // 评论内容 VARCHAR(500)
createdTime = null; // 评论时间 DATETIME(0)
return this;
}
// 方法------------------------------------------------
public Integer getPkey() {
return pkey;
}
public void setPkey(Integer pkey) {
this.pkey = pkey;
}
public Integer getWorks() {
return works;
}
public void setWorks(Integer works) {
this.works = works;
}
public Works gtWorks() {
return selectFrom(Works.class, getWorks());
}
public void stWorks(Works works) {
this.works = works.getPkey();
}
public Integer getReplyTo() {
return replyTo;
}
public void setReplyTo(Integer replyTo) {
this.replyTo = replyTo;
}
public Member gtReplyTo() {
return selectFrom(Member.class, getReplyTo());
}
public void stReplyTo(Member replyTo) {
this.replyTo = replyTo.getPkey();
}
public String getReplyToName() {
return replyToName;
}
public void setReplyToName(String replyToName) {
this.replyToName = replyToName;
}
public Integer getMember() {
return member;
}
public void setMember(Integer member) {
this.member = member;
}
public Member gtMember() {
return selectFrom(Member.class, getMember());
}
public void stMember(Member member) {
this.member = member.getPkey();
}
public String getMemberName() {
return memberName;
}
public void setMemberName(String memberName) {
this.memberName = memberName;
}
public String getMemberHeadPic() {
return memberHeadPic;
}
public void setMemberHeadPic(String memberHeadPic) {
this.memberHeadPic = memberHeadPic;
}
public String getContents() {
return contents;
}
public void setContents(String contents) {
this.contents = contents;
}
public Date getCreatedTime() {
return createdTime;
}
public void setCreatedTime(Date createdTime) {
this.createdTime = createdTime;
}
// <<<以上是自动产生的源代码行--源代码--请保留此行用于识别<<<
}
|
package com.nuuedscore.domain;
import java.time.LocalDateTime;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.PrePersist;
import com.nuuedscore.refdata.RefBloom;
import com.nuuedscore.refdata.RefLearningPersonality;
import com.nuuedscore.refdata.RefScore;
import com.nuuedscore.refdata.RefSubject;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
/**
* Student Resource
* Any Learning Resource for a Student
*
* @author PATavares
* @since Feb 2021
*
*/
@Slf4j
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
@ToString
@Entity
public class StudentResource extends BaseDomain {
private static final long serialVersionUID = -6185731271053302664L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected Long id;
private String topic;
@Enumerated(EnumType.STRING)
private RefScore score;
@Enumerated(EnumType.STRING)
@Column(name = "learning_personality")
private RefLearningPersonality learningPersonality;
@Enumerated(EnumType.STRING)
private RefBloom bloom;
private String subject;
private String name;
private String description;
private String resource;
@Column(name = "created_on")
private LocalDateTime createdOn;
public StudentResource(String topic, String score, String learningPersonality, String bloom, String subject, String name, String description, String resource) {
this(topic, RefScore.get(score), RefLearningPersonality.get(learningPersonality), RefBloom.get(bloom), subject, name, description, resource);
}
public StudentResource(String topic, RefScore score, RefLearningPersonality learningPersonality, RefBloom bloom, String subject, String name, String description, String resource) {
this.topic = topic;
this.score = score;
this.learningPersonality = learningPersonality;
this.bloom = bloom;
this.subject = subject;
this.name = name;
this.description = description;
this.resource = resource;
}
/*
* LifeCycle
*/
@PrePersist
public void prePersist() {
log.info("prePersist...");
if (this.getLearningPersonality() == null) {
this.setLearningPersonality(RefLearningPersonality.TODO_LEARNING_PERSONALITY);
}
if (this.getBloom() == null) {
this.setBloom(RefBloom.TODO_BLOOM);
}
if (this.getSubject() == null) {
this.setSubject(RefSubject.TODO_SUBJECT.toString());
}
this.setCreatedOn(LocalDateTime.now());
}
} |
package br.net.pvp.model;
public class User {
public int id;
public String name;
public User() {
}
public User(final int id, final String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(final int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
}
|
package model;
import java.sql.Connection;
import java.sql.Statement;
import controller.database.DatabaseInterface;
public class SlotControl {
//prepare statement
private Statement sm=null;
private Connection ct=null;
private DatabaseInterface di=null;
/**
* @param name:String
* @param id:int
* @param beginning:Date
* @param duration:int
* @param type:String
* @return boolean:succes=>true;fail=>false
*/
public boolean delSlotById(int id) {
boolean b= false;
try {
di = DatabaseInterface.getInstance();
di.connect();
ct=di.getConnection();
sm=ct.createStatement();
int a=sm.executeUpdate("delete from Slot where id='"+id+"'");
if(a==1){
b=true;
}
} catch (Exception e) {
e.printStackTrace();
}finally{
di.disconnect();
}
return b;
}
public boolean addSlot(String name, DateUsed beginning, int duration, Person teacher,
String type) {
boolean b= false;
try {
di = DatabaseInterface.getInstance();
di.connect();
ct=di.getConnection();
sm=ct.createStatement();
int a=sm.executeUpdate("insert into Slot (name, beginning, duration, teacher_id, class_type)"
+ "values('"+name+"','\""+beginning+"\"','"+duration+"','\""+teacher.getId()+"\"','"+type+"')");
if(a==1){
b=true;
}
} catch (Exception e) {
e.printStackTrace();
}finally{
di.disconnect();
}
return b;
}
public boolean modifierSlot(int id, String name, DateUsed beginning,
int duration, Person teacher,String type) {
boolean b= false;
//il n'y pas de prof du nom ce que vous avez donné
if(teacher==null)return false;
else{
try {
di = DatabaseInterface.getInstance();
int teacher_id = di.getTeacherId(id);
di.disconnect();
di.connect();
ct=di.getConnection();
sm=ct.createStatement();
beginning.synchronizeDate();
long time = beginning.getDate().getTime();
String query = "update Slot set "
+ "name = '" + name + "', "
+ "beginning = " + time + ", "
+ "duration = " + duration + ", "
+ "teacher_id = " + teacher_id + ", "
+ "class_type = '" + type + "' "
+ " where id = " + id + ";";
System.out.println(query);
int a = sm.executeUpdate(query);
if(a==1){
b=true;
}
} catch (Exception e) {
e.printStackTrace();
}finally{
di.disconnect();
}
return b;
}
}
}
|
package com.example.windows10now.muathe24h.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.example.windows10now.muathe24h.R;
import com.example.windows10now.muathe24h.model.CardType;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import static com.example.windows10now.muathe24h.R.drawable.bg_home_network;
/**
* Created by Windows 10 Now on 11/14/2017.
*/
public class ChoseHomeNetWorkAdapter
extends RecyclerView.Adapter<ChoseHomeNetWorkAdapter.CardTypeViewHolder> {
private Context mContext;
private ArrayList<CardType> mCardTypes = new ArrayList<>();
private onHandleClick mOnHandleClick;
public ChoseHomeNetWorkAdapter(Context context, ArrayList<CardType> cardTypes) {
mContext = context;
mCardTypes = cardTypes;
}
@Override
public CardTypeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.item_card_type, parent, false);
return new CardTypeViewHolder(view);
}
@Override
public void onBindViewHolder(CardTypeViewHolder holder, final int position) {
CardType cardType = mCardTypes.get(position);
Picasso.with(mContext).load(cardType.getImgLogo()).fit().centerInside().into(holder.imgCardType);
holder.txtNameHomeNet.setText(cardType.getNameHomeNetWork());
if (cardType.isWatch()){
holder.llItemCardType.setBackgroundResource(bg_home_network);
}
holder.llItemCardType.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mOnHandleClick.onClickCardType(position);
notifyDataSetChanged();
}
});
}
@Override
public int getItemCount() {
return mCardTypes.size();
}
public void setOnHandleClick(onHandleClick onHandleClick) {
mOnHandleClick = onHandleClick;
}
public class CardTypeViewHolder extends RecyclerView.ViewHolder{
private ImageView imgCardType;
private TextView txtNameHomeNet;
private LinearLayout llItemCardType;
public CardTypeViewHolder(View itemView) {
super(itemView);
imgCardType = itemView.findViewById(R.id.img_cart_type);
txtNameHomeNet = itemView.findViewById(R.id.txt_home_net);
llItemCardType = itemView.findViewById(R.id.ll_item_card);
}
}
public interface onHandleClick{
void onClickCardType(int position);
}
}
|
package com.example.ryan.electronicstore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Button;
import android.widget.TextView;
import com.example.ryan.electronicstore.Common.Common;
import com.example.ryan.electronicstore.ViewHolder.OrderDetailAdapter;
public class OrderDetail extends AppCompatActivity {
TextView order_id,order_userName,order_total,order_expectedDelivery,order_comment;
Button update;
String order_id_value="";
RecyclerView lstProducts;
RecyclerView.LayoutManager layoutManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_detail);
order_id = (TextView) findViewById(R.id.order_id);
order_userName = (TextView) findViewById(R.id.order_userName);
order_total = (TextView) findViewById(R.id.order_total);
order_expectedDelivery = (TextView) findViewById(R.id.order_expectedDelivery);
order_comment = (TextView) findViewById(R.id.order_comment);
lstProducts = (RecyclerView) findViewById(R.id.lstProducts);
lstProducts.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
lstProducts.setLayoutManager(layoutManager);
if (getIntent() != null)
order_id_value = getIntent().getStringExtra("OrderId");
order_id.setText(order_id_value);
order_userName.setText(Common.currentUser.getUserName());
order_total.setText(Common.currentRequest.getTotal());
order_expectedDelivery.setText(Common.currentRequest.getRequestedDeliveryDate());
order_comment.setText(Common.currentRequest.getComment());
final OrderDetailAdapter adapter = new OrderDetailAdapter(Common.currentRequest.getProducts());
adapter.notifyDataSetChanged();
lstProducts.setAdapter(adapter);
}
}
|
package sos.services.utility;
import java.util.ArrayList;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import sos.pojo.dto.Branch;
import sos.pojo.dto.Bus;
import sos.pojo.dto.Driver;
import sos.pojo.dto.Journey;
import sos.pojo.dto.Passenger;
import sos.pojo.dto.Route;
import sos.pojo.dto.RouteStation;
import sos.pojo.dto.Station;
import sos.pojo.dto.Ticket;
import sos.pojo.dto.UserAdmin;
import sos.pojo.dto.UserEmployee;
import sos.services.DbOperation;
public class AddObjectDetails {
// This class adds details,from request, to object and returns back
private HttpServletRequest request = null;
private DbOperation dbOperation = null;
public AddObjectDetails(HttpServletRequest request, DbOperation dbOperation) {
this.request = request;
this.dbOperation = dbOperation;
}
public Object addStation() {
String name = Util.charToTurkish(request.getParameter("name"));
Object object = new Station(name);
return object;
}
public Object addPassenger() {
String name = Util.charToTurkish(request.getParameter("name"));
String surname = Util.charToTurkish(request.getParameter("surname"));
String phone = request.getParameter("phone");
String gender = Util.charToTurkish(request.getParameter("gender"));
Object object = new Passenger(name, surname, phone, gender);
return object;
}
public Object addUserAdmin() {
String name = Util.charToTurkish(request.getParameter("name"));
String surname = Util.charToTurkish(request.getParameter("surname"));
String phone = request.getParameter("phone");
String password = request.getParameter("password");
String username = request.getParameter("username");
Object object = new UserAdmin(name, surname, phone, username, password);
return object;
}
public Object addBus() {
String brand = Util.charToTurkish(request.getParameter("brand"));
int capacity = Integer.parseInt(request.getParameter("capacity"));
String model = Util.charToTurkish(request.getParameter("model"));
String plate = request.getParameter("plate");
int modelYear = Integer.parseInt(request.getParameter("modelYear"));
Object object = new Bus(plate, brand, model, capacity, modelYear);
return object;
}
public Object addBranch() {
String branchName = Util.charToTurkish(request
.getParameter("branchName"));
String country = Util.charToTurkish(request.getParameter("country"));
String city = Util.charToTurkish(request.getParameter("city"));
String county = Util.charToTurkish(request.getParameter("county"));
String district = Util.charToTurkish(request.getParameter("district"));
String phone = request.getParameter("phone");
Object object = new Branch(branchName, country, city, county, district,
phone);
return object;
}
public Object addDriver() {
String name = Util.charToTurkish(request.getParameter("name"));
String surname = Util.charToTurkish(request.getParameter("surname"));
String phone = request.getParameter("phone");
String tcno = request.getParameter("tcno");
int birthYear = Integer.parseInt(request.getParameter("birthYear"));
Object object = new Driver(name, surname, phone, tcno, birthYear);
return object;
}
public Object addRoute() {
String routeName = Util
.charToTurkish(request.getParameter("routeName"));
long fromStationId = Long.parseLong(request.getParameter("fStationId"));
long toStationId = Long.parseLong(request.getParameter("tStationId"));
Station from = (Station) dbOperation.getSession().get(Station.class,
fromStationId);
Station to = (Station) dbOperation.getSession().get(Station.class,
toStationId);
Object object = new Route(routeName, from, to);
return object;
}
public Object addRouteStation() {
Double price = Double.parseDouble(request.getParameter("price"));
long routeId = Long.parseLong(request.getParameter("routeId"));
long stopId = Long.parseLong(request.getParameter("stopId"));
String routeStationName = Util.charToTurkish(request
.getParameter("routeStationName"));
Route route = (Route) dbOperation.getSession()
.get(Route.class, routeId);
Station stop = (Station) dbOperation.getSession().get(Station.class,
stopId);
Object object = new RouteStation(route, stop, price, routeStationName);
return object;
}
public Object addJourney() {
String journeyNo = Util
.charToTurkish(request.getParameter("journeyNo"));
long driverId1 = Long.parseLong(request.getParameter("driverId1"));
long driverId2 = Long.parseLong(request.getParameter("driverId2"));
long routeId = Long.parseLong(request.getParameter("routeId"));
long busId = Long.parseLong(request.getParameter("busId"));
// getting Objects according to their Id's
Driver driver1 = (Driver) dbOperation.getSession().get(Driver.class,
driverId1);
Driver driver2;
if (request.getParameter("driverId2").equalsIgnoreCase("null")) {
driver2 = null;
} else {
driver2 = (Driver) dbOperation.getSession().get(Driver.class,
driverId2);
}
Route route = (Route) dbOperation.getSession()
.get(Route.class, routeId);
Bus bus = (Bus) dbOperation.getSession().get(Bus.class, busId);
// Formatting times and dates
String departureTime = request.getParameter("departureTime");
String departureDate = request.getParameter("departureDate");
String arrivalTime = request.getParameter("arrivalTime");
String arrivalDate = request.getParameter("arrivalDate");
Date dArrivalTime = null, dDepartureTime = null;
dArrivalTime = Util.productDate(arrivalTime, arrivalDate);
dDepartureTime = Util.productDate(departureTime, departureDate);
Object object = new Journey(bus, driver1, driver2, route, journeyNo,
dDepartureTime, dArrivalTime);
return object;
}
public Object addTicket() {
long employeeId = Long.parseLong(request.getParameter("employeeId"));
long journeyId = Long.parseLong(request.getParameter("journeyId"));
long routeStationId = Long.parseLong(request
.getParameter("routeStationId"));
int seatNumber = Integer.parseInt(request.getParameter("seatNumber"));
// Adding passenger to Db and getting Passenger Id if there is not
// passenger=>
String name = Util.charToTurkish(request.getParameter("name"));
String surname = Util.charToTurkish(request.getParameter("surname"));
String phone = request.getParameter("phone");
String gender = Util.charToTurkish(request.getParameter("gender"));
Object obj = new Passenger(name, surname, phone, gender);
// Adding restrictions to criteria and getting Passenger Id if there is
// a passenger
Criteria criteria = dbOperation.getSession().createCriteria(
Passenger.class);
criteria.add(Restrictions.eq("name", name));
criteria.add(Restrictions.eq("surname", surname));
criteria.add(Restrictions.eq("phone", phone));
criteria.add(Restrictions.eq("gender", gender));
ArrayList<Object> passengers = dbOperation.listObjects(criteria);
Passenger psngr = new Passenger(name, surname, phone, gender);
long passengerId;
if (!passengers.isEmpty()) { // Get passengerId, if there is
// passenger
for (Object p : passengers) {
psngr = ((Passenger) (p));
}
passengerId = psngr.getId();
} else { // Add passenger and get Id if there is not passenger
dbOperation.saveObject(psngr);
passengers = dbOperation.listObjects(criteria);
for (Object p : passengers) {
psngr = ((Passenger) (p));
}
passengerId = psngr.getId();
}
// <=got PassengerId
// Get and Add details
Journey journey = (Journey) dbOperation.getSession().get(Journey.class,
journeyId);
Passenger passenger = (Passenger) dbOperation.getSession().get(
Passenger.class, passengerId);
RouteStation routeStation = (RouteStation) dbOperation.getSession()
.get(RouteStation.class, routeStationId);
UserEmployee employee = (UserEmployee) dbOperation.getSession().get(
UserEmployee.class, employeeId);
Date takenDate = new Date();
Object object = new Ticket(journey, passenger, routeStation, takenDate,
employee, seatNumber);
return object;
}
public Object addUserEmployee() {
String name = Util.charToTurkish(request.getParameter("name"));
String surname = Util.charToTurkish(request.getParameter("surname"));
String phone = request.getParameter("phone");
String password = request.getParameter("password");
String username = request.getParameter("username");
long branchId = Long.parseLong(request.getParameter("branchId"));
Branch branch = (Branch) dbOperation.getSession().get(Branch.class,
branchId);
Object object = new UserEmployee(name, surname, phone, username,
password, branch);
return object;
}
}
|
/*
* 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 modul2;
/**
*
* @author LAB_TI
*/
import java.awt.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
public class contoh5 {
public static void main(String[] args) {
Image image=null;
try{
File sourceimage =new File("d:/images.jpg");
image = ImageIO.read(sourceimage);
InputStream is=new BufferedInputStream(new FileInputStream("d:/images.jpg"));
image = ImageIO.read(is);
}catch(IOException e)
{
}
JFrame frame=new JFrame();
JLabel label =new JLabel(new ImageIcon(image));
frame.getContentPane().add(label,BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}}
|
package com.website.views.includes;
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;
import com.website.tools.navigation.ContextManager;
import com.website.tools.navigation.SessionManager;
/**
* A view for the banner showed on most of this project web pages.</br>
* This {@link Named} class is bound with the same named xhtml file.
*
* @author Jérémy Pansier
*/
@Named
@RequestScoped
public class Banner {
/**
* Gets the flash message to be displayed in the banner of the web page.
*
* @return the flash message to be displayed in the banner of the web page
*/
public String getMessage() {
return ContextManager.getMessage();
}
/**
* Gets the connected user name to be displayed in the banner of the web page.
*
* @return the user name to be displayed in the banner of the web page
*/
public String getUsername() {
return SessionManager.getSessionUserName();
}
}
|
package com.example.webviewtest.inter;
/**
* author: JST - Dayu
* date: 2019/8/22 14:38
* context:
*/
@SuppressWarnings("all")
public interface JsBridge {
//判断是否登录成功
void isLoginSuccess(String is) ;
}
|
package com.aifurion.track.config;
import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.aifurion.track.shiro.CustomRealm;
import com.aifurion.track.shiro.cache.RedisCacheManager;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;
/**
* @author :zzy
* @description:TODO shiro配置类
* @date :2021/3/23 9:52
*/
@Configuration
public class ShiroConfig {
/**
* 创建shiroFilter负责拦截请求
*
* @param securityManager
* @return
*/
@Bean(name = "shiroFilterFactoryBean")
public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
Map<String, String> map = new HashMap<>();
/*
排除用户操作项
*/
/* map.put("/auth/login", "anon");
map.put("/auth/register/**", "anon");
map.put("/auth/test", "anon");
map.put("/auth/ifUsernameExit", "anon");
map.put("/auth/doctorRegister", "anon");
*/
map.put("/auth/**", "anon");
/*
排除静态资源
*/
map.put("/css/**", "anon");
map.put("/images/**", "anon");
map.put("/js/**", "anon");
map.put("/fonts/**", "anon");
map.put("/bootstrap-table/**", "anon");
/*
公开查看链接
/view/author_name/page_id
*/
map.put("/view/**", "anon");
map.put("/**", "authc");
shiroFilterFactoryBean.setLoginUrl("/auth/login");
shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
return shiroFilterFactoryBean;
}
/**
* 创建安全管理器
* 使用自定义realm
*
* @param realm
* @return
*/
@Bean
public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("realm") Realm realm) {
DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
defaultWebSecurityManager.setRealm(realm);
return defaultWebSecurityManager;
}
/**
* 创建自定义realm
*
* @return
*/
@Bean("realm")
public Realm getRealm() {
CustomRealm customRealm = new CustomRealm();
/*
修改默认凭证匹配器
*/
HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
/*
MD5加密,迭代1024次
*/
credentialsMatcher.setHashAlgorithmName("MD5");
credentialsMatcher.setHashIterations(1024);
customRealm.setCredentialsMatcher(credentialsMatcher);
/**
* redis缓存
*
*/
customRealm.setCacheManager(new RedisCacheManager());
customRealm.setCachingEnabled(true);
customRealm.setAuthenticationCachingEnabled(true);
customRealm.setAuthenticationCacheName("authenticationCache");
customRealm.setAuthorizationCachingEnabled(true);
customRealm.setAuthorizationCacheName("authorizationCache");
return customRealm;
}
/**
* 添加thymeleaf对shiro的支持
*
* @return
*/
@Bean
public ShiroDialect shiroDialect() {
return new ShiroDialect();
}
}
|
package com.example.demo;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.example.demo.application.dtos.ActorEditDTO;
import com.example.demo.application.dtos.CityEdit;
import com.example.demo.domains.entities.Actor;
import com.example.demo.domains.entities.projections.ActorShort;
import com.example.demo.domains.services.ActorService;
import com.example.demo.exception.NotFoundException;
import com.example.demo.infraestructure.repositories.ActorRepository;
import com.example.demo.infraestructure.repositories.CityRepository;
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Autowired
ActorRepository dao;
@Autowired
ActorService srv;
@Autowired
CityRepository citys;
@Override
public void run(String... args) {
System.out.println("Hola mundo");
// dao.findAll().forEach(item -> System.out.println(item));
// dao.findTop10ByFirstNameStartingWith("KI").forEach(item ->
// System.out.println(item.getFilmActors()));
// Actor actor = new Actor(0, "Pepito", "Grillo");
// srv.add(actor);
// try {
// Optional<Actor> rslt = srv.get(229);
// if (rslt.isPresent()) {
// Actor actor = rslt.get();
// //actor.setActorId(999);
// actor.setFirstName("PEPITO");
// srv.modify(actor);
// }
// //srv.delete(227);
// srv.getAll().forEach(item -> System.out.println(item));
// } catch (NotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// citys.findAll().stream()
// .map(item -> CityEdit.from(item))
// .forEach(item -> System.out.println(item));
// CityEdit req = new CityEdit(0, "Almeria", 87);
// citys.save(CityEdit.from(req));
// citys.findAll().stream()
// .forEach(item -> System.out.println(item));
dao.findByActorIdIsNotNull(ActorShort.class)
.forEach(item -> System.out.println(item.getName()));
}
}
|
package app.home;
import com.hqb.patshop.PatshopApplication;
import com.hqb.patshop.app.home.dto.TopicPostDTO;
import com.hqb.patshop.app.home.service.CommunityService;
import com.hqb.patshop.mbg.dao.SmsSecTopicDao;
import com.hqb.patshop.mbg.dao.SmsTopicDao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.ResourceUtils;
import java.io.FileNotFoundException;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {PatshopApplication.class})
public class CommunityTest {
@Autowired
private CommunityService communityService;
@Autowired
SmsTopicDao smsTopicDao;
@Autowired
SmsSecTopicDao smsSecTopicDao;
@Test
public void testHotTopic() {
// CommunityResult communityResult = communityService.hotTopicList(1);
// System.out.println(communityResult.getTopicList().size());
// System.out.println(communityResult.getTopicList());
System.out.println(smsTopicDao.selectAllByHotTopic(1));
}
@Test
public void testPostTopic() {
TopicPostDTO topicPostDTO = new TopicPostDTO();
topicPostDTO.setTopicContent("测试测试");
topicPostDTO.setTopicSecType("我买过的惊喜好物");
topicPostDTO.setTopicType("游戏手办");
System.out.println(communityService.postTopic(topicPostDTO));
}
@Test
public void testSelectIdByTopicName() {
System.out.println("我买过的惊喜好物" + smsSecTopicDao.selectPrimaryKeyBySecTopicName("我买过的惊喜好物"));
}
@Test
public void testPath() {
try {
System.out.println(ResourceUtils.getURL("classpath:static").getPath());
System.out.println(ResourceUtils.getURL("classpath:static").getPath());
System.out.println(this.getClass().getResource("/").getPath());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
|
package com.ozgur.kutuphane.web.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.ozgur.kutuphane.model.Kitap;
import com.ozgur.kutuphane.model.YayinEvi;
import com.ozgur.kutuphane.model.Yazar;
import com.ozgur.kutuphane.service.KitapService;
import com.ozgur.kutuphane.service.YayinEviService;
import com.ozgur.kutuphane.service.YazarService;
@Controller
public class KitapController {
@Autowired
private KitapService kitapService;
@Autowired
private YayinEviService yayinEviService;
@Autowired
private YazarService yazarService;
@GetMapping("/kitapForUye")
public String kitapForUye(Model model) {
model.addAttribute("listKitap", kitapService.getAllKitap());
return "uye_form";
}
@GetMapping("/kitapForYonetici")
public String kitapForYonetici(Model model) {
model.addAttribute("listKitap", kitapService.getAllKitap());
return "list_kitap";
}
@RequestMapping("/kitapSearchFormForUye")
public String kitapSearchFormForUye(Model model) {
Kitap kitap = new Kitap();
model.addAttribute("kitap", kitap);
return "search_kitap_form_uye";
}
@RequestMapping("/kitapSearchFormForYonetici")
public String kitapSearchFormForYonetici(Model model) {
Kitap kitap = new Kitap();
model.addAttribute("kitap", kitap);
return "search_kitap_form_yonetici";
}
@RequestMapping("/kitapSearchForYonetici")
public String kitapSearchForYonetici(@ModelAttribute("kitap") Kitap kitap, Model model) {
Kitap findKitap = kitapService.getKitapByName(kitap.getBookName());
model.addAttribute("findKitap", findKitap);
return "search_kitap_form_yonetici";
}
@RequestMapping("/kitapSearchForUye")
public String kitapSearchForUye(@ModelAttribute("kitap") Kitap kitap, Model model) {
Kitap findKitap = kitapService.getKitapByName(kitap.getBookName());
model.addAttribute("findKitap", findKitap);
return "search_kitap_form_uye";
}
@RequestMapping("/showFormForKitapUpdate")
public String kitapUpdate(Model model) {
model.addAttribute("listKitap", kitapService.getAllKitap());
return "update_kitap_form";
}
@GetMapping("/showFormForKitapUpdate/{id}")
public String showFormForUpdate(@PathVariable(value = "id") long id, Model model) {
Kitap kitap = kitapService.getKitapById(id);
model.addAttribute("kitap", kitap);
return "update_kitap";
}
@PostMapping("/saveKitap")
public String saveKitapForUpdate(@ModelAttribute("kitap") Kitap kitap) {
kitapService.saveKitap(kitap);
return "redirect:showFormForKitapUpdate";
}
@GetMapping("/deleteKitap/{id}")
public String deleteKitapForm(@PathVariable(value = "id") long id, Model model) {
kitapService.deleteKitapById(id);
return "redirect:/showFormForDeleteKitap";
}
@RequestMapping("/showFormForDeleteKitap")
public String deleteKitap(Model model) {
model.addAttribute("listKitap", kitapService.getAllKitap());
return "delete_kitap";
}
@GetMapping("/showNewKitapForm")
public String showNewKitapForm(Model model) {
Kitap kitap = new Kitap();
Yazar yazar = new Yazar();
YayinEvi yayinEvi = new YayinEvi();
model.addAttribute("kitap", kitap);
model.addAttribute("author", yazar);
model.addAttribute("publisher", yayinEvi);
return "new_kitap";
}
@RequestMapping("/saveKitapNew")
public String saveUyeForNewKitap(@ModelAttribute("kitap") Kitap kitap, @ModelAttribute("author") Yazar yazar,
@ModelAttribute("publisher") YayinEvi yayinEvi, RedirectAttributes redirAttrs) {
YayinEvi newYayinEvi = yayinEviService.getYayinEviByName(yayinEvi.getPublisherName());
Yazar newYazar = yazarService.getAuthorByName(yazar.getAuthorName());
if (newYazar == null) {
redirAttrs.addFlashAttribute("error", "Böyle bir yazar bulunamadı,İlk önce yazarı ekleyin");
return "redirect:/showNewKitapForm";
}
if (newYayinEvi == null) {
redirAttrs.addFlashAttribute("error", "Böyle bir yayın evi bulunamadı,İlk önce yayın evini ekleyin");
return "redirect:/showNewKitapForm";
}
System.out.println(newYazar);
System.out.println(newYayinEvi);
kitap.setAuthor(newYazar);
kitap.getPublisher().add(newYayinEvi);
kitapService.saveKitap(kitap);
return "redirect:/showNewKitapForm";
}
}
|
package Concrete;
import Abstract.SellingService;
import Entities.Campaign;
import Entities.Sell;
public class SellingManager implements SellingService
{
Campaign campaign;
public SellingManager()
{
System.out.println("Kampayasız alım gerçekleştirildi.");
}
public SellingManager(Campaign campaign)
{
this.campaign = campaign;
System.out.println("Kampanyalı alım gerçekleştirildi.");
}
@Override
public void sell(Sell sell)
{
var userFullName = sell.getUser().getFirstName() + " " + sell.getUser().getLastName();
var gamePrice = sell.getGame().getPrice();
var gameName = sell.getGame().getName();
if (campaign == null)
{
System.out.println(userFullName + " " + gameName + " isimli oyunu satın aldınız.");
System.out.println("Tutar: " + gamePrice);
} else
{
var discountedPrice = CampaignCalculatorHelper.calculate(sell.getGame(), campaign);
System.out.println(userFullName + " " + gameName + " isimli oyunu" + campaign.getName()
+ " kampanyası ile indirimli aldınız.");
System.out.println("Normal fiyat: " + sell.getGame().getPrice());
System.out.println("İndirimli tutar: " + discountedPrice);
System.out.println("İndirim oranı: %" + campaign.getDiscountAmount());
}
}
}
|
package falconrobotics.scoutingprogram;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
/**
* Created on 2/22/2016.
*/
public class Helper extends SQLiteOpenHelper
{
//table names
public static final String TABLE_MATCHES ="Matches",
TABLE_PIT ="Pit",
TABLE_SCHEDULE ="Schedule",
TABLE_TEAMS ="Teams";
//common key, won't be included in every table
public static final String KEY_SYNCNUM ="syncNum";
public static final String INTEGER =" INTEGER NOT NULL, ";
public static final String TEXT =" TEXT NOT NULL, ";
//Match Table keys
public static final String KEY_MATCH_ID ="_id",
KEY_MATCH_TEAMNUM ="teamNum",
KEY_MATCH_AUTOLOWMISS ="autoLowMiss",
KEY_MATCH_AUTOLOWHIT ="autoLowHit",
KEY_MATCH_AUTOHIGHMISS ="autoHighMiss",
KEY_MATCH_AUTOHIGHHIT ="autoHighHit",
KEY_MATCH_AUTOLOWBARMISS ="autoLowBarMiss",
KEY_MATCH_AUTOLOWBARHIT ="autoLowBarHit",
KEY_MATCH_AUTOCMISS ="autoCMiss",
KEY_MATCH_AUTOCHIT ="autoCHit",
KEY_MATCH_TELELOWBARMISS = "teleLowBarMiss",
KEY_MATCH_TELELOWBARHIT = "teleLowBarHit",
KEY_MATCH_TELECMISS = "teleCMiss",
KEY_MATCH_TELECHIT = "teleCHit",
KEY_MATCH_TELESECTOR1MISS = "teleSector1Miss",
KEY_MATCH_TELESECTOR1HIT = "teleSector1Hit",
KEY_MATCH_TELESECTOR2MISS = "teleSector2Miss",
KEY_MATCH_TELESECTOR2HIT = "teleSector2Hit",
KEY_MATCH_TELESECTOR3MISS = "teleSector3Miss",
KEY_MATCH_TELESECTOR3HIT = "teleSector3Hit",
KEY_MATCH_TELESECTOR4MISS = "teleSector4Miss",
KEY_MATCH_TELESECTOR4HIT = "teleSector4Hit",
KEY_MATCH_TELESECTOR5MISS = "teleSector5Miss",
KEY_MATCH_TELESECTOR5HIT = "teleSector5Hit",
KEY_MATCH_TELESECTOR6MISS = "teleSector6Miss",
KEY_MATCH_TELESECTOR6HIT = "teleSector6Hit",
KEY_MATCH_POSTCLIMB ="postClimb",
KEY_MATCH_POSTCOMMENTS = "postComments";
public static final String[] ARRAY_MATCH = {
KEY_MATCH_ID,
KEY_MATCH_TEAMNUM,
KEY_MATCH_AUTOLOWMISS,
KEY_MATCH_AUTOLOWHIT,
KEY_MATCH_AUTOHIGHMISS,
KEY_MATCH_AUTOHIGHHIT,
KEY_MATCH_AUTOLOWBARMISS,
KEY_MATCH_AUTOLOWBARHIT,
KEY_MATCH_AUTOCMISS,
KEY_MATCH_AUTOCHIT,
KEY_MATCH_TELELOWBARMISS,
KEY_MATCH_TELELOWBARHIT,
KEY_MATCH_TELECMISS,
KEY_MATCH_TELECHIT,
KEY_MATCH_TELESECTOR1MISS,
KEY_MATCH_TELESECTOR1HIT,
KEY_MATCH_TELESECTOR2MISS,
KEY_MATCH_TELESECTOR2HIT,
KEY_MATCH_TELESECTOR3MISS,
KEY_MATCH_TELESECTOR3HIT,
KEY_MATCH_TELESECTOR4MISS,
KEY_MATCH_TELESECTOR4HIT,
KEY_MATCH_TELESECTOR5MISS,
KEY_MATCH_TELESECTOR5HIT,
KEY_MATCH_TELESECTOR6MISS,
KEY_MATCH_TELESECTOR6HIT,
KEY_MATCH_POSTCLIMB,
KEY_MATCH_POSTCOMMENTS,
KEY_SYNCNUM};
//Pit Table keys
public static final String KEY_PIT_ID ="_id",
KEY_PIT_DRIVER_XP ="driverXP",
KEY_PIT_OPERATOR_XP = "operatorXP",
KEY_PIT_DRIVETRAIN ="drivetrain",
KEY_PIT_PNEUMATICS = "pneumatics",
KEY_PIT_SHOOTER_TYPE ="shooterType",
KEY_PIT_SHOOTING_TYPE = "shootingType",
KEY_PIT_CLIMB ="climb",
KEY_PIT_CLIMBSPEED ="climbSpeed",
KEY_PIT_WEIGHT = "weight",
KEY_PIT_ROBOT_DIMENSIONS = "robotDimensions",
KEY_PIT_PORTCULLIS ="portcullis",
KEY_PIT_CHEVALDEFRISE ="chevalDeFrise",
KEY_PIT_MOAT ="moat",
KEY_PIT_RAMPARTS ="ramparts",
KEY_PIT_DRAWBRIDGE ="drawbridge",
KEY_PIT_SALLYPORT ="sallyPort",
KEY_PIT_ROCKWALL ="rockWall",
KEY_PIT_ROUGHTERRAIN ="roughTerrain",
KEY_PIT_LOWBAR ="lowBar",
KEY_PIT_COMMENTS ="comments",
KEY_PIT_ROBOTPHOTO ="robotPhoto";
public static final String[] ARRAY_PIT = {
KEY_PIT_ID,
KEY_PIT_DRIVER_XP,
KEY_PIT_OPERATOR_XP,
KEY_PIT_DRIVETRAIN,
KEY_PIT_PNEUMATICS,
KEY_PIT_SHOOTER_TYPE,
KEY_PIT_SHOOTING_TYPE,
KEY_PIT_CLIMB,
KEY_PIT_CLIMBSPEED,
KEY_PIT_WEIGHT,
KEY_PIT_ROBOT_DIMENSIONS,
KEY_PIT_PORTCULLIS,
KEY_PIT_CHEVALDEFRISE,
KEY_PIT_MOAT,
KEY_PIT_RAMPARTS,
KEY_PIT_DRAWBRIDGE,
KEY_PIT_SALLYPORT,
KEY_PIT_ROCKWALL,
KEY_PIT_ROUGHTERRAIN,
KEY_PIT_LOWBAR,
KEY_PIT_COMMENTS,
KEY_PIT_ROBOTPHOTO,
KEY_SYNCNUM};
//Schedule Table keys
public static final String KEY_SCHEDULE_ID ="_id",
KEY_SCHEDULE_DESCRIPTION ="description",
KEY_SCHEDULE_BLUEROBOT1 ="blueRobot1",
KEY_SCHEDULE_BLUEROBOT2 ="blueRobot2",
KEY_SCHEDULE_BLUEROBOT3 ="blueRobot3",
KEY_SCHEDULE_REDROBOT1 ="redRobot1",
KEY_SCHEDULE_REDROBOT2 ="redRobot2",
KEY_SCHEDULE_REDROBOT3 ="redRobot3";
public static final String[] ARRAY_SCHEDULE = {
KEY_SCHEDULE_ID,
KEY_SCHEDULE_DESCRIPTION,
KEY_SCHEDULE_BLUEROBOT1,
KEY_SCHEDULE_BLUEROBOT2,
KEY_SCHEDULE_BLUEROBOT3,
KEY_SCHEDULE_REDROBOT1,
KEY_SCHEDULE_REDROBOT2,
KEY_SCHEDULE_REDROBOT3};
//Teams Table keys
public static final String KEY_TEAMS_ID = "_id",
KEY_TEAMS_SHORTNAME = "shortName";
public static final String[] ARRAY_TEAMS ={
KEY_TEAMS_ID,
KEY_TEAMS_SHORTNAME
};
//Match Table create statement
public static final String CREATE_TABLE_MATCH =
"CREATE TABLE IF NOT EXISTS "
+ TABLE_MATCHES + "("
+ KEY_MATCH_ID + " INTEGER PRIMARY KEY NOT NULL, "
+ KEY_MATCH_TEAMNUM + INTEGER
+ KEY_MATCH_AUTOLOWMISS + INTEGER
+ KEY_MATCH_AUTOLOWHIT + INTEGER
+ KEY_MATCH_AUTOHIGHMISS + INTEGER
+ KEY_MATCH_AUTOHIGHHIT + INTEGER
+ KEY_MATCH_AUTOLOWBARMISS + INTEGER
+ KEY_MATCH_AUTOLOWBARHIT + INTEGER
+ KEY_MATCH_AUTOCMISS + INTEGER
+ KEY_MATCH_AUTOCHIT + INTEGER
+ KEY_MATCH_TELELOWBARMISS + INTEGER
+ KEY_MATCH_TELELOWBARHIT + INTEGER
+ KEY_MATCH_TELECMISS + INTEGER
+ KEY_MATCH_TELECHIT + INTEGER
+ KEY_MATCH_TELESECTOR1MISS + INTEGER
+ KEY_MATCH_TELESECTOR1HIT + INTEGER
+ KEY_MATCH_TELESECTOR2MISS + INTEGER
+ KEY_MATCH_TELESECTOR2HIT + INTEGER
+ KEY_MATCH_TELESECTOR3MISS + INTEGER
+ KEY_MATCH_TELESECTOR3HIT + INTEGER
+ KEY_MATCH_TELESECTOR4MISS + INTEGER
+ KEY_MATCH_TELESECTOR4HIT + INTEGER
+ KEY_MATCH_TELESECTOR5MISS + INTEGER
+ KEY_MATCH_TELESECTOR5HIT + INTEGER
+ KEY_MATCH_TELESECTOR6MISS + INTEGER
+ KEY_MATCH_TELESECTOR6HIT + INTEGER
+ KEY_MATCH_POSTCLIMB + INTEGER
+ KEY_MATCH_POSTCOMMENTS + TEXT
+ KEY_SYNCNUM + " INT NOT NULL"
+ ");";
//Pit Table create statement
public static final String CREATE_TABLE_PIT =
"CREATE TABLE IF NOT EXISTS "
+ TABLE_PIT + "("
+ KEY_PIT_ID + " INTEGER PRIMARY KEY NOT NULL, "
+ KEY_PIT_DRIVER_XP + INTEGER
+ KEY_PIT_OPERATOR_XP + INTEGER
+ KEY_PIT_DRIVETRAIN + INTEGER
+ KEY_PIT_PNEUMATICS + INTEGER
+ KEY_PIT_SHOOTER_TYPE + INTEGER
+ KEY_PIT_SHOOTING_TYPE + INTEGER
+ KEY_PIT_CLIMB + INTEGER
+ KEY_PIT_CLIMBSPEED + INTEGER
+ KEY_PIT_WEIGHT + INTEGER
+ KEY_PIT_ROBOT_DIMENSIONS + INTEGER
+ KEY_PIT_PORTCULLIS + INTEGER
+ KEY_PIT_CHEVALDEFRISE + INTEGER
+ KEY_PIT_MOAT + INTEGER
+ KEY_PIT_RAMPARTS + INTEGER
+ KEY_PIT_DRAWBRIDGE + INTEGER
+ KEY_PIT_SALLYPORT + INTEGER
+ KEY_PIT_ROCKWALL + INTEGER
+ KEY_PIT_ROUGHTERRAIN + INTEGER
+ KEY_PIT_LOWBAR + INTEGER
+ KEY_PIT_COMMENTS + TEXT
+ KEY_PIT_ROBOTPHOTO + INTEGER
+ KEY_SYNCNUM + " INT NOT NULL "
+ ");";
//Schedule Table create statement
public static final String CREATE_TABLE_SCHEDULE =
"CREATE TABLE IF NOT EXISTS "
+ TABLE_SCHEDULE + "("
+ KEY_SCHEDULE_ID + " INT PRIMARY KEY NOT NULL, "
+ KEY_SCHEDULE_DESCRIPTION + TEXT
+ KEY_SCHEDULE_BLUEROBOT1 + INTEGER
+ KEY_SCHEDULE_BLUEROBOT2 + INTEGER
+ KEY_SCHEDULE_BLUEROBOT3 + INTEGER
+ KEY_SCHEDULE_REDROBOT1 + INTEGER
+ KEY_SCHEDULE_REDROBOT2 + INTEGER
+ KEY_SCHEDULE_REDROBOT3 + INTEGER
+ KEY_SYNCNUM + " INT NOT NULL "
+ ");";
//Team Table create statement
public static final String CREATE_TABLE_TEAMS =
"CREATE TABLE IF NOT EXISTS "
+ TABLE_TEAMS + "("
+ KEY_TEAMS_ID + " INT PRIMARY KEY NOT NULL, "
+ KEY_TEAMS_SHORTNAME + TEXT
+ KEY_SYNCNUM + " INT NOT NULL "
+ ");";
public static String mainDirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "falconrobotics2016";
public static String picDirPath = mainDirPath + File.separator + "pictures";
public static String dbDirPath = mainDirPath + File.separator + "databases";
public Helper() {
super(MainActivity.context, dbDirPath + File.separator + MainActivity.eventName, null, 1);
}
/**
* For easy access from the outside for on the go execution.
*
* @param statement
* An executable SQLite statement.
*/
public void exec(String statement){
getWritableDatabase().execSQL(statement);
}
/**
* Creates the necessary directories.
*
* Static because helps with accessibility.
*/
public void createDir() {
File picDir = new File(picDirPath);
if (!picDir.exists()) {
if (!picDir.mkdirs()) {
// WARN USER
Toast.makeText(MainActivity.context, "WARNING! UNABLE TO CREATE WORKING DIRECTORY. PLEASE REINSTALL AND DELETE ALL ASSOCIATED FILES", Toast.LENGTH_LONG).show();
}
}
File dbDir = new File(dbDirPath);
if (!dbDir.exists()) {
if (!dbDir.mkdirs()) {
// WARN USER
Toast.makeText(MainActivity.context, "WARNING! UNABLE TO CREATE WORKING DIRECTORY. PLEASE REINSTALL AND DELETE ALL ASSOCIATED FILES", Toast.LENGTH_LONG).show();
}
}
}
/**
* Updates the pit table, only adds or replaces information, no deletion.
*
* @param updateStatement
* INSERT OR REPLACE; INSERT; REPLACE; All found as a static String in MainActivity.
* @param pitObject
* A model for the pit data structure, need it to update the information on the database file.
*/
public void pit_update(String updateStatement, Model_Pit pitObject)
{
SQLiteDatabase db = getWritableDatabase();
if (db != null) {
db.execSQL( updateStatement + " INTO " + TABLE_PIT +
"(_id, driverXP, operatorXP, drivetrain, pneumatics, shooterType, shootingType, " +
"climb, climbSpeed, weight, robotDimensions, " +
"portcullis, chevalDeFrise, moat, ramparts, drawbridge, sallyPort, rockWall, " +
"roughTerrain, lowBar, comments, robotPhoto, syncNum)" +
" VALUES(" +
pitObject.get_id() + ", " + pitObject.getDriverXP() + ", " + pitObject.getOperatorXP() + ", " + pitObject.getDrivetrain() + ", " + pitObject.getPneumatics() + ", " +
pitObject.getShooterType() + ", " + pitObject.getShootingType() + ", " + pitObject.getClimb() + ", " + pitObject.getClimbSpeed() + ", " + pitObject.getWeight() + ", '" + pitObject.getRobotDimensions()+ "', " +
pitObject.getPortcullis() + ", " + pitObject.getChevalDeFrise() + ", " + pitObject.getMoat() + ", " + pitObject.getRamparts() + ", " + pitObject.getDrawbridge() + ", " + pitObject.getSallyPort() + ", " + pitObject.getRockWall() + ", " +
pitObject.getRoughTerrain() + ", " + pitObject.getLowBar() + ", '" + pitObject.getComments() + "', " + pitObject.getRobotPhoto() + ", " + pitObject.getSyncNum() + ")");
db.close();
}
export(TABLE_PIT);
}
/**
* Updates the matches table, only adds or replaces information, no deletion.
*
* @param updateStatement
* INSERT OR REPLACE; INSERT; REPLACE; All found as a static String in MainActivity.
* @param matchObject
* A model for the match data structure, need it to update the information on the database file.
*/
public void match_update(String updateStatement, Model_Match matchObject)
{
SQLiteDatabase db = getWritableDatabase();
if(db!=null) {
db.execSQL(updateStatement + " INTO " + TABLE_MATCHES +
"(_id, teamNum, " +
"autoLowMiss, autoLowHit, autoHighMiss, autoHighHit, autoLowBarMiss, autoLowBarHit, autoCMiss, autoCHit, " +
"teleLowBarMiss, teleLowBarHit, teleCMiss, teleCMiss, " +
"teleSector1Miss, teleSector1Hit, teleSector2Miss, teleSector2Hit, teleSector3Miss, teleSector3Hit, teleSector4Miss, teleSector4Hit, teleSector5Miss, teleSector5Hit, teleSector6Miss, teleSector6Hit, " +
"postClimb, postComments, syncNum)" +
" VALUES(" +
matchObject.get_id() + ", " + matchObject.getTeamNum() + ", " +
matchObject.getAutoLowMiss() + ", " + matchObject.getAutoLowHit() + ", " + matchObject.getAutoHighMiss() + ", " + matchObject.getAutoHighHit() + ", " + matchObject.getAutoLowBarMiss() + ", " + matchObject.getAutoLowBarHit() + ", " + matchObject.getAutoCMiss() + ", " + matchObject.getAutoCHit() + ", " +
matchObject.getTeleLowBarMiss() + ", " + matchObject.getTeleLowBarHit() + ", " + matchObject.getTeleCMiss() + ", " + matchObject.getTeleCMiss() + ", " +
matchObject.getTeleSector1Miss() + ", " + matchObject.getTeleSector1Hit() + ", " + matchObject.getTeleSector2Miss() + ", " + matchObject.getTeleSector2Hit() + ", " + matchObject.getTeleSector3Miss() + ", " + matchObject.getTeleSector3Hit() + ", " + matchObject.getTeleSector4Miss() + ", " + matchObject.getTeleSector4Hit() + ", " + matchObject.getTeleSector5Miss() + ", " + matchObject.getTeleSector5Hit() + ", " + matchObject.getTeleSector6Miss() + ", " + matchObject.getTeleSector6Hit() + ", " +
matchObject.getPostClimb() + ", '" + matchObject.getPostComments() + "', " + matchObject.getSyncNum() + ")");
db.close();
}
export(TABLE_MATCHES);
}
/**
* Reads all the information on the specified team in the pit table in the database.
* All information provided must already be in the database.
*
* @param teamNum
* The number of the team the data is wanted from.
* @return
* The model structure with the information of the team from pit scouting table.
*/
public Model_Pit pit_readTeam(int teamNum)
{
SQLiteDatabase db = getReadableDatabase();
if(db == null) return null;
Cursor c = db.query(TABLE_PIT, ARRAY_PIT, KEY_PIT_ID + "=?",
new String[]{String.valueOf(teamNum)}, null, null, null, null);
Model_Pit model;
if(c != null) {
c.moveToFirst();
model = new Model_Pit(
c.getInt(0),
c.getInt(1),
c.getInt(2),
c.getInt(3),
c.getInt(4),
c.getInt(5),
c.getInt(6),
c.getInt(7),
c.getInt(8),
c.getInt(9),
c.getString(10),
c.getInt(11),
c.getInt(12),
c.getInt(13),
c.getInt(14),
c.getInt(15),
c.getInt(16),
c.getInt(17),
c.getInt(18),
c.getInt(19),
c.getString(20),
c.getInt(21),
c.getInt(22));
db.close();
c.close();
return model;
}
return null;
}
/**
* Reads all the information on the specified team in the match table in the database.
* All information provided must already be in the database.
*
* @param _id
* Match number with level.
* @param teamNum
* Number of the team the data is wanted from.
* @return
* The model structure with the information of the team in the specified match from the match scouting table.
*/
public Model_Match match_readTeam(int _id, int teamNum)
{
SQLiteDatabase db = getReadableDatabase();
if(db == null) {
Toast.makeText(MainActivity.context,"I failed to load the database!",Toast.LENGTH_SHORT).show();
return null;
}
Cursor c = db.rawQuery("SELECT * FROM " + TABLE_MATCHES + " WHERE _id =? AND teamNum =? ", new String[]{_id + "", teamNum + ""});
Model_Match model;
if(c.getCount() > 0) {
c.moveToFirst();
model = new Model_Match(
c.getInt(0),
c.getInt(1),
c.getInt(2),
c.getInt(3),
c.getInt(4),
c.getInt(5),
c.getInt(6),
c.getInt(7),
c.getInt(8),
c.getInt(9),
c.getInt(10),
c.getInt(11),
c.getInt(12),
c.getInt(13),
c.getInt(14),
c.getInt(15),
c.getInt(16),
c.getInt(17),
c.getInt(18),
c.getInt(19),
c.getInt(20),
c.getInt(21),
c.getInt(22),
c.getInt(23),
c.getInt(24),
c.getInt(25),
c.getInt(26),
c.getString(27),
c.getInt(28)
);
c.close();
return model;
}
return null;
}
/**
* Create statement for all the tables.
*
* @param db
* Database in use.
*/
@Override
public void onCreate(SQLiteDatabase db) {
createDir();
db.execSQL(CREATE_TABLE_MATCH);
db.execSQL(CREATE_TABLE_PIT);
db.execSQL(CREATE_TABLE_SCHEDULE);
db.execSQL(CREATE_TABLE_TEAMS);
}
/**
* Should probably drop the table but won't be working with this for now I think.
* @param db
* Database in use.
* @param oldVersion
* Version number of the previous database.
* @param newVersion
* Version number of the new database.
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// DO NOTHING
// SHOULD PROBABLY DROP IT
}
/**
* WILL DELETE ALL DATA.
*
* @param areYouSure
* Whether or not you really want to delete all associated files with the app.
*/
public void resetData(File dir, boolean areYouSure)
{if(areYouSure)
{
if(dir.exists())
{
File[] files = dir.listFiles();
for(File file : files)
{
if(file.isDirectory())
{
resetData(file, true);
}
else
{
file.delete();
}
}
}
if(dir.delete()) Toast.makeText(MainActivity.context, "Success!", Toast.LENGTH_SHORT).show();
onCreate(getWritableDatabase());
doRestart(MainActivity.context);
}}
/**
* Checks whether or not the data exists in the pit scouting table in the database.
*
* @param _id
* Team number.
* @return
* True for the data exists, False for it doesn't.
*/
public boolean pitDataCheck(int _id) {
return DatabaseUtils.longForQuery(getReadableDatabase(), "SELECT COUNT(*) FROM " + TABLE_PIT + " WHERE _id=? LIMIT 1", new String[] {_id + ""}) > 0;
}
/**
* Checks whether or not the data exists in the match scouting table in the database.
*
* @param _id
* Match number with level.
* @param teamNum
* Team number.
* @return
* True for the data exists, False for it doesn't.
*/
public boolean matchDataCheck(int _id, int teamNum) {
return DatabaseUtils.longForQuery(getReadableDatabase(), "SELECT COUNT(*) FROM " + TABLE_MATCHES + " WHERE _id=? AND teamNum=? ", new String[] {_id + "", teamNum + ""}) > 0;
}
/**
* Exports the specified table name to a csv file in the main folder.
*
* @param table
* Table name to be
*/
private void export(String table)
{
Cursor c = getWritableDatabase().rawQuery("SELECT * FROM "+ table, null);
int rowcount = 0;
int colcount = 0;
String filename = table + "_export.csv";
try{
File saveFile = new File(new File(Helper.mainDirPath), filename);
FileWriter fw = new FileWriter(saveFile);
BufferedWriter bw = new BufferedWriter(fw);
rowcount = c.getCount();
colcount = c.getColumnCount();
if (rowcount > 0) {
c.moveToFirst();
for (int i = 0; i < colcount; i++) {
if (i != colcount - 1) {
bw.write(c.getColumnName(i) + ",");
} else {
bw.write(c.getColumnName(i));
}
}
bw.newLine();
for (int i = 0; i < rowcount; i++) {
c.moveToPosition(i);
for (int j = 0; j < colcount; j++) {
if (j != colcount - 1)
bw.write(c.getString(j) + ",");
else
bw.write(c.getString(j));
}
bw.newLine();
}
bw.flush();
}
} catch (Exception ex) {
Toast.makeText(MainActivity.context, "Error exporting " + table, Toast.LENGTH_LONG).show();
}
c.close();
}
public void doRestart(Context c) {
final String TAG = (R.string.app_name + "");
try {
//check if the context is given
if (c != null) {
//fetch the packagemanager so we can get the default launch activity
// (you can replace this intent with any other activity if you want
PackageManager pm = c.getPackageManager();
//check if we got the PackageManager
if (pm != null) {
//create the intent with the default start activity for your application
Intent mStartActivity = pm.getLaunchIntentForPackage(
c.getPackageName()
);
if (mStartActivity != null) {
mStartActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//create a pending intent so the application is restarted after System.exit(0) was called.
// We use an AlarmManager to call this intent in 100ms
int mPendingIntentId = 223344;
PendingIntent mPendingIntent = PendingIntent
.getActivity(c, mPendingIntentId, mStartActivity,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) c.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
//kill the application
System.exit(0);
} else {
Log.e(TAG, "Was not able to restart application, mStartActivity null");
}
} else {
Log.e(TAG, "Was not able to restart application, PM null");
}
} else {
Log.e(TAG, "Was not able to restart application, Context null");
}
} catch (Exception ex) {
Log.e(TAG, "Was not able to restart application");
}
}
} |
/**
* Copyright (c) 2004-2022 QOS.ch Sarl (Switzerland)
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package org.slf4j.simple;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.regex.Pattern;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class SimpleLoggerTest {
String A_KEY = SimpleLogger.LOG_KEY_PREFIX + "a";
PrintStream original = System.out;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
PrintStream replacement = new PrintStream(bout);
@Before
public void before() {
System.setProperty(A_KEY, "info");
}
@After
public void after() {
System.clearProperty(A_KEY);
System.clearProperty(SimpleLogger.CACHE_OUTPUT_STREAM_STRING_KEY);
System.clearProperty(SimpleLogger.SHOW_THREAD_ID_KEY);
System.clearProperty(SimpleLogger.SHOW_THREAD_NAME_KEY);
System.setErr(original);
}
@Test
public void emptyLoggerName() {
SimpleLogger simpleLogger = new SimpleLogger("a");
assertEquals("info", simpleLogger.recursivelyComputeLevelString());
}
@Test
public void offLevel() {
System.setProperty(A_KEY, "off");
SimpleLogger.init();
SimpleLogger simpleLogger = new SimpleLogger("a");
assertEquals("off", simpleLogger.recursivelyComputeLevelString());
assertFalse(simpleLogger.isErrorEnabled());
}
@Test
public void loggerNameWithNoDots_WithLevel() {
SimpleLogger.init();
SimpleLogger simpleLogger = new SimpleLogger("a");
assertEquals("info", simpleLogger.recursivelyComputeLevelString());
}
@Test
public void loggerNameWithOneDotShouldInheritFromParent() {
SimpleLogger simpleLogger = new SimpleLogger("a.b");
assertEquals("info", simpleLogger.recursivelyComputeLevelString());
}
@Test
public void loggerNameWithNoDots_WithNoSetLevel() {
SimpleLogger simpleLogger = new SimpleLogger("x");
assertNull(simpleLogger.recursivelyComputeLevelString());
}
@Test
public void loggerNameWithOneDot_NoSetLevel() {
SimpleLogger simpleLogger = new SimpleLogger("x.y");
assertNull(simpleLogger.recursivelyComputeLevelString());
}
@Test
public void checkUseOfLastSystemStreamReference() {
SimpleLogger.init();
SimpleLogger simpleLogger = new SimpleLogger(this.getClass().getName());
System.setErr(replacement);
simpleLogger.info("hello");
replacement.flush();
assertTrue(bout.toString().contains("INFO " + this.getClass().getName() + " - hello"));
}
@Test
public void checkUseOfCachedOutputStream() {
System.setErr(replacement);
System.setProperty(SimpleLogger.CACHE_OUTPUT_STREAM_STRING_KEY, "true");
SimpleLogger.init();
SimpleLogger simpleLogger = new SimpleLogger(this.getClass().getName());
// change reference to original before logging
System.setErr(original);
simpleLogger.info("hello");
replacement.flush();
assertTrue(bout.toString().contains("INFO " + this.getClass().getName() + " - hello"));
}
@Test
public void testTheadIdWithoutThreadName() {
System.setProperty(SimpleLogger.SHOW_THREAD_NAME_KEY, Boolean.FALSE.toString());
String patternStr = "^tid=\\d{1,12} INFO org.slf4j.simple.SimpleLoggerTest - hello";
commonTestThreadId(patternStr);
}
@Test
public void testThreadId() {
String patternStr = "^\\[.*\\] tid=\\d{1,12} INFO org.slf4j.simple.SimpleLoggerTest - hello";
commonTestThreadId(patternStr);
}
private void commonTestThreadId(String patternStr) {
System.setErr(replacement);
System.setProperty(SimpleLogger.SHOW_THREAD_ID_KEY, Boolean.TRUE.toString());
SimpleLogger.init();
SimpleLogger simpleLogger = new SimpleLogger(this.getClass().getName());
simpleLogger.info("hello");
replacement.flush();
String output = bout.toString();
System.out.println(patternStr);
System.out.println(output);
assertTrue(Pattern.compile(patternStr).matcher(output).lookingAt());
}
}
|
/**
* In this problem, we would consider divide the problem into three parts,
* if the length of two strings is same, if the length of string 1 is more than string 2,
* and if the length of string 1 is less than string 2
*/
public class Solution05 {
public static boolean Oneaway(String s1, String s2) {
// remove a character
// and replace a character
if (s1.length() - s2.length() == 1 || s1.length() == s2.length()) {
int diffcount = 0;
for (int i = 0; i < s1.length(); i++) {
if (s2.indexOf(s1.charAt(i)) == -1) {
diffcount++;
}
}
if (diffcount == 1)
return true;
else
return false;
} // insert a character
else if (s2.length() - s1.length() == 1) {
int diffcount = 0;
for (int i = 0; i < s2.length(); i++) {
if (s1.indexOf(s2.charAt(i)) == -1) {
diffcount++;
}
}
if (diffcount == 1)
return true;
else
return false;
}
return false;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String a = "pale";
String b = "bake";
if (Oneaway(a,b))
System.out.println("True");
else
System.out.println("Fasle");
}
}
|
package xyz.bumbing.restapitool.controller;
import java.util.List;
import java.util.Optional;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import xyz.bumbing.restapitool.dto.RestApiDto;
import xyz.bumbing.restapitool.dto.RestApiParameterDto;
import xyz.bumbing.restapitool.repo.RestApiParamRepository;
import xyz.bumbing.restapitool.repo.RestApiRepository;
@Controller
public class RestApiToolController {
@Autowired
RestApiRepository repo;
@Autowired
RestApiParamRepository repop;
@PostMapping("/insert")
public String insert(RestApiDto dto, String search) {
RestApiDto dbdto = repo.findByUrl(dto.getUrl());
if (dbdto == null) {
repo.save(dto);
} else {
dbdto.setClassName(dto.getClassName());
dbdto.setContentType(dto.getContentType());
dbdto.setTemplateUrl(dto.getTemplateUrl());
dbdto.setMethodName(dto.getMethodName());
dbdto.setRequestMethod(dto.getRequestMethod());
repo.save(dbdto);
}
if ("".equals(search)) {
return "redirect:/";
} else {
return "redirect:/?search=" + search;
}
}
@RequestMapping("/delete")
public String delete(int no, String search) {
repo.deleteById(no);
if ("".equals(search)) {
return "redirect:/";
} else {
return "redirect:/?search=" + search;
}
}
@PostMapping("/status")
public String status(int restapino, String status, String search) {
Optional<RestApiDto> dto = repo.findById(restapino);
dto.get().setStatus(status);
repo.save(dto.get());
if ("".equals(search)) {
return "redirect:/";
} else {
return "redirect:/?search=" + search;
}
}
@GetMapping("/")
public String list(Model mo, String search) {
if (search == null || "".equals(search)) {
List<RestApiDto> list = repo.findAllByUrlContainingOrderByUrlAsc("");
mo.addAttribute("list", list);
return "index";
} else {
if (search.charAt(search.length() - 1) == '/') {
search = search.substring(0, search.length() - 1);
}
mo.addAttribute("search", search);
List<RestApiDto> list = repo.findAllByUrlContainingOrderByUrlAsc(search);
mo.addAttribute("list", list);
return "index";
}
}
@Transactional
@RequestMapping("param")
public String param(int restapino, Model mo) {
List<RestApiParameterDto> result = repo.findById(restapino).get().getParameter();
mo.addAttribute("list", result);
return "param";
}
@PostMapping("paramin")
public @ResponseBody void paramin(int restapino, RestApiParameterDto dto, RedirectAttributes redirectAttributes) {
Optional<RestApiDto> dbdto = repo.findById(restapino);
dto.setRestapi(dbdto.get());
repop.save(dto);
redirectAttributes.addAttribute("restapino", restapino);
}
@PostMapping("paramdel")
public @ResponseBody void paramdel(int restapino, int paramno, RedirectAttributes redirectAttributes) {
repop.deleteById(paramno);
redirectAttributes.addAttribute("restapino", restapino);
}
@GetMapping("all")
public @ResponseBody List<RestApiDto> tojson(String search) {
if (search == null) {
return repo.findAllByUrlContainingOrderByUrlAsc("");
} else {
return repo.findAllByUrlContainingOrderByUrlAsc(search);
}
}
}
|
package com.jk.web.security;
import java.util.List;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import com.jk.db.dataaccess.orm.JKObjectDataAccess;
import com.jk.util.JK;
import com.jk.util.exceptions.JKSecurityException;
import com.jk.util.factory.JKFactory;
import com.jk.util.logging.JKLogger;
import com.jk.util.logging.JKLoggerFactory;
public class UserService implements UserDetailsService {
private static final String ROLE_USER = "ROLE_USER";
private static final String ROLE_ADMIN = "ROLE_ADMIN";
static JKLogger logger = JKLoggerFactory.getLogger(UserService.class);
JKObjectDataAccess dataAccess = JKFactory.instance(JKObjectDataAccess.class);
//////////////////////////////////////////////////////////////////////////////
@Override
public User loadUserByUsername(String username) throws UsernameNotFoundException {
User user = dataAccess.findOneByFieldName(User.class, "username", username);
if (user == null) {
if (username.equals("admin")) {
if (Boolean.parseBoolean(System.getProperty("jk.allow-admin", "true"))) {
logger.info("Admin account doesnot exist, create one with admin/admin");
user = createAdminAccount();
}
} else {
throw new UsernameNotFoundException("User doesn't exist");
}
}
return user;
}
//////////////////////////////////////////////////////////////////////////////
private User createAdminAccount() {
String password = new BCryptPasswordEncoder().encode("admin");
dataAccess.insert(new Role(ROLE_ADMIN));
dataAccess.insert(new Role(ROLE_USER));
User user = new User("admin", password, getAllRoles());
dataAccess.insert(user);
return user;
}
//////////////////////////////////////////////////////////////////////////////
public List<Role> getAllRoles() {
return dataAccess.getList(Role.class);
}
//////////////////////////////////////////////////////////////////////////////
public void updateUserPassword(String userName, String password, String newPassword) {
User user = loadUserByUsername(userName);
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
if (bCryptPasswordEncoder.matches(password, user.getPassword())) {
user.setPassword(bCryptPasswordEncoder.encode(newPassword));
dataAccess.update(user);
} else {
throw new JKSecurityException("Current password is not correct");
}
}
public static void main(String[] args) {
// System.out.println(new BCryptPasswordEncoder().encode("admin"));
UserService s=new UserService();
}
}
|
package bg.sofia.uni.fmi.mjt.restaurant.customer;
import bg.sofia.uni.fmi.mjt.restaurant.Meal;
import bg.sofia.uni.fmi.mjt.restaurant.Restaurant;
import java.util.Random;
public abstract class AbstractCustomer extends Thread {
private final Restaurant restaurant;
private static final int MIN_TIME_TO_WAIT = 1;
private static final int MAX_TIME_TO_WAIT = 4;
public AbstractCustomer(Restaurant restaurant) {
this.restaurant = restaurant;
}
@Override
public void run() {
try {
Thread.sleep(new Random().nextInt(MAX_TIME_TO_WAIT) + MIN_TIME_TO_WAIT);
} catch (InterruptedException e) {
throw new RuntimeException();
}
restaurant.submitOrder(new Order(Meal.chooseFromMenu(), this));
}
public abstract boolean hasVipCard();
} |
package MybatisApp.Controller;
import MybatisApp.Service.mybatisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class sqlController {
@Autowired
private mybatisService mybatisService;
@RequestMapping("/mybatisTest")
@ResponseBody
public Integer sqlTest(String name, int age) {
Integer test = mybatisService.test(name, age);
return test;
}
}
|
package com.liu.Class;
import java.io.Serializable;
/**
* Created by LHD on 2018/6/14.
*/
public class vehicle implements Serializable {
private int id;
private int lon;
private int lat;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getLon() {
return lon;
}
public void setLon(int lon) {
this.lon = lon;
}
public int getLat() {
return lat;
}
public void setLat(int lat) {
this.lat = lat;
}
}
|
package com.web.JavaRltd;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.testng.annotations.Test;
public class ArrayLstCls {
@Test()
public void arrayLstMth(){
List<String> arr=new ArrayList<String>();
/*This is how elements should be added to the array list*/
arr.add("vijay");
arr.add("Mohiddin");
arr.add("Shiva");
arr.add("Chandrika");
arr.add("Asha");
arr.add("Sjna");
System.out.println(arr);
arr.remove("Mohiddin");
System.out.println(arr);
/* SORTING */
System.out.println("Sorting");
Collections.sort(arr);
System.out.println("After Sorting");
for(String s:arr){
System.out.println(s);
}
System.out.println("In reverse Order");
Collections.reverse(arr);
for(String ds:arr){
System.out.println(ds);
}
// add(int index, Object o)
arr.add(2,"Mohiddin");
arr.add("Mohiddin");
//remove(Object o)
//remove(int index)
// set(int index, Object o)
//int indexOf(Object o)
//Object get(int index)
System.out.println("***************************"+arr.indexOf("Mohiddin"));
}
}
|
package task11;
import java.util.Scanner;
public class PrimeNumberMethod {
//default value, will change to false if value is found to be divisible by anything other than 1 or itself
//Determines whether or not a number is prime
public boolean isPrime(int inputNum) {
boolean prime = true;
for (int i = 2; i < inputNum && i < inputNum/2; i++ ){
if (inputNum % i == 0) {
prime = false;
}
}
return prime;
}
public static void main(String[] args) {
PrimeNumberMethod newTest = new PrimeNumberMethod();
//Get integer from user
Scanner input = new Scanner(System.in);
int userInput = -1;
while (userInput != 0) {
System.out.println("\nType in an integer to check if it is prime... (Zero/0 to exit): ");
userInput = input.nextInt();
//Determine output string
String outputMessage;
if (newTest.isPrime(userInput) == true) {
outputMessage = "IS a prime number";
} else {
outputMessage = "IS NOT a prime number";
}
System.out.println("The number you entered (" + userInput + ") " + outputMessage);
}
input.close();
}
} |
abstract class Shape {
protected DrawingAPI api;
protected Shape(DrawingAPI api) {
this.api = api;
}
public abstract void draw();
public abstract void resizeByPercentage(double pct);
}
|
package com.google.android.exoplayer2;
import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Looper;
import com.google.android.exoplayer2.f.c;
import com.google.android.exoplayer2.g.e;
import com.google.android.exoplayer2.g.f;
import com.google.android.exoplayer2.g.g;
import com.google.android.exoplayer2.i.t;
import com.google.android.exoplayer2.source.m;
import com.google.android.exoplayer2.w.a;
import com.google.android.exoplayer2.w.b;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArraySet;
final class h implements f {
private final r[] acG;
final g acH;
private final f acI;
private final Handler acJ;
private final i acK;
final CopyOnWriteArraySet<q$a> acL;
private final b acM;
private final a acN;
boolean acO;
boolean acP;
int acQ;
int acR;
int acS;
boolean acT;
w acU;
Object acV;
m acW;
f acX;
p acY;
i.b acZ;
int ada;
int adb;
long adc;
private int repeatMode;
@SuppressLint({"HandlerLeak"})
public h(r[] rVarArr, g gVar, m mVar) {
new StringBuilder("Init ").append(Integer.toHexString(System.identityHashCode(this))).append(" [ExoPlayerLib/2.5.4] [").append(t.aCH).append("]");
com.google.android.exoplayer2.i.a.ap(rVarArr.length > 0);
this.acG = (r[]) com.google.android.exoplayer2.i.a.Z(rVarArr);
this.acH = (g) com.google.android.exoplayer2.i.a.Z(gVar);
this.acP = false;
this.repeatMode = 0;
this.acQ = 1;
this.acL = new CopyOnWriteArraySet();
this.acI = new f(new e[rVarArr.length]);
this.acU = w.aeW;
this.acM = new b();
this.acN = new a();
this.acW = m.asH;
this.acX = this.acI;
this.acY = p.aew;
this.acJ = new 1(this, Looper.myLooper() != null ? Looper.myLooper() : Looper.getMainLooper());
this.acZ = new i.b(0);
this.acK = new i(rVarArr, gVar, mVar, this.acP, this.repeatMode, this.acJ, this.acZ, this);
}
public final void a(q$a q_a) {
this.acL.add(q_a);
}
public final void b(q$a q_a) {
this.acL.remove(q_a);
}
public final int iB() {
return this.acQ;
}
public final void a(com.google.android.exoplayer2.source.f fVar) {
Iterator it;
if (!(this.acU.isEmpty() && this.acV == null)) {
this.acU = w.aeW;
this.acV = null;
it = this.acL.iterator();
while (it.hasNext()) {
it.next();
}
}
if (this.acO) {
this.acO = false;
this.acW = m.asH;
this.acX = this.acI;
this.acH.X(null);
it = this.acL.iterator();
while (it.hasNext()) {
it.next();
}
}
this.acS++;
this.acK.handler.obtainMessage(0, 1, 0, fVar).sendToTarget();
}
public final void af(boolean z) {
if (this.acP != z) {
int i;
this.acP = z;
Handler handler = this.acK.handler;
if (z) {
i = 1;
} else {
i = 0;
}
handler.obtainMessage(1, i, 0).sendToTarget();
Iterator it = this.acL.iterator();
while (it.hasNext()) {
((q$a) it.next()).b(z, this.acQ);
}
}
}
public final boolean iC() {
return this.acP;
}
public final boolean iD() {
return this.acT;
}
public final void seekTo(long j) {
int iE = iE();
if (iE < 0 || (!this.acU.isEmpty() && iE >= this.acU.iU())) {
throw new l(this.acU, iE, j);
}
this.acR++;
this.ada = iE;
if (this.acU.isEmpty()) {
this.adb = 0;
} else {
this.acU.a(iE, this.acM, 0);
long o = j == -9223372036854775807L ? this.acM.afl : b.o(j);
int i = this.acM.afj;
long j2 = this.acM.afm + o;
o = this.acU.a(i, this.acN, false).aet;
while (o != -9223372036854775807L && j2 >= o && i < this.acM.afk) {
j2 -= o;
i++;
o = this.acU.a(i, this.acN, false).aet;
}
this.adb = i;
}
if (j == -9223372036854775807L) {
this.adc = 0;
this.acK.a(this.acU, iE, -9223372036854775807L);
return;
}
this.adc = j;
this.acK.a(this.acU, iE, b.o(j));
Iterator it = this.acL.iterator();
while (it.hasNext()) {
((q$a) it.next()).iS();
}
}
public final void stop() {
this.acK.handler.sendEmptyMessage(5);
}
public final void release() {
new StringBuilder("Release ").append(Integer.toHexString(System.identityHashCode(this))).append(" [ExoPlayerLib/2.5.4] [").append(t.aCH).append("] [").append(j.iO()).append("]");
this.acK.release();
this.acJ.removeCallbacksAndMessages(null);
}
public final void a(c... cVarArr) {
i iVar = this.acK;
if (!iVar.released) {
iVar.adp++;
iVar.handler.obtainMessage(11, cVarArr).sendToTarget();
}
}
public final void b(c... cVarArr) {
this.acK.b(cVarArr);
}
private int iE() {
if (this.acU.isEmpty() || this.acR > 0) {
return this.ada;
}
return this.acU.a(this.acZ.adJ.arU, this.acN, false).adO;
}
public final long getDuration() {
if (this.acU.isEmpty()) {
return -9223372036854775807L;
}
boolean z;
if (!this.acU.isEmpty() && this.acR == 0 && this.acZ.adJ.kF()) {
z = true;
} else {
z = false;
}
if (!z) {
return b.n(this.acU.a(iE(), this.acM, 0).aet);
}
com.google.android.exoplayer2.source.f.b bVar = this.acZ.adJ;
this.acU.a(bVar.arU, this.acN, false);
return b.n(this.acN.ar(bVar.arV, bVar.arW));
}
public final long getCurrentPosition() {
if (this.acU.isEmpty() || this.acR > 0) {
return this.adc;
}
return q(this.acZ.adM);
}
public final long getBufferedPosition() {
if (this.acU.isEmpty() || this.acR > 0) {
return this.adc;
}
return q(this.acZ.adN);
}
public final int getBufferedPercentage() {
if (this.acU.isEmpty()) {
return 0;
}
long bufferedPosition = getBufferedPosition();
long duration = getDuration();
if (bufferedPosition == -9223372036854775807L || duration == -9223372036854775807L) {
return 0;
}
if (duration == 0) {
return 100;
}
return t.u((int) ((bufferedPosition * 100) / duration), 0, 100);
}
private long q(long j) {
long n = b.n(j);
if (this.acZ.adJ.kF()) {
return n;
}
this.acU.a(this.acZ.adJ.arU, this.acN, false);
return n + b.n(this.acN.aeY);
}
}
|
abstract public class Audio implements AudioControl{}
private int volume;
private int minutes;
private String format;
// public String status;
// public int volume;
// public int brightness;
public void Audio(){
this.volume = 0;
this.minutes = 3;
this.format = "MIDI";
}
@Override
void play(){
System.out.println("...Running...");
}
@Override
void lauder(){
String temp = "";
this.volume++;
for(int i = 0; i < this.volume; i++){
temp+= "!";
}
System.out.println(temp);
}
@Override
void weaker(){
String temp = "";
this.volume--;
for(int i = 0; i < this.volume; i++){
temp+= "!";
}
System.out.println(temp);
}
}
|
package fr.atlasmuseum.contribution;
import java.io.File;
import java.io.Serializable;
import org.jdom2.Attribute;
import org.jdom2.Element;
import fr.atlasmuseum.search.SearchActivity;
public class ContributionProperty implements Serializable {
/**
*
*/
private static final long serialVersionUID = 968617293162758396L;
public static enum ContribType
{
text, check, radio, date
}
private String mDbField;
private String mJsonField;
private int mTitle; /* reference to a resource string */
private String mValue;
private String mOriginalValue;
private int mDefaultValue;
private int mInfo; /* reference to a resource string */
private ContribType mType;
private String[] mChoices;
private int mShowViewText;
private int mShowViewToHide;
private Boolean mDumpInXML;
public ContributionProperty(
String dbField,
String jsonField,
int title,
String value,
int defaultValue,
int info,
ContribType type,
String[] choices,
int showViewText,
int showViewToHide,
Boolean dumpInXML
) {
mDbField = dbField;
mJsonField = jsonField;
mTitle = title;
mValue = value;
mOriginalValue = value;
mDefaultValue = defaultValue;
mInfo = info;
mType = type;
mChoices = choices;
mShowViewText = showViewText;
mShowViewToHide = showViewToHide;
mDumpInXML = dumpInXML;
}
public String getDbField() {
return mDbField;
}
public void setDbField(String dbField) {
mDbField = dbField;
}
public String getJsonField() {
return mJsonField;
}
public void setJsonField(String jsonField) {
mJsonField = jsonField;
}
public int getTitle() {
return mTitle;
}
public void setTitle(int title) {
mTitle = title;
}
public String getValue() {
return mValue;
}
public void setValue(String value) {
mValue = value;
mValue = mValue.trim();
if( mValue.equals("?") ) mValue = "";
}
public String getOriginalValue() {
return mOriginalValue;
}
public void setOriginalValue(String originalValue) {
mOriginalValue = originalValue;
mOriginalValue = mOriginalValue.trim();
if( mOriginalValue == "?" ) mOriginalValue = "";
}
public int getDefaultValue() {
return mDefaultValue;
}
public void setDefaultValue(int defaultValue) {
mDefaultValue = defaultValue;
}
public void resetValue(String value) {
setValue( value );
setOriginalValue( value );
}
public int getInfo() {
return mInfo;
}
public void setInfo(int info) {
mInfo = info;
}
public ContribType getType() {
return mType;
}
public void setType(ContribType type) {
mType = type;
}
public Boolean isOfType(ContribType type) {
return (mType == type);
}
public Boolean isText() {
return isOfType(ContribType.text);
}
public Boolean isCheck() {
return isOfType(ContribType.check);
}
public Boolean isRadio() {
return isOfType(ContribType.radio);
}
public Boolean isDate() {
return isOfType(ContribType.date);
}
public String[] getChoices() {
return mChoices;
}
public void setChoices(String[] choices) {
mChoices = choices;
}
public int getShowViewText() {
return mShowViewText;
}
public void setShowViewText(int showViewText) {
mShowViewText = showViewText;
}
public int getShowViewToHide() {
return mShowViewToHide;
}
public void setShowViewToHide(int showViewToHide) {
mShowViewToHide = showViewToHide;
}
public Boolean isModified() {
return (! mOriginalValue.equals(mValue));
}
public void updateFromDb(int index) {
resetValue(SearchActivity.extractDataFromDb(index, mJsonField));
// Check if the image is in cache and update with absolute path
if( mDbField == Contribution.PHOTO ) {
File file = new File(Contribution.getPhotoDir(), mValue);
if( file.exists() ) {
resetValue(file.getAbsolutePath());
}
}
}
public void addXML( Element parent, Boolean original ) {
if( ! mDumpInXML ) {
return;
}
if( mValue.equals("") && !original ) {
return;
}
if( mOriginalValue.equals("") && original ) {
return;
}
String value = original ? mOriginalValue : mValue;
if( mDbField.equals(Contribution.PHOTO) ) {
value = new File(value).getName();
}
Element elem = new Element(mDbField);
Attribute attr = new Attribute(Contribution.VALUE, value);
elem.setAttribute(attr);
parent.addContent(elem);
}
} |
package com.pineapple.mobilecraft.utils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* Created by yihao on 15/6/5.
*/
public abstract class SyncHttpGet<T> extends SyncHTTPCaller<T> {
/**
*
* @param URL
* @param token
*/
public SyncHttpGet(String URL, String token) {
super(URL, token);
}
public T execute()
{
Callable<T> callable = new Callable<T>() {
@Override
public T call() throws Exception {
T result = null;
HttpGet get = new HttpGet(mURL);
get.addHeader("Content-Type", "application/json");
if(null!=mToken){
get.addHeader("Authorization", "Bearer " + mToken);
}
HttpResponse httpResponse;
try {
httpResponse = new DefaultHttpClient().execute(get);
if(httpResponse.getStatusLine().getStatusCode()==200){
String str = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
result = postExcute(str);
}
else{
String str = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
reportError(str);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
result = postExcute(e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
result = postExcute(e.getMessage());
}
return result;
}
};
Future<T> future = Executors.newSingleThreadExecutor().submit(callable);
try {
return future.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void reportError(String message){
try {
JSONObject jsonObject = new JSONObject(message);
throw new ApiException(jsonObject.getInt("code"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
|
/* 1: */ package com.kaldin.test.executetest.action;
/* 2: */
/* 3: */ import com.kaldin.common.util.RandomUtil;
/* 4: */ import com.kaldin.common.util.StateInfo;
/* 5: */ import com.kaldin.reports.dao.ChartReportDAO;
/* 6: */ import com.kaldin.test.executetest.common.UtilTest;
/* 7: */ import com.kaldin.test.executetest.dao.TemporaryExamDAO;
/* 8: */ import com.kaldin.test.executetest.dao.impl.ExecuteTestImplementor;
/* 9: */ import com.kaldin.test.executetest.dto.QuestAnsDTO;
/* 10: */ import com.kaldin.test.executetest.dto.QuestionStatusDTO;
/* 11: */ import com.kaldin.test.executetest.dto.TemporaryExamQuestionAnswersDTO;
/* 12: */ import com.kaldin.test.scheduletest.dao.ExamDAO;
/* 13: */ import com.kaldin.test.settest.dao.impl.QuestionPaperImplementor;
/* 14: */ import com.kaldin.test.settest.dto.QuestionPaperDTO;
/* 15: */ import com.kaldin.test.settest.dto.TopicQuestionDTO;
/* 16: */ import com.kaldin.user.register.dto.CandidateDTO;
/* 17: */ import java.util.ArrayList;
/* 18: */ import java.util.HashMap;
/* 19: */ import java.util.Iterator;
/* 20: */ import java.util.List;
import java.util.Map;
/* 21: */ import java.util.Map.Entry;
/* 22: */ import java.util.Set;
/* 23: */ import javax.servlet.http.HttpServletRequest;
/* 24: */ import javax.servlet.http.HttpServletResponse;
/* 25: */ import javax.servlet.http.HttpSession;
/* 26: */ import org.apache.struts.action.Action;
/* 27: */ import org.apache.struts.action.ActionForm;
/* 28: */ import org.apache.struts.action.ActionForward;
/* 29: */ import org.apache.struts.action.ActionMapping;
/* 30: */
/* 31: */ public class execteTestAction
/* 32: */ extends Action
/* 33: */ {
/* 34: */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
/* 35: */ throws Exception
/* 36: */ {
/* 37: 54 */ String str = "success";
/* 38: 55 */ ArrayList<QuestionStatusDTO> qstatusList = new ArrayList();
/* 39: */
/* 40: 57 */ int qsAttempted = 0;
/* 41: 58 */ int qsMarkedforReview = 0;
/* 42: 59 */ int qsSkipped = 0;
/* 43: 60 */ int companyid = ((Integer)request.getSession().getAttribute("CompanyId")).intValue();
/* 44: 61 */ ChartReportDAO chartReportDAO = new ChartReportDAO();
/* 45: 63 */ if (request.getSession().getAttribute("testStarted") == null)
/* 46: */ {
/* 47: 64 */ UtilTest utTest = new UtilTest();
/* 48: 65 */ utTest.initialize();
/* 49: */
/* 50: 67 */ ExecuteTestImplementor extImpl = new ExecuteTestImplementor();
/* 51: 68 */ String testid = "" + request.getParameter("testid");
/* 52: 69 */ if ((testid.equals(null)) || ("".equals(testid)) || (testid == "") || (testid == null) || ("null".equals(testid))) {
/* 53: 70 */ testid = (String)request.getAttribute("testid");
/* 54: */ }
/* 55: 72 */ String examid = "" + request.getParameter("examid");
/* 56: 73 */ if ((examid.equals(null)) || ("".equals(examid)) || (examid == "") || (examid == null) || ("null".equals(examid))) {
/* 57: 74 */ examid = (String)request.getAttribute("examid");
/* 58: */ }
/* 59: 76 */ request.getSession().setAttribute("TestId", testid);
/* 60: 77 */ request.getSession().setAttribute("ExamId", examid);
/* 61: 78 */ QuestionPaperImplementor qpImplemontor = new QuestionPaperImplementor();
/* 62: 79 */ QuestionPaperDTO questpaperDTO = qpImplemontor.getTest(testid);
/* 63: */
/* 64: 81 */ String strTest = "";
/* 65: 82 */ if (questpaperDTO.getTestName() != null) {
/* 66: 83 */ strTest = questpaperDTO.getTestName();
/* 67: */ }
/* 68: 84 */ ExamDAO examDAO = new ExamDAO();
/* 69: 85 */ int questionSequence = examDAO.getQuestionSequenceFromExamId(examid);
/* 70: */
/* 71: 87 */ request.getSession().setAttribute("TestName", strTest);
/* 72: */
/* 73: 89 */ List<?> TestTpcList = extImpl.getTestTopic(testid);
/* 74: */
/* 75: */
/* 76: 92 */ int time = extImpl.getTime(testid) * 60;
/* 77: 93 */ QuestionPaperDTO qpDTO = extImpl.getTestInfo(testid);
/* 78: */
/* 79: */
/* 80: 96 */ request.getSession().setAttribute("TotalTime", Integer.valueOf(time));
/* 81: 97 */ long cureentMilis = System.currentTimeMillis();
/* 82: 98 */ long cureentSeconds = cureentMilis / 1000L;
/* 83: */
/* 84:100 */ request.getSession(false).setAttribute("StartSeconds", Long.valueOf(cureentSeconds));
/* 85:101 */ request.getSession(false).setAttribute("questionTime", Long.valueOf(cureentSeconds));
/* 86: */
/* 87:103 */ CandidateDTO candidateDTO = (CandidateDTO)request.getSession().getAttribute("User");
/* 88:104 */ int intExamid = Integer.parseInt(examid);
/* 89:105 */ TemporaryExamDAO temporaryExamDAO = new TemporaryExamDAO();
/* 90:106 */ int tempInfoid = temporaryExamDAO.getTemporaryExamInfoid(candidateDTO.getUserId(), testid, intExamid);
/* 91:107 */ boolean insertTempExam = true;
/* 92: */
/* 93:109 */ request.setAttribute("TestTime", Integer.valueOf(time - temporaryExamDAO.getUsedExamTime(tempInfoid)));
/* 94:112 */ if (tempInfoid == 0)
/* 95: */ {
/* 96: */ int[] questids;
/* 97: */ try
/* 98: */ {
/* 99:116 */ questids = (int[])extImpl.getQuestionIds(testid);
/* 100: */ }
/* 101: */ catch (Exception e)
/* 102: */ {
/* 103:118 */ questids = null;
/* 104: */ }
/* 105:121 */ if ((questids != null) && (questids.length != 0))
/* 106: */ {
/* 107:124 */ RandomUtil ru = new RandomUtil();
/* 108: */ int[] randomquestids;
/* 109: */ //int[] randomquestids;
/* 110:126 */ if (questionSequence == 1) {
/* 111:127 */ randomquestids = ru.getRandomQuestionIds(questids, questids.length);
/* 112: */ } else {
/* 113:129 */ randomquestids = questids;
/* 114: */ }
/* 115:131 */ for (int i = 0; i < randomquestids.length; i++)
/* 116: */ {
/* 117:132 */ QuestAnsDTO dtoObj = extImpl.getQuestionById(randomquestids[i]);
/* 118:133 */ utTest.listQuestions.add(dtoObj);
/* 119:134 */ QuestionStatusDTO qstatus = new QuestionStatusDTO();
/* 120:135 */ qstatus.setIndex(i + 1);
/* 121:136 */ qstatus.setQuestionid(dtoObj.getQuestionid());
/* 122:137 */ if (qstatus.getIndex() == 1) {
/* 123:138 */ qstatus.setStatus(3);
/* 124: */ } else {
/* 125:140 */ qstatus.setStatus(0);
/* 126: */ }
/* 127:141 */ qstatusList.add(qstatus);
/* 128: */ }
/* 129: */ }
/* 130: */ else
/* 131: */ {
/* 132:144 */ Iterator<?> itr = TestTpcList.iterator();
/* 133:145 */ int qc = 1;
/* 134:146 */ while (itr.hasNext())
/* 135: */ {
/* 136:147 */ TopicQuestionDTO tsttopic = (TopicQuestionDTO)itr.next();
/* 137:148 */ int countofquest = tsttopic.getQuestioncount();
/* 138:151 */ if (tsttopic.getTopicid() == 0) {
/* 139:152 */ questids = (int[])extImpl.getQuestionIdsbySubject(tsttopic.getSubjectid(), tsttopic.getLevelid());
/* 140: */ } else {
/* 141:154 */ questids = (int[])extImpl.getQuestionIds(tsttopic.getTopicid(), tsttopic.getLevelid());
/* 142: */ }
/* 143:158 */ RandomUtil ru = new RandomUtil();
/* 144: */ int[] randomquestids;
/* 145: */ //int[] randomquestids;
/* 146:160 */ if (questionSequence == 1) {
/* 147:161 */ randomquestids = ru.getRandomQuestionIds(questids, questids.length);
/* 148: */ } else {
/* 149:163 */ randomquestids = questids;
/* 150: */ }
/* 151:167 */ int i = 0;
/* 152:168 */ if ((i < countofquest) && (i < randomquestids.length))
/* 153: */ {
/* 154:169 */ if (tsttopic.getTopicid() == 0)
/* 155: */ {
/* 156:170 */ QuestAnsDTO dtoObj = extImpl.getQuestionbySubject(tsttopic.getSubjectid(), randomquestids[i]);
/* 157:171 */ utTest.listQuestions.add(dtoObj);
/* 158:172 */ QuestionStatusDTO qstatus = new QuestionStatusDTO();
/* 159:173 */ qstatus.setIndex(qc++);
/* 160:174 */ qstatus.setQuestionid(dtoObj.getQuestionid());
/* 161:175 */ if (qstatus.getIndex() == 1) {
/* 162:176 */ qstatus.setStatus(3);
/* 163: */ } else {
/* 164:178 */ qstatus.setStatus(0);
/* 165: */ }
/* 166:179 */ qstatusList.add(qstatus);
/* 167: */ }
/* 168: */ else
/* 169: */ {
/* 170:181 */ QuestAnsDTO dtoObj = extImpl.getQuestion(tsttopic.getTopicid(), randomquestids[i]);
/* 171:182 */ utTest.listQuestions.add(dtoObj);
/* 172:183 */ QuestionStatusDTO qstatus = new QuestionStatusDTO();
/* 173:184 */ qstatus.setIndex(qc++);
/* 174:185 */ qstatus.setQuestionid(dtoObj.getQuestionid());
/* 175:186 */ if (qstatus.getIndex() == 1) {
/* 176:187 */ qstatus.setStatus(3);
/* 177: */ } else {
/* 178:189 */ qstatus.setStatus(0);
/* 179: */ }
/* 180:190 */ qstatusList.add(qstatus);
/* 181: */ }
/* 182:168 */ i++;
/* 183: */ }
/* 184: */ }
/* 185: */ }
/* 186:196 */ chartReportDAO.insertUpdateExamCount(companyid, 0);
/* 187: */ }
/* 188: */ else
/* 189: */ {
/* 190:198 */ ArrayList<TemporaryExamQuestionAnswersDTO> tempExamQADTO = temporaryExamDAO.getTempExamQuestions(tempInfoid);
/* 191:199 */ for (int count = 0; count < tempExamQADTO.size(); count++)
/* 192: */ {
/* 193:200 */ QuestAnsDTO dtoObj = temporaryExamDAO.getQuestion(((TemporaryExamQuestionAnswersDTO)tempExamQADTO.get(count)).getQuestionid(), ((TemporaryExamQuestionAnswersDTO)tempExamQADTO.get(count)).getAnswer());
/* 194:201 */ utTest.listQuestions.add(dtoObj);
/* 195:202 */ QuestionStatusDTO qstatus = new QuestionStatusDTO();
/* 196:203 */ qstatus.setIndex(count + 1);
/* 197:204 */ qstatus.setQuestionid(dtoObj.getQuestionid());
/* 198:205 */ qstatus.setStatus(((TemporaryExamQuestionAnswersDTO)tempExamQADTO.get(count)).getStatus());
/* 199:206 */ qstatusList.add(qstatus);
/* 200: */ }
/* 201:208 */ insertTempExam = false;
/* 202: */
/* 203:210 */ str = "preview";
/* 204:211 */ request.setAttribute("firstpreview", "firstpreview");
/* 205: */
/* 206:213 */ chartReportDAO.insertUpdateResumeExamCount(companyid, 0);
/* 207: */ }
/* 208:215 */ utTest.questionIndexCount = 0;
/* 209:216 */ int indexPos = utTest.questionIndexCount + 1;
/* 210:217 */ request.setAttribute("index", Integer.valueOf(indexPos));
/* 211: */
/* 212:219 */ request.setAttribute("prevstatus", "start");
/* 213:220 */ Iterator<QuestAnsDTO> iterator = utTest.listQuestions.iterator();
/* 214: */
/* 215:222 */ utTest.idArray = new int[utTest.listQuestions.size()];
/* 216:223 */ while (iterator.hasNext())
/* 217: */ {
/* 218:224 */ QuestAnsDTO obj = (QuestAnsDTO)iterator.next();
/* 219:225 */ String key = String.valueOf(obj.getQuestionid());
/* 220:226 */ utTest.mapAns.put(key, obj);
/* 221: */ }
/* 222:229 */ if (utTest.mapAns.size() == 1) {
/* 223:230 */ request.setAttribute("nextstatus", "finish");
/* 224: */ } else {
/* 225:232 */ request.setAttribute("nextstatus", "next");
/* 226: */ }
/* 227:235 */ Set<Map.Entry<Object, Object>> ansSet = utTest.mapAns.entrySet();
/* 228: */
/* 229:237 */ int index = 0;
/* 230:238 */ for (Map.Entry tstans : ansSet)
/* 231: */ {
/* 232:239 */ QuestAnsDTO obj = (QuestAnsDTO)tstans.getValue();
/* 233:240 */ utTest.idArray[index] = obj.getQuestionid();
/* 234:241 */ index++;
/* 235: */ }
/* 236:243 */ if ((utTest != null) && (utTest.idArray.length < 1))
/* 237: */ {
/* 238:244 */ str = "failure";
/* 239: */ }
/* 240: */ else
/* 241: */ {
/* 242:246 */ String poskey = String.valueOf(utTest.idArray[utTest.questionIndexCount]);
/* 243: */
/* 244: */
/* 245:249 */ QuestAnsDTO questAns = (QuestAnsDTO)utTest.mapAns.get(poskey);
/* 246:252 */ if (questAns.getShowAsMCQ() == 1) {
/* 247:253 */ request.setAttribute("MultiSelect", "MultiSelect");
/* 248: */ }
/* 249:256 */ if (questAns.getShowAsMCQ() == 3) {
/* 250:257 */ request.setAttribute("Subjective", "Yes");
/* 251: */ }
/* 252:260 */ request.setAttribute("Question", utTest.mapAns.get(poskey));
/* 253:261 */ if (insertTempExam) {
/* 254:262 */ questAns.setGivenAnswer("");
/* 255: */ } else {
/* 256:264 */ questAns.setGivenAnswer(questAns.getGivenAnswer());
/* 257: */ }
/* 258:266 */ questAns.setView(true);
/* 259: */
/* 260:268 */ StateInfo stateInfo = new StateInfo();
/* 261:269 */ request.getSession(false).setAttribute("utilTestObj", utTest);
/* 262:270 */ stateInfo.setStatus(request);
/* 263:271 */ if ((!str.equals("preview")) && (str != "preview")) {
/* 264:274 */ str = "success";
/* 265: */ }
/* 266:275 */ request.getSession(false).setAttribute("testStarted", "true");
/* 267: */ }
/* 268:280 */ if (insertTempExam)
/* 269: */ {
/* 270:282 */ Set<Map.Entry<Object, Object>> questansSet = utTest.mapAns.entrySet();
/* 271:283 */ temporaryExamDAO.insertTemporaryExamInfo(candidateDTO.getUserId(), testid, intExamid, "" + cureentSeconds);
/* 272:284 */ tempInfoid = temporaryExamDAO.getTemporaryExamInfoid(candidateDTO.getUserId(), testid, intExamid);
/* 273:285 */ temporaryExamDAO.insertTemporaryQuestionAnswers(tempInfoid, questansSet);
/* 274: */ }
/* 275:287 */ request.getSession(false).setAttribute("tempInfoid", Integer.valueOf(tempInfoid));
/* 276: */ }
/* 277: */ else
/* 278: */ {
/* 279:291 */ long cureentMilis = System.currentTimeMillis();
/* 280:292 */ long cureentSeconds = cureentMilis / 1000L;
/* 281:293 */ String strStartSecond = request.getSession().getAttribute("StartSeconds").toString();
/* 282: */
/* 283:295 */ long ct = Long.parseLong(strStartSecond);
/* 284: */
/* 285:297 */ int timeseconds = (int)(cureentSeconds - ct);
/* 286:298 */ int time = Integer.parseInt(request.getSession().getAttribute("TotalTime").toString());
/* 287: */
/* 288:300 */ time -= timeseconds;
/* 289:301 */ request.setAttribute("TestTime", Integer.valueOf(time));
/* 290: */
/* 291:303 */ UtilTest utilTest = (UtilTest)request.getSession(false).getAttribute("utilTestObj");
/* 292: */
/* 293:305 */ String poskey = String.valueOf(utilTest.idArray[utilTest.questionIndexCount]);
/* 294: */
/* 295: */
/* 296:308 */ QuestAnsDTO questAns = (QuestAnsDTO)utilTest.mapAns.get(poskey);
/* 297:309 */ if (questAns.getShowAsMCQ() == 1) {
/* 298:311 */ request.setAttribute("MultiSelect", "MultiSelect");
/* 299: */ }
/* 300:313 */ int index = utilTest.questionIndexCount + 1;
/* 301:314 */ request.setAttribute("index", Integer.valueOf(index));
/* 302: */
/* 303:316 */ request.setAttribute("nextstatus", "next");
/* 304:317 */ request.setAttribute("prevstatus", "start");
/* 305:318 */ request.setAttribute("Question", utilTest.mapAns.get(poskey));
/* 306:319 */ questAns.setGivenAnswer("");
/* 307:320 */ StateInfo stateInfo = new StateInfo();
/* 308:321 */ request.getSession(false).setAttribute("utilTestObj", utilTest);
/* 309:322 */ stateInfo.setStatus(request);
/* 310: */
/* 311:324 */ int tempInfoid = Integer.parseInt(request.getSession().getAttribute("tempInfoid").toString());
/* 312:325 */ TemporaryExamDAO temporaryExamDAO = new TemporaryExamDAO();
/* 313:326 */ ArrayList<TemporaryExamQuestionAnswersDTO> tempExamQADTO = temporaryExamDAO.getTempExamQuestions(tempInfoid);
/* 314:327 */ for (int count = 0; count < tempExamQADTO.size(); count++)
/* 315: */ {
/* 316:328 */ QuestAnsDTO dtoObj = temporaryExamDAO.getQuestion(((TemporaryExamQuestionAnswersDTO)tempExamQADTO.get(count)).getQuestionid(), ((TemporaryExamQuestionAnswersDTO)tempExamQADTO.get(count)).getAnswer());
/* 317:329 */ QuestionStatusDTO qstatus = new QuestionStatusDTO();
/* 318:330 */ qstatus.setIndex(count + 1);
/* 319:331 */ qstatus.setQuestionid(dtoObj.getQuestionid());
/* 320:332 */ qstatus.setStatus(((TemporaryExamQuestionAnswersDTO)tempExamQADTO.get(count)).getStatus());
/* 321:333 */ if (((TemporaryExamQuestionAnswersDTO)tempExamQADTO.get(count)).getStatus() == 2) {
/* 322:334 */ qsAttempted++;
/* 323:335 */ } else if (((TemporaryExamQuestionAnswersDTO)tempExamQADTO.get(count)).getStatus() == 1) {
/* 324:336 */ qsSkipped++;
/* 325:337 */ } else if (((TemporaryExamQuestionAnswersDTO)tempExamQADTO.get(count)).getStatus() == 4) {
/* 326:338 */ qsMarkedforReview++;
/* 327: */ }
/* 328:340 */ qstatusList.add(qstatus);
/* 329: */ }
/* 330: */ }
/* 331:344 */ request.getSession(false).setAttribute("qstatusList", qstatusList);
/* 332:345 */ request.setAttribute("qsa", Integer.valueOf(qsAttempted));
/* 333:346 */ request.setAttribute("qss", Integer.valueOf(qsSkipped));
/* 334:347 */ request.setAttribute("qsm", Integer.valueOf(qsMarkedforReview));
/* 335:348 */ return mapping.findForward(str);
/* 336: */ }
/* 337: */ }
/* Location: C:\Java Work\Workspace\Kaldin\WebContent\WEB-INF\classes\com\kaldin\kaldin_java.zip
* Qualified Name: kaldin.test.executetest.action.execteTestAction
* JD-Core Version: 0.7.0.1
*/ |
package com.stark.design23.flyweight;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Stark on 2018/1/26.
* 画笔工厂,用以获取画笔
* 如果没有就进行创建保存,如果有就直接返回
*/
public class PencilFactory {
private static Map<String, Pencil> cache = new HashMap<>();
public static Pencil getPencil(String color) {
if (cache.containsKey(color)) {
return cache.get(color);
} else {
Pencil pencil = new PencilImp(color);
cache.put(color, pencil);
return pencil;
}
}
}
|
package twilight.bgfx.font;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import twilight.bgfx.BGFXException;
import twilight.bgfx.font.TextBuffer.GlyphType;
import twilight.bgfx.font.TextBuffer.UsageType;
import twilight.bgfx.util.ResourceUtil;
/**
*
* @author tmccrary
*
*/
public class FontManager {
/** */
private long fontManagerPtr;
/** */
private long textBufferManagerPtr;
/** */
private int count;
/** */
private FontFace defaultFontFace;
/** */
private Font defaultFont;
/** */
private float defaultFontSize = 21f;
/**
*
* @param textureSizeSize
*/
public FontManager(int textureSizeSize) {
this.count = textureSizeSize;
nInit(textureSizeSize);
try {
InputStream resourceAsStream = FontManager.class.getClassLoader().getResourceAsStream("l33tlabs/twilight/bgfx/font/DroidSans.ttf");
if (resourceAsStream == null) {
throw new Exception("Couldn't locate default font.");
}
byte[] byteArray = ResourceUtil.inputStreamToByteArray(resourceAsStream);
ByteBuffer allocateDirect = ByteBuffer.allocateDirect(byteArray.length);
allocateDirect.put(byteArray);
allocateDirect.flip();
defaultFontFace = createTTF(allocateDirect);
defaultFont = createFontByPixelSize(defaultFontFace, defaultFontSize);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* @param buffer
* @return
*/
public FontFace createTTF(ByteBuffer buffer) {
if (buffer == null) {
throw new BGFXException("Cannot create font face from null ByteBuffer.");
}
if (!buffer.isDirect()) {
throw new BGFXException("All ByteBuffer instances pased to BFGX must be direct.");
}
long ttfHandle = nCreateTTF(buffer, buffer.limit());
if (ttfHandle == -1) {
throw new BGFXException("Error creating font face.");
}
return new FontFace(ttfHandle);
}
/**
*
* @param fontDef
* @param height
* @return
*/
public Font createFontByPixelSize(FontFace fontFace, float height) {
long fontDefPtr = nCreateFontByPixelSize(fontFace.truetypeHandle, height);
if (fontDefPtr == -1) {
throw new BGFXException("Error creating font.");
}
return new Font(fontDefPtr);
}
/**
*
* @return
*/
public TextBuffer createTextBuffer(GlyphType glyphType, UsageType usage) {
if (glyphType == null) {
throw new BGFXException("GlyphType cannot be null.");
}
if (usage == null) {
throw new BGFXException("UsageType cannot be null");
}
long handle = nCreateTextBuffer(glyphType.getValue(), usage.getValue());
if (handle == -1) {
throw new BGFXException("Error creating text buffer.");
}
return new TextBuffer(this, handle, glyphType, usage);
}
/**
*
* @param buffer
*/
public void destroyTextBuffer(TextBuffer buffer) {
nDestroyTextBuffer(buffer.handle);
}
/**
*
* @param buffer
* @param fontInstance
* @param text
*/
public void updateTextBuffer(TextBuffer buffer, Font fontInstance, String text, float x, float y) {
nUpdateTextBuffer(buffer.handle, fontInstance.handle, text, x, y);
}
/**
*
* @param buffer
* @param x
* @param y
*/
public void draw(TextBuffer buffer, float x, float y) {
nDrawTextBuffer(buffer.handle, x, y);
}
/**
*
* @param buffer
* @return
*/
public float getWidth(TextBuffer buffer) {
return nGetTextBufferRect(buffer.handle);
}
/**
*
* @return
*/
public Font getDefaultFont() {
return defaultFont;
}
/**
*
* @return
*/
public FontFace getDefaultFontFace() {
return defaultFontFace;
}
/**
* Native Methods
*/
public native void nInit(int count);
private native float nGetTextBufferRect(long handle);
private native void nDrawTextBuffer(long textBuffer, float x, float y);
public native long nCreateTTF(ByteBuffer buffer, int size);
public native long nCreateFontByPixelSize(long fontHandle, float height);
public native long nCreateTextBuffer(long glyphType, long usage);
public native void nUpdateTextBuffer(long bufferHandle, long font, String text, float x, float y);
private native void nDestroyTextBuffer(long ptr);
}
|
package interfaceTest;
public class Carinterface implements Car {
@Override
public void speed(int sp) {
// TODO Auto-generated method stub
}
@Override
public void wheel(String wh) {
// TODO Auto-generated method stub
}
@Override
public void key(String k) {
// TODO Auto-generated method stub
}
}
|
/*
* 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 co.id.mii.clientapp.controllers;
import co.id.mii.clientapp.models.Employee;
import co.id.mii.clientapp.models.dto.ResponseModel;
import co.id.mii.clientapp.services.DepartmentService;
import co.id.mii.clientapp.services.EmployeeService;
import co.id.mii.clientapp.services.JobService;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
/**
*
* @author hp
*/
@Controller
@RequestMapping("/employee")
@PreAuthorize("isAuthenticated()")
public class EmployeeController {
private JobService jobService;
private EmployeeService employeeService;
private DepartmentService departmentService;
@Autowired
public EmployeeController(EmployeeService employeeService,
JobService jobService, DepartmentService departmentService) {
this.employeeService = employeeService;
this.jobService = jobService;
this.departmentService = departmentService;
}
@GetMapping
@PreAuthorize("hasAuthority('READ_DATA')")
public String getAll(Employee employee, Model model) {
model.addAttribute("jobs", jobService.getAll());
model.addAttribute("departments", departmentService.getAll());
model.addAttribute("employees", employeeService.getAll());
return "employee/index";
}
@GetMapping("/getAll")
public @ResponseBody List<Employee> getAll(){
return employeeService.getAll();
}
@GetMapping("/add")
@PreAuthorize("hasAuthority('READ_DATA')")
public String create(Employee employee, Model model) {
model.addAttribute("jobs", jobService.getAll());
model.addAttribute("departments", departmentService.getAll());
model.addAttribute("employees", employeeService.getAll());
return "employee/add-form";
}
@PostMapping("/add")
@PreAuthorize("hasAuthority('CREATE_DATA')")
public @ResponseBody ResponseModel<Employee> add(@RequestBody Employee employee) {
// model.addAttribute("jobs", jobService.getAll());
// model.addAttribute("departments", departmentService.getAll());
// model.addAttribute("employees", employeeService.getAll());
return employeeService.create(employee);
}
// @PostMapping("/add")
// @PreAuthorize("hasAuthority('CREATE_DATA')")
// public String create(@Valid Employee employee,
// BindingResult result, RedirectAttributes redirect, Model model) {
//
// if (result.hasErrors()) {
// model.addAttribute("jobs", jobService.getAll());
// model.addAttribute("departments", departmentService.getAll());
// model.addAttribute("employees", employeeService.getAll());
// return "employee/add-form";
// }
//
//// employee
// employeeService.create(employee);
//
// redirect.addFlashAttribute("message", "Employee created");
//
// return "redirect:/employee";
// }
@GetMapping("/edit/{id}")
@PreAuthorize("hasAuthority('EDIT_DATA')")
public String update(@PathVariable Integer id, Model model) {
model.addAttribute("jobs", jobService.getAll());
model.addAttribute("departments", departmentService.getAll());
model.addAttribute("employees", employeeService.getAll());
model.addAttribute("employee", employeeService.getById(id));
return "employee/update-form";
}
@PutMapping("/{id}")
@PreAuthorize("hasAuthority('EDIT_DATA')")
public @ResponseBody ResponseModel<Employee> update(@PathVariable Integer id, @RequestBody Employee employee) {
return employeeService.update(id, employee);
}
// @PutMapping("/{id}")
// @PreAuthorize("hasAuthority('EDIT_DATA')")
// public String update(@PathVariable Integer id, @Valid Employee employee,
// BindingResult result, RedirectAttributes redirect, Model model) {
//
// System.out.println(employee.toString());
// if (result.hasErrors()) {
// model.addAttribute("jobs", jobService.getAll());
// model.addAttribute("departments", departmentService.getAll());
// model.addAttribute("employees", employeeService.getAll());
// return "employee/update-form";
// }
//
// employeeService.update(id, employee);
//
// redirect.addFlashAttribute("message", "Employee updated");
//
// return "redirect:/employee";
// }
@DeleteMapping("/{id}")
@PreAuthorize("hasAuthority('DELETE_DATA')")
public @ResponseBody ResponseModel<Employee> delete(@PathVariable Integer id) {
return employeeService.delete(id);
}
// @DeleteMapping("/{id}")
// @PreAuthorize("hasAuthority('DELETE_DATA')")
// public String delete(@PathVariable Integer id) {
// employeeService.delete(id);
// return "redirect:/employee";
// }
}
|
package com.seemoreinteractive.seemoreinteractive.Model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import android.util.Log;
public class ProductModel implements Serializable {
private static final long serialVersionUID = 1L;
List<UserProduct> product;
public ProductModel() {
product = new ArrayList<UserProduct>();
}
public void add(UserProduct userProduct) {
product.add(userProduct);
}
public UserProduct getUserProduct(long id) {
for (UserProduct userProduct : product) {
if (userProduct.getId() == id)
return userProduct;
}
return null;
}
public UserProduct getUserProductById(int id) {
for (UserProduct userProduct : product) {
if (userProduct.getProductId() == id)
return userProduct;
}
return null;
}
public UserProduct getProductByClientId(int clientId) {
for (UserProduct userProduct : product) {
if (userProduct.getClientId() != 0
&& userProduct.getClientId() == clientId)
return userProduct;
}
return null;
}
public List<UserProduct> getRelatedProduct(String pdids) {
List<UserProduct> list = new ArrayList<UserProduct>();
Collections.sort(product, new UserProduct.OrderByPId());
String [] arrPdid = pdids.split(",");
for (UserProduct userProduct : product) {
for(int i=0;i<arrPdid.length;i++){
if(arrPdid[i] !=""){
if (userProduct.getProductId() != 0 && userProduct.getProductId() == Integer.parseInt(arrPdid[i]))
list.add(userProduct);
}
}
}
return list;
}
public int size() {
return product.size();
}
public List<UserProduct> list() {
return product;
}
public void remove(int id) {
UserProduct userProduct = getUserProduct(id);
if (userProduct != null)
product.remove(userProduct);
return;
}
public void removeAll() {
product.clear();
}
public void mergeWith(ProductModel newProduct) {
List<UserProduct> oldProduct = new ArrayList<UserProduct>(product);
/*for (Visual oldVisual : oldVisuals) {
newVisuals.add(oldVisual);
}*/
oldProduct.addAll(newProduct.list());
//visuals = newVisuals.list();
product = oldProduct;
}
public void removeItem(UserProduct userproduct) {
if (userproduct != null)
product.remove(userproduct);
return;
}
}
|
package com.shop.dao;
import java.util.Date;
import java.util.List;
import com.shop.model.Category;
public interface CategoryDao extends BaseDao<Category> {
// 查询一级分类的总的个数
public Integer countCategory();
// 分页查找所有用户
public List<Category> findAll(Integer page);
public List<Category> findAll();
public Category findOne(Integer cid);
//查询优惠时间
public Date queryPrivilegeTime(Integer cid);
}
|
package pms.dao;
public interface MailDao {
}
|
package java_XML;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.SAXException;
public class create_xml_parsexml {
public ArrayList<Book> parserXML(){
// 先获取一个SAXParserFactory的实例.
SAXParserFactory factory = SAXParserFactory.newInstance();
// 通过factory湖区SAXParser实例.
SAXParserHardler handler = null;
try {
SAXParser parser = factory.newSAXParser();
// 创建SAXParserHandler对象.
handler = new SAXParserHardler();
parser.parse("books.xml", handler);
} catch (ParserConfigurationException | SAXException e) {
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return handler.getBooks_list();
}
public void creatXML(){
ArrayList<Book> booklist = parserXML();
// 生成xml
// 生成一个TransformerFactory类的对象.
SAXTransformerFactory tff = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
try {
// 通过SAXTransformerFactory对象创建一个TransformerHandler对象.
TransformerHandler handler = tff.newTransformerHandler();
// 通过handler对象创建一个Transfomer对象.
Transformer tr = handler.getTransformer();
// 通过Transformer对象生成的xml文件进行设置
// 设置xml的编码
tr.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
// 设置xml的是否换行.
tr.setOutputProperty(OutputKeys.INDENT,"yes");
// 创建Result对象.
File f = new File("src/res/newbooks.xml");
if(!f.exists()){
f.createNewFile();
}
try {
// 创建Result对象并且使其与handler关联.
Result result = new StreamResult(new FileOutputStream(f));
handler.setResult(result);
// 利用handler对象进行xml文件内容的编辑.
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (TransformerConfigurationException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
}
}
|
package com.mdb;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.util.stream.Collectors;
import static com.mdb.ServerMain.workdir;
import static com.mdb.Utilities.readFileToStringHun;
import static org.apache.commons.io.FileUtils.readFileToString;
import static org.apache.commons.io.FileUtils.writeStringToFile;
@Slf4j
public class HandlerV2Ping implements HttpHandler {
public void handle(HttpExchange h) throws IOException {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = h.getRequestBody();
byte[] buf = new byte[4096];
for (int n = in.read(buf); n > 0; n = in.read(buf)) {
out.write(buf, 0, n);
}
RandomAccessFile f;
f = new RandomAccessFile("v2ping-post", "rw");
f.write(out.toByteArray());
f.close();
writeStringToFile(new File("v2ping-head"),
h.getRequestHeaders()
.entrySet()
.stream()
.map(
e -> e.getKey() + ": " + e.getValue().stream().collect(Collectors.joining(" , ")))
.collect(Collectors.joining("\n"))
);
String q = h.getRequestURI().getQuery();
JSONObject j = new JSONObject();
switch (q) {
case "1":
log.info("String constant from java code:");
dump("Kódszám");
break;
case "2":
log.info("String constant from cikk.inf file, readFileToString:");
dump(readFileToString(new File(workdir + "/" + "cikk.inf")).split("\n")[31].substring(22, 29));
break;
case "3":
log.info("String constant from java code to JSON and toString:");
j.put("key", "Kódszám");
dump(j.toString());
break;
case "4":
log.info("String constant from cikk.inf file to JSON and toString:");
j.put("key",
readFileToString(new File(workdir + "/" + "cikk.inf")).split("\n")[31].substring(22, 29));
dump(j.toString());
break;
case "5":
log.info("String constant from cikk.inf file, BufferedReader:");
BufferedReader reader = new BufferedReader(new FileReader(workdir + "/" + "cikk.inf"));
String line = "";
int n = 0;
while ((line = reader.readLine()) != null) {
if (n == 31) {
break;
}
n++;
}
reader.close();
dump(line.substring(22, 29));
break;
case "6":
log.info("String constant from cikk.inf file, readFileToStringHun:");
dump(readFileToStringHun(workdir + "/" + "cikk.inf").split("\n")[31].substring(22, 29));
break;
case "7":
log.info("String constant from chr file, readFileToStringHun:");
dump(readFileToStringHun(workdir + "/" + "chr"));
break;
}
} catch (Exception e) {
e.printStackTrace();
}
StringBuilder out = new StringBuilder();
out.append("{\n"
+ " \"server\": \"fbz_server\",\n"
+ " \"charset\": \"áÁéÉíÍóÓöÖőŐúÚüÜűŰ\"\n"
+ "}\n");
// RandomAccessFile f = new RandomAccessFile("devdata/chr", "r");
// int l = (int) f.length();
// byte[] data = new byte[l + 1];
// f.read(data, 0, l);
// f.close();
// ByteBuffer bb = ByteBuffer.wrap(data);
// bb.order(ByteOrder.LITTLE_ENDIAN);
// String o = IntStream.range(0, 18)
// .mapToObj(i -> "case " +
// (
// bb.getChar(i * 2) + 0
// ) +
// ": c='" +
// out.toString().substring(42, 60).substring(i, i + 1) + "';break;"
// )
// .collect(Collectors.joining("\n"));
// System.out.println(o);
new ResponseSender(h, out, 200);
}
private void dump(String s) throws UnsupportedEncodingException {
log.info(s);
byte[] b = s.getBytes();
for (int i = 0; i < b.length; i++) {
log.info(String.format("b %3d %3d", i, b[i] & 0xFF));
}
byte[] u = s.getBytes("UTF-16");
for (int i = 0; i < u.length; i++) {
log.info(String.format("u %3d %3d", i, u[i] & 0xFF));
}
}
}
|
package com.ybh.front.model;
public class HostProductlist_AGN {
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column FreeHost_HostProductlist_AGN.id
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
private Integer id;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column FreeHost_HostProductlist_AGN.Hosttype
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
private String hosttype;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column FreeHost_HostProductlist_AGN.usermoney
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
private Double usermoney;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column FreeHost_HostProductlist_AGN.ServerlistID
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
private Integer serverlistid;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column FreeHost_HostProductlist_AGN.FreeHostlimt
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
private Integer freehostlimt;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column FreeHost_HostProductlist_AGN.MaxConnections
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
private Long maxconnections;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column FreeHost_HostProductlist_AGN.cpulimt
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
private Integer cpulimt;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column FreeHost_HostProductlist_AGN.timetake
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
private Integer timetake;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column FreeHost_HostProductlist_AGN.spacelimt
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
private Integer spacelimt;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column FreeHost_HostProductlist_AGN.AppPoolnum
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
private Integer apppoolnum;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column FreeHost_HostProductlist_AGN.html
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
private String html;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column FreeHost_HostProductlist_AGN.asp
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
private String asp;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column FreeHost_HostProductlist_AGN.aspx
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
private String aspx;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column FreeHost_HostProductlist_AGN.php
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
private String php;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column FreeHost_HostProductlist_AGN.cgi
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
private String cgi;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column FreeHost_HostProductlist_AGN.jsp
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
private String jsp;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column FreeHost_HostProductlist_AGN.cantest
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
private String cantest;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column FreeHost_HostProductlist_AGN.agent1
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
private String agent1;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column FreeHost_HostProductlist_AGN.agent2
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
private String agent2;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column FreeHost_HostProductlist_AGN.id
*
* @return the value of FreeHost_HostProductlist_AGN.id
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public Integer getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column FreeHost_HostProductlist_AGN.id
*
* @param id the value for FreeHost_HostProductlist_AGN.id
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public void setId(Integer id) {
this.id = id;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column FreeHost_HostProductlist_AGN.Hosttype
*
* @return the value of FreeHost_HostProductlist_AGN.Hosttype
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public String getHosttype() {
return hosttype;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column FreeHost_HostProductlist_AGN.Hosttype
*
* @param hosttype the value for FreeHost_HostProductlist_AGN.Hosttype
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public void setHosttype(String hosttype) {
this.hosttype = hosttype == null ? null : hosttype.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column FreeHost_HostProductlist_AGN.usermoney
*
* @return the value of FreeHost_HostProductlist_AGN.usermoney
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public Double getUsermoney() {
return usermoney;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column FreeHost_HostProductlist_AGN.usermoney
*
* @param usermoney the value for FreeHost_HostProductlist_AGN.usermoney
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public void setUsermoney(Double usermoney) {
this.usermoney = usermoney;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column FreeHost_HostProductlist_AGN.ServerlistID
*
* @return the value of FreeHost_HostProductlist_AGN.ServerlistID
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public Integer getServerlistid() {
return serverlistid;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column FreeHost_HostProductlist_AGN.ServerlistID
*
* @param serverlistid the value for FreeHost_HostProductlist_AGN.ServerlistID
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public void setServerlistid(Integer serverlistid) {
this.serverlistid = serverlistid;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column FreeHost_HostProductlist_AGN.FreeHostlimt
*
* @return the value of FreeHost_HostProductlist_AGN.FreeHostlimt
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public Integer getFreehostlimt() {
return freehostlimt;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column FreeHost_HostProductlist_AGN.FreeHostlimt
*
* @param freehostlimt the value for FreeHost_HostProductlist_AGN.FreeHostlimt
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public void setFreehostlimt(Integer freehostlimt) {
this.freehostlimt = freehostlimt;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column FreeHost_HostProductlist_AGN.MaxConnections
*
* @return the value of FreeHost_HostProductlist_AGN.MaxConnections
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public Long getMaxconnections() {
return maxconnections;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column FreeHost_HostProductlist_AGN.MaxConnections
*
* @param maxconnections the value for FreeHost_HostProductlist_AGN.MaxConnections
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public void setMaxconnections(Long maxconnections) {
this.maxconnections = maxconnections;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column FreeHost_HostProductlist_AGN.cpulimt
*
* @return the value of FreeHost_HostProductlist_AGN.cpulimt
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public Integer getCpulimt() {
return cpulimt;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column FreeHost_HostProductlist_AGN.cpulimt
*
* @param cpulimt the value for FreeHost_HostProductlist_AGN.cpulimt
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public void setCpulimt(Integer cpulimt) {
this.cpulimt = cpulimt;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column FreeHost_HostProductlist_AGN.timetake
*
* @return the value of FreeHost_HostProductlist_AGN.timetake
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public Integer getTimetake() {
return timetake;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column FreeHost_HostProductlist_AGN.timetake
*
* @param timetake the value for FreeHost_HostProductlist_AGN.timetake
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public void setTimetake(Integer timetake) {
this.timetake = timetake;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column FreeHost_HostProductlist_AGN.spacelimt
*
* @return the value of FreeHost_HostProductlist_AGN.spacelimt
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public Integer getSpacelimt() {
return spacelimt;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column FreeHost_HostProductlist_AGN.spacelimt
*
* @param spacelimt the value for FreeHost_HostProductlist_AGN.spacelimt
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public void setSpacelimt(Integer spacelimt) {
this.spacelimt = spacelimt;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column FreeHost_HostProductlist_AGN.AppPoolnum
*
* @return the value of FreeHost_HostProductlist_AGN.AppPoolnum
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public Integer getApppoolnum() {
return apppoolnum;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column FreeHost_HostProductlist_AGN.AppPoolnum
*
* @param apppoolnum the value for FreeHost_HostProductlist_AGN.AppPoolnum
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public void setApppoolnum(Integer apppoolnum) {
this.apppoolnum = apppoolnum;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column FreeHost_HostProductlist_AGN.html
*
* @return the value of FreeHost_HostProductlist_AGN.html
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public String getHtml() {
return html;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column FreeHost_HostProductlist_AGN.html
*
* @param html the value for FreeHost_HostProductlist_AGN.html
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public void setHtml(String html) {
this.html = html == null ? null : html.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column FreeHost_HostProductlist_AGN.asp
*
* @return the value of FreeHost_HostProductlist_AGN.asp
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public String getAsp() {
return asp;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column FreeHost_HostProductlist_AGN.asp
*
* @param asp the value for FreeHost_HostProductlist_AGN.asp
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public void setAsp(String asp) {
this.asp = asp == null ? null : asp.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column FreeHost_HostProductlist_AGN.aspx
*
* @return the value of FreeHost_HostProductlist_AGN.aspx
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public String getAspx() {
return aspx;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column FreeHost_HostProductlist_AGN.aspx
*
* @param aspx the value for FreeHost_HostProductlist_AGN.aspx
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public void setAspx(String aspx) {
this.aspx = aspx == null ? null : aspx.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column FreeHost_HostProductlist_AGN.php
*
* @return the value of FreeHost_HostProductlist_AGN.php
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public String getPhp() {
return php;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column FreeHost_HostProductlist_AGN.php
*
* @param php the value for FreeHost_HostProductlist_AGN.php
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public void setPhp(String php) {
this.php = php == null ? null : php.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column FreeHost_HostProductlist_AGN.cgi
*
* @return the value of FreeHost_HostProductlist_AGN.cgi
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public String getCgi() {
return cgi;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column FreeHost_HostProductlist_AGN.cgi
*
* @param cgi the value for FreeHost_HostProductlist_AGN.cgi
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public void setCgi(String cgi) {
this.cgi = cgi == null ? null : cgi.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column FreeHost_HostProductlist_AGN.jsp
*
* @return the value of FreeHost_HostProductlist_AGN.jsp
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public String getJsp() {
return jsp;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column FreeHost_HostProductlist_AGN.jsp
*
* @param jsp the value for FreeHost_HostProductlist_AGN.jsp
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public void setJsp(String jsp) {
this.jsp = jsp == null ? null : jsp.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column FreeHost_HostProductlist_AGN.cantest
*
* @return the value of FreeHost_HostProductlist_AGN.cantest
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public String getCantest() {
return cantest;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column FreeHost_HostProductlist_AGN.cantest
*
* @param cantest the value for FreeHost_HostProductlist_AGN.cantest
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public void setCantest(String cantest) {
this.cantest = cantest == null ? null : cantest.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column FreeHost_HostProductlist_AGN.agent1
*
* @return the value of FreeHost_HostProductlist_AGN.agent1
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public String getAgent1() {
return agent1;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column FreeHost_HostProductlist_AGN.agent1
*
* @param agent1 the value for FreeHost_HostProductlist_AGN.agent1
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public void setAgent1(String agent1) {
this.agent1 = agent1 == null ? null : agent1.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column FreeHost_HostProductlist_AGN.agent2
*
* @return the value of FreeHost_HostProductlist_AGN.agent2
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public String getAgent2() {
return agent2;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column FreeHost_HostProductlist_AGN.agent2
*
* @param agent2 the value for FreeHost_HostProductlist_AGN.agent2
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public void setAgent2(String agent2) {
this.agent2 = agent2 == null ? null : agent2.trim();
}
} |
package com.tw.auth.domain.authority;
import com.tw.auth.domain.AbstractAuditEntity;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.validator.constraints.Email;
import javax.persistence.*;
import java.util.List;
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper=false)
@Entity
@Table(name = "AuthUsers")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class AuthUsers extends AbstractAuditEntity {
@Id @Column(name = "UserId")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer userId;
@Column(name = "UserAccount")
private String userAccount;
@Column(name = "DisplayName")
private String displayName;
@Column(name = "Email") @Email
private String email;
@Column(name = "SourceType")
private String sourceType = "SDB";
@Column(name = "DeviceToken")
private String deviceToken;
@Column(name = "DeviceName")
private String deviceName;
@Column(name = "Memo")
private String memo;
@Column(name = "IsActive")
private String isActive = "Y";
@Transient
@JsonSerialize
private Integer roleMasterId;
@Transient
@JsonSerialize
private String roleName;
@Transient
@JsonSerialize
private List<Ap> authorities;
public AuthUsers(String userAccount, String displayName, String email, String memo) {
this.userAccount = userAccount;
this.displayName = displayName;
this.email = email;
this.memo = memo;
}
@Data
@AllArgsConstructor
public static class Ap {
private Integer applicationId;
private String applicationName;
private List<AItem> items;
@Data
@AllArgsConstructor
public static class AItem {
private Integer aItemId;
private String aItemCode;
private String aItemName;
private String aItemValue;
}
}
}
|
package com.example.v3.utils;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* 我的工具类
*/
public class MyUtils {
/**
* 创建数组
*
* @param values
* @param <T>
* @return
*/
public static <T> T[] of(T... values) {
return values;
}
/**
* 二维数组转Map
*
* @param vals
* @param <T>
* @return
*/
public static <T> Map<String, T> asMap(T[][] vals) {
Map<String, T> mp = new LinkedHashMap<String, T>();
if (vals != null && vals.length > 0) {
for (int i = 0; i < vals.length; i++) {
T[] objects = vals[i];
if (objects != null && objects.length > 0) {
T k = objects[0];
T v = objects.length == 2 ? objects[1] : null;
mp.put(k.toString(), v);
}
}
}
return mp;
}
public static void main(String[] args) {
Integer[] v1 = MyUtils.of(1, 2, 3);
String[] v2 = MyUtils.of("a", "b", "c");
System.out.println("Integer类型数组:" + Arrays.toString(v1));
System.out.println("String类型数组:" + Arrays.toString(v2));
Map<String, Object> map = MyUtils.asMap(new Object[][]{
{"a", "value_a"},
{"b", 1}
});
System.out.println("二维数组转map:" + map.toString());
}
}
|
package ca.mohawk.jdw.shifty.clientapi.event.mapper;
/*
I, Josh Maione, 000320309 certify that this material is my original work.
No other person's work has been used without due acknowledgement.
I have not made my work available to anyone else.
Module: client-api
Developed By: Josh Maione (000320309)
*/
import ca.mohawk.jdw.shifty.clientapi.ShiftyClient;
import ca.mohawk.jdw.shifty.clientapi.event.EventMapper;
import ca.mohawk.jdw.shifty.clientapi.event.type.AddMyActivityLogEvent;
import ca.mohawk.jdw.shifty.clientapi.net.Packet;
import ca.mohawk.jdw.shifty.clientapi.utils.NetUtils;
public class AddMyActivityLogEventMapper implements EventMapper<AddMyActivityLogEvent> {
@Override
public AddMyActivityLogEvent map(final ShiftyClient client, final Packet pkt){
return new AddMyActivityLogEvent(
NetUtils.deserializeActivityLog(
client.employee(),
pkt
)
);
}
}
|
package com.sm.anapp;
import java.util.ArrayList;
import java.util.List;
public class AddressArray {
private List list;
public AddressArray() {
super();
list = new ArrayList();
}
public void addToList(AddressEntity addressEntity) {
list.add(addressEntity);
}
public List getList() {
return list;
}
@Override
public String toString() {
return "AddressArray " + list.toString();
}
}
|
package com.monits.findbugs.effectivejava;
import java.util.Set;
import javax.annotation.Nonnull;
import org.apache.bcel.classfile.Method;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.BytecodeScanningDetector;
import edu.umd.cs.findbugs.ba.Hierarchy2;
import edu.umd.cs.findbugs.ba.XMethod;
import edu.umd.cs.findbugs.classfile.ClassDescriptor;
import edu.umd.cs.findbugs.classfile.DescriptorFactory;
public class EqualsOverrideDetector extends BytecodeScanningDetector {
private final static ClassDescriptor OBJECT_CLASS_DESCRIPTOR
= DescriptorFactory.createClassDescriptor(Object.class);
private final BugReporter bugReporter;
public EqualsOverrideDetector(@Nonnull final BugReporter bugReporter) {
this.bugReporter = bugReporter;
}
@Override
public void visitMethod(@Nonnull final Method method) {
// Is this equals?
if ("equals".equals(method.getName()) && "(Ljava/lang/Object;)Z".equals(method.getSignature())) {
final Set<XMethod> superMethods = Hierarchy2.findSuperMethods(getXMethod());
for (final XMethod xm : superMethods) {
final ClassDescriptor classDescriptor = xm.getClassDescriptor();
if (!OBJECT_CLASS_DESCRIPTOR.equals(classDescriptor)) {
final BugInstance bug = new BugInstance(this, "DONT_OVERRIDE_EQUALS", NORMAL_PRIORITY)
.addClass(this)
.addClass(classDescriptor);
bugReporter.reportBug(bug);
return;
}
}
}
}
}
|
package designpattern.observer;
import java.util.Observable;
import java.util.Observer;
/**
* Created by john(Zhewei) on 2016/12/10.
* 这是观察者
*/
public class ObserverImpl implements Observer {
private String name;
public ObserverImpl(String name) {
this.name = name;
}
/**
* 当观察的对象发生改变时,收到通知,并作出对应的操作
*/
@Override
public void update(Observable o, Object arg) {
System.out.println("收到了"+o.getClass().getName()+"内容是:" + arg.toString());
}
}
|
package com.classcheck.panel;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import com.change_vision.jude.api.inf.AstahAPI;
import com.change_vision.jude.api.inf.project.ProjectAccessor;
import com.change_vision.jude.api.inf.project.ProjectEvent;
import com.change_vision.jude.api.inf.project.ProjectEventListener;
import com.change_vision.jude.api.inf.ui.IPluginExtraTabView;
import com.change_vision.jude.api.inf.ui.ISelectionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class CompileTabPanel extends JPanel implements IPluginExtraTabView, ProjectEventListener {
private static final long serialVersionUID = 1L;
private JPanel bottonPane;
private JButton folderBtn;
private JButton javacBtn;
private JButton runBtn;
private Label maintextLabel;
private TextField mainFile;
private JScrollPane folderPane;
private JScrollPane msgPane;
private JTextArea folderTextArea;
private JTextArea msgTextArea;
private File compileFolder;
public CompileTabPanel() {
initComponents();
addEvent();
addProjectEventListener();
}
private void addProjectEventListener() {
try {
AstahAPI api = AstahAPI.getAstahAPI();
ProjectAccessor projectAccessor = api.getProjectAccessor();
projectAccessor.addProjectEventListener(this);
} catch (ClassNotFoundException e) {
e.getMessage();
}
}
private void initComponents() {
setLayout(new BorderLayout());
javacBtn = new JButton("javac");
folderBtn = new JButton("folder");
maintextLabel = new Label("mainClass :");
mainFile = new TextField(20);
runBtn = new JButton("run");
bottonPane = new JPanel();
bottonPane.add(folderBtn);
bottonPane.add(javacBtn);
bottonPane.add(maintextLabel);
bottonPane.add(mainFile);
bottonPane.add(runBtn);
folderTextArea = new JTextArea(10,10);
folderPane = new JScrollPane(folderTextArea);
msgTextArea = new JTextArea(10,10);
msgPane = new JScrollPane(msgTextArea);
add(bottonPane, BorderLayout.NORTH);
add(folderPane, BorderLayout.WEST);
add(msgPane,BorderLayout.CENTER);
setVisible(true);
}
private void addEvent() {
folderBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
selectFolder(getComponent());
}
});
javacBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
List<String> command = new ArrayList<String>();
ProcessBuilder pb = new ProcessBuilder();
BufferedReader br = null;
StringBuilder sb;
command.add("javac");
command.add(compileFolder.toString()+"/"+mainFile.getText());
command.add("-d");
command.add(compileFolder.toString());
pb.command(command);
try {
Process process = pb.start();
process.waitFor();
br = new BufferedReader(new InputStreamReader(process.getInputStream()));
sb = new StringBuilder();
for(String line = br.readLine(); line != null ; line = br.readLine()){
sb.append(line+"\n");
}
msgTextArea.setText(sb.toString());
if (br!=null) {
br.close();
}
} catch (IOException e1) {
msgTextArea.setText(e1.getMessage());
} catch (InterruptedException e1) {
msgTextArea.setText(e1.getMessage());
}
}
});
runBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
List<String> command = new ArrayList<String>();
ProcessBuilder pb = new ProcessBuilder();
String str = mainFile.getText();
BufferedReader br = null;
StringBuilder sb;
command.add("java");
command.add("-cp");
command.add(compileFolder.toString()+"/");
command.add(str.substring(0, str.lastIndexOf(".java")));
pb.command(command);
try {
Process process = pb.start();
process.waitFor();
br = new BufferedReader(new InputStreamReader(process.getInputStream()));
sb = new StringBuilder();
for(String line = br.readLine(); line != null ; line = br.readLine()){
sb.append(line+"\n");
}
msgTextArea.setText(sb.toString());
if (br!=null) {
br.close();
}
} catch (IOException e1) {
msgTextArea.setText(e1.getMessage());
} catch (InterruptedException e1) {
msgTextArea.setText(e1.getMessage());
}
}
});
}
/**
* @param comp
*/
private void selectFolder(Component comp) {
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = chooser.showOpenDialog(comp);
if(returnVal == JFileChooser.APPROVE_OPTION) {
compileFolder = chooser.getSelectedFile();
folderTextArea.setText(compileFolder.toString());
}
}
@Override
public void projectChanged(ProjectEvent e) {
}
@Override
public void projectClosed(ProjectEvent e) {
}
@Override
public void projectOpened(ProjectEvent e) {
}
@Override
public void addSelectionListener(ISelectionListener listener) {
}
@Override
public Component getComponent() {
return this;
}
@Override
public String getDescription() {
return "Show CompileTabView here";
}
@Override
public String getTitle() {
return "CompileTabView";
}
public void activated() {
}
public void deactivated() {
}
} |
public enum ReaderType {
BYTE_BUFFER, SEEKABLE_BYTE_CHANNEL, SCANNER
}
|
package com.smxknife.java2.nio.channel;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
/**
* @author smxknife
* 2020/10/2
*/
public class _13_FileChannel_FileLock_1 {
public static void main(String[] args) {
// 获取此通道的文件给定区域上的锁定
// 在可以锁定该区域之前、已关闭此通道之前、或已中断调用线程之前,将阻塞此方法调用
// 在此方法调用期间,如果另一个线程关闭了此通道,则抛出AsynchronousCloseException
// 如果在等待获取锁定的同时中断了调用线程,则将状态设置为中断并抛出FileLockInterruptionException异常
// 如果调用此方法是已设置调用方的中断状态,则立即抛出该异常,不更改线程的调用状态
// 由position和size参数所指定的区域无须包含在实际的底层文件中,设置无须与文件重叠。
// 锁定区域的大小是固定的;如果某个已锁定区域最初包含整个文件,并且文件因扩大而超出了该区域,则该锁定不覆盖此文件的新部分。如果期望文件大小扩容并且要求锁定整个文件,则应锁定position从零开始,size传入大于或等于预计文件的最大值
// 零参数的lock方法只是锁定大小为Long.MAX_VALUE的区域
// 文件锁要么是独占的,要么是共享的
// 共享锁定可以阻止其他并发运行的程序获取重叠的独占锁定,但允许该程序偶去重叠的共享锁定
// 独占锁定则阻止其他程序获取共享锁定或者独占锁定的重叠部分
// 某些操作系统不支持共享锁定,自动对共享锁定转换为独占锁定的请求,可以通过调用所得的锁定对象的isShared()方法来测试新获取的锁定是共享的还是独占的
// 文件锁定是以整个Java虚拟机来保持的。但是不适用于控制同一虚拟机内多个线程对文件的访问
// 验证FileLock lock(long position, long size, boolean shared)是同步的
// lockTest1();
// 验证AsynchronousCloseException异常的发生
// lockTest2();
// 验证FileLockInterruptionException异常发生,线程在获取锁时被interrupt
// lockTest3();
// 验证FileLockInterruptionException异常发生,两个线程间; 需要FileLock_2的lockTest4配合
// 这里注意,必须使用两个main,也就是两个进程,如果在同一个进程中启动两个线程,那么抛出的异常是OverlappingFileinterruptionException
// 其实fileLock是进程锁,不适用多线程,但是对于多线程会抛出上面的异常,测试见lockTest5
// lockTest4();
// 验证同一个进程,不同线程调用interrupt,即lockTest4的注意测试
// lockTest5();
// 验证共享锁自己不能写(出现异常)
// TODO 很遗憾这里竟然可写,测试系统是Mac
lockTest6();
// 验证共享锁别人不能写(出现异常),同样需要借助FileLock_2的同名方法来测试
// TODO 很遗憾同样不会抛出异常,测试系统是Mac和Centos7,抱歉当前家里没有windows测试环境
// lockTest7();
// 验证共享锁自己能读
// lockTest8();
// 验证共享锁别人能读(这里就不验证了,由于当前的mac和linux系统写都可写,读基本不成问题)
// 验证独占锁自己能写
// TODO mac是没有问题的,windows没有测试
// lockTest9();
// 验证独占锁别人不能写,这里需要借助FileLock_2的同名方法来测试
// TODO 很遗憾,mac测试时无效,其他系统也可以写
// lockTest10();
// 验证独占锁自己能读(这里不做验证)
// 验证独占锁别人能读(TODO 这里也不做验证,但是如果有windows系统最好验证一下)
// 验证lock方法position和size的含义
// 这一部分是为了说明未锁定的部分可以写,但是已锁定的部分是不可以写的
// TODO 但是在目前的mac测试中,测试不通过,无论是否在锁定区域都是可以写
// lockTest11();
// 验证提前锁定,目的就是设置的position比现有的文件大小还大,那么在写入的时候,可以写入部分数据,当到达限制后,才被锁定
// TODO 不做试验了,mac无法处理
// TODO ... 想办法借用了一台windows电脑,安装jdk8的环境进行测试,竟然上面的条件都ok,那么严重说明FileLock与操作系统有关
// TODO ... 所以在实际使用过程中,要绝对严谨的使用,尽量减少使用,避免因为操作系统的差异而导致这种bug
// 验证独占锁与独占锁是互斥的,(考虑到mac系统的特殊性,只有这个通过测试,其他的共享锁非互斥才具有可测试性)
// 经过测试,即使是在mac系统上也能测试通过
// lockTest12();
// 验证独占锁与共享锁是互斥的,借助同名函数
// lockTest13();
// 验证共享锁与共享锁是非互斥,借助同名函数
// lockTest14();
// 验证共享锁与独占锁是互斥的,借助同名函数
// lockTest15();
// tryLock与lock的区别就是,前者非阻塞,后者阻塞,借助于同名函数
// 对应2里面的同名函数,采用tryLock后没有像lock一样阻塞,而是运行完,只是返回的FileLock为null
// fileTryLockTest16();
// ********************************************************************
// ********************************************************************
// ********************************************************************
/**
* 概念:
* FileLock表示文件区域锁定的标记,每次通过lock或tryLock方法获取文件上的锁定时,就会创建一个FileLock对象
* 有效性:
* lock或tryLock成功获取FileLock对象开始
* release调用、关闭通道、终止虚拟机任一操作之前
* 上面两个阶段之间,FileLock都是有效的,可以通过FileLock对象的isValid来测试锁定特性
* 特点:
* 单个虚拟机上的锁定是不可以重叠的,可以通过overlap来测试是否重叠锁定
* FileLock对象只有是否有效是随着时间变化的,其他都是不变的,包括保持锁定的文件通道、锁定类型、锁定区域和大小
* 文件锁定是以整个虚拟机来保持的。但不适用于同一个虚拟机内多个线程对文件的访问
* 多个并发线程可以安全的使用FileLock对象
* FileLock类具有平台依赖性,此文件锁定API直接映射到底层的操作系统的本机锁定机制。因为程序无论用何种语言编写的,某个文件上所保持的锁定对所有访问该文件的程序是可见的
*/
// FileLock API测试
// fileLockTest17();
// overlaps测试
// fileLockTest18();
}
private static void fileLockTest18() {
try(FileChannel channel = new RandomAccessFile(_13_FileChannel_FileLock_1.class.getClassLoader()
.getResource("channel/_13_FileChannel_fileLock").getPath(), "rw").getChannel()) {
FileLock fileLock = channel.lock(1, 10, true);
System.out.println(fileLock.size());
System.out.println(fileLock.overlaps(1, 10));
System.out.println(fileLock.overlaps(8, 13));
System.out.println(fileLock.overlaps(11, 12));
System.out.println("------------");
System.out.println(fileLock.overlaps(0, 1));
System.out.println(fileLock.overlaps(1, 1));
System.out.println(fileLock.overlaps(10, 1));
System.out.println(fileLock.overlaps(11, 1));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void fileLockTest17() {
try(FileChannel channel = new RandomAccessFile(_13_FileChannel_FileLock_1.class.getClassLoader()
.getResource("channel/_13_FileChannel_fileLock").getPath(), "rw").getChannel()) {
System.out.printf("channel hashCode = %s\r\n", channel.hashCode());
FileLock fileLock = channel.lock(1, 10, true);
System.out.printf("A lock position = %s, size = %s, isValid = %s, isShared = %s, channel hashCode = %s, acquiredBy hashCode = %s\r\n",
fileLock.position(), fileLock.size(), fileLock.isValid(), fileLock.isShared(), fileLock.channel().hashCode(), fileLock.acquiredBy().hashCode());
fileLock.release();
fileLock = channel.lock(1, 10, false);
System.out.printf("B lock position = %s, size = %s, isValid = %s, isShared = %s, channel hashCode = %s, acquiredBy hashCode = %s\r\n",
fileLock.position(), fileLock.size(), fileLock.isValid(), fileLock.isShared(), fileLock.channel().hashCode(), fileLock.acquiredBy().hashCode());
fileLock.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void fileTryLockTest16() {
try(FileChannel channel = new RandomAccessFile(_13_FileChannel_FileLock_1.class.getClassLoader()
.getResource("channel/_13_FileChannel_fileLock").getPath(), "rw").getChannel()) {
System.out.println("1 before tryLock");
FileLock fileLock = channel.tryLock(0, Integer.MAX_VALUE, false);
System.out.println("1 after tryLock fileLock = " + fileLock);
TimeUnit.HOURS.sleep(1);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void lockTest15() {
try(FileChannel channel = new RandomAccessFile(_13_FileChannel_FileLock_1.class.getClassLoader()
.getResource("channel/_13_FileChannel_fileLock").getPath(), "rw").getChannel()) {
channel.lock(0, Integer.MAX_VALUE, true);
TimeUnit.HOURS.sleep(1);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void lockTest14() {
try(FileChannel channel = new RandomAccessFile(_13_FileChannel_FileLock_1.class.getClassLoader()
.getResource("channel/_13_FileChannel_fileLock").getPath(), "rw").getChannel()) {
channel.lock(0, Integer.MAX_VALUE, true);
TimeUnit.HOURS.sleep(1);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void lockTest13() {
try(FileChannel channel = new RandomAccessFile(_13_FileChannel_FileLock_1.class.getClassLoader()
.getResource("channel/_13_FileChannel_fileLock").getPath(), "rw").getChannel()) {
channel.lock(0, Integer.MAX_VALUE, false);
TimeUnit.HOURS.sleep(1);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void lockTest12() {
try(FileChannel channel = new RandomAccessFile(_13_FileChannel_FileLock_1.class.getClassLoader()
.getResource("channel/_13_FileChannel_fileLock").getPath(), "rw").getChannel()) {
channel.lock(0, Integer.MAX_VALUE, false);
TimeUnit.HOURS.sleep(1);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void lockTest11() {
try(FileChannel channel = new RandomAccessFile(_13_FileChannel_FileLock_1.class.getClassLoader()
.getResource("channel/_13_FileChannel_fileLock").getPath(), "rw").getChannel()) {
System.out.println("A channel position = " + channel.position());
channel.lock(3, 2, true); // 这里最好使用true,虽然对于mac没区别
System.out.println("B channel position = " + channel.position());
channel.write(ByteBuffer.wrap("0".getBytes())); // index=0;
System.out.println("C channel position = " + channel.position());
channel.write(ByteBuffer.wrap("1".getBytes())); // index=1;
System.out.println("D channel position = " + channel.position());
channel.write(ByteBuffer.wrap("2".getBytes())); // index=2;
System.out.println("E channel position = " + channel.position());
channel.write(ByteBuffer.wrap("3".getBytes())); // index=3;
System.out.println("F channel position = " + channel.position());
channel.write(ByteBuffer.wrap("4".getBytes())); // index=4;
System.out.println("G channel position = " + channel.position());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void lockTest10() {
try(FileChannel channel = new RandomAccessFile(_13_FileChannel_FileLock_1.class.getClassLoader()
.getResource("channel/_13_FileChannel_fileLock").getPath(), "rw").getChannel()) {
channel.lock(1, 2, false);
TimeUnit.HOURS.sleep(1);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void lockTest9() {
try(FileChannel channel = new RandomAccessFile(_13_FileChannel_FileLock_1.class.getClassLoader()
.getResource("channel/_13_FileChannel_fileLock").getPath(), "rw").getChannel()) {
channel.lock(1, 2, false);
channel.write(ByteBuffer.wrap("123456".getBytes()));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void lockTest8() {
try(FileChannel channel = new RandomAccessFile(_13_FileChannel_FileLock_1.class.getClassLoader()
.getResource("channel/_13_FileChannel_fileLock").getPath(), "rw").getChannel()) {
channel.lock(1, 2, true);
ByteBuffer byteBuffer = ByteBuffer.allocate(10);
channel.read(byteBuffer);
byteBuffer.rewind();
System.out.println(new String(byteBuffer.array()));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void lockTest7() {
try(FileChannel channel = new RandomAccessFile(_13_FileChannel_FileLock_1.class.getClassLoader()
.getResource("channel/_13_FileChannel_fileLock").getPath(), "rw").getChannel()) {
channel.lock(1, 2, true);
TimeUnit.HOURS.sleep(1);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void lockTest6() {
try(FileChannel channel = new RandomAccessFile(_13_FileChannel_FileLock_1.class.getClassLoader()
.getResource("channel/_13_FileChannel_fileLock").getPath(), "rw").getChannel()) {
channel.lock(0, 2, true);
System.out.printf("channel position %s, size %s", channel.position(), channel.size());
channel.write(ByteBuffer.wrap("hello".getBytes()));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void lockTest5() {
try(FileChannel channel = new FileOutputStream(_13_FileChannel_FileLock_1.class.getClassLoader()
.getResource("channel/_13_FileChannel_fileLock").getPath()).getChannel()) {
Thread lockThread1 = new Thread(() -> {
try {
System.out.println("lockThread1 before lock");
channel.lock(1, 2, false);
System.out.println("lockThread1 has get lock");
TimeUnit.SECONDS.sleep(3); // 这里是为了让线程多待一会,防止线程执行完了,再关闭就没有效果了
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
});
Thread lockThread2 = new Thread(() -> {
try {
System.out.println("lockThread2 before lock");
channel.lock(1, 2, false); // 与lockThread一样获取
System.out.println("lockThread2 has get lock");
} catch (IOException e) {
e.printStackTrace();
}
});
lockThread1.start();
TimeUnit.MICROSECONDS.sleep(100);
lockThread2.start();
TimeUnit.SECONDS.sleep(1);
lockThread2.interrupt(); // 这里应该是lockThread2处于阻塞状态,等待获取fileLock,这里调用interrupt之后,会抛出异常
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void lockTest4() {
try(FileChannel channel = new FileOutputStream(_13_FileChannel_FileLock_1.class.getClassLoader()
.getResource("channel/_13_FileChannel_fileLock").getPath()).getChannel()) {
System.out.println("lockThread1 before lock");
channel.lock(1, 2, false);
System.out.println("lockThread1 has get lock");
TimeUnit.SECONDS.sleep(30); // 这里是为了让线程多待一会,防止线程执行完了,再关闭就没有效果了
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void lockTest3() {
try(FileChannel channel = new FileOutputStream(_13_FileChannel_FileLock_1.class.getClassLoader()
.getResource("channel/_13_FileChannel_fileLock").getPath()).getChannel()) {
Thread lockThread1 = new Thread(() -> {
try {
for (int i = 0; i < 1000000; i++) {
long anInt = ThreadLocalRandom.current().nextInt(i + 1);
if (i % 50000 == 0) {
System.out.println(i);
}
}
System.out.println("lockThread1 before lock");
channel.lock(1, 2, false);
System.out.println("lockThread1 has get lock");
System.out.println("lockThread1 finish");
} catch (IOException e) {
e.printStackTrace();
}
});
lockThread1.start();
TimeUnit.MICROSECONDS.sleep(500);
lockThread1.interrupt();
TimeUnit.SECONDS.sleep(10);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void lockTest2() {
try(FileChannel channel = new FileOutputStream(_13_FileChannel_FileLock_1.class.getClassLoader()
.getResource("channel/_13_FileChannel_fileLock").getPath()).getChannel()) {
Thread lockThread = new Thread(() -> {
try {
channel.lock(1, 2, false);
TimeUnit.SECONDS.sleep(1); // 这里是为了让线程多待一会,防止线程执行完了,再关闭就没有效果了
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
});
Thread channelCloseThread = new Thread(() -> {
try {
channel.close();
} catch (IOException e) {
e.printStackTrace();
}
});
lockThread.start();
TimeUnit.MICROSECONDS.sleep(100);
channelCloseThread.start();
TimeUnit.SECONDS.sleep(1);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void lockTest1() {
try(FileChannel fileChannel = new RandomAccessFile(new File(_13_FileChannel_FileLock_1.class.getClassLoader().getResource("channel/_13_FileChannel_fileLock").getPath()),"rw").getChannel()) {
System.out.println("1_1 begin");
fileChannel.lock(1, 2, false);
System.out.println("1_2 end");
TimeUnit.SECONDS.sleep(30);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
package chapter9;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
public class NUMBERGAME {
private static final int MAXIMUM_BOARD_SIZE = 50;
private static final int EMPTY_VALUE = -987654321;
private static int[][] cache = new int[MAXIMUM_BOARD_SIZE][MAXIMUM_BOARD_SIZE];
public static void main(String[] args) {
playGame();
}
public static void playGame() {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
int cases = Integer.parseInt(reader.readLine());
while (cases-- > 0) {
for (int index = 0; index < MAXIMUM_BOARD_SIZE; index++) {
Arrays.fill(cache[index], EMPTY_VALUE);
}
int length = Integer.parseInt(reader.readLine());
int[] board = new int[length];
String[] input = reader.readLine().split(" ");
for (int index = 0; index < length; index++) {
board[index] = Integer.parseInt(input[index]);
}
int diffValue = getDiffValue(board, 0, length - 1);
writer.append(String.valueOf(diffValue));
writer.append("\n");
}
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static int getDiffValue(int[] board, int leftindex, int rightindex) {
//기저 사례 제
if (leftindex > rightindex) {
return 0;
}
//메모이제이션
int ret = cache[leftindex][rightindex];
if (ret != EMPTY_VALUE) {
return ret;
}
//실제 계산
ret = Math.max(board[leftindex] - getDiffValue(board, leftindex + 1, rightindex),
board[rightindex] - getDiffValue(board, leftindex, rightindex - 1));
if (rightindex - leftindex >= 1){
ret = Math.max(ret, - getDiffValue(board, leftindex + 2, rightindex));
ret = Math.max(ret, - getDiffValue(board, leftindex, rightindex - 2));
}
cache[leftindex][rightindex] = ret;
return ret;
}
}
|
package ai.odoo.doctodigit.util;
import ai.odoo.doctodigit.config.TesseractProperties;
import net.sourceforge.tess4j.Tesseract;
public class TesseractUtils {
public Tesseract getTesseract(TesseractProperties tesseractProperties) {
Tesseract instance = new Tesseract();
instance.setDatapath(tesseractProperties.getDatapath());
instance.setLanguage(tesseractProperties.getLanguage());
instance.setHocr(tesseractProperties.getHocr());
instance.setTessVariable("preserve_interword_spaces", tesseractProperties.getPreserveInterwordSpaces());
instance.setTessVariable("textord_tabfind_find_tables", "1");
instance.setTessVariable("textord_tablefind_recognize_tables", "1");
return instance;
}
}
|
package com.framework.model;
import java.util.Date;
public class SysRoleAuthRelation {
private Integer id;
private String roleCode;
private String authCode;
private Date createDate;
private String createBy;
private Date modifyDate;
private String modifyBy;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getRoleCode() {
return roleCode;
}
public void setRoleCode(String roleCode) {
this.roleCode = roleCode;
}
public String getAuthCode() {
return authCode;
}
public void setAuthCode(String authCode) {
this.authCode = authCode;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public String getCreateBy() {
return createBy;
}
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}
public String getModifyBy() {
return modifyBy;
}
public void setModifyBy(String modifyBy) {
this.modifyBy = modifyBy;
}
} |
package ogo.spec.game.model;
import java.util.Set;
import java.util.HashSet;
import java.util.Iterator;
public class Tile
{
private Inhabitant inhabitant;
private TileType type;
protected int x, y;
public Tile(TileType type, int x, int y)
{
this.type = type;
this.x = x;
this.y = y;
}
public Inhabitant getInhabitant() {
return this.inhabitant;
}
/**
* Set an inhabitant to this tile.
*
* This method also calls the setTile() method on the inhabitant.
*/
public void setInhabitant(Inhabitant i)
{
this.inhabitant = i;
i.setCurrentTile(this);
}
/**
* Does this tile have this inhabitant.
*/
public boolean hasInhabitant()
{
return (this.inhabitant != null);
}
/**
* Get the type.
*/
public TileType getType()
{
return type;
}
/**
* Is the given tile adjacent to this one.
*/
public boolean isAdjacent(Tile t)
{
return (Math.abs(this.x - t.x) <= 1) && (Math.abs(this.y - t.y) <=1);
}
public int x() {
return x;
}
public int y() {
return y;
}
}
|
package edu.handong.csee.java.exceptionhandle.example.prob2;//package name
import java.util.InputMismatchException;//use InputMismatchException class
import java.util.Scanner;//use scanner class
public class InException {//class name
private int x=0, y=0;//declare and initialize x,y variable
public InException() {//constructor
}
public void distinguishError() {//distinguishError method
try {
Scanner keyboard = new Scanner(System.in);//use scanner class with keyboard
System.out.print("x: ");//print message for input x data
x = keyboard.nextInt();//save input data to x
System.out.print("y: ");//print message for input y data
y = keyboard.nextInt();//save input data to y
System.out.println(this.x/this.y);//print divided result
}
catch(ArithmeticException e) {//if y is 0, implement this
System.out.println("java.lang.ArithmeticExcetion: "+e.getMessage());//print out error message with Exception String
}
catch(InputMismatchException e) {//if x or y is not integer, implement this
System.out.println("java.util.InputMismatchException");//print out error message
}
catch(Exception e) {//etc error
System.out.println("Some other exception has occurred: "+e.getMessage());//print out error message with Exception String
}
}
}
|
package br.ufrgs.rmpestano.intrabundle.model;
import br.ufrgs.rmpestano.intrabundle.metric.MetricsCalculation;
import java.io.Serializable;
/**
* Created by rmpestano on 2/4/14.
* used by jasper reports
*/
public class ModuleDTO implements Serializable {
protected OSGiModule module;
protected MetricPoints metricPoints;
public ModuleDTO() {
}
public ModuleDTO(OSGiModule module, MetricsCalculation metrics) {
module.getNumberOfClasses();//forces visitAllClasses to be available in report as its called on demand
module.getManifestMetadata();//forces createManifestMetadata to be available in report
this.module = module;
metricPoints = metrics.calculateBundleQuality(module);
}
public OSGiModule getModule() {
return module;
}
public void setModule(OSGiModule module) {
this.module = module;
}
public MetricPoints getMetricPoints() {
return metricPoints;
}
public void setMetricPoints(MetricPoints metricsPoints) {
this.metricPoints = metricsPoints;
}
}
|
package com.goShopp.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.goShopp.dao.ProductDao;
import com.goShopp.model.Product;
import com.goShopp.service.ProductService;
@Service
public class ProductServiceImpl implements ProductService {
@Autowired
private ProductDao productDao;
public void setProductDao(ProductDao productDao) {
this.productDao = productDao;
}
@Transactional
public void addProduct(Product p) {
this.productDao.addProduct(p);
}
@Transactional
public void updateProduct(Product p) {
this.productDao.updateProduct(p);
}
@Transactional
public List<Product> listProducts() {
// TODO Auto-generated method stub
return this.productDao.listProducts();
}
@Transactional
public List<Product> listWcategory() {
// TODO Auto-generated method stub
return this.productDao.listWcategory();
}
@Transactional
public Product getProductById(int id) {
// TODO Auto-generated method stub
return this.productDao.getProductById(id);
}
@Transactional
public void removeProduct(int id) {
this.productDao.removeProduct(id);
}
@Transactional
public List<Product> listMcategory() {
// TODO Auto-generated method stub
return this.productDao.listMcategory();
}
@Transactional
public List<Product> listKcategory() {
// TODO Auto-generated method stub
return this.productDao.listKcategory();
}
}
|
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import javax.swing.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.text.SimpleDateFormat;
public class xml550ans {
public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//String fileName = "CB_ES550P_20170627_002.XML";
String IdnOR = "NNNN_0000";
String OPER = "Иванова И.И.";
String TEL_OPER = "8(123) 456-78-90";
long curTime;
String curStringDate;
String curStringTime;
File[] fileList = getFiles("C:/550P/input",".xml");
for(File file : fileList){
curTime = System.currentTimeMillis();
curStringDate = new SimpleDateFormat("dd/MM/yyyy").format(curTime);
curStringTime = new SimpleDateFormat("HH:mm:ss").format(curTime);
//File file = new File(fileName);
long fileSize = file.length();
String fileName = file.getName();
String filePath = file.getPath();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(filePath);
Node dateMsgNode = doc.getElementsByTagName("ДатаСообщения").item(0);
String dateMsg = dateMsgNode.getTextContent();
NodeList numZapList = doc.getElementsByTagName("НомерЗаписи");
/*
for (int i = 0; i < numZapList.getLength(); i++) {
System.out.println(numZapList.item(i).getTextContent());
}
*/
FileWriter writeFile = null;
try {
File xmlAns = new File("C:/550P/output/"+"UV_"+IdnOR+"_"+ fileName.substring(0,fileName.length()-4) +".xml");
writeFile = new FileWriter(xmlAns);
writeFile.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
writeFile.append("<KVIT>\n");
writeFile.append("<IDNOR>"+IdnOR+"</IDNOR>\n");
writeFile.append("<ES>"+fileName+"</ES>\n");
writeFile.append("<SIZE_ES>"+fileSize+"</SIZE_ES>\n");
writeFile.append("<DATE_ES>"+dateMsg+"</DATE_ES>\n");
writeFile.append("<RECNO_ES nRec=\""+numZapList.getLength()+"\">\n");
for (int i = 0; i < numZapList.getLength(); i++) {
writeFile.append("<ES_REC IdInfoOR=\""+numZapList.item(i).getTextContent()+"\">\n");
writeFile.append("<REZ_ES>0</REZ_ES>\n");
writeFile.append("</ES_REC>\n");
}
writeFile.append("</RECNO_ES>\n");
writeFile.append("<DATE_KVIT>"+curStringDate+"</DATE_KVIT>\n");
writeFile.append("<TIME_KVIT>"+curStringTime+"</TIME_KVIT>\n");
writeFile.append("<OPER>"+OPER+"</OPER>\n");
writeFile.append("<TEL_OPER>"+TEL_OPER+"</TEL_OPER>\n");
writeFile.append("</KVIT>\n");
} catch (IOException e) {
e.printStackTrace();
} finally {
if(writeFile != null) {
try {
writeFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/*
//обёртка для выбора файлов
int nextOrExit = JOptionPane.YES_OPTION;
while(nextOrExit== JOptionPane.YES_OPTION) {
JFileChooser fileopen = new JFileChooser("C:/JavaProj/xml550ans");
int ret = fileopen.showDialog(null, "Выбрать файл");
if (ret == JFileChooser.APPROVE_OPTION) {
File file = fileopen.getSelectedFile();
String fileName = file.getName();
//String filePath = file.getPath();
//System.out.print(filePath);
//здесь основное действо
}
nextOrExit = JOptionPane.showOptionDialog(
null,
"Можно нажать \"Следующий файл\" и продолжить обработку другого файла.",
"Выйти или продолжить?",
JOptionPane.YES_NO_OPTION,
JOptionPane.INFORMATION_MESSAGE,
null,
new Object[]{"Следующий файл","Выйти"},
"Выйти");
}
*/
}
// метод сбора файлов из папки
private static File[] getFiles(String dir, String ext) {
File file = new File(dir);
if(!file.exists()) System.out.println(dir + " папка не существует");
File[] listFiles = file.listFiles(new MyFileNameFilter(ext));
/*
if(listFiles.length == 0){
System.out.println(dir + " не содержит файлов с расширением " + ext);
}else{
for(File f : listFiles)
System.out.println("Файл: " + dir + File.separator + f.getName());
}
*/
return listFiles;
}
// Реализация интерфейса FileNameFilter
public static class MyFileNameFilter implements FilenameFilter {
private String ext;
public MyFileNameFilter(String ext){
this.ext = ext.toLowerCase();
}
@Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(ext);
}
}
}
|
package com.cxjd.nvwabao.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import com.cxjd.nvwabao.R;
import com.cxjd.nvwabao.adapter.ListView45Adapter;
import com.cxjd.nvwabao.bean.ListView;
import com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.sheng.A;
import com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.sheng.B;
import com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.sheng.C;
import com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.sheng.D;
import com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.sheng.E;
import com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.sheng.F;
import com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.sheng.G;
import com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.sheng.H;
import com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.sheng.I;
import com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.sheng.J;
import com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.sheng.K;
import com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.sheng.L;
import com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.sheng.M;
import com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.sheng.N;
import com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.sheng.O;
import com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.sheng.P;
import com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.sheng.Q;
import com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.sheng.S;
import com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.sheng.T;
import com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.sheng.U;
import com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.sheng.V;
import com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.sheng.W;
import com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.sheng.X;
import com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.sheng.Y;
import com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.sheng.Z;
import java.util.ArrayList;
import java.util.List;
public class ShengOrKe extends AppCompatActivity {
//相生
ImageButton imageButton1;
//相生图片的状态,决定图片的显示,默认为1
int state1 = 1;
//相克图片的状态,决定图片的显示,默认为0
int state2 = 0;
//相克
ImageButton imageButton2;
//集合,用来存放ListView中各项的数据
private List<ListView> itemList = new ArrayList<>();
//全局属性
android.widget.ListView listView;
//数据数组
String[] items = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
//当前的选中项,默认为第一项即A
int defaultPosition = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sheng_or_ke);
//找到用于存放相生相克图片的ImageView组件
imageButton1 = (ImageButton) findViewById(R.id.imageButton_xiangsheng);
imageButton2 = (ImageButton) findViewById(R.id.imageButton_xiangke);
//初始化ListView中的数据
initListView();
ListView45Adapter adapter = new ListView45Adapter(ShengOrKe.this, R.layout.fragment_left_fourandfive_item,itemList);
listView = (android.widget.ListView) findViewById(R.id.list_view_45);
listView.setAdapter(adapter);
//默认显示
if (state1 == 1 && defaultPosition == 0){
listView.setSelection(defaultPosition);
replaceFragment(new A());
}
imageButton1.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN){
//按下
state1 = 1;
state2 = 0;
imageButton1.setImageDrawable(getResources().getDrawable(R.drawable.xiangsheng_press));
imageButton2.setImageDrawable(getResources().getDrawable(R.drawable.xiangke));
switch (defaultPosition){
case 0 :
replaceFragment(new A());
break;
case 1 :
replaceFragment(new B());
break;
case 2 :
replaceFragment(new C());
break;
case 3 :
replaceFragment(new D());
break;
case 4 :
replaceFragment(new E());
break;
case 5 :
replaceFragment(new F());
break;
case 6 :
replaceFragment(new G());
break;
case 7 :
replaceFragment(new H());
break;
case 8 :
replaceFragment(new I());
break;
case 9 :
replaceFragment(new J());
break;
case 10 :
replaceFragment(new K());
break;
case 11 :
replaceFragment(new L());
break;
case 12 :
replaceFragment(new M());
break;
case 13 :
replaceFragment(new N());
break;
case 14 :
replaceFragment(new O());
break;
case 15 :
replaceFragment(new P());
break;
case 16 :
replaceFragment(new Q());
break;
case 17 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.sheng.R());
break;
case 18 :
replaceFragment(new S());
break;
case 19 :
replaceFragment(new T());
break;
case 20 :
replaceFragment(new U());
break;
case 21 :
replaceFragment(new V());
break;
case 22 :
replaceFragment(new W());
break;
case 23 :
replaceFragment(new X());
break;
case 24 :
replaceFragment(new Y());
break;
case 25 :
replaceFragment(new Z());
break;
default :
break;
}
}else if(event.getAction() == MotionEvent.ACTION_UP){
if (state1 == 0 || state2 == 1){
imageButton2.setImageDrawable(getResources().getDrawable(R.drawable.xiangke_press));
imageButton1.setImageDrawable(getResources().getDrawable(R.drawable.xiangsheng));
}else if (state1 == 1 || state2 ==0){
imageButton2.setImageDrawable(getResources().getDrawable(R.drawable.xiangke));
imageButton1.setImageDrawable(getResources().getDrawable(R.drawable.xiangsheng_press));
}
}
return false;
}
});
imageButton2.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN){
//按下
state1 = 0;
state2 = 1;
imageButton2.setImageDrawable(getResources().getDrawable(R.drawable.xiangke_press));
imageButton1.setImageDrawable(getResources().getDrawable(R.drawable.xiangsheng));
switch (defaultPosition){
case 0 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.A());
break;
case 1 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.B());
break;
case 2 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.C());
break;
case 3 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.D());
break;
case 4 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.E());
break;
case 5 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.F());
break;
case 6 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.G());
break;
case 7 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.H());
break;
case 8 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.I());
break;
case 9 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.J());
break;
case 10 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.K());
break;
case 11 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.L());
break;
case 12 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.M());
break;
case 13 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.N());
break;
case 14 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.O());
break;
case 15 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.P());
break;
case 16 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.Q());
break;
case 17 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.R());
break;
case 18 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.S());
break;
case 19 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.T());
break;
case 20 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.U());
break;
case 21 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.V());
break;
case 22 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.W());
break;
case 23 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.X());
break;
case 24 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.Y());
break;
case 25 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.Z());
break;
default :
break;
}
}else if(event.getAction() == MotionEvent.ACTION_UP){
if (state1 == 0 || state2 == 1){
imageButton2.setImageDrawable(getResources().getDrawable(R.drawable.xiangke_press));
imageButton1.setImageDrawable(getResources().getDrawable(R.drawable.xiangsheng));
}else if (state1 == 1 || state2 ==0){
imageButton2.setImageDrawable(getResources().getDrawable(R.drawable.xiangke));
imageButton1.setImageDrawable(getResources().getDrawable(R.drawable.xiangsheng_press));
}
}
return false;
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
if(state1 == 1){
switch (position){
case 0 :
replaceFragment(new A());
break;
case 1 :
replaceFragment(new B());
break;
case 2 :
replaceFragment(new C());
break;
case 3 :
replaceFragment(new D());
break;
case 4 :
replaceFragment(new E());
break;
case 5 :
replaceFragment(new F());
break;
case 6 :
replaceFragment(new G());
break;
case 7 :
replaceFragment(new H());
break;
case 8 :
replaceFragment(new I());
break;
case 9 :
replaceFragment(new J());
break;
case 10 :
replaceFragment(new K());
break;
case 11 :
replaceFragment(new L());
break;
case 12 :
replaceFragment(new M());
break;
case 13 :
replaceFragment(new N());
break;
case 14 :
replaceFragment(new O());
break;
case 15 :
replaceFragment(new P());
break;
case 16 :
replaceFragment(new Q());
break;
case 17 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.sheng.R());
break;
case 18 :
replaceFragment(new S());
break;
case 19 :
replaceFragment(new T());
break;
case 20 :
replaceFragment(new U());
break;
case 21 :
replaceFragment(new V());
break;
case 22 :
replaceFragment(new W());
break;
case 23 :
replaceFragment(new X());
break;
case 24 :
replaceFragment(new Y());
break;
case 25 :
replaceFragment(new Z());
break;
default :
break;
}
}else if(state2 == 1){
switch (position){
case 0 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.A());
break;
case 1 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.B());
break;
case 2 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.C());
break;
case 3 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.D());
break;
case 4 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.E());
break;
case 5 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.F());
break;
case 6 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.G());
break;
case 7 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.H());
break;
case 8 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.I());
break;
case 9 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.J());
break;
case 10 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.K());
break;
case 11 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.L());
break;
case 12 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.M());
break;
case 13 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.N());
break;
case 14 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.O());
break;
case 15 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.P());
break;
case 16 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.Q());
break;
case 17 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.R());
break;
case 18 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.S());
break;
case 19 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.T());
break;
case 20 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.U());
break;
case 21 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.V());
break;
case 22 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.W());
break;
case 23 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.X());
break;
case 24 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.Y());
break;
case 25 :
replaceFragment(new com.cxjd.nvwabao.fragment.findFunctions.shengAndKe.ke.Z());
break;
default :
break;
}
}
}
});
}
/**
* 为ListView组件中的每一项赋值
*/
private void initListView() {
for(int i=0; i<items.length; i++){
ListView item = new ListView(items[i]);
itemList.add(item);
}
}
private void replaceFragment(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.right_shengAndKe_fragment,fragment);
fragmentTransaction.commit();
}
}
|
package com.kdp.wanandroidclient.ui.tree;
import com.kdp.wanandroidclient.bean.Article;
import com.kdp.wanandroidclient.ui.core.view.IPageLoadDataView;
/**
* 知识体系列表协约类
* author: 康栋普
* date: 2018/3/6
*/
public interface TreeListContract {
interface ITreePresenter {
void loadTreeList();
void collectArticle();
void unCollectArticle();
}
interface ITreeListView extends IPageLoadDataView<Article> {
int getCid();
int getArticleId();//文章id
void collect(boolean isCollect,String result);
}
}
|
import java.util.*;
/**
* Map
*/
public class MapExample {
public static void main(String[] args) {
Map<String, String> languages = new HashMap<>();
languages.put("Java", "a compiled high level object orient programming language");
languages.put("Python", "an interpreted object oriented high level programming language with dynamic semantics");
languages.put("Algol", "an algorithmic language");
languages.put("BASIC", "Beginners All Symbolic Instruction Code");
languages.put("Lisp", "there in les madness");
// System.out.println(languages.get("Java"));
// languages.put("Java", "this course is about Java");
// System.out.println(languages.get("Java"));
System.out.println(languages.putIfAbsent("JavaScript", "an interpreted language specifically for web browsers"));
System.out.println(languages.putIfAbsent("JavaScript", "trying to add JavaScript again"));
System.out.println(languages.get("JavaScript"));
// languages.remove("Lisp");
if (languages.remove("Algol", "a family of algorithmic languages")) {
System.out.println("Algol removed");
} else {
System.out.println("Algol not removed. Key/Value pair not found");
}
System.out.println(languages.replace("Lisp", "a functional programming language with imperative features"));
System.out.println(languages.replace("Scala", "will not be replaced"));
for (String key : languages.keySet()) {
System.out.println(key + ": " + languages.get(key));
}
}
} |
import java.util.HashMap;
public class Aplicacao {
public static void main(String[] args) {
// TODO Auto-generated method stub
HashMap<String, String> nomeSobrenome = new HashMap<String, String>();
//Criando HashMap
nomeSobrenome.put("Andre","Lucas");
nomeSobrenome.put("André", "Luiz");
nomeSobrenome.put("Lucas", "André");
//Exibindo lista
System.out.println(nomeSobrenome);
System.out.println("");
//Exibindo segundo nome de quem chama Andre
System.out.println(nomeSobrenome.get("Andre"));
System.out.println("");
//Removendo quem tem o primeiro nome como Andre
nomeSobrenome.remove("Andre");
System.out.println("");
//Exibindo sem o nome Andre
System.out.println("Lista sem o nome Andre");
System.out.println(nomeSobrenome);
System.out.println("");
//Exibindo tamanho do HashMap
System.out.println("Tamanho da lista");
System.out.println(nomeSobrenome.size());
System.out.println("");
//Removendo toda a HashMap
System.out.println("Removendo todos os itens da lista");
nomeSobrenome.clear();
System.out.println(nomeSobrenome);
}
}
|
package com.dinu;
//Amazon Question
public class MissingNumber {
public static void main(String[] args) {
int[] arr= {0,4,1,3};
System.out.println(find(arr));
}
static int find(int[] arr) {
int i=0;
while(i<arr.length) {
int element=i;
int pos=arr[i];
if((arr[i]!=arr.length) && (arr[pos]!=arr[element])) {
swap(arr,element, pos);
}else {
i++;
}
}
for(int j=0;j<arr.length;j++) {
if(j!=arr[j]) {
return j;
}
}
return arr.length;
}
static void swap(int arr[], int f,int s) {
int temp=arr[f];
arr[f]=arr[s];
arr[s]=temp;
}
}
|
package com.e.jobkwetu.Model;
public class TasksList {
private String title,description, skills,start_date,subcounty;
public TasksList() {
}
public TasksList(String title, String description, String skills, String start_date, String subcounty) {
this.title = title;
this.description = description;
this.skills = skills;
this.start_date = start_date;
this.subcounty = subcounty;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getSkills() {
return skills;
}
public void setSkills(String skills) {
this.skills = skills;
}
public String getStart_date() {
return start_date;
}
public void setStart_date(String start_date) {
this.start_date = start_date;
}
public String getSubcounty() {
return subcounty;
}
public void setSubcounty(String subcounty) {
this.subcounty = subcounty;
}
}
|
package main;
import javax.swing.JOptionPane;
import main.Ball.Color;
public class Main {
public static void main(String[] args) {
Basket basket = new Basket();
basket.add(new Ball(2.1, Color.BLUE));
basket.add(new Ball(3.7, Color.BLUE));
basket.add(new Ball(7.3, Color.GREEN));
basket.add(new Ball(1.1, Color.YELLOW));
StringBuffer sb = new StringBuffer().append(String.format("Weight of Balls: %.2f", basket.countWeight()) + "\n"
+ "Count of Balls: " + basket.countBlueBalls());
JOptionPane.showMessageDialog(null, sb.toString(), "Ball & Basket", JOptionPane.INFORMATION_MESSAGE);
}
}
|
package com.company.bank.domain;
public interface Savable {
String save();
void load(String content);
}
|
package Exception.BlockException;
public class BlockNullException extends BlockException{
public BlockNullException(String message) {
super(message);
}
}
|
package com.smxknife.energy.services.alarm.infras.dao;
import com.smxknife.energy.services.alarm.core.dao.AlarmRecordDao;
import com.smxknife.energy.services.alarm.infras.converter.AlarmRecordConverter;
import com.smxknife.energy.services.alarm.infras.entity.AlarmRecordMetaRepository;
import com.smxknife.energy.services.alarm.spi.domain.AlarmRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author smxknife
* 2021/5/17
*/
@Service
public class AlarmRecordMySqlDao implements AlarmRecordDao {
@Autowired
private AlarmRecordMetaRepository repository;
@Autowired
private AlarmRecordConverter converter;
@Override
public List<AlarmRecord> findAll() {
return converter.fromMetas(repository.findAll());
}
@Override
public List<AlarmRecord> findByReporter(String reporter) {
return converter.fromMetas(repository.findByReporter(reporter));
}
}
|
package db.model.musicInterruptedChannel;
public class MusicInterruptedChannel implements MusicInterruptedChannelId {
private final String vcId;
private final String textChannelId;
public MusicInterruptedChannel(String vcId, String textChannelId) {
this.vcId = vcId;
this.textChannelId = textChannelId;
}
public String getVcId() {
return vcId;
}
public String getTextChannelId() {
return textChannelId;
}
}
|
package com.rekoe.model.gameobjects;
import java.util.UUID;
import org.nutz.lang.random.R;
/**
* @author 科技㊣²º¹³
* Feb 16, 2013 2:35:33 PM
* http://www.rekoe.com
* QQ:5382211
*/
public abstract class RkObject {
/**
* Unique id, for all game objects such as: items, players, monsters.
*/
private String objectId;
public RkObject()
{
this.objectId = R.UU16(UUID.randomUUID());
}
/**
* Returns unique ObjectId of AionObject
*
* @return Int ObjectId
*/
public String getObjectId() {
return objectId;
}
/**
* Returns name of the object.<br>
* Unique for players, common for NPCs, items, etc
*
* @return name of the object
*/
public abstract String getName();
}
|
package com.sneaker.mall.api.api.inc;
import com.google.common.base.Strings;
import com.sneaker.mall.api.model.*;
import com.sneaker.mall.api.service.*;
import com.sneaker.mall.api.service.impl.B2CompanyService;
import com.sneaker.mall.api.util.JsonParser;
import com.sneaker.mall.api.util.RequestUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.
* 内部API
*/
@Controller
@RequestMapping(value = "/inc")
public class IncApi {
private Logger logger = LoggerFactory.getLogger(IncApi.class);
@Autowired
private StoreService storeService;
@Autowired
private OrderService orderService;
@Autowired
private UserService userService;
@Autowired
private B2CompanyService companyService;
@Autowired
private GTypeService gTypeService;
/**
* @param request
* @param response
* @return
* @apiDescription 同步ERP订单信息到商城
* @api {get} /inc/orderStatus.do
* @apiName 同步ERP订单信息到商城
* @apiGroup inc
* @apiParam {String} [orderNo] 订单的ERP编号
* @apiParam {Number} [status] 同步状态 3 表示审核订单 4表示创建出库单 5表示审核出库单 8表示取消订单 9表示结算 10表示未结算,11表示已派车,12表示取消派车,13 表示没货待配,99表示错误
* @apiParam {String} [action] 操作详细信息,第一步都应该记录详细信息
* @apiSuccess {Number} [status] 状态
* @apiSuccess {string} [message] 消息
* <p>
* 回调通知订单
*/
@ResponseBody
@RequestMapping(value = "orderStatus.do")
public String callbackOrder(HttpServletRequest request, HttpServletResponse response) {
ResponseMessage<String> responseMessage = new ResponseMessage<>(300, "parameter is error");
String orderNo = request.getParameter("orderno"); //商城订单编号
String status = request.getParameter("status"); //订单状态
String action = request.getParameter("action");// 执行操作说明
String erpOrderNo = request.getParameter("erporderno");//ERP订单号
String sign = request.getParameter("sign"); //签名
logger.info(erpOrderNo + "," + orderNo + "," + action + "," + status);
if (!Strings.isNullOrEmpty(orderNo) && !Strings.isNullOrEmpty(status)) {
int iStatus = Integer.parseInt(status);
//3 表示审核订单 4表示创建出库单 5表示审核出库单 8表示取消订单 9表示结算 10表示未结算,11表示已派车,12表示取消派车,13表示没货待配
if (iStatus == 3 || iStatus == 4 || iStatus == 5 || iStatus == 8 || iStatus == 9 || iStatus == 10 || iStatus == 11 || iStatus == 12 || iStatus == 13||iStatus==99) {
if (iStatus == 9 || iStatus == 10) {
this.orderService.updateOrderIsPay(orderNo, iStatus);
} else if (iStatus == 11 || iStatus == 12) {
//派车字段更新
this.orderService.updateSendCar(orderNo, (iStatus == 11 ? 1 : 0));
} else {
this.orderService.updateOrderStatus(orderNo, iStatus);
}
OrderOper orderOper = new OrderOper();
orderOper.setStatus(iStatus);
orderOper.setOper_time(new Date());
orderOper.setAction(action);
this.orderService.addOrderOper(orderNo, orderOper);
}
if (!Strings.isNullOrEmpty(erpOrderNo)) {
//当ERP订单号不为空时,则更新ERP的订单号
this.orderService.updateErpOrderId(orderNo, erpOrderNo);
}
responseMessage.setStatus(200);
responseMessage.setMessage("success");
}
return JsonParser.simpleJson(responseMessage);
}
/**
* 读取品牌信息
*
* @param request
* @param response
* @return
*/
@RequestMapping(value = "getBrand.action")
public String getBrand(HttpServletRequest request, HttpServletResponse response) {
ResponseMessage<List<Brand>> responseMessage = new ResponseMessage<>(200, "success");
try {
} catch (Exception e) {
e.printStackTrace();
}
return JsonParser.simpleJson(responseMessage);
}
/**
* @param request
* @param response
* @return
*/
@ResponseBody
@RequestMapping(value = "getGtype.action")
public String getGType(HttpServletRequest request, HttpServletResponse response) {
ResponseMessage<List<GType>> responseMessage = new ResponseMessage<>(200, "success");
try {
long cid = RequestUtil.getLong(request, "cid", 0); //公司ID
String parentCode = RequestUtil.getString(request, "code", null); //父级分类的Code
List<GType> gTypes = null;
if (!Strings.isNullOrEmpty(parentCode)) {
//查询子父栏目
gTypes = this.gTypeService.getGtypeForCid(cid, parentCode + "__");
} else {
//查询顶级栏目
gTypes = this.gTypeService.getGtypeForCid(cid, "__");
}
responseMessage.setData(gTypes);
} catch (Exception e) {
e.printStackTrace();
}
return JsonParser.simpleJson(responseMessage);
}
/**
* 业务管理后台登陆
*
* @param request
* @param response
* @return
*/
@ResponseBody
@RequestMapping(value = "businessadminlogin.action")
public String businessAdminLogin(HttpServletRequest request, HttpServletResponse response) {
ResponseMessage<User> responseMessage = new ResponseMessage<User>(200, "success");
try {
String username = RequestUtil.validateParam(request, "username", responseMessage);
String password = RequestUtil.validateParam(request, "password", responseMessage);
User user = this.userService.loginForSalesAdminMan(username, password);
if (user != null) {
user.setCom(this.companyService.getCompanyById(user.getCid()));
}
responseMessage.setData(user);
} catch (Exception e) {
e.printStackTrace();
}
return JsonParser.simpleJson(responseMessage);
}
/**
* 根据公司查询仓库
*
* @param request
* @param response
* @return
*/
@ResponseBody
@RequestMapping(value = "getstorebycid.action")
public String getStoreByCid(HttpServletRequest request, HttpServletResponse response) {
ResponseMessage<List<Store>> responseMessage = new ResponseMessage<>(200, "success");
try {
long cid = RequestUtil.getLong(request, "cid", 0);
List<Store> stores = this.storeService.getStoreByCid(cid);
if (stores != null) {
responseMessage.setData(stores);
}
} catch (Exception e) {
e.printStackTrace();
}
return JsonParser.simpleJson(responseMessage);
}
}
|
package com.yfy.controller;
import com.yfy.entity.Result;
import com.yfy.entity.User;
import com.yfy.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@PostMapping(value="/user")
public Result validateUser(@RequestBody User user){
List<Map> maps = userMapper.queryUser(user.getId(), user.getName());
Result r=new Result();
if(maps.size()>0){
r.setCode(1);
r.setMsg("请输入正确的数值");
}
return r;
}
}
|
package com.shopify.mapper;
import org.apache.ibatis.annotations.Mapper;
import com.shopify.common.RestApiData;
import com.shopify.schedule.CronJobData;
@Mapper
public interface RestMapper {
public int insertRestApiData (RestApiData data);
public int updateRestApiData(RestApiData restApiData);
public void insertCronJobData(CronJobData cronData);
}
|
package com.example.roberto.startedservice;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.os.PowerManager;
import android.support.annotation.Nullable;
import android.support.v7.app.NotificationCompat;
import android.widget.Toast;
/**
* Created by roberto on 07.11.2015.
*/
public class MyService extends Service {
Boolean running=false;
MediaPlayer player=null;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!running) //Service can be requested several times....
{
player = MediaPlayer.create(this, R.raw.braincandy);
player.setWakeMode(this, PowerManager.PARTIAL_WAKE_LOCK);
player.start();
running=true;
Intent i=new Intent(this,MainActivity.class);
//getActivity is a Factory method
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,i, PendingIntent.FLAG_ONE_SHOT);
//Define a new Notification from the compatibility builder
NotificationCompat.Builder mBulider = new NotificationCompat.Builder(this);
//Set the main parameters....
mBulider
.setContentTitle("Stop the music")
.setContentText("Click to Stop the music")
.setSmallIcon(R.drawable.mail)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
//Build the notification
Notification notification = mBulider.build();
startForeground(10,notification);
Toast.makeText(this,"Service PID: "+Integer.toString(android.os.Process.myPid()),Toast.LENGTH_SHORT).show();
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
if (running){
player.stop();
player.release();
running=false;
}
}
}
|
package com.algorithms.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> obj = new ArrayList<String>();
System.out.println("\n\n");
System.out.println("Basic Operations");
System.out.println("================");
obj.add("San Jose");
obj.add("San Francisco");
obj.add("San Ramon");
System.out.println("Current Size is " + obj.size());
System.out.println("Current array list is:" + obj);
obj.add(0, "Santa Barbara");
obj.add(1, "Dublin");
System.out.println("Current Size is " + obj.size());
System.out.println("Current array list is:" + obj);
obj.remove(0);
obj.remove("Dublin");
System.out.println("Current Size is " + obj.size());
System.out.println("Current array list is:" + obj);
System.out.println("\n\n");
System.out.println("Initialize Example");
System.out.println("==================");
ArrayList<String> obj1 = new ArrayList<String>(Arrays.asList("Pratap", "Peter", "Harsh"));
System.out.println("Current array list is:" + obj1);
ArrayList<String> cities = new ArrayList<String>() {
{
add("Delhi");
add("Agra");
add("Chennai");
}
};
System.out.println("Content of Array list cities:" + cities);
System.out.println("\n\n");
System.out.println("Array to Arraylist");
System.out.println("=================");
String citynames[] = { "Agra", "Mysore", "Chandigarh", "Bhopal" };
ArrayList<String> citylist = new ArrayList<String>(Arrays.asList(citynames));
System.out.println(citylist);
System.out.println("\n\n");
System.out.println("ncopies exmaple");
System.out.println("=================");
ArrayList<Integer> intlist = new ArrayList<Integer>(Collections.nCopies(10, 5));
System.out.println("ArrayList items: " + intlist);
System.out.println("\n\n");
System.out.println("get without loop");
System.out.println("=================");
System.out.println(obj.get(0));
// Loop Arraylist
System.out.println("\n\n");
System.out.println("Looping Example");
System.out.println("===============");
for (int i = 0; i < obj.size(); i++) {
System.out.println(obj.get(i));
}
System.out.println("\n\n");
System.out.println("Advance For Loop");
System.out.println("=================");
for (String str : obj) {
System.out.println(str);
}
System.out.println("\n\n");
System.out.println("Iterator Example");
System.out.println("=================");
Iterator<String> iter = obj.iterator();
while (iter.hasNext()) {
System.out.println(iter.next());
}
System.out.println("\n\n");
System.out.println("Sorting Example");
System.out.println("=================");
System.out.println("\nBefore Sorting:");
for (String str : obj) {
System.out.println(str);
}
Collections.sort(obj);
// Collections.sort(obj, Collections.reverseOrder()); //descending
// oreder
System.out.println("\nAfter Sorting:");
for (String str : obj) {
System.out.println(str);
}
System.out.println("\n\n");
System.out.println("Sorting Objects example with Comparable (Please note student object implements compoarable");
System.out.println("=================");
ArrayList<Student> arraylist = new ArrayList<Student>();
arraylist.add(new Student(223, "Chaitanya", 26));
arraylist.add(new Student(245, "Rahul", 24));
arraylist.add(new Student(249, "Ajeet", 32));
Collections.sort(arraylist);
for (Student str : arraylist) {
System.out.println(str);
}
System.out.println("\n\n");
System.out.println("Sorting Objects example with Comparator (Please note 2 methods in Student Class");
System.out.println("=================");
/* Sorting based on Student Name */
System.out.println("\nStudent Name Sorting:");
Collections.sort(arraylist, Student.StuNameComparator);
for (Student str : arraylist) {
System.out.println(str);
}
/* Sorting on Rollno property */
System.out.println("\nRollNum Sorting:");
Collections.sort(arraylist, Student.StuRollno);
for (Student str : arraylist) {
System.out.println(str);
}
System.out.println("\n\n");
System.out.println("Merging Arraylist");
System.out.println("=================");
obj.addAll(obj1);
System.out.println("Current Size is " + obj.size());
System.out.println("Current array list is:" + obj);
System.out.println("\n\n");
System.out.println("Sublist Example");
System.out.println("=================");
ArrayList<String> sublist = new ArrayList<String>(obj.subList(1, 4));
System.out.println("Current array sub list is:" + sublist);
System.out.println("\n\n");
System.out.println("Compare 2 Arraylist");
System.out.println("=================");
ArrayList<String> obj3 = new ArrayList<String>();
for (String temp : obj)
obj3.add(obj1.contains(temp) ? "Yes" : "No");
System.out.println(obj3);
System.out.println("\n\n");
System.out.println("Swap Example");
System.out.println("=================");
System.out.println("Before Swap");
System.out.println(obj);
Collections.swap(obj, 1, 4);
System.out.println("After Swap");
System.out.println(obj);
System.out.println("\n\n");
System.out.println("lastindex of element : obj.lastIndexOf(i)");
System.out.println("indexOf of element : obj.indexOf(str)");
System.out.println("contains element : obj.contains(str)");
System.out.println("ensureCapacity : obj.ensureCapacity(int)");
System.out.println("\n\n");
System.out.println(" More Exmaples : http://beginnersbook.com/2014/08/arraylist-in-java/");
}
}
|
// Authors: Mika, Thomas, Mason, Sohan
package org.team3128.common.autonomous;
import org.team3128.common.drive.Drive;
import org.team3128.common.drive.DriveSignal;
import org.team3128.common.hardware.gyroscope.Gyro;
import org.team3128.compbot.subsystems.FalconDrive;
import edu.wpi.first.wpilibj.command.CommandGroup;
public class CmdInPlaceTurn extends CommandGroup {
double startAngle, angle, timeoutMs, power;
FalconDrive drive;
Gyro gyro;
public CmdInPlaceTurn(FalconDrive drive, Gyro gyro, double angle, double power, double timeoutMs) {
this.drive = drive;
this.angle = angle;
this.gyro = gyro;
this.power = power;
this.timeoutMs = timeoutMs;
}
@Override
protected void initialize() {
startAngle = drive.getAngle();
if (angle > 0) {
drive.setWheelPower(new DriveSignal(-power, power));
}
else if (angle < 0) {
drive.setWheelPower(new DriveSignal(power, -power));
}
}
@Override
protected boolean isFinished() {
return drive.getAngle() - startAngle >= angle;
}
@Override
protected void end() {
drive.setWheelPower(new DriveSignal(0, 0));
}
} |
package gr.athena.innovation.fagi.core.similarity;
import gr.athena.innovation.fagi.core.normalizer.generic.AlphabeticalNormalizer;
/**
* Class for computing a sorted version of Jaro-Winkler distance.
*
* @author nkarag
*/
public class SortedJaroWinkler {
/**
* Computes a version of Jaro-Winkler Similarity by sorting the words of each string alphabetically.
*
* @param a The first string.
* @param b The second string.
* @return The result score.
*/
public static double computeSimilarity(String a, String b){
AlphabeticalNormalizer alphabeticalNormalizer = new AlphabeticalNormalizer();
String sortedA = alphabeticalNormalizer.normalize(a);
String sortedB = alphabeticalNormalizer.normalize(b);
double result = JaroWinkler.computeSimilarity(sortedA, sortedB);
return result;
}
/**
* Computes a version of Jaro-Winkler Distance by using the complement of
* {@link gr.athena.innovation.fagi.core.similarity.SortedJaroWinkler#computeSimilarity(String, String) computeSimilarity}.
*
* @param a The first string.
* @param b The second string.
* @return The result score.
*/
public static double computeDistance(String a, String b){
return 1 - computeSimilarity(a, b);
}
}
|
package com.realcom.helloambulance.pojo;
public class EmergencyBook {
private int emergency_book_id;
private int user_id;
private String address;
private String street;
private String city;
private String state;
private String zipcode;
private String country;
private String mobile;
private String latitude ;
private String longitude ;
private String date;
private String session_id;
/**
* @return the session_id
*/
public String getSession_id() {
return session_id;
}
/**
* @param session_id the session_id to set
*/
public void setSession_id(String session_id) {
this.session_id = session_id;
}
public int getEmergency_book_id() {
return emergency_book_id;
}
public void setEmergency_book_id(int emergency_book_id) {
this.emergency_book_id = emergency_book_id;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "EmergencyBook [emergency_book_id=" + emergency_book_id + ", user_id=" + user_id + ", address=" + address
+ ", street=" + street + ", city=" + city + ", state=" + state + ", zipcode=" + zipcode + ", country="
+ country + ", mobile=" + mobile + ", latitude=" + latitude + ", longitude=" + longitude + ", date="
+ date + ", session_id=" + session_id + "]";
}
}
|
package cn.codef1.library.markdownview.core;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by CoderF1 on 2017/11/9.
*/
public class HTMLDecoder {
public static String decode(String html) {
TextEditor ed = new TextEditor(html);
Pattern p1 = Pattern.compile("&#(\\d+);");
ed.replaceAll(p1, new Replacement() {
public String replacement(Matcher m) {
String charDecimal = m.group(1);
char ch = (char) Integer.parseInt(charDecimal);
return Character.toString(ch);
}
});
Pattern p2 = Pattern.compile("&#x([0-9a-fA-F]+);");
ed.replaceAll(p2, new Replacement() {
public String replacement(Matcher m) {
String charHex = m.group(1);
char ch = (char) Integer.parseInt(charHex, 16);
return Character.toString(ch);
}
});
return ed.toString();
}
} |
package com.zmji.arrangeactassert;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/**
* @Description:
* @Author: zhongmou.ji
* @Date: 2021/9/8 上午10:04
**/
public class CashAAATest {
@Test
void testPlus() {
// Arrange 初始化
Cash cash = new Cash(3);
//Act 操作
cash.plus(4);
//Assert 断言, 判断处理是否正确
assertEquals(7, cash.count());
}
@Test
void testMinus() {
//Arrange 初始化
Cash cash = new Cash(8);
//Act 操作
Boolean result = cash.minus(5);
//Assert 断言, 判断处理是否正确
assertTrue(result);
assertEquals(3, cash.count());
}
@Test
void testInsufficientMinus() {
//Arrange 初始化
Cash cash = new Cash(1);
//Act 操作
boolean result = cash.minus(6);
//Assert 断言, 判断处理是否正确
assertFalse(result);
assertEquals(1, cash.count());
}
@Test
void testUpdate() {
//Arrange 初始化
Cash cash = new Cash(5);
//Act 操作
cash.plus(6);
boolean result = cash.minus(3);
//Assert 断言, 判断处理是否正确
assertTrue(result);
assertEquals(8, cash.count());
}
}
|
package controle;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import modelo.Filme;
import modelo.Sessao;
import modelo.Usuario;
import repositorio.SessaoRepositorio;
/**
*
* @author mathe
*/
@Named
@SessionScoped
public class SessaoControle implements Serializable{
@Inject
private Sessao sessao;
@Inject
private SessaoRepositorio sessaoRepositorio;
public Sessao getSessao() {
return sessao;
}
Usuario usuario;
public void cadastrar() {
String msg;
try {
sessaoRepositorio.create(sessao);
msg = "Sessao " + sessao.getNumero() + " cadastrada com sucesso!";
sessao = new Sessao();
} catch (Exception e) {
msg = "Erro ao cadastrar sessao!";
}
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(msg));
}
public void deletar(Long numero) {
String msg;
try {
sessaoRepositorio.delete(numero);
msg = "Sessao deletada com sucesso!";
} catch (Exception e) {
msg = "Erro ao deletar sessão!";
}
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(msg));
}
public List<Sessao> getSessoes() {
List<Sessao> sessoes = new ArrayList<>();
try {
sessoes = sessaoRepositorio.findAll();
} catch (Exception e) {
System.out.println("Erro ao buscar sessoes!");
}
return sessoes;
}
public Sessao buscarSessaoPorId(Long numero) {
return sessaoRepositorio.findById(numero);
}
public List<Sessao> buscarSessaoPorFilme(Long id) {
return sessaoRepositorio.findByNumber(id);
}
public List<Sessao> buscarSessoesPorDatasIguais(){
return null;
}
public List<Sessao> buscarSessoesPorDataEFilme(Long id,Long idData){
return sessaoRepositorio.findSessoesByDataFilme(id, idData);
}
public String navegacaoSessoesDoFilme(Usuario usuario, Filme filme) {
System.out.println(usuario.getNome());
sessao.setFilme(filme);
return usuario.getNome().equals("admin") ? "sessoes_adm" : "sessoes";
}
}
|
import javax.swing.JOptionPane;
public class PopoUpDivByZero
{
public static void getPopUpMsgDivByZero() {
JOptionPane.showMessageDialog(null, "Cannot divide by zero");
}
}
|
package com.tencent.mm.plugin.appbrand.jsapi.i;
import android.content.Intent;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.MMActivity.a;
class a$1 implements a {
final /* synthetic */ b.a fWJ;
final /* synthetic */ a fWK;
a$1(a aVar, b.a aVar2) {
this.fWK = aVar;
this.fWJ = aVar2;
}
public final void b(int i, int i2, Intent intent) {
if (i == (this.fWK.hashCode() & 65535)) {
if (i2 == -1) {
if (this.fWJ != null) {
this.fWJ.a(1, null, null);
}
} else if (i2 == 5) {
int intExtra = intent.getIntExtra("key_jsapi_pay_err_code", 0);
x.e("MicroMsg.AppBrandJsApiPayService", "errCode: %d, errMsg: %s", new Object[]{Integer.valueOf(intExtra), bi.oV(intent.getStringExtra("key_jsapi_pay_err_msg"))});
if (this.fWJ != null) {
this.fWJ.a(2, r1, null);
}
} else if (this.fWJ != null) {
this.fWJ.a(3, null, null);
}
}
}
}
|
package com.jackpf.facebooknotifications.Facebook;
import com.restfb.Facebook;
import org.ocpsoft.prettytime.PrettyTime;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import javax.swing.ImageIcon;
public class Notification
{
public static class User
{
@Facebook
public String id;
@Facebook
public String name;
}
public static class Application
{
@Facebook
public String id;
@Facebook
public String name;
@Facebook
public String namespace;
}
@Facebook
public String id;
@Facebook
public User from;
@Facebook
public User to;
@Facebook("created_time")
public String createdTime;
@Facebook("updated_time")
public String updatedTime;
@Facebook
public String title;
@Facebook
public String link;
@Facebook
public Application application;
@Facebook
public int unread;
public ImageIcon image;
// Object?
public String getTitle(int len)
{
if (title.length() > len) {
return title.substring(0, len) + "...";
} else {
return title;
}
}
public Date getParsedDate() throws ParseException
{
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ssZZZZ", Locale.getDefault());
return df.parse(updatedTime);
}
public String getPrettyDate()
{
try {
return new PrettyTime().format(getParsedDate());
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
} |
package Recursion_Dynamic;
import java.util.ArrayList;
import java.util.List;
public class PowerSet {
private List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if (nums.length == 0) return res;
this.getSubSet(nums, 0, res, new ArrayList<>());
return res;
}
private void getSubSet(int[] nums, int curr, List<List<Integer>> res, List<Integer> subset) {
res.add(new ArrayList<>(subset));
for (int index = curr; index < nums.length; index++) {
subset.add(nums[index]);
getSubSet(nums, index + 1, res, subset);
subset.remove(subset.size() - 1);
}
}
public static void main(String[] argv) {
PowerSet ps = new PowerSet();
List<List<Integer>> res = ps.subsets(new int[]{1, 2, 3});
for (List<Integer> list : res) {
for (Integer a : list) {
System.out.print("" + a + ",");
}
System.out.println();
}
}
}
|
package Queue;
// jain pan 5728309
public class QueueDriver {
public static void main(String [] args){
Queue queue = new Queue();
queue.enqueue(3);
queue.enqueue(4);
queue.enqueue("a");
queue.enqueue(5);
queue.enqueue("c");
queue.dequeue();
//queue.dequeue();
System.out.println(queue.isEmpty());
System.out.println(queue.getFrontItem());
while(queue.isEmpty() == false){
System.out.print(queue.toString() + " ");
queue.dequeue();
}
// System.out.println(queue.toString());
}
}
|
package edu.sjsu.cmpe.cache.client;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import com.google.common.base.Charsets;
import com.google.common.hash.Funnel;
import com.google.common.hash.Funnels;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
/**
* @author Kandarp
*
*/
public class Client {
private static final Funnel<CharSequence> strFunnel = Funnels
.stringFunnel(Charset.defaultCharset());
private final static HashFunction hasher = Hashing.md5();
public static ArrayList<String> nodes = new ArrayList<String>();
public static void main(String[] args) throws Exception {
System.out.println("Starting Cache Client...");
SortedMap<Long, String> circle = new TreeMap<Long, String>();
nodes.add("http://localhost:3000");
nodes.add("http://localhost:3001");
nodes.add("http://localhost:3002");
for (int i = 0; i < nodes.size(); i++) {
//System.out.println( hasher.hashString(nodes.get(i), Charsets.UTF_8).padToLong() );
circle.put( hasher.hashString(nodes.get(i), Charsets.UTF_8).padToLong(), nodes.get(i));
}
List<Character> listChar = new ArrayList<Character>();
listChar.add('a');
listChar.add('b');
listChar.add('c');
listChar.add('d');
listChar.add('e');
listChar.add('f');
listChar.add('g');
listChar.add('h');
listChar.add('i');
listChar.add('j');
for (int i = 0; i < listChar.size(); i++) {
// For consistent hash
//String node = consistentHash( hasher.hashString(listChar.get(i).toString(), Charsets.UTF_8).padToLong(), circle);
// For rendezvous hash
String node = rendezvousHash(listChar.get(i).toString());
CacheServiceInterface cache = new DistributedCacheService(node);
cache.put(i + 1, listChar.get(i).toString());
System.out.println("put(" + (i + 1) + " => " + listChar.get(i) + ")");
}
System.out.println("Starting Cache Client...");
for (int i = 0; i < listChar.size(); i++) {
// For consistent hash
//String node = consistentHash( hasher.hashString( listChar.get(i).toString(), Charsets.UTF_8 ).padToLong(), circle);
// For rendezvous hash
String node = rendezvousHash(listChar.get(i).toString());
CacheServiceInterface cache = new DistributedCacheService(node);
String value = cache.get(i + 1);
System.out.println("get(" + (i + 1) + ") => " + value);
}
System.out.println("Existing Cache Client...");
}
/**
* Implementation of Consistent hashing
*
* @param hashfunction
* @param circle
* @return
*/
public static String consistentHash(Long hashfunction,
SortedMap<Long, String> circle) {
if (!circle.containsKey(hashfunction)) {
SortedMap<Long, String> tailMap = circle.tailMap(hashfunction);
hashfunction = tailMap.isEmpty() ? circle.firstKey() : tailMap.firstKey();
}
return circle.get(hashfunction);
}
/**
* Implementation of Rendezvous or Highest Random Weight (HRW)
*
* @param key
* @return value
*/
public static String rendezvousHash(String key) {
long maxValue = Long.MIN_VALUE;
String max = null;
for (String node : nodes) {
long nodesHash = hasher.newHasher().putObject(key, strFunnel)
.putObject(node, strFunnel).hash().asLong();
if (nodesHash > maxValue) {
max = node;
maxValue = nodesHash;
}
}
return max;
}
} |
package com.udian.entity;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
/**
* <p>
* 公交车辆基础信息表
* </p>
*
* @author Junkie
* @since 2018-05-18
*/
@TableName("tbl_base_bus")
public class TblBaseBus implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 车辆数据主键
*/
@TableId("bus_id")
private String busId;
/**
* 车牌号
*/
@TableField("bus_plate_number")
private String busPlateNumber;
/**
* 车辆自编号
*/
@TableField("bus_self_id")
private String busSelfId;
/**
* 燃料类型 1:汽油 2:柴油 3:纯电 4:混合
*/
@TableField("bus_fuel_type")
private Integer busFuelType;
/**
* 车辆型号表数据主键
*/
@TableField("bus_type_id")
private String busTypeId;
/**
* 购买日期
*/
@TableField("bus_purchase_date")
private Date busPurchaseDate;
/**
* 车辆投放日期
*/
@TableField("bus_delivery_date")
private Date busDeliveryDate;
/**
* 车辆计划报废日期
*/
@TableField("bus_plan_scrap_date")
private Date busPlanScrapDate;
/**
* 车辆实际报废日期
*/
@TableField("bus_real_scrap_date")
private Date busRealScrapDate;
/**
* 车辆运营证号
*/
@TableField("bus_operate_license")
private String busOperateLicense;
/**
* 车辆行驶证号
*/
@TableField("bus_driving_license")
private String busDrivingLicense;
/**
* 营运性质 1:营运 2:非营运
*/
@TableField("bus_is_operate")
private Integer busIsOperate;
/**
* 车辆状态 1:使用 2:停用 3:报废
*/
@TableField("bus_status")
private Integer busStatus;
/**
* 车辆VIN码
*/
@TableField("bus_vin_code")
private String busVinCode;
/**
* 车辆底盘号
*/
@TableField("bus_chassis_no")
private String busChassisNo;
/**
* 车辆发动机号
*/
@TableField("bus_engine_id")
private String busEngineId;
/**
* 车辆保修日期
*/
@TableField("bus_warranty_date")
private Date busWarrantyDate;
/**
* 车辆出厂日期
*/
@TableField("bus_product_date")
private Date busProductDate;
/**
* 车辆购买价格
*/
@TableField("bus_price")
private BigDecimal busPrice;
/**
* 备注
*/
@TableField("bus_memos")
private String busMemos;
/**
* 车辆所属组织ID
*/
@TableField("bus_org_id")
private String busOrgId;
@TableField("bus_plate_own")
private String busPlateOwn;
@TableField("bus_purpose")
private String busPurpose;
/**
* 车牌号颜色
*/
@TableField("bus_plate_color")
private String busPlateColor;
/**
* 图片名称可以多张图片
*/
@TableField("picture_name_json")
private String pictureNameJson;
/**
* 是否删除 0:否 1:是
*/
@TableField("is_delete")
private Integer isDelete;
/**
* 创建时间
*/
@TableField("create_time")
private Date createTime;
/**
* 修改时间
*/
@TableField("modify_time")
private Date modifyTime;
/**
* 最后一次操作人
*/
@TableField("modify_user_id")
private String modifyUserId;
public String getBusId() {
return busId;
}
public void setBusId(String busId) {
this.busId = busId;
}
public String getBusPlateNumber() {
return busPlateNumber;
}
public void setBusPlateNumber(String busPlateNumber) {
this.busPlateNumber = busPlateNumber;
}
public String getBusSelfId() {
return busSelfId;
}
public void setBusSelfId(String busSelfId) {
this.busSelfId = busSelfId;
}
public Integer getBusFuelType() {
return busFuelType;
}
public void setBusFuelType(Integer busFuelType) {
this.busFuelType = busFuelType;
}
public String getBusTypeId() {
return busTypeId;
}
public void setBusTypeId(String busTypeId) {
this.busTypeId = busTypeId;
}
public Date getBusPurchaseDate() {
return busPurchaseDate;
}
public void setBusPurchaseDate(Date busPurchaseDate) {
this.busPurchaseDate = busPurchaseDate;
}
public Date getBusDeliveryDate() {
return busDeliveryDate;
}
public void setBusDeliveryDate(Date busDeliveryDate) {
this.busDeliveryDate = busDeliveryDate;
}
public Date getBusPlanScrapDate() {
return busPlanScrapDate;
}
public void setBusPlanScrapDate(Date busPlanScrapDate) {
this.busPlanScrapDate = busPlanScrapDate;
}
public Date getBusRealScrapDate() {
return busRealScrapDate;
}
public void setBusRealScrapDate(Date busRealScrapDate) {
this.busRealScrapDate = busRealScrapDate;
}
public String getBusOperateLicense() {
return busOperateLicense;
}
public void setBusOperateLicense(String busOperateLicense) {
this.busOperateLicense = busOperateLicense;
}
public String getBusDrivingLicense() {
return busDrivingLicense;
}
public void setBusDrivingLicense(String busDrivingLicense) {
this.busDrivingLicense = busDrivingLicense;
}
public Integer getBusIsOperate() {
return busIsOperate;
}
public void setBusIsOperate(Integer busIsOperate) {
this.busIsOperate = busIsOperate;
}
public Integer getBusStatus() {
return busStatus;
}
public void setBusStatus(Integer busStatus) {
this.busStatus = busStatus;
}
public String getBusVinCode() {
return busVinCode;
}
public void setBusVinCode(String busVinCode) {
this.busVinCode = busVinCode;
}
public String getBusChassisNo() {
return busChassisNo;
}
public void setBusChassisNo(String busChassisNo) {
this.busChassisNo = busChassisNo;
}
public String getBusEngineId() {
return busEngineId;
}
public void setBusEngineId(String busEngineId) {
this.busEngineId = busEngineId;
}
public Date getBusWarrantyDate() {
return busWarrantyDate;
}
public void setBusWarrantyDate(Date busWarrantyDate) {
this.busWarrantyDate = busWarrantyDate;
}
public Date getBusProductDate() {
return busProductDate;
}
public void setBusProductDate(Date busProductDate) {
this.busProductDate = busProductDate;
}
public BigDecimal getBusPrice() {
return busPrice;
}
public void setBusPrice(BigDecimal busPrice) {
this.busPrice = busPrice;
}
public String getBusMemos() {
return busMemos;
}
public void setBusMemos(String busMemos) {
this.busMemos = busMemos;
}
public String getBusOrgId() {
return busOrgId;
}
public void setBusOrgId(String busOrgId) {
this.busOrgId = busOrgId;
}
public String getBusPlateOwn() {
return busPlateOwn;
}
public void setBusPlateOwn(String busPlateOwn) {
this.busPlateOwn = busPlateOwn;
}
public String getBusPurpose() {
return busPurpose;
}
public void setBusPurpose(String busPurpose) {
this.busPurpose = busPurpose;
}
public String getBusPlateColor() {
return busPlateColor;
}
public void setBusPlateColor(String busPlateColor) {
this.busPlateColor = busPlateColor;
}
public String getPictureNameJson() {
return pictureNameJson;
}
public void setPictureNameJson(String pictureNameJson) {
this.pictureNameJson = pictureNameJson;
}
public Integer getIsDelete() {
return isDelete;
}
public void setIsDelete(Integer isDelete) {
this.isDelete = isDelete;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getModifyTime() {
return modifyTime;
}
public void setModifyTime(Date modifyTime) {
this.modifyTime = modifyTime;
}
public String getModifyUserId() {
return modifyUserId;
}
public void setModifyUserId(String modifyUserId) {
this.modifyUserId = modifyUserId;
}
@Override
public String toString() {
return "TblBaseBus{" +
", busId=" + busId +
", busPlateNumber=" + busPlateNumber +
", busSelfId=" + busSelfId +
", busFuelType=" + busFuelType +
", busTypeId=" + busTypeId +
", busPurchaseDate=" + busPurchaseDate +
", busDeliveryDate=" + busDeliveryDate +
", busPlanScrapDate=" + busPlanScrapDate +
", busRealScrapDate=" + busRealScrapDate +
", busOperateLicense=" + busOperateLicense +
", busDrivingLicense=" + busDrivingLicense +
", busIsOperate=" + busIsOperate +
", busStatus=" + busStatus +
", busVinCode=" + busVinCode +
", busChassisNo=" + busChassisNo +
", busEngineId=" + busEngineId +
", busWarrantyDate=" + busWarrantyDate +
", busProductDate=" + busProductDate +
", busPrice=" + busPrice +
", busMemos=" + busMemos +
", busOrgId=" + busOrgId +
", busPlateOwn=" + busPlateOwn +
", busPurpose=" + busPurpose +
", busPlateColor=" + busPlateColor +
", pictureNameJson=" + pictureNameJson +
", isDelete=" + isDelete +
", createTime=" + createTime +
", modifyTime=" + modifyTime +
", modifyUserId=" + modifyUserId +
"}";
}
}
|
package pl.gabinetynagodziny.officesforrent.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.Repository;
import pl.gabinetynagodziny.officesforrent.entity.User;
import java.util.Optional;
public interface UserRepository extends JpaRepository<User, Long> {
//interface bez public
Optional<User> findByUsername(String username);
Optional<User> findByToken(String token);
}
|
package com.gregfmartin.smsdemo.components.services;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
/**
* Service for interacting with SMS Messages headlessly (quick response)
*
* @author gregfmartin
*/
public class HeadlessSmsSenderService extends Service {
@Override public IBinder onBind(Intent intent) {
return null;
}
}
|
package com.lhx.shiro.demo.web;
public class SessionConstants {
public static final String SESSION_LOGIN_USER = "loginUser";
public static final String SESSION_LOGIN_ROLES = "loginRoles";
public static final String SESSION_LOGIN_RESOURCE_URLS = "loginResourceUrls";
}
|
package sample.contractorsWindow;
public class ContractorRow {
private int id;
private String position;
private String fio;
private String orgName;
private String address;
private int okpo;
public ContractorRow(int id, String position, String fio, String orgName, String address, int okpo) {
this.id = id;
this.position = position;
this.fio = fio;
this.orgName = orgName;
this.address = address;
this.okpo = okpo;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public String getFio() {
return fio;
}
public void setFio(String fio) {
this.fio = fio;
}
public String getOrgName() {
return orgName;
}
public void setOrgName(String orgName) {
this.orgName = orgName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getOkpo() {
return okpo;
}
public void setOkpo(int okpo) {
this.okpo = okpo;
}
}
|
package FinalExam_04_April_2020_Group2;
import java.util.Scanner;
public class _01_PasswordReset {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
String cmd = scanner.nextLine();
StringBuilder pass = new StringBuilder();
while (!cmd.equals("Done")) {
String[] tokens = cmd.split(" ");
if (tokens[0].equals("TakeOdd")) {
for (int i = 0; i < input.length(); i++) {
if (i % 2 != 0) {
pass.append(input.charAt(i));
}
}
System.out.println(pass.toString());
input = pass.toString();
} else if (tokens[0].equals("Cut")) {
// String toRemove = input.substring(Integer.parseInt(tokens[1]),
// Integer.parseInt(tokens[2]) + Integer.parseInt(tokens[1]));
//pass = new StringBuilder();
//pass.append(input);
//input = input.replace(toRemove, "");
input = input.substring(0, Integer.parseInt(tokens[1])) +
input.substring( Integer.parseInt(tokens[2]) + Integer.parseInt(tokens[1]));
System.out.println(input);
} else if (tokens[0].equals("Substitute")) {
if (input.contains(tokens[1])) {
input = input.replaceAll(tokens[1], tokens[2]);
System.out.println(input);
} else {
System.out.println("Nothing to replace!");
}
}
cmd = scanner.nextLine();
}
if (input.length() != 0) {
System.out.printf("Your password is: %s", input);
}
}
}
|
package co.uniqueid.authentication.client.uniqueid;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
/**
* The client side stub for the RPC service.
*/
@RemoteServiceRelativePath("uniqueID")
public interface UniqueIDService extends RemoteService {
String getUniqueID(final String unoUserID);
String getUniqueIDByField(final String fieldName, final String fieldValue);
String saveUniqueID(final String unoUserJsonString);
}
|
package pl.cwanix.opensun.utils.files;
import org.apache.commons.lang3.StringUtils;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;
public class SUNFileReader extends Reader {
private static final String COMMENT_PREFIX = "//";
private static final String DELIMITER = "\\t";
private final BufferedReader in;
private Map<String, Integer> header;
private String[] currentLine;
private int currentLineIndex;
private int currentElementIndex;
public SUNFileReader(final String filePath) throws IOException {
this.in = new BufferedReader(new FileReader(filePath));
loadHeader();
}
public int read(final char[] chars, final int i, final int i1) throws IOException {
return in.read(chars, i, i1);
}
public boolean readLine() throws IOException {
String line;
boolean changed = false;
while ((line = in.readLine()) != null) {
++currentLineIndex;
line = line.trim();
if (StringUtils.isNotBlank(line) && !line.startsWith(COMMENT_PREFIX)) {
currentLine = line.split(DELIMITER);
currentElementIndex = 0;
changed = true;
break;
}
}
return changed;
}
public String readNextStringValue() {
return currentLine[currentElementIndex++];
}
public int readNextIntValue() {
return Integer.parseInt(currentLine[currentElementIndex++]);
}
public byte readNextByteValue() {
return Byte.parseByte(currentLine[currentElementIndex++]);
}
public String readNextStringValue(final String key) {
return currentLine[header.get(key)];
}
public int readNextIntValue(final String key) {
return Integer.parseInt(currentLine[header.get(key)]);
}
public void close() throws IOException {
in.close();
}
private void loadHeader() throws IOException {
header = new HashMap<>();
readLine();
for (int i = 0; i < currentLine.length; i++) {
header.put(currentLine[i], i);
}
}
}
|
package com.komaxx.komaxx_gl.texturing;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Hashtable;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLES20;
import android.opengl.GLUtils;
import com.komaxx.komaxx_gl.RenderConfig;
import com.komaxx.komaxx_gl.RenderContext;
import com.komaxx.komaxx_gl.util.KoLog;
import com.komaxx.komaxx_gl.util.RenderUtil;
public class TextureStore {
private static final boolean DEBUG = false;
private Hashtable<Integer, ResourceTexture> resourceTextures = new Hashtable<Integer, TextureStore.ResourceTexture>();
private static int[] tmpTextureHandle = new int[1];
private static int nextOwnerID = 1;
/**
* Whenever requesting a texture (or texture segment), obtain one
* of these global IDs first and use it to own the texture (segment).
*/
public static int createOwnerID(){
return nextOwnerID++;
}
public TextureStore(){
}
public void reset(){
// discard all old textures
Enumeration<ResourceTexture> elements = resourceTextures.elements();
while (elements.hasMoreElements()) elements.nextElement().delete();
resourceTextures.clear();
clearAllocationTracking();
}
public TextureStrip getTextureStrip(TextureStripConfig config){
// TODO: check in pool whether still one stored in a cache.
TextureStrip ret = new TextureStrip(config);
return ret;
}
/**
* Delivers the texture (possibly creates it first). In case of new creation, the bound
* texture may change! No need to extra "create" like TextureStrips!
*/
public ResourceTexture getResourceTexture(RenderContext rc, int rawId, boolean mipMapped){
ResourceTexture ret = resourceTextures.get(rawId);
if (ret != null) return ret;
ret = new ResourceTexture();
ret.resourceId = rawId;
ret.mipMapped = mipMapped;
GLES20.glGenTextures(1, tmpTextureHandle, 0);
ret.handle = tmpTextureHandle[0];
rc.bindTexture(tmpTextureHandle[0]);
if (mipMapped){
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR_MIPMAP_LINEAR);
} else {
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
}
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
Bitmap bitmap = getBitmap(rc, rawId);
ret.width = bitmap.getWidth();
ret.height = bitmap.getWidth();
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);
RenderUtil.checkGlError("Bind resource texture");
if (RenderConfig.RECYCLE_BITMAPS) bitmap.recycle();
if (mipMapped){
GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D);
RenderUtil.checkGlError("Generate mipmaps");
}
textureCreated(ret);
resourceTextures.put(rawId, ret);
return ret;
}
public static class ResourceTexture {
private int resourceId;
private int handle;
private int width;
private int height;
private boolean mipMapped = false;
private ResourceTexture(){
// not publicly constructible
}
public int getHandle() {
return handle;
}
public void delete() {
tmpTextureHandle[0] = this.handle;
GLES20.glDeleteTextures(1, tmpTextureHandle, 0);
TextureStore.textureDeleted(this);
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public int getResourceId() {
return resourceId;
}
public boolean isMipMapped() {
return mipMapped;
}
}
/**
* Reads a BitmapDrawable from the application package and returns
* the encapsulated Bitmap.
*/
public static Bitmap getBitmap(RenderContext rc, int id){
return getBitmap(rc.resources, id);
}
public static Bitmap getBitmap(Resources res, int id) {
InputStream is = res.openRawResource(id);
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeStream(is);
} finally {
try {
is.close();
} catch(Exception e) {
KoLog.e("RenderUtil", "Error when loading bitmap " + id + ": " + e.toString());
}
}
return bitmap;
}
// //////////////////////////////////////////////////////////////////
// profiling
private static int textureAllocations = 0;
private static int usedTextureMemory = 0;
public static void clearAllocationTracking(){
textureAllocations = 0;
usedTextureMemory = 0;
}
public static void textureCreated(Texture tex){
TextureConfig config = tex.getConfig();
textureMemoryAllocated(estimateSizeBytes(
tex.getWidth(), tex.getHeight(), config.alphaChannel, config.mipMapped));
}
public static void textureCreated(ResourceTexture tex) {
textureMemoryAllocated(
estimateSizeBytes(tex.getWidth(), tex.getHeight(), true, tex.mipMapped));
}
public static void textureDeleted(Texture tex) {
TextureConfig config = tex.getConfig();
textureMemoryFreed(
estimateSizeBytes(tex.getWidth(), tex.getHeight(), config.alphaChannel, config.mipMapped));
}
public static void textureDeleted(ResourceTexture tex) {
textureMemoryFreed(
estimateSizeBytes(tex.getWidth(), tex.getHeight(), true, tex.mipMapped));
}
private static void textureMemoryAllocated(int size){
usedTextureMemory += size;
textureAllocations++;
if (DEBUG) KoLog.i("TextureStore", "Texture memory allocated! Allocations: "+textureAllocations
+", overall size: "+usedTextureMemory);
}
private static void textureMemoryFreed(int size){
usedTextureMemory -= size;
textureAllocations--;
if (DEBUG) KoLog.i("TextureStore", "Texture memory freed! Allocations: "+textureAllocations
+", overall size: "+usedTextureMemory);
}
private static int estimateSizeBytes
(int width, int height, boolean alpha, boolean mipMapped) {
int pixelSize = (alpha ? 4 : 2);
int ret = width * height * pixelSize;
if (mipMapped){
int tmpWidth = width/2;
int tmpHeight = height/2;
while (tmpWidth > 1 && tmpHeight > 1){
ret += tmpWidth * tmpHeight * pixelSize;
tmpWidth /= 2;
tmpHeight /= 2;
}
}
return ret;
}
}
|
package springframework;
public interface WithoutSpringInterface {
String add(String a, String b);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.