text stringlengths 10 2.72M |
|---|
// Generated code from Butter Knife. Do not modify!
package com.zhicai.byteera.activity.initialize;
import android.view.View;
import butterknife.ButterKnife.Finder;
import butterknife.ButterKnife.ViewBinder;
public class LoginActivity$$ViewBinder<T extends com.zhicai.byteera.activity.initialize.LoginActivity> implements ViewBinder<T> {
@Override public void bind(final Finder finder, final T target, Object source) {
View view;
view = finder.findRequiredView(source, 2131427552, "field 'et_username' and method 'onTextChanged'");
target.et_username = finder.castView(view, 2131427552, "field 'et_username'");
((android.widget.TextView) view).addTextChangedListener(
new android.text.TextWatcher() {
@Override public void onTextChanged(
java.lang.CharSequence p0,
int p1,
int p2,
int p3
) {
target.onTextChanged();
}
@Override public void beforeTextChanged(
java.lang.CharSequence p0,
int p1,
int p2,
int p3
) {
}
@Override public void afterTextChanged(
android.text.Editable p0
) {
}
});
view = finder.findRequiredView(source, 2131427628, "field 'et_pwd'");
target.et_pwd = finder.castView(view, 2131427628, "field 'et_pwd'");
view = finder.findRequiredView(source, 2131427551, "field 'mHeadView'");
target.mHeadView = finder.castView(view, 2131427551, "field 'mHeadView'");
view = finder.findRequiredView(source, 2131427631, "method 'onClick'");
view.setOnClickListener(
new butterknife.internal.DebouncingOnClickListener() {
@Override public void doClick(
android.view.View p0
) {
target.onClick(p0);
}
});
view = finder.findRequiredView(source, 2131427632, "method 'onClick'");
view.setOnClickListener(
new butterknife.internal.DebouncingOnClickListener() {
@Override public void doClick(
android.view.View p0
) {
target.onClick(p0);
}
});
view = finder.findRequiredView(source, 2131427630, "method 'onClick'");
view.setOnClickListener(
new butterknife.internal.DebouncingOnClickListener() {
@Override public void doClick(
android.view.View p0
) {
target.onClick(p0);
}
});
}
@Override public void unbind(T target) {
target.et_username = null;
target.et_pwd = null;
target.mHeadView = null;
}
}
|
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Regression tests for BCE.
*/
public class Main {
static int[] array = new int[10];
/// CHECK-START: int Main.doNotVisitAfterForwardBCE(int[]) BCE (before)
/// CHECK-DAG: BoundsCheck loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: BoundsCheck loop:<<Loop>> outer_loop:none
//
/// CHECK-START: int Main.doNotVisitAfterForwardBCE(int[]) BCE (after)
/// CHECK-NOT: BoundsCheck
static int doNotVisitAfterForwardBCE(int[] a) {
if (a == null) {
throw new Error("Null");
}
int k = 0;
int j = 0;
for (int i = 1; i < 10; i++) {
j = i - 1;
// b/32547652: after DCE, bounds checks become consecutive,
// and second should not be revisited after forward BCE.
k = a[i] + a[i - 1];
}
return j;
}
static public void $noinline$regressionTest123284765(String str) {
try {
int l = str.length();
if (l == 34) {
str.charAt(l);
fail();
}
} catch (StringIndexOutOfBoundsException expected) {
expectEquals(34, str.length());
}
}
public static void main(String[] args) {
expectEquals(8, doNotVisitAfterForwardBCE(array));
$noinline$regressionTest123284765("0123456789012345678901234567890123");
$noinline$regressionTest123284765("012345678901");
System.out.println("passed");
}
private static void expectEquals(int expected, int result) {
if (expected != result) {
throw new Error("Expected: " + expected + ", found: " + result);
}
}
private static void fail() {
throw new Error("FAIL");
}
}
|
/*
* 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 hotels;
import javax.swing.table.DefaultTableModel;
/**
*
* @author Nyagritin
*/
public class MayaStock extends javax.swing.JFrame {
/**
* Creates new form MayaStock
*/
public MayaStock() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jTextField5 = new javax.swing.JTextField();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jProductID = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
jProducts = new javax.swing.JTable();
IMessage = new javax.swing.JLabel();
jAdd = new javax.swing.JButton();
jUodate = new javax.swing.JButton();
jClear = new javax.swing.JButton();
jProductCategory = new javax.swing.JTextField();
jProductQuantity = new javax.swing.JTextField();
jTextField5.setText("jTextField5");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Algerian", 1, 18)); // NOI18N
jLabel1.setText("Maya Stock");
jLabel2.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
jLabel2.setText("Inventory ID");
jLabel5.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
jLabel5.setText("Inventory type");
jLabel7.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
jLabel7.setText("Inventory Status");
jProductID.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
jProductID.setText("jTextField1");
jProducts.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null}
},
new String [] {
"InventoryID", "InventoryStatus", "InventoryType"
}
) {
Class[] types = new Class [] {
java.lang.Integer.class, java.lang.Integer.class, java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(jProducts);
if (jProducts.getColumnModel().getColumnCount() > 0) {
jProducts.getColumnModel().getColumn(0).setResizable(false);
jProducts.getColumnModel().getColumn(1).setResizable(false);
jProducts.getColumnModel().getColumn(2).setResizable(false);
}
jAdd.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
jAdd.setText("Add");
jAdd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jAddActionPerformed(evt);
}
});
jUodate.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
jUodate.setText("Update");
jUodate.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jUodateActionPerformed(evt);
}
});
jClear.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
jClear.setText("Clear");
jClear.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jClearActionPerformed(evt);
}
});
jProductCategory.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
jProductCategory.setText("jTextField4");
jProductQuantity.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
jProductQuantity.setText("jTextField7");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(232, 232, 232)
.addComponent(jLabel1))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(139, 139, 139)
.addComponent(IMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(79, 79, 79)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jAdd)
.addGap(59, 59, 59)
.addComponent(jUodate)
.addGap(89, 89, 89)
.addComponent(jClear))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(50, 50, 50)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel7))
.addGap(27, 27, 27)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jProductID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(130, 130, 130)
.addComponent(jLabel5)
.addGap(56, 56, 56)
.addComponent(jProductCategory, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jProductQuantity, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(38, 38, 38)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jLabel5)
.addComponent(jProductID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jProductCategory, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(23, 23, 23)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(jProductQuantity, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(IMessage)
.addGap(25, 25, 25)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jAdd)
.addComponent(jUodate)
.addComponent(jClear))
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(296, 296, 296))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(94, 94, 94)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(291, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(45, 45, 45)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 493, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(262, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jAddActionPerformed
// TODO add your handling code here:
IMessage.setText("");
DefaultTableModel model = (DefaultTableModel)jProducts.getModel();
if(!jProductID.getText().trim().equals("")){
model.addRow(new Object[]{jProductID.getText(),jProductCategory.getText(),jProductQuantity.getText()});
}else{
IMessage.setText("Product ID cannot be empty");
}
}//GEN-LAST:event_jAddActionPerformed
private void jUodateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jUodateActionPerformed
// TODO add your handling code here:
IMessage.setText("");
DefaultTableModel model = (DefaultTableModel) jProducts.getModel();
if(jProducts.getSelectedRow()==-1){
if(jProducts.getRowCount()==0){
IMessage.setText("The table is empty");
}else{
IMessage.setText("Please select product to update");
}
}else{
model.setValueAt(jProductID.getText(),jProducts.getSelectedRow(),0);
model.setValueAt(jProductCategory.getText(),jProducts.getSelectedRow(),3);
model.setValueAt(jProductQuantity.getText(),jProducts.getSelectedRow(),5);
}
}//GEN-LAST:event_jUodateActionPerformed
private void jClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jClearActionPerformed
// TODO add your handling code here:
IMessage.setText("");
DefaultTableModel model = (DefaultTableModel) jProducts.getModel();
if(jProducts.getSelectedRow()==-1){
if(jProducts.getRowCount()==0){
IMessage.setText("The table is empty");
}else{
IMessage.setText("Please select a product");
}
}else{
model.removeRow(jProducts.getSelectedRow());
}
}//GEN-LAST:event_jClearActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MayaStock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MayaStock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MayaStock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MayaStock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MayaStock().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel IMessage;
private javax.swing.JButton jAdd;
private javax.swing.JButton jClear;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel7;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField jProductCategory;
private javax.swing.JTextField jProductID;
private javax.swing.JTextField jProductQuantity;
private javax.swing.JTable jProducts;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField jTextField5;
private javax.swing.JButton jUodate;
// End of variables declaration//GEN-END:variables
}
|
package dk.sidereal.lumm.architecture.core.input;
/**
* Class encapsulating an event to run when scrolling
*
* @author Claudiu Bele
*/
public abstract class OnScrollListener {
/**
* Event to run whenever the mouse wheel is scrolled. The amount of scroll
* is not guaranteed to be the same for the same scroll amount on multiple
* mice.
*
* @param scrollAmount the amount that been scrolled
* @return whether the action was handled, for multiplexing.
*/
public boolean run(int scrollAmount) {
return false;
}
}
|
/**
* Write a description of class Runner here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Runner
{
public static void main(String[] args) {
Square1 s = new Square1(1);
Rectangle1 r = new Rectangle1(1,1);
System.out.println(s);
System.out.println(r);
System.out.println(s instanceof Square1); //true
System.out.println(s instanceof Rectangle1); //true
System.out.println(r instanceof Square1); //false
System.out.println(r instanceof Rectangle1); //true
}
}
|
package jire.persist;
public interface Persistable {
} |
package com.gsccs.sme.web.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.gsccs.sme.api.domain.corp.Corp;
import com.gsccs.sme.api.exception.ApiException;
import com.gsccs.sme.api.service.ConfigServiceI;
import com.gsccs.sme.api.service.CorpServiceI;
import com.gsccs.sme.api.service.AccountServiceI;
import com.gsccs.sme.web.api.service.RedisService;
/**
* 中小企业控制类
*
* @author x.d zhang
*
*/
@Controller
public class CorpController {
@Autowired
private AccountServiceI accountAPI;
@Autowired
private CorpServiceI corpAPI;
@Autowired
private ConfigServiceI configAPI;
@Autowired
private RedisService redisService;
/**
* 中小企业列表页面
*
* @param model
* @param response
* @return
*/
@RequestMapping(value = "corp.html", method = RequestMethod.GET)
public String scorplist(@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "10") int num, String keyword,
String scode, String subscode, String pcode, String ccode,
String acode,Long parkid,
Model model, HttpServletRequest request,
HttpServletResponse response) {
model.addAttribute("keyword", keyword);
model.addAttribute("scode", scode);
model.addAttribute("subscode", subscode);
model.addAttribute("pcode", pcode);
model.addAttribute("ccode", ccode);
model.addAttribute("acode", acode);
model.addAttribute("page", page);
model.addAttribute("num", num);
model.addAttribute("parkid", parkid);
return "corplist";
}
/**
* 中小企业详情页
*
* @param id
* @param model
* @return
*/
@RequestMapping(value = "/corp-{id}.html", method = RequestMethod.GET)
public String corpDetail(@PathVariable("id") Long id, Model model,
HttpServletResponse response) {
String tempPath = "corp";
try {
Corp corp = corpAPI.getCorp(id);
model.addAttribute("currCorp", corp);
} catch (ApiException e) {
e.printStackTrace();
}
return tempPath;
}
}
|
package hu.mitro.ejb.facade;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import org.apache.log4j.Logger;
import hu.mitro.ejb.converter.CarConverter;
import hu.mitro.ejb.converter.ClientConverter;
import hu.mitro.ejb.converter.ContractConverter;
import hu.mitro.ejb.domain.CarStub;
import hu.mitro.ejb.domain.ClientStub;
import hu.mitro.ejb.domain.ContractStub;
import hu.mitro.ejb.exception.FacadeLayerException;
import hu.mitro.persistence.entity.Car;
import hu.mitro.persistence.entity.Client;
import hu.mitro.persistence.entity.Contract;
import hu.mitro.persistence.exception.PersistenceLayerException;
import hu.mitro.persistence.service.ClientService;
import hu.mitro.persistence.service.ContractService;
@Stateless
public class ContractFacadeImpl implements ContractFacade {
@EJB
ContractService contractService;
@EJB
ContractConverter contractConverter;
@EJB
ClientService clientService;
@EJB
ClientConverter clientConverter;
@EJB
CarConverter carConverter;
private static final Logger LOGGER = Logger.getLogger(ContractFacadeImpl.class);
@Override
public List<ContractStub> getAllOfContracts() throws FacadeLayerException {
LOGGER.info("[INFO] Get all of Contracts [facade].");
List<ContractStub> contracts = new ArrayList<>();
List<Contract> entities = new ArrayList<>();
try {
entities = contractService.readAllContracts();
for (Contract c : entities) {
contracts.add(contractConverter.convert(c));
}
} catch (Exception e) {
throw new FacadeLayerException(
"[ERROR] Error occured during the fetch all of Contracts [facade].",
e);
}
return contracts;
}
@Override
public ContractStub getContractById(Long id) throws FacadeLayerException {
LOGGER.info("[INFO] Get a Contract by id [facade].");
ContractStub contractStub = null;
try {
contractStub = contractConverter
.convert(contractService.readContractById(id));
} catch (Exception e) {
throw new FacadeLayerException(
"[ERROR] Error occured during the fetch of Contract by id (" + id
+ ") [facade].",
e);
}
return contractStub;
}
@Override
public ContractStub getContractByContractId(String contractId)
throws FacadeLayerException {
LOGGER.info("[INFO] Get a Contract by contract id [facade].");
ContractStub contractStub = null;
try {
contractStub = contractConverter
.convert(contractService.readContractByContractId(contractId));
} catch (Exception e) {
throw new FacadeLayerException(
"[ERROR] Error occured during the fetch of Contract by contract id ("
+ contractId + ") [facade].",
e);
}
return contractStub;
}
@Override
public List<ContractStub> getContractsOfClient(String clientEmail)
throws FacadeLayerException {
LOGGER.info("[INFO] Get Contracts by Client [facade].");
List<ContractStub> contracts = new ArrayList<>();
List<Contract> entities = new ArrayList<>();
try {
entities = contractService.readContractByClient(clientEmail);
for (Contract c : entities) {
contracts.add(contractConverter.convert(c));
}
} catch (Exception e) {
throw new FacadeLayerException(
"[ERROR] Error occured during the fetch of all Contracts [facade].",
e);
}
return contracts;
}
@Override
public ContractStub getContractByCar(String licencePlateNumber)
throws FacadeLayerException {
LOGGER.info("[INFO] Get a Contract by Car [facade].");
ContractStub contractStub = null;
try {
contractStub = contractConverter
.convert(contractService.readContractByCar(licencePlateNumber));
} catch (Exception e) {
throw new FacadeLayerException(
"Error occured during the fetch of Contract by Car ("
+ licencePlateNumber + ") [facade].",
e);
}
return contractStub;
}
@Override
public List<ContractStub> getContractByDate(Date date) throws FacadeLayerException {
LOGGER.info("[INFO] Get all of Contracts by date [facade].");
List<ContractStub> contracts = new ArrayList<>();
List<Contract> entities = new ArrayList<>();
try {
entities = contractService.readContractByDate(date);
for (Contract c : entities) {
contracts.add(contractConverter.convert(c));
}
} catch (Exception e) {
throw new FacadeLayerException(
"[ERROR] Error occured during the fetch of all Contracts by date: "
+ date + " [facade].",
e);
}
return contracts;
}
@Override
public List<ContractStub> getActiveContracts() throws FacadeLayerException {
LOGGER.info("[INFO] Get all of active Contracts [facade].");
List<ContractStub> contractStubs = new ArrayList<>();
List<Contract> entities = new ArrayList<>();
try {
entities = contractService.readActiveContracts();
for (Contract c : entities) {
contractStubs.add(contractConverter.convert(c));
}
} catch (Exception e) {
throw new FacadeLayerException(
"Error occured during the fetch all of active Contracts [facade].",
e);
}
return contractStubs;
}
@Override
public ContractStub createContract(ContractStub contractStub, CarStub carStub,
ClientStub clientStub) throws FacadeLayerException {
LOGGER.info("[INFO] Create a new contract with given Client and Car [facade].");
ContractStub createContract = null;
Contract contract = null;
Car car = null;
Client client = null;
try {
car = carConverter.convertBack(carStub);
client = clientConverter.convertBack(clientStub);
contract = contractConverter.convertBack(contractStub);
createContract = contractConverter
.convert(contractService.createContract(contract, car, client));
LOGGER.info("[INFO] The creation of contract was successfull [facade].");
} catch (PersistenceLayerException e) {
throw new FacadeLayerException(e.getLocalizedMessage(), e);
} catch (Exception e) {
throw new FacadeLayerException(
"[ERROR] Error occured during the creational of contract [facade].",
e);
}
return createContract;
}
@Override
public ContractStub updateContract(ContractStub contractStub)
throws FacadeLayerException {
LOGGER.info("[INFO] Update an existing Contract [facade].");
ContractStub updateContract = null;
try {
updateContract = contractConverter.convert(contractService
.updateContract(contractConverter.convertBack(contractStub)));
LOGGER.info("[INFO] The update of Contract was successfull [facade].");
} catch (Exception e) {
throw new FacadeLayerException(
"[ERROR] Error occured during the update of Contract [facade].", e);
}
return updateContract;
}
@Override
public ContractStub removeContract(ContractStub contractStub)
throws FacadeLayerException {
LOGGER.info("[INFO] Remove an existing Contract. [facade]");
ContractStub deleteContract = null;
try {
deleteContract = contractConverter.convert(contractService
.removeContract(contractConverter.convertBack(contractStub)));
LOGGER.info("[INFO] The deletion of Contract was successfull [facade].");
} catch (Exception e) {
throw new FacadeLayerException(
"[ERROR] Error occured during the deletion of Contract [facade].", e);
}
return deleteContract;
}
@Override
public boolean setContractToActive(String contractId) throws FacadeLayerException {
LOGGER.info("[INFO] Set to active an existing Contract. [facade]");
boolean result = false;
try {
result = contractService.setContractToActive(contractId);
LOGGER.info(
"[INFO] The setting of Contract's state was successfull [facade].");
} catch (Exception e) {
throw new FacadeLayerException(
"[ERROR] Error occured during the setting of Contract's state [facade].",
e);
}
return result;
}
@Override
public boolean setContractToInActive(String contractId) throws FacadeLayerException {
LOGGER.info("[INFO] Set to inactive an existing Contract. [facade]");
boolean result = false;
try {
result = contractService.setContractToInActive(contractId);
LOGGER.info(
"[INFO] The setting of Contract's state was successfull [facade].");
} catch (Exception e) {
throw new FacadeLayerException(
"[ERROR] Error occured during the setting of Contract's state [facade].",
e);
}
return result;
}
}
|
/*
* 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 giacomoglotzerprojectdata;
import com.google.gson.Gson;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.Scanner;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.XYChart;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.Slider;
import javafx.scene.input.MouseEvent;
import javafx.scene.media.AudioClip;
/**
*
* @author csstudent
*/
public class GiacomoGlotzerProjectDataController implements Initializable {
@FXML
private BarChart chart;
@FXML
private MenuBar menubar;
@FXML
private MenuItem menuitem;
@FXML
private MenuItem reset;
@FXML
private MenuItem about;
@FXML
private Slider slider1;
@FXML
private Slider slider2;
@FXML
public void handleGetNewData(ActionEvent event){
updateData();
}
@FXML
private void handleAbout(ActionEvent event){
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("Polio Immunization Data");
alert.setHeaderText("Information Dialog");
alert.setContentText("This is data representing countries and their immunization reports. On the y-axis, is the percent of people who have polio vaccinations. On the x-axis, are the names of the countries examined. Use the sliders to change the zoom and perspective. ");
alert.showAndWait();
}
@FXML
private void handleCloseButton(ActionEvent event){
Platform.exit();
}
@FXML
private void handleReset(ActionEvent event){
updateData();
}
// This may vary depending on how the control is changed: mouse vs. keyboard
@FXML
private void handleChangeFilter(MouseEvent event) {
int min = (int) slider1.getValue();
int max = (int) slider2.getValue();
Settings.setMinValue(min);
Settings.setMaxValue(max);
updateGraph(min, max);
AudioClip sound = new AudioClip(getClass().getResource("airplane.mp3").toString());
sound.play();
}
@Override
public void initialize(URL url, ResourceBundle rb) {
if(Settings.getArray()== null) {
updateData();
}
updateGraph(Settings.getMinimum(), Settings.getMaximum());
}
public void updateData(){
String s = "http://apps.who.int/gho/athena/data/GHO/WHS4_544.json?profile=simple&filter=YEAR:1980";
URL myUrl;
myUrl = null;
try {
myUrl = new URL(s);
} catch (Exception e) {
System.out.println("Improper URL " + s);
System.exit(-1);
}
// read from the URL
Scanner scan = null;
try {
scan = new Scanner(myUrl.openStream());
} catch (Exception e) {
System.out.println("Could not connect to " + s);
System.exit(-1);
}
String str = new String();
while (scan.hasNext()) {
str += scan.nextLine() + "\n";
}
scan.close();
Gson gson = new Gson();
DataSet Data = gson.fromJson(str, DataSet.class);
Country[] Mycountries = Data.getCountry();
XYChart.Series<String, Number> polioData = new XYChart.Series();
polioData.setName("Polio Immunization Inspections");
for(Country c : Mycountries){
if(c.getDim().getCountry() != null){
String name = c.getDim().getCountry();
int val = c.getValue();
polioData.getData().add(new XYChart.Data(name, val));
}
}
Settings.setArray(Mycountries);
chart.getData().add(polioData);
}
public void updateGraph(int min, int max){
chart.getData().clear();
Country[] Mycountries = Settings.getArray();
XYChart.Series<String, Number> polioData = new XYChart.Series();
polioData.setName("Polio Immunization Inspections");
for(Country c : Mycountries){
if(c.getDim().getCountry() != null){
if(c.getValue() >= min && c.getValue() <= max){
String name = c.getDim().getCountry();
int val = c.getValue();
polioData.getData().add(new XYChart.Data(name, val));
}
}
}
chart.getData().add(polioData);
}
}
|
package com.landschootl.kinesis;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
@JsonInclude(JsonInclude.Include.NON_NULL)
public class DataKinesis {
@JsonProperty("key")
public String key;
@JsonProperty("value1")
public Integer value1;
@JsonProperty("value2")
public Integer value2;
@JsonProperty("value3")
public Integer value3;
@JsonProperty("value4")
public Integer value4;
} |
package creational.factorymethod.product;
// 产品接口
public interface Product {
void name();
}
|
package test;
import java.util.ArrayList;
import java.util.List;
import system.Yoyakukun;
public class Test2 {
public static void main(String[] args) {
Yoyakukun yoyaku01 = new Yoyakukun("スポーツ(屋内)", "サロンフットボール・フットサル", "札幌市", null,"2021/02/01","2021/02/27",null);
String placeName = yoyaku01.getPlaceName();
if(placeName.equals("スポーツ交流")){
System.out.println("等しい");
}
List<String> days = new ArrayList<>();
days.add("4");
String month = "2";
for(String day : days){
System.out.println(month + "月" + day + "日");
}
}
}
|
/*
* 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 agenda;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashSet;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Tzunfo
*/
public class Archivo implements Serializable {
private String path;
File archivo= null;
public String getPath() {
return path;
}
public void setPath(String path) {
this.archivo = new File(path);
this.path = path;
}
public void addPersonas(HashSet<Persona> nuevasPersona) {
HashSet<Persona> todasLasPersonas = this.readPersonas();
todasLasPersonas.addAll(nuevasPersona);
this.writeListaPersonas(todasLasPersonas);
}
public void writeListaPersonas(HashSet<Persona> lista) {
try {
FileOutputStream fos = new FileOutputStream(path);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(lista);
oos.close();
fos.close();
System.out.println("Archivo guardado en:" + path);
} catch (IOException ex) {
Logger.getLogger(Archivo.class.getName()).log(Level.SEVERE, null, ex);
}
}
public HashSet<Persona> readPersonas() {
HashSet<Persona> lista = new HashSet<>();
if (!archivo.exists()) {
return lista;
}
FileInputStream fis = null;
try {
fis = new FileInputStream(path);
System.out.println("Leyendo el fichero:" + path);
try (ObjectInputStream ois = new ObjectInputStream(fis)) {
lista = (HashSet<Persona>) ois.readObject();
}
} catch (Exception ex) {
Logger.getLogger(Archivo.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (fis != null) {
try {
fis.close();
} catch (Exception ex) {
Logger.getLogger(Archivo.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return lista;
}
/*
public void exampleTryCath(){
Object recurso = null;
try{
recurso = asdfasdf;
//...
} catch(Exception e){
} finally {
if(recurso != null) recurso.close()
}
}
*/
}
|
package com.java.practice.array;
/**
* https://www.hackerrank.com/challenges/jumping-on-the-clouds-revisited/problem
*/
public class JumpingCloud {
public static void main(String[] args) {
int[] clouds = {0, 0, 1, 0, 0, 1, 1, 0};
int k = 2;
System.out.println(jumpingOnClouds(clouds, k));
}
public static int jumpingOnClouds(int[] c, int k) {
int enrg = 100; // initial energy
int clouds = c.length; // number of clouds
int index = k % clouds; // check if we are on original position
enrg -= (c[index] * 2 + 1);
while (index != 0) {
index = (index + k) % clouds;
enrg -= (c[index] * 2 + 1);
}
return enrg;
}
}
|
package com.ism.projects.th;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.ism.common.exception.ISMException;
public abstract class FinancialReversalBaseService extends
FinancialTransactionBaseService {
/*
* Value should be :
* 1 - Deposit reversal
* 2 - Withdrawal reversal
* 3 - TH to TH transfer reversal
*/
//protected String reversalType;
//#1 modification - 20190317 Scott - no need to change.
protected String reversal_dpscpp_query = "insert into DPASCPP (" +
"ASL9CE, ASADTS, ASBNCE, " +
"ASJMST, ASQTCE, ASHBST, " +
"ASHJST, ASAGTS, ASLICE, " +
"ASLJCE, ASK0DZ, ASFHCD, " +
"ASALVA, ASA4CD, ASJQVA, " +
"ASAGVN, ASACDT, ASPXCE, " +
"ASABDT, ASAEST, ASHQCE ) " +
"SELECT " +
"ASL9CE, CURRENT TIMESTAMP + (row_number() OVER (order by ASL9CE) + 1) second, " +
"(CASE WHEN TRIM(ASBNCE) = '6' THEN '7' ELSE '6' END) AS BNCE, " +
"ASJMST, ASQTCE, '#THStatus#', " +
"(CASE WHEN TRIM(ASHJST) = '1' THEN '2' ELSE '1' END) AS HJST, " +
// 27032015: ASAGTS follow value of ASADTS
// "ASAGTS, ASLICE, " +
"ASADTS, ASLICE, " +
"concat(substring(ASLJCE, 1, 5), '8') AS LJCE, ASK0DZ, ASFHCD, " +
"(CASE WHEN TRIM(ASHJST) = '1' " +
" THEN " +
" (SELECT AOAOVA FROM DPAOCPP WHERE AOBFCD = ASL9CE) + " +
" (SELECT SUM(ASJQVA) FROM DPASCPP T2 " +
" WHERE T2.ASL9CE = T1.ASL9CE " +
" AND T2.ASADTS <= T1.ASADTS " +
" AND T2.ASPXCE = '#ReverseTxId#') " +
" ELSE " +
" (SELECT AOAOVA FROM DPAOCPP WHERE AOBFCD = ASL9CE) - " +
" (SELECT SUM(ASJQVA) FROM DPASCPP T3 " +
" WHERE T3.ASL9CE = T1.ASL9CE " +
" AND T3.ASADTS <= T1.ASADTS " +
" AND T3.ASPXCE = '#ReverseTxId#') " +
" END) AS ALVA, " +
"ASA4CD, ASJQVA, " +
"ASAGVN, CURRENT DATE, '#TxId#', " +
"'0001-01-01', ASAEST, ASPXCE " +
"FROM DPASCPP T1 " +
"WHERE ASPXCE = '#ReverseTxId#' ORDER BY ASADTS";
protected String reversal_dprcpp_query = "insert into DPARCPP (" +
"ARBFCD, ARJKDZ, ARAYTZ, ARHFST, " +
"ARAJVA, ARAKVA, ARA3CD, ARJPVA, " +
"ARAGVN, ARACDT, ARAEST, ARABDT) " +
"SELECT " +
"ASL9CE, CURRENT DATE, TIME(ASADTS) - (row_number() OVER (order by ASL9CE desc) + 1) second, '#HFST#', " +
// CURRENT TIME CHANGE TO TIME(ASADTS) 20140722. Issue: #32
// "ASL9CE, CURRENT DATE, CURRENT TIME - (row_number() OVER (order by ASL9CE desc) + 1) second, '#HFST#', " +
// ALVA2 PASTE SINI 050514
"(CASE WHEN TRIM(ASHJST) = '1' " +
" THEN " +
" (SELECT AOAOVA FROM DPAOCPP WHERE AOBFCD = ASL9CE) + " +
" (SELECT SUM(ASJQVA) FROM DPASCPP T2 " +
" WHERE T2.ASL9CE = T1.ASL9CE " +
" AND T2.ASADTS <= T1.ASADTS " +
" AND T2.ASPXCE = '#PXCE#') " +
" ELSE " +
" (SELECT AOAOVA FROM DPAOCPP WHERE AOBFCD = ASL9CE) - " +
" (SELECT SUM(ASJQVA) FROM DPASCPP T3 " +
" WHERE T3.ASL9CE = T1.ASL9CE " +
" AND T3.ASADTS <= T1.ASADTS " +
" AND T3.ASPXCE = '#PXCE#') " +
" END) AS ALVA2, " +
// "(CASE WHEN TRIM(ASHJST) = '1' THEN ASALVA + ASJQVA ELSE ASALVA - ASJQVA END) AS ALVA1, " +
// TUKAR SINI 050514: ALVA1 TURUN BAWAH
"(CASE WHEN TRIM(ASHJST) = '1' THEN ASJQVA ELSE ASJQVA * -1 END) AS JQVA, " +
"concat(substring(ASLJCE, 1, 5), '8') AS LJCE, " +
// 050514 KALAU X JADI NAIK ATAS BALIK
// "(CASE WHEN TRIM(ASHJST) = '1' THEN ASALVA + ASJQVA ELSE ASALVA - ASJQVA END) AS ALVA1, " +
// Comment: 270315: ALVA1 follow value ALVA2
"(CASE WHEN TRIM(ASHJST) = '1' " +
" THEN " +
" (SELECT AOAOVA FROM DPAOCPP WHERE AOBFCD = ASL9CE) + " +
" (SELECT SUM(ASJQVA) FROM DPASCPP T2 " +
" WHERE T2.ASL9CE = T1.ASL9CE " +
" AND T2.ASADTS <= T1.ASADTS " +
" AND T2.ASPXCE = '#PXCE#') " +
" ELSE " +
" (SELECT AOAOVA FROM DPAOCPP WHERE AOBFCD = ASL9CE) - " +
" (SELECT SUM(ASJQVA) FROM DPASCPP T3 " +
" WHERE T3.ASL9CE = T1.ASL9CE " +
" AND T3.ASADTS <= T1.ASADTS " +
" AND T3.ASPXCE = '#PXCE#') " +
" END) AS ALVA1, " +
// 050514: KOMEN BAWAH NI NAIK ATAS
// "(CASE WHEN TRIM(ASHJST) = '1' " +
// " THEN " +
// " (SELECT AOAOVA FROM DPAOCPP WHERE AOBFCD = ASL9CE) + " +
// " (SELECT SUM(ASJQVA) FROM DPASCPP T2 " +
// " WHERE T2.ASL9CE = T1.ASL9CE " +
// " AND T2.ASADTS <= T1.ASADTS " +
// " AND T2.ASPXCE = '#PXCE#') " +
// " ELSE " +
// " (SELECT AOAOVA FROM DPAOCPP WHERE AOBFCD = ASL9CE) - " +
// " (SELECT SUM(ASJQVA) FROM DPASCPP T3 " +
// " WHERE T3.ASL9CE = T1.ASL9CE " +
// " AND T3.ASADTS <= T1.ASADTS " +
// " AND T3.ASPXCE = '#PXCE#') " +
// " END) AS ALVA2, " +
"'#AGVN#', CURRENT DATE, '#statusRekod#', '0001-01-01' " +
"FROM DPASCPP T1 " +
"WHERE ASPXCE = '#PXCE#' ORDER BY ASADTS ASC";
// TUKAR JADI ASC
// "WHERE ASPXCE = '#PXCE#' ORDER BY ASADTS DESC";
protected String reversal_query_for_update =
"SELECT SUM(CASE WHEN TRIM(ASHJST) = '1' THEN ASJQVA * -1 ELSE ASJQVA END) AS AMT," +
" ASL9CE " +
" FROM DPASCPP " +
" WHERE ASPXCE = ? " +
" AND ASHBST = ? " +
" GROUP BY ASL9CE";
protected String transcodeQuery =
"SELECT ASLJCE FROM DPASCPP WHERE ASPXCE = ?";
/* (non-Javadoc)
* @see com.ism.projects.th.FinancialTransactionBaseService#execute(byte[])
*/
@Override
public byte[] execute(byte[] input) {
isReversal = true;
transactionAmount = BigDecimal.valueOf(1.00); // this is just a dummy amount to indicate a valid transaction amount
return super.execute(input);
}
@Override
protected BigDecimal executeTransaction() throws Exception {
logN("Financial Reversal Base Service: executeTransaction()");
/**
* added on 24 Sep 2019 for rollback
*/
SQL_TRANSACTION_FLAG = 1;
int result = TXN_SUCCESS;
/*
* Reverse transaction from DPASCPP
*/
if (result==TXN_SUCCESS) {
result = reverseBookKeeping(receiptNo, originalReceiptNo);
}
/*
* Reverse transaction from DPARCPP
*/
/**
* commented on 25 Sep 2019 for passbookless migration
*/
// if (result==TXN_SUCCESS) {
// result = reverseBookPrinting(originalReceiptNo);
// }
/*
* Add or substract balance from DPAOCPP
* IMPORTANT - ensure balance is updated LAST
*/
if (result==TXN_SUCCESS) {
result = reverseBalance(originalReceiptNo);
}
return getBalance(accountNo, exchangeRate);
}
protected int reverseBookKeeping(String receipt_no, String original_receipt_no) throws SQLException {
int result = TXN_SUCCESS;
String query = reversal_dpscpp_query;
PreparedStatement pstmt = null;
ResultSet rs = null;
logN("reverseBookKeeping");
try {
query = query.replaceAll("#THStatus#", TRANSACTION_MODE_REVERSED);
query = query.replaceAll("#TxId#", receipt_no);
query = query.replaceAll("#ReverseTxId#", original_receipt_no);
logN("1. SQL statement [" + query + "]");
pstmt = target.createPreparedStatement(query);
int updateCount = pstmt.executeUpdate();
if (updateCount==0) {
result = TXN_REVERSE_UNNECESSARY;
} else {
result = TXN_SUCCESS;
}
}catch( SQLException se ) {
logE("failed to communicate with TH core", se);
throw se;
}finally {
if ( pstmt != null ) {
try{pstmt.close();}catch( Exception e ) {}
}
if ( rs != null ) {
try{rs.close();}catch( Exception e ) {}
}
}
return result;
}
protected int reverseBookPrinting(String original_receipt_no) throws SQLException, ISMException {
logN("reverseBookPrinting");
String query = reversal_dprcpp_query;
int result = TXN_SUCCESS;
query = query.replaceAll("#HFST#", transactionStatus);
query = query.replaceAll("#AGVN#", mediumTypeCode);
query = query.replaceAll("#statusRekod#", statusRekod);
query = query.replaceAll("#PXCE#", originalReceiptNo);
logN("2. SQL statement [" + query + "]");
Object [] params = new Object[] {};
try {
if (runQuery(query, params)) {
result = TXN_SUCCESS;
} else {
result = TXN_UNKNOWN_ERROR;
}
} catch (ISMException e) {
logE("failed to update book printing", e);
throw e;
} catch (SQLException e) {
logE("failed to update book printing", e);
throw e;
}
return result;
}
protected int reverseBalance(String original_receipt_no) throws Exception {
logN("reverseBalance");
String query = reversal_query_for_update;
int result = TXN_SUCCESS;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
pstmt = target.createPreparedStatement(query);
target.setParameter(pstmt, 1, original_receipt_no);
target.setParameter(pstmt, 2, TRANSACTION_MODE_VOID);
rs = pstmt.executeQuery();
logN("reverseBalance query ["+query+"]");
while (rs.next()) {
BigDecimal testAmount = rs.getBigDecimal(1);
BigDecimal amount = rs.getBigDecimal(1).setScale(GLOBAL_CONTEXT.getPrecision(), GLOBAL_CONTEXT.getRoundingMode());
logN("AMOUNT1 = ["+testAmount+"] AMOUNT2 = ["+amount+"]");
String acct_no = rs.getString(2);
boolean updated = false;
logV("3. To reverse balance : account no[" + acct_no + "], amount[" + amount + "]");
if (amount.doubleValue() > 0) {
logN("updateBalanceForDeposit");
updateBalanceForDeposit(acct_no, amount, ONE, mediumTypeCode);
updated = true;
} else
if (amount.doubleValue() < 0) {
logN("updateBalanceForWithdrawal");
updateBalanceForWithdrawal(acct_no, amount.multiply(MINUS_ONE), ZERO, ONE, mediumTypeCode);
updated = true;
}
if (!updated) {
throw new Exception("Invalid original transaction. No balance was updated.");
}
}
}catch( SQLException se ) {
logE("failed to communicate with TH core", se);
throw se;
} catch (Exception e) {
logE("failed to communicate with TH core", e);
throw e;
}finally {
if ( pstmt != null ) {
try{pstmt.close();}catch( Exception e ) {}
}
if ( rs != null ) {
try{rs.close();}catch( Exception e ) {}
}
}
return result;
}
}
|
package server;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.ArrayList;
import java.util.List;
import server.dao.Manager;
import server.entity.User;
import util.Message;
import util.MessageType;
import util.Translate;
/**
* 服务器接收消息和处理消息的线程类
*
* @author sakura
*
*/
public class RevMessage extends Thread {
private DatagramSocket serverSocket = null; // 服务器套接字
private DatagramPacket packet = null; // 通信报文
private ServerView parentUI = null; // 窗口
private List<User> userList = new ArrayList<User>(); // 在线用户列表
private Manager manager = null;
private boolean isRunnable = true;
private byte[] data = new byte[8096]; // 8k
/**
* 构造函数
*
* @param serverSocket 服务器套接字
* @param ParentUI 操作窗口数据显示
*/
public RevMessage(DatagramSocket serverSocket, ServerView parentUI) {
this.serverSocket = serverSocket;
this.parentUI = parentUI;
manager = new Manager();
}
public void stopServer() {
isRunnable = false;
}
@Override
public void run() {
int type = -1;
// 循环处理收到的各种消息
while (isRunnable) {
try {
packet = new DatagramPacket(data, data.length); // 接收报文
serverSocket.receive(packet); // 接收数据
// 将收到的信息转化为对象
Message msg = (Message) Translate.ByteToObject(packet.getData());
// 获取消息类型
// 消息类型有登录,注册,发信息,确认,成功,失败
type = msg.getType();
parentUI.updateLog("接受到客户端数据:" + type);
switch (type) {
case MessageType.M_REGIST:
registHandle(msg.getUserId(), msg.getPassword());
break;
case MessageType.M_LOGIN:
loginHandle(msg.getUserId(), msg.getPassword());
break;
case MessageType.M_GROUP:
groupMessageHandle(msg.getUserId(), msg.getText());
break;
case MessageType.M_MSG:
messageHandle(msg.getUserId(), msg.getTargetId());
break;
case MessageType.M_QUIT:
logoutHandle(msg.getUserId());
break;
default:
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 处理注册
* @throws IOException
*/
public void registHandle(String userId, String password) throws IOException {
Message backMsg = new Message();
// 注册成功
if (manager.register(userId, password)) {
backMsg.setType(MessageType.M_SUCCESS);
byte[] buf = Translate.ObjectToByte(backMsg);
DatagramPacket backPacket = new DatagramPacket(buf, buf.length, packet.getAddress(), packet.getPort());
serverSocket.send(backPacket);
// 注册失败
} else {
backMsg.setType(MessageType.M_FAILURE);
byte[] buf = Translate.ObjectToByte(backMsg);
DatagramPacket backPacket = new DatagramPacket(buf, buf.length, packet.getAddress(), packet.getPort());
serverSocket.send(backPacket);
}
}
/**
* 处理登录
* @param userId
* @throws IOException
*/
public void loginHandle(String userId, String password) throws IOException {
Message backMsg = new Message();
// 登录成功
// if ("1000".equals(userId) || "2000".equals(userId) || "4000".equals(userId)) {
if (manager.login(userId, password)) {
// 回送成功报文
backMsg.setType(MessageType.M_SUCCESS);
byte[] buf = Translate.ObjectToByte(backMsg);
DatagramPacket backPacket = new DatagramPacket(buf, buf.length, packet.getAddress(), packet.getPort());
serverSocket.send(backPacket);
User user = new User();
user.setId(userId); // 保存用户名
user.setPacket(packet); // 保存收到的报文
userList.add(user);
// 更新服务器日志
parentUI.updateLog(userId + "登录");
// 更新在线用户列表
parentUI.updateUserList(true, userId);
// 向其他用户发送M_LOGIN消息,向新用户发送在线用户列表
DatagramPacket oldPacket, newPacket;
Message current = new Message();
for (int i = 0; i < userList.size(); i++) {
// 遍历在线用户列表
// if 老用户 发送新用户信息
// 发送所有老用户信息 if 新用户 不发送
// 给老用户发送M_LOGIN消息,此出的data是新用户发送过来的数据的缓存,里面的类型是M_LOGIN
if (!userId.equalsIgnoreCase(userList.get(i).getId())) {
oldPacket = userList.get(i).getPacket(); // 老用户的报文
newPacket = new DatagramPacket(data, data.length, oldPacket.getAddress(), // 待发送的新报文
oldPacket.getPort());
serverSocket.send(newPacket);
// 向当前用户发送M_ACK信息-在线用户列表(不算自己)
// 给新用户发送的信息
System.out.println("发送的信息ACK给" + userId + userList.get(i).getId());
current.setUserId(userList.get(i).getId()); // 设置发送报文的用户id为老用户id
current.setType(MessageType.M_ACK);
byte[] buffer = Translate.ObjectToByte(current);
newPacket = new DatagramPacket(buffer, buffer.length, packet.getAddress(), packet.getPort());
serverSocket.send(newPacket);
}
}
} else { // 登录失败
backMsg.setType(MessageType.M_FAILURE);
byte[] buf = Translate.ObjectToByte(backMsg);
DatagramPacket backPacket = new DatagramPacket(buf, buf.length, packet.getAddress(), packet.getPort());
serverSocket.send(backPacket);
}
}
/**
*
* @param userId
* @param text
* @throws IOException
*/
public void groupMessageHandle(String userId, String text) throws IOException {
// 更新服务器消息列表 public
parentUI.updateMessageList(userId + ": " + text);
// 遍历其他用户发送消息
DatagramPacket oldPacket, newPacket;
for (int i = 0; i < userList.size(); i++) {
if (!userList.get(i).getId().equalsIgnoreCase(userId)) {
oldPacket = userList.get(i).getPacket();
newPacket = new DatagramPacket(data, data.length, oldPacket.getAddress(), oldPacket.getPort());
serverSocket.send(newPacket);
}
}
}
/**
*
* @param userId 来源用户id
* @param targetId 目标用户id
* @param text 发送的内容
* @throws IOException
*/
public void messageHandle(String userId, String targetId) throws IOException {
// 转发给目标用户 遍历列表取得目标用户的报文
for (int i = 0; i < userList.size(); i++) {
if (userList.get(i).getId().equalsIgnoreCase(targetId)) {
DatagramPacket oldPacket = userList.get(i).getPacket();
DatagramPacket newPacket = new DatagramPacket(data, data.length, oldPacket.getAddress(),
oldPacket.getPort());
serverSocket.send(newPacket);
return;
}
}
}
/**
*
* @param userId
* @throws IOException
*/
public void logoutHandle(String userId) throws IOException {
// 从在线用户列表移除该用户
for (int i = 0; i < userList.size(); i++) {
if (userList.get(i).getId().equalsIgnoreCase(userId)) {
userList.remove(i);
break;
}
}
// 从服务器面板移除用户,更新日志
parentUI.updateUserList(false, userId);
parentUI.updateLog(userId + "下线");
// 向其他用户转发下线信息
DatagramPacket oldPacket, newPacket;
for (int i = 0; i < userList.size(); i++) {
oldPacket = userList.get(i).getPacket();
newPacket = new DatagramPacket(data, data.length, oldPacket.getAddress(), oldPacket.getPort());
serverSocket.send(newPacket);
}
}
}
|
package com.proyecto.ui.utils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.WrongValuesException;
import org.zkoss.zul.Constraint;
import org.zkoss.zul.impl.InputElement;
/**
* The Class Validate.
*
* @author <a href="manuel.demanuel.rodriguez@everis.com">Manuel Demanuel Rodriguez</a>
*/
public class Validate {
/**
* Extract and disable constraints.
*
* @param component
* component
* @return the map<? extends component,? extends constraint>
*/
public static Map<? extends Component, ? extends Constraint> extractAndDisableConstraints(final Component component) {
final Map<Component, Constraint> result = new HashMap<Component, Constraint>();
if (component != null && component.getChildren() != null) {
for (final Component each : component.getChildren()) {
result.putAll(extractAndDisableConstraints(each));
}
}
if (component instanceof InputElement && ((InputElement) component).getConstraint() != null) {
result.put(component, ((InputElement) component).getConstraint());
final Constraint aux = null;
((InputElement) component).setConstraint(aux);
}
return result;
}
/**
* Validate.
*
* @param container
* container
* @param constraints
* constraints
*/
public static void validate(final Component container, final Map<Component, Constraint> constraints) {
final List<WrongValueException> validationErrors = new ArrayList<WrongValueException>();
final List<Component> descendants = UtilsUI.getAllDescendants(container);
for (final Component each : descendants) {
if (constraints.containsKey(each)) {
try {
constraints.get(each).validate(each, ((InputElement) each).getRawValue());
} catch (final WrongValueException e) {
validationErrors.add(e);
}
}
}
if (validationErrors.size() > 0) {
final WrongValueException[] errorsArray = new WrongValueException[validationErrors.size()];
final WrongValuesException errors = new WrongValuesException(validationErrors.toArray(errorsArray));
throw errors;
}
}
/**
* Validate edited.
*
* @param container container
* @param constraints constraints
* @param keys keys
*/
public static void validateEdited(final Component container, final Map<Component, Constraint> constraints,List<String> keys) {
final List<WrongValueException> validationErrors = new ArrayList<WrongValueException>();
final List<Component> descendants = UtilsUI.getAllDescendants(container);
for (final Component each : descendants) {
if (!keys.contains(each.getId())) {
if (constraints.containsKey(each)) {
try {
constraints.get(each).validate(each, ((InputElement) each).getRawValue());
} catch (final WrongValueException e) {
validationErrors.add(e);
}
}
}
}
if (validationErrors.size() > 0) {
final WrongValueException[] errorsArray = new WrongValueException[validationErrors.size()];
final WrongValuesException errors = new WrongValuesException(validationErrors.toArray(errorsArray));
throw errors;
}
}
} |
package jstu.edu.entity;
/**
* Created by 张 磊 on 2017/3/13.
*/
public class UserLog {
private int userLog_id;
private int userLog_manager;
private int userLog_user;
private String userLog_time;
private int userLog_opertation;
private String userLog_reason;
public UserLog(){}
/**
* 全参数构造
* @param userLog_id
* @param userLog_manager
* @param userLog_user
* @param userLog_time
* @param userLog_opertation
* @param userLog_reason
*/
public UserLog(int userLog_id, int userLog_manager, int userLog_user, String userLog_time, int userLog_opertation, String userLog_reason) {
this.userLog_id = userLog_id;
this.userLog_manager = userLog_manager;
this.userLog_user = userLog_user;
this.userLog_time = userLog_time;
this.userLog_opertation = userLog_opertation;
this.userLog_reason = userLog_reason;
}
public int getUserLog_id() {
return userLog_id;
}
public void setUserLog_id(int userLog_id) {
this.userLog_id = userLog_id;
}
public int getUserLog_manager() {
return userLog_manager;
}
public void setUserLog_manager(int userLog_manager) {
this.userLog_manager = userLog_manager;
}
public int getUserLog_user() {
return userLog_user;
}
public void setUserLog_user(int userLog_user) {
this.userLog_user = userLog_user;
}
public String getUserLog_time() {
return userLog_time;
}
public void setUserLog_time(String userLog_time) {
this.userLog_time = userLog_time;
}
public int getUserLog_opertation() {
return userLog_opertation;
}
public void setUserLog_opertation(int userLog_opertation) {
this.userLog_opertation = userLog_opertation;
}
public String getUserLog_reason() {
return userLog_reason;
}
public void setUserLog_reason(String userLog_reason) {
this.userLog_reason = userLog_reason;
}
}
|
//*Vladimir Ventura
// 00301144
// CIS252 Data Structures
// Problem Set 8: HashMap (Linear Probing Implementation)
//
// This class is an attempt to approach the Linear Probing technique with records. *//
public class MyHashMap<K extends Comparable<K>, V> {
private Record[] table;
private int tableSize;
public MyHashMap(){
this.table = new Record[25]; //I will suppress unchecked later on
this.tableSize = 0;
}
public MyHashMap(int maxSize){
this.tableSize = 0;
this.table = new Record[maxSize];
}
public void clear(){
for (int i = 0; i < tableSize; i++) {
table[i] = null;
}
tableSize = 0;
}
public void insert(K key, V value){
int hashToTableSpecs = Math.abs(key.hashCode() % table.length);
insert(key, value, hashToTableSpecs);
}
@SuppressWarnings("unchecked")
private void insert(K key, V value, int hash){
if (table[hash] == null){
table[hash] = new Record<>(key, value);
tableSize++;
} else if (table[hash].getKey().compareTo(key) == 0){
table[hash].setValue(value);
} else {
if (tableSize < table.length){
hash = (hash + 1) % table.length;
insert(key, value, hash);
} else {
System.out.println("Space nowhere to be found");
}
}
}
@SuppressWarnings("unchecked")
public V remove(K key){
V removedValue = null;
int recordIndex = Math.abs(key.hashCode() % tableSize);
recordIndex = locate(recordIndex, key);
if (recordIndex != -1){
removedValue = (V)table[recordIndex].getValue();
table[recordIndex] = null;
tableSize--;
}
return removedValue;
}
@SuppressWarnings("unchecked")
public V getValue(K key){
V value = null;
int recordIndex = Math.abs(key.hashCode() % table.length);
recordIndex = locate(recordIndex, key);
if (recordIndex != -1) value = (V)table[recordIndex].getValue();
return value;
}
private int locate (int index, K key){
boolean foundKey = false;
int marker = 0;
while(!foundKey && (table[index] != null) && marker < table.length){
if (key.equals(table[index].getKey())){
foundKey = true;
} else {
index = (index + 1) % table.length;
marker++;
}
}
int resultIndex = -1;
if (foundKey) resultIndex = index;
return resultIndex;
}
}
|
package graphics;
import maths.Vector3f;
import maths.Vector4f;
public class Color {
public Vector4f color;
public Color(float r, float g, float b) {
this( r, g, b, 1.0f);
}
public Color(float r, float g, float b, float a) {
this( new Vector4f(r,g,b,a));
}
public Color(Vector4f rgba) {
this.color = rgba;
}
public Color(Vector3f rgb) {
color = new Vector4f(rgb.x, rgb.y, rgb.z, 1.0f);
}
public static Color BLACK() { return new Color( 0,0,0 ); }
public static Color WHITE() { return new Color( 1,1,1 ); }
public static Color RED() { return new Color( 1,0,0 ); }
public static Color GREEN() { return new Color( 0,1,0 ); }
public static Color BLUE() { return new Color( 0,0,1 ); }
public static Color AA() { return new Color( 1,1,0 ); }
public static Color BB() { return new Color( 0,1,1 ); }
public static Color PURPLE() { return new Color( 1,0,1 ); }
}
|
package net.tanpeng.arithmetic.offers;
/**
* 约瑟夫环
*/
public class Demo {
public static int findLastNumber(int n, int m) {
if (n < 1 | m < 1) {
return -1;
}
int[] array = new int[n];
int i = -1, step = 0, count = n;
while (count > 0) {
i++;
if (i >= n)
i = 0; //这个是为了模拟环
if (array[i] == -1)
continue;
step++;
if (step == m) {
array[i] = -1;
count--;
step = 0;
}
}
return i;
}
public static void main(String[] args) {
}
}
|
package com.wrathOfLoD.VisitorInterfaces;
import com.wrathOfLoD.Models.Inventory.Equipment;
import com.wrathOfLoD.Models.Inventory.Inventory;
import com.wrathOfLoD.Models.Items.EquippableItems.EquippableItem;
/**
* Created by icavitt on 4/12/2016.
*/
//to use this interface in any useful way you'll likely have to implement the itemvisitor
//interface as well...if we consistently have to do both could add visit takeable here
// along with other needed ones
public interface HeldItemVisitor {
public void visitInventory(Inventory inventory);
public void visitEquipment(Equipment equipment);
}
|
package com.Aahan;
import java.text.DecimalFormat;
/**
* Created by aahan on 16-02-2017.
*/
class heronsForm {
private static varGen heronsForm = new varGen(3);
static void generate(int dif){
heronsForm.setVars(dif*4);
}
static String print(){
int[] x=heronsForm.getVars();
x[0]=Math.abs(x[0]);
x[1]=Math.abs(x[1]);
x[2]=Math.abs(x[2]);
return ("Find the area of the triangle with sides\n"+x[0]+"\t"+x[1]+"\t"+x[2]);
}
static String answer(){
int[] x=heronsForm.getVars();
x[0]=Math.abs(x[0]);
x[1]=Math.abs(x[1]);
x[2]=Math.abs(x[2]);
boolean valid=checkValid(x[0], x[1], x[2]);
if(valid) {
double s = (x[0] + x[1] + x[2]) / 2.0;
double ans = s * (s - x[0]) * (s - x[1]) * (s - x[2]);
double finAns = Math.sqrt(ans);
finAns = Double.parseDouble(new DecimalFormat("##.###").format(finAns));
if(finAns!=0)
return ("The area of the triangle is: " + finAns);
else
return ("Triangle forms a line.");
}
else
return ("Impossible Triangle");
}
private static boolean checkValid(int a, int b, int c) {
if((a+b)<c||(b+c)<a||(a+c)<b){
return false;
}
return true;
}
}
|
package com.akua;
import com.akua.search.*;
import com.akua.sorting.*;
import com.sun.net.httpserver.Headers;
//import com.akua.sorting.InsertionSort;
public class App
{
public static void main( String[] args )
{
int arr[] = {43,11,55,1,44,3,6,43,5,7,4,34};
//sortAlgorithms(arr);
searchAlgorithms(arr, 34);
}
public static void sortAlgorithms(int[] arr){
//BubbleSort bs = new BubbleSort();
//bs.sort(arr);
//InsertionSort is = new InsertionSort();
//is.sort(arr);
//SelectionSort ss = new SelectionSort();
//ss.sort(arr);
//MergeSort ms = new MergeSort();
//ms.mergeSort(arr, arr.length);
//QuickSort qs = new QuickSort();
//qs.sorted(arr);
//HeapSort hs = new HeapSort();
//hs.sort(arr);
//BucketSort bucketSort = new BucketSort();
//bucketSort.sort(arr);
}
public static void searchAlgorithms(int[] arr,int wanted){
int[] sortedArray = new BucketSort().sort(arr);
BinarySearch bs = new BinarySearch();
int binarySIndex = bs.search(sortedArray,0,arr.length-1, wanted);
System.out.println("bsIndex = " + binarySIndex);
LinearSearch ls = new LinearSearch();
int linearSIndex = ls.search(arr, wanted);
System.out.println("linearSIndex = " + linearSIndex);
JumpSearch js = new JumpSearch();
int jumpSIndex = js.search(sortedArray, wanted);
System.out.println("jumpSIndex = " + jumpSIndex);
FibonacciSearch fs = new FibonacciSearch();
int fiboSIndex = fs.search(sortedArray, wanted);
System.out.println("fiboSIndex = " + fiboSIndex);
InterpolationSearch is = new InterpolationSearch();
int interpolationSIndex =is.search(sortedArray,wanted);
System.out.println("interpolationSIndex = " + interpolationSIndex);
ExponentialSearch es = new ExponentialSearch();
int exponentialSIndex = es.search(sortedArray,wanted);
System.out.println("exponentialSIndex = " + exponentialSIndex);
}
}
|
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Set;
import java.util.Arrays;
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
HashMap<Integer, HostPort> userMap = new HashMap<>(); // silinti.
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(Integer.parseInt(args[0]));
System.out.println("Listening on " + args[0]);
} catch (Exception e) {
System.out.println(e.getMessage());
System.exit(0);
}
String message;
while(true) {
try {
if (serverSocket != null) {
Socket connSocket = serverSocket.accept();
BufferedReader incoming = new BufferedReader(
new InputStreamReader(connSocket.getInputStream()));
message = incoming.readLine();
System.out.println(">>> " + message);
if (message.split(":")[0].equals("info")) {
int id = Integer.parseInt(message.split(":")[1].split(",")[0]);
String hostName = message.split(":")[1].split(",")[1];
int port = Integer.parseInt(message.split(":")[1].split(",")[2]);
if (userMap.get(id) == null)
userMap.put(id, new HostPort(hostName, port));
} else if (message.split(":")[0].equals("recipients")) {
String[] recipients = message.split(":")[1].split(",");
String sender = message.split(":")[3];
String[] splitMessage = Arrays.copyOfRange(
message.split(":"), 5, message.split(":").length);
String outMessage = "";
for (String m : splitMessage)
outMessage += m;
for (String recipient : recipients) {
int recipient_id = Integer.parseInt(recipient);
HostPort user = userMap.get(recipient_id);
try {
Socket socket = new Socket(
user.getHostName(), user.getPortNumber());
DataOutputStream outgoing = new DataOutputStream(socket.getOutputStream());
outgoing.writeBytes(sender + ":" + outMessage);
System.out.println("<<< " + sender + ":" + outMessage);
socket.close();
} catch (Exception e) {
}
}
}
}
} catch (Exception e) {
}
}
}
private static class HostPort {
private String hostName;
private int portNumber;
public HostPort(String hostName, int portNumber) {
this.hostName = hostName;
this.portNumber = portNumber;
}
public String toString() {
return hostName + "," + String.valueOf(portNumber);
}
public String getHostName() { return hostName; }
public int getPortNumber() { return portNumber; }
}
}
|
package com.mingrisoft;
public class AppendCharacter {
/**
* @param args
*/
public static void main(String[] args) {
String appendStr = "";// 创建字符串变量
long startTime = System.nanoTime();// 开始记事
for (int i = 20000; i < 50000; i++) {// 遍历30000个字符
appendStr += (char) i;// 字符串与每个字符执行连接操作
}
long endTime = System.nanoTime();// 结束计时
System.out.println("String追加字符3万个。");
// 输出用时
System.out.println("用时:" + (endTime - startTime) / 1000000d + "毫秒");
// ///////////////////////////////////////////////////////////////
StringBuilder strBuilder = new StringBuilder();// 创建字符串构建器
startTime = System.nanoTime();// 开始计时
for (int i = 20000; i < 50000; i++) {// 遍历30000个字符
strBuilder.append((char) i);// 把每个字符追加到构建器
}
endTime = System.nanoTime();// 结束记事
System.out.println("字符串构建器追加字符3万个。");
// 输出用时
System.out.print("用时:" + (endTime - startTime) / 1000000d + "毫秒");
}
}
|
package com.service.dao;
import java.util.List;
public interface IReservationDAO {
List<Reservation> getAllUserReservation(String userId);
List<Reservation> getAllUserObjectWatched(String userId);
}
|
package com.citibank.ods.persistence.pl.dao.rdb.oracle;
import com.citibank.ods.persistence.util.CitiStatement;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import com.citibank.ods.common.connection.rdb.ManagedRdbConnection;
import com.citibank.ods.common.dataset.DataSet;
import com.citibank.ods.common.dataset.DataSetRow;
import com.citibank.ods.common.dataset.ResultSetDataSet;
import com.citibank.ods.common.exception.UnexpectedException;
import com.citibank.ods.common.util.BaseConstraintDecoder;
import com.citibank.ods.common.util.ODSConstraintDecoder;
import com.citibank.ods.entity.pl.BaseTplPlayerRoleEntity;
import com.citibank.ods.entity.pl.TplProdPlayerRoleEntity;
import com.citibank.ods.entity.pl.TplProductEntity;
import com.citibank.ods.entity.pl.valueobject.TplProdPlayerRoleEntityVO;
import com.citibank.ods.entity.pl.valueobject.TplProductEntityVO;
import com.citibank.ods.persistence.pl.dao.TplProdPlayerRoleDAO;
import com.citibank.ods.persistence.pl.dao.TplProductDAO;
import com.citibank.ods.persistence.pl.dao.factory.ODSDAOFactory;
import com.citibank.ods.persistence.pl.dao.rdb.oracle.factory.OracleODSDAOFactory;
//
//©2002-2007 Accenture. All rights reserved.
//
/**
* @author acacio.domingos,Apr 10, 2007
*
*/
public class OracleTplProdPlayerRoleDAO extends BaseOracleTplProdPlayerRoleDAO
implements TplProdPlayerRoleDAO
{
/*
* Nome da tabela
*/
private static final String C_TPL_PROD_PLAYER_ROLE = C_PL_SCHEMA
+ "TPL_PROD_PLAYER_ROLE";
private static final String C_TPL_PRODUCT = C_PL_SCHEMA + "TPL_PRODUCT";
private static final String C_TPL_PLAYER = C_PL_SCHEMA + "TPL_PLAYER";
/*
* Campos específicos da tabela
*/
private String C_LAST_AUTH_DATE = "LAST_AUTH_DATE";
private String C_LAST_AUTH_USER_ID = "LAST_AUTH_USER_ID";
private String C_REC_STAT_CODE = "REC_STAT_CODE";
private String C_REC_STAT_TEXT = "REC_STAT_TEXT";
private String C_PROD_NAME = "PROD_NAME";
private String C_PLYR_ROLE_TYPE_TEXT = "PLYR_ROLE_TYPE_TEXT";
private String C_PLYR_NAME = "PLYR_NAME";
/**
* Insere um novo registro
* @see com.citibank.ods.persistence.pl.dao.TplProdPlayerRoleDAO#insert(com.citibank.ods.entity.pl.TplProdPlayerRoleEntity)
*/
public TplProdPlayerRoleEntity insert(
TplProdPlayerRoleEntity tplProdPlayerRoleEntity_ )
{
ManagedRdbConnection connection = null;
CitiStatement preparedStatement = null;
StringBuffer query = new StringBuffer();
try
{
connection = OracleODSDAOFactory.getConnection();
query.append( "INSERT INTO " + C_TPL_PROD_PLAYER_ROLE + " (" );
query.append( C_PROD_CODE + ", " );
query.append( C_SYS_CODE + ", " );
query.append( C_SYS_SEG_CODE + ", " );
query.append( C_PLYR_CNPJ_NBR + ", " );
query.append( C_PLYR_ROLE_TYPE_CODE + ", " );
query.append( C_LAST_UPD_USER_ID + ", " );
query.append( C_LAST_UPD_DATE + ", " );
query.append( C_LAST_AUTH_USER_ID + ", " );
query.append( C_LAST_AUTH_DATE + ", " );
query.append( C_REC_STAT_CODE );
query.append( " ) VALUES ( " );
query.append( "?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) " );
preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() ));
int count = 1;
if ( tplProdPlayerRoleEntity_.getData().getProdCode() != null )
{
preparedStatement.setString( count++,
tplProdPlayerRoleEntity_.getData().getProdCode() );
}
else
{
preparedStatement.setString( count++, null );
}
if ( tplProdPlayerRoleEntity_.getData().getSysCode() != null )
{
preparedStatement.setString( count++,
tplProdPlayerRoleEntity_.getData().getSysCode() );
}
else
{
preparedStatement.setString( count++, null );
}
if ( tplProdPlayerRoleEntity_.getData().getSysSegCode() != null )
{
preparedStatement.setLong(
count++,
tplProdPlayerRoleEntity_.getData().getSysSegCode().longValue() );
}
else
{
preparedStatement.setString( count++, null );
}
if ( tplProdPlayerRoleEntity_.getData().getPlyrCnpjNbr() != null )
{
preparedStatement.setString(
count++,
tplProdPlayerRoleEntity_.getData().getPlyrCnpjNbr() );
}
else
{
preparedStatement.setString( count++, null );
}
if ( tplProdPlayerRoleEntity_.getData().getPlyrRoleTypeCode() != null )
{
preparedStatement.setString(
count++,
tplProdPlayerRoleEntity_.getData().getPlyrRoleTypeCode() );
}
else
{
preparedStatement.setString( count++, null );
}
if ( tplProdPlayerRoleEntity_.getData().getLastUpdUserId() != null )
{
preparedStatement.setString(
count++,
tplProdPlayerRoleEntity_.getData().getLastUpdUserId() );
}
else
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null );
}
if ( tplProdPlayerRoleEntity_.getData().getLastUpdDate() != null )
{
preparedStatement.setTimestamp(
count++,
new Timestamp(
tplProdPlayerRoleEntity_.getData().getLastUpdDate().getTime() ) );
}
else
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null );
}
// Casting para Obter os campos especificos da tabela
TplProdPlayerRoleEntityVO tplProdPlayerRoleEntityVO = ( TplProdPlayerRoleEntityVO ) tplProdPlayerRoleEntity_.getData();
if ( tplProdPlayerRoleEntityVO.getLastAuthUserId() != null )
{
preparedStatement.setString( count++,
tplProdPlayerRoleEntityVO.getLastAuthUserId() );
}
else
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null );
}
if ( tplProdPlayerRoleEntityVO.getLastAuthDate() != null )
{
preparedStatement.setTimestamp(
count++,
new Timestamp(
tplProdPlayerRoleEntityVO.getLastAuthDate().getTime() ) );
}
else
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null );
}
if ( tplProdPlayerRoleEntityVO.getRecStatCode() != null )
{
preparedStatement.setString( count++,
tplProdPlayerRoleEntityVO.getRecStatCode() );
}
else
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null );
}
preparedStatement.executeUpdate();
preparedStatement.replaceParametersInQuery(query.toString());
return tplProdPlayerRoleEntity_;
}
catch ( Exception e )
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, e );
}
finally
{
closeStatement( preparedStatement );
closeConnection( connection );
}
}
/**
* Atualiza um registro
* @see com.citibank.ods.persistence.pl.dao.TplProdPlayerRoleDAO#insert(com.citibank.ods.entity.pl.TplProdPlayerRoleEntity)
*/
public TplProdPlayerRoleEntity update(
TplProdPlayerRoleEntity tplProdPlayerRoleEntity_ )
{
ManagedRdbConnection connection = null;
CitiStatement preparedStatement = null;
StringBuffer query = new StringBuffer();
try
{
connection = OracleODSDAOFactory.getConnection();
query.append( "UPDATE " + C_TPL_PROD_PLAYER_ROLE + " SET " );
query.append( C_LAST_UPD_USER_ID + " = ?, " );
query.append( C_LAST_UPD_DATE + " = ?, " );
query.append( C_LAST_AUTH_USER_ID + " = ?, " );
query.append( C_LAST_AUTH_DATE + " = ?, " );
query.append( C_REC_STAT_CODE + " = ? " );
query.append( " WHERE " );
query.append( C_PROD_CODE + " = ? AND " );
query.append( C_SYS_CODE + " = ? AND " );
query.append( C_SYS_SEG_CODE + " = ? AND " );
query.append( C_PLYR_CNPJ_NBR + " = ? AND " );
query.append( C_PLYR_ROLE_TYPE_CODE + " = ? " );
preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() ));
int count = 1;
if ( tplProdPlayerRoleEntity_.getData().getLastUpdUserId() != null )
{
preparedStatement.setString(
count++,
tplProdPlayerRoleEntity_.getData().getLastUpdUserId() );
}
else
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null );
}
if ( tplProdPlayerRoleEntity_.getData().getLastUpdDate() != null )
{
preparedStatement.setTimestamp(
count++,
new Timestamp(
tplProdPlayerRoleEntity_.getData().getLastUpdDate().getTime() ) );
}
else
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null );
}
// Casting para Obter os campos especificos da tabela
TplProdPlayerRoleEntityVO tplProdPlayerRoleEntityVO = ( TplProdPlayerRoleEntityVO ) tplProdPlayerRoleEntity_.getData();
if ( tplProdPlayerRoleEntityVO.getLastAuthUserId() != null )
{
preparedStatement.setString( count++,
tplProdPlayerRoleEntityVO.getLastAuthUserId() );
}
else
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null );
}
if ( tplProdPlayerRoleEntityVO.getLastAuthDate() != null )
{
preparedStatement.setTimestamp(
count++,
new Timestamp(
tplProdPlayerRoleEntityVO.getLastAuthDate().getTime() ) );
}
else
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null );
}
if ( tplProdPlayerRoleEntityVO.getRecStatCode() != null )
{
preparedStatement.setString( count++,
tplProdPlayerRoleEntityVO.getRecStatCode() );
}
else
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null );
}
if ( tplProdPlayerRoleEntity_.getData().getProdCode() != null )
{
preparedStatement.setString( count++,
tplProdPlayerRoleEntity_.getData().getProdCode() );
}
else
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null );
}
if ( tplProdPlayerRoleEntity_.getData().getSysCode() != null )
{
preparedStatement.setString( count++,
tplProdPlayerRoleEntity_.getData().getSysCode() );
}
else
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null );
}
if ( tplProdPlayerRoleEntity_.getData().getSysSegCode() != null )
{
preparedStatement.setLong(
count++,
tplProdPlayerRoleEntity_.getData().getSysSegCode().longValue() );
}
else
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null );
}
if ( tplProdPlayerRoleEntity_.getData().getPlyrCnpjNbr() != null )
{
preparedStatement.setString(
count++,
tplProdPlayerRoleEntity_.getData().getPlyrCnpjNbr() );
}
else
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null );
}
if ( tplProdPlayerRoleEntity_.getData().getPlyrRoleTypeCode() != null )
{
preparedStatement.setString(
count++,
tplProdPlayerRoleEntity_.getData().getPlyrRoleTypeCode() );
}
else
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null );
}
preparedStatement.executeUpdate();
preparedStatement.replaceParametersInQuery(query.toString());
return tplProdPlayerRoleEntity_;
}
catch ( Exception e )
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, e );
}
finally
{
closeStatement( preparedStatement );
closeConnection( connection );
}
}
/**
* Retorna um dataset , com os parametros informados
* @see com.citibank.ods.persistence.pl.dao.TplProdPlayerRoleDAO#list(java.lang.String,
* java.lang.String)
*/
public DataSet list( String plyrCnpjNbr_, String plyrName_,
String plyrRoleTypeCode_, String prodCode_,
String sysCode_, String sysSegCode_, String productName_ )
{
ManagedRdbConnection connection = null;
CitiStatement preparedStatement = null;
ResultSet resultSet = null;
ResultSetDataSet rsds = null;
StringBuffer query = new StringBuffer();
try
{
connection = OracleODSDAOFactory.getConnection();
query.append( " SELECT " );
query.append( "PROD_PLAYER." + C_PLYR_CNPJ_NBR + ", " );
query.append( "(SELECT COUNT(*) FROM " );
query.append( C_TPL_PROD_PLAYER_ROLE + " " + "PROD_PLAYER_ROLE" );
query.append( " WHERE " );
query.append( "PROD_PLAYER." + C_PLYR_CNPJ_NBR + " = " );
query.append( "PROD_PLAYER_ROLE." + C_PLYR_CNPJ_NBR + ")QTDE_PROD, " );
query.append( "PLAYER." + C_PLYR_NAME );
query.append( " FROM " );
query.append( C_TPL_PROD_PLAYER_ROLE + " PROD_PLAYER, " );
query.append( C_TPL_PLAYER + " PLAYER, " );
query.append( C_TPL_PRODUCT + " PRODUCT" );
query.append( " WHERE " );
query.append( "PROD_PLAYER." + C_PLYR_CNPJ_NBR );
query.append( " = PLAYER." + C_PLYR_CNPJ_NBR + " AND " );
query.append( " PRODUCT." + C_PROD_CODE + " = " );
query.append( "PROD_PLAYER." + C_PROD_CODE );
query.append( " AND PROD_PLAYER." + C_REC_STAT_CODE );
query.append( " != " + "'"
+ TplProdPlayerRoleEntity.C_REC_STAT_CODE_INACTIVE + "'" );
String criteria = "";
if ( plyrCnpjNbr_ != null && !"".equals( plyrCnpjNbr_ ) )
{
criteria = criteria + " AND PROD_PLAYER." + C_PLYR_CNPJ_NBR + " = ? ";
}
if ( plyrName_ != null && !"".equals( plyrName_ ) )
{
criteria = criteria + " AND UPPER(PLAYER." + C_PLYR_NAME + ") LIKE ? ";
}
if ( plyrRoleTypeCode_ != null && !"".equals( plyrRoleTypeCode_ ) )
{
criteria = criteria + " AND PROD_PLAYER." + C_PLYR_ROLE_TYPE_CODE
+ " = ? ";
}
if ( prodCode_ != null && !"".equals( prodCode_ ) )
{
criteria = criteria + " AND UPPER(TRIM( PROD_PLAYER." + C_PROD_CODE
+ ")) = ? ";
}
if ( sysCode_ != null && !"".equals( sysCode_ ) )
{
criteria = criteria + " AND UPPER(PROD_PLAYER." + C_SYS_CODE
+ ") = ? ";
}
if ( sysSegCode_ != null )
{
criteria = criteria + " AND UPPER(PROD_PLAYER." + C_SYS_SEG_CODE
+ ") = ? ";
}
if ( productName_ != null && !"".equals( productName_ ) )
{
criteria = criteria + " AND UPPER( PRODUCT." + C_PROD_NAME
+ ")LIKE ? ";
}
if ( criteria.length() > 0 )
{
query.append( criteria );
}
query.append( " GROUP BY " );
query.append( "PLAYER." + C_PLYR_NAME + ", " );
query.append( "PROD_PLAYER." + C_PLYR_CNPJ_NBR );
preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() ));
int count = 1;
if ( plyrCnpjNbr_ != null && !"".equals( plyrCnpjNbr_ ) )
{
preparedStatement.setString( count++, plyrCnpjNbr_ );
}
if ( plyrName_ != null && !"".equals( plyrName_ ) )
{
preparedStatement.setString( count++, "%" + plyrName_.toUpperCase() + "%" );
}
if ( plyrRoleTypeCode_ != null && !"".equals( plyrRoleTypeCode_ ) )
{
preparedStatement.setString( count++, plyrRoleTypeCode_ );
}
if ( prodCode_ != null && !"".equals( prodCode_ ) )
{
preparedStatement.setString( count++, prodCode_.toUpperCase() );
}
if ( sysCode_ != null && !"".equals( sysCode_ ) )
{
preparedStatement.setString( count++, sysCode_.toUpperCase() );
}
if ( sysSegCode_ != null && !"".equals( sysSegCode_ ) )
{
preparedStatement.setString( count++, sysSegCode_.toUpperCase() );
}
if ( productName_ != null && !"".equals( productName_ ) )
{
preparedStatement.setString( count++, "%" + productName_.toUpperCase() + "%" );
}
resultSet = preparedStatement.executeQuery();
preparedStatement.replaceParametersInQuery(query.toString());
rsds = new ResultSetDataSet( resultSet );
resultSet.close();
}
catch ( SQLException e )
{
throw new UnexpectedException( e.getErrorCode(),
C_ERROR_EXECUTING_STATEMENT, e );
}
finally
{
closeStatement( preparedStatement );
closeConnection( connection );
}
return rsds;
}
/**
* Remove um registro
* @see com.citibank.ods.persistence.pl.dao.TplProdPlayerRoleDAO#selectByPk(com.citibank.ods.entity.pl.TplPlayerEntity)
*/
public void delete( String recStatCode_, String plyrCnpjNbr_ )
{
ManagedRdbConnection connection = null;
CitiStatement preparedStatement = null;
StringBuffer query = new StringBuffer();
try
{
connection = OracleODSDAOFactory.getConnection();
query.append( " UPDATE " + C_TPL_PROD_PLAYER_ROLE );
query.append( " SET " );
query.append( C_REC_STAT_CODE + "= ?" );
query.append( " WHERE " + C_PLYR_CNPJ_NBR + " = ? " );
preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() ));
int count = 1;
if ( recStatCode_ != null )
{
preparedStatement.setString( count++, recStatCode_ );
}
else
{
preparedStatement.setString( count++, null );
}
if ( plyrCnpjNbr_ != null )
{
preparedStatement.setString( count++, plyrCnpjNbr_ );
}
else
{
preparedStatement.setString( count++, null );
}
preparedStatement.executeUpdate();
preparedStatement.replaceParametersInQuery(query.toString());
}
catch ( SQLException e )
{
throw new UnexpectedException( e.getErrorCode(),
C_ERROR_EXECUTING_STATEMENT, e );
}
finally
{
closeStatement( preparedStatement );
closeConnection( connection );
}
}
/**
* Retorna se um registro possui um relacionamento ativo entre produto e
* player
* @see com.citibank.ods.persistence.pl.dao.TplProdPlayerRoleDAO#existsRelationActive(com.citibank.ods.entity.pl.TplPlayerEntity)
*/
public boolean existsRelationActive( String plyrCnpjNbr_,
String plyrRoleTypeCode_ )
{
ManagedRdbConnection connection = null;
CitiStatement preparedStatement = null;
ResultSet resultSet = null;
StringBuffer query = new StringBuffer();
try
{
connection = OracleODSDAOFactory.getConnection();
query.append( "SELECT COUNT(*)" );
query.append( " FROM " );
query.append( C_TPL_PROD_PLAYER_ROLE );
query.append( " WHERE " + C_PLYR_CNPJ_NBR + " = ? AND " );
query.append( C_PLYR_ROLE_TYPE_CODE + " NOT IN ( ? ) AND " );
query.append( C_REC_STAT_CODE + " = ? " );
preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() ));
int count = 1;
preparedStatement.setString( count++, plyrCnpjNbr_ );
preparedStatement.setString( count++, plyrRoleTypeCode_ );
preparedStatement.setString( count++,
BaseTplPlayerRoleEntity.C_REC_STAT_CODE_ACTIVE );
resultSet = preparedStatement.executeQuery();
preparedStatement.replaceParametersInQuery(query.toString());
if ( resultSet.next() )
{
if ( resultSet.getInt( 1 ) != 0 )
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
catch ( SQLException e )
{
throw new UnexpectedException( e.getErrorCode(),
C_ERROR_EXECUTING_STATEMENT, e );
}
finally
{
closeStatement( preparedStatement );
closeConnection( connection );
}
}
public boolean exists( TplProdPlayerRoleEntity tplProdPlayerRoleEntity_ )
{
ManagedRdbConnection connection = null;
CitiStatement preparedStatement = null;
ResultSet resultSet = null;
StringBuffer query = new StringBuffer();
try
{
connection = OracleODSDAOFactory.getConnection();
query.append( "SELECT COUNT(*)" );
query.append( " FROM " );
query.append( C_TPL_PROD_PLAYER_ROLE );
query.append( " WHERE " + C_PLYR_CNPJ_NBR + " = ? AND " );
query.append( C_PLYR_ROLE_TYPE_CODE + " = ? AND " );
query.append( C_PROD_CODE + " = ? AND " );
query.append( C_SYS_CODE + " = ? AND " );
query.append( C_SYS_SEG_CODE + " = ?" );
preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() ));
int count = 1;
TplProdPlayerRoleEntityVO tplProdPlayerRoleEntityVO = ( TplProdPlayerRoleEntityVO ) tplProdPlayerRoleEntity_.getData();
preparedStatement.setString( count++, tplProdPlayerRoleEntityVO.getPlyrCnpjNbr() );
preparedStatement.setString( count++,
tplProdPlayerRoleEntityVO.getPlyrRoleTypeCode() );
preparedStatement.setString( count++, tplProdPlayerRoleEntityVO.getProdCode() );
preparedStatement.setString( count++, tplProdPlayerRoleEntityVO.getSysCode() );
preparedStatement.setLong( count++,
tplProdPlayerRoleEntityVO.getSysSegCode().longValue() );
resultSet = preparedStatement.executeQuery();
preparedStatement.replaceParametersInQuery(query.toString());
if ( resultSet.next() )
{
if ( resultSet.getInt( 1 ) != 0 )
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
catch ( SQLException e )
{
throw new UnexpectedException( e.getErrorCode(),
C_ERROR_EXECUTING_STATEMENT, e );
}
finally
{
closeStatement( preparedStatement );
closeConnection( connection );
}
}
public ArrayList selectByPlyr( String plyrCnpjNbr_ )
{
ManagedRdbConnection connection = null;
CitiStatement preparedStatement = null;
ResultSet resultSet = null;
StringBuffer query = new StringBuffer();
ArrayList prodPlayerRoleEntities;
try
{
connection = OracleODSDAOFactory.getConnection();
query.append( "SELECT " );
query.append( C_TPL_PROD_PLAYER_ROLE + "." + C_PROD_CODE + ", " );
query.append( C_TPL_PROD_PLAYER_ROLE + "." + C_SYS_CODE + ", " );
query.append( C_TPL_PROD_PLAYER_ROLE + "." + C_SYS_SEG_CODE + ", " );
query.append( C_TPL_PROD_PLAYER_ROLE + "." + C_PLYR_CNPJ_NBR + ", " );
query.append( C_TPL_PROD_PLAYER_ROLE + "." + C_PLYR_ROLE_TYPE_CODE + ", " );
query.append( C_TPL_PROD_PLAYER_ROLE + "." + C_LAST_UPD_USER_ID + ", " );
query.append( C_TPL_PROD_PLAYER_ROLE + "." + C_LAST_UPD_DATE + ", " );
query.append( C_TPL_PROD_PLAYER_ROLE + "." + C_LAST_AUTH_USER_ID + ", " );
query.append( C_TPL_PROD_PLAYER_ROLE + "." + C_LAST_AUTH_DATE + ", " );
query.append( C_TPL_PROD_PLAYER_ROLE + "." + C_REC_STAT_CODE );
query.append( " FROM " );
query.append( C_TPL_PROD_PLAYER_ROLE + " , " );
query.append( C_TPL_PRODUCT );
query.append( " WHERE " + C_TPL_PROD_PLAYER_ROLE + "." + C_PROD_CODE );
query.append( " = " + C_TPL_PRODUCT + "." + C_PROD_CODE );
query.append( " AND " + C_TPL_PROD_PLAYER_ROLE + "." + C_SYS_CODE );
query.append( " = " + C_TPL_PRODUCT + "." + C_SYS_CODE );
query.append( " AND " + C_TPL_PROD_PLAYER_ROLE + "." + C_SYS_SEG_CODE );
query.append( " = " + C_TPL_PRODUCT + "." + C_SYS_SEG_CODE );
query.append( " AND " + C_TPL_PROD_PLAYER_ROLE + "." + C_REC_STAT_CODE );
query.append( " != " + "'"
+ TplProdPlayerRoleEntity.C_REC_STAT_CODE_INACTIVE + "'" );
String criteria = "";
if ( plyrCnpjNbr_ != null && !"".equals( plyrCnpjNbr_ ) )
{
criteria = criteria + " AND " + C_TPL_PROD_PLAYER_ROLE + "."
+ C_PLYR_CNPJ_NBR + " = " + " ? ";
}
if ( criteria.length() > 0 )
{
query.append( criteria );
}
preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() ));
int count = 1;
if ( plyrCnpjNbr_ != null && !"".equals( plyrCnpjNbr_ ) )
{
preparedStatement.setString( count++, plyrCnpjNbr_ );
}
resultSet = preparedStatement.executeQuery();
preparedStatement.replaceParametersInQuery(query.toString());
prodPlayerRoleEntities = instantiateFromResultSet( resultSet );
resultSet.close();
}
catch ( SQLException e )
{
throw new UnexpectedException( e.getErrorCode(),
C_ERROR_EXECUTING_STATEMENT, e );
}
finally
{
closeStatement( preparedStatement );
closeConnection( connection );
}
return prodPlayerRoleEntities;
}
/*
* Retorna uma coleção de entities a partir do rs
*/
private ArrayList instantiateFromResultSet( ResultSet resultSet_ )
{
TplProdPlayerRoleEntityVO tplProdPlayerRoleEntityVO;
TplProdPlayerRoleEntity tplProdPlayerRoleEntity;
ArrayList tplProdPlayerRoleEntities = new ArrayList();
try
{
while ( resultSet_.next() )
{
tplProdPlayerRoleEntity = new TplProdPlayerRoleEntity();
tplProdPlayerRoleEntity.getData().setPlyrCnpjNbr(
resultSet_.getString( C_PLYR_CNPJ_NBR ) );
tplProdPlayerRoleEntity.getData().setPlyrRoleTypeCode(
resultSet_.getString( C_PLYR_ROLE_TYPE_CODE ) );
tplProdPlayerRoleEntity.getData().setProdCode(
resultSet_.getString( C_PROD_CODE ) );
tplProdPlayerRoleEntity.getData().setSysCode(
resultSet_.getString( C_SYS_CODE ) );
tplProdPlayerRoleEntity.getData().setSysSegCode(
new BigInteger(
resultSet_.getString( C_SYS_SEG_CODE ) ) );
tplProdPlayerRoleEntity.getData().setLastUpdDate(
resultSet_.getDate( C_LAST_UPD_DATE ) );
tplProdPlayerRoleEntity.getData().setLastUpdUserId(
resultSet_.getString( C_LAST_UPD_USER_ID ) );
//Casting para a atribuicao das colunas especificas
tplProdPlayerRoleEntityVO = ( TplProdPlayerRoleEntityVO ) tplProdPlayerRoleEntity.getData();
tplProdPlayerRoleEntityVO.setRecStatCode( resultSet_.getString( C_REC_STAT_CODE ) );
tplProdPlayerRoleEntityVO.setLastAuthDate( resultSet_.getDate( C_LAST_AUTH_DATE ) );
tplProdPlayerRoleEntityVO.setLastAuthUserId( resultSet_.getString( C_LAST_AUTH_USER_ID ) );
tplProdPlayerRoleEntities.add( tplProdPlayerRoleEntity );
}
}
catch ( SQLException e )
{
throw new UnexpectedException( e.getErrorCode(),
C_ERROR_INSTANTIATE_FROM_RESULT_SET, e );
}
return tplProdPlayerRoleEntities;
}
/*
* (non-Javadoc)
* @see com.citibank.ods.persistence.pl.dao.TplProdPlayerRoleDAO#getRoleTypes(java.lang.String,
* java.lang.String)
*/
public ArrayList getRoleTypes( String plyrCnpjNbr_, String plyrRoleTypeCode_ )
{
String roleType;
ManagedRdbConnection connection = null;
CitiStatement preparedStatement = null;
ResultSet resultSet = null;
StringBuffer query = new StringBuffer();
ArrayList listRoleType = new ArrayList();
String[] splitPlyrRoleTypeCode = plyrRoleTypeCode_.split( "," );
try
{
connection = OracleODSDAOFactory.getConnection();
query.append( "SELECT DISTINCT " );
query.append( C_PLYR_ROLE_TYPE_CODE );
query.append( " FROM " );
query.append( C_TPL_PROD_PLAYER_ROLE );
query.append( " WHERE " + C_PLYR_CNPJ_NBR + " = ? AND " );
query.append( C_REC_STAT_CODE + " = ? AND " );
query.append( C_PLYR_ROLE_TYPE_CODE + " NOT IN ( " + plyrRoleTypeCode_
+ ")" );
preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() ));
int count = 1;
preparedStatement.setString( count++, plyrCnpjNbr_ );
preparedStatement.setString( count++,
BaseTplPlayerRoleEntity.C_REC_STAT_CODE_ACTIVE );
resultSet = preparedStatement.executeQuery();
preparedStatement.replaceParametersInQuery(query.toString());
while ( resultSet.next() )
{
roleType = resultSet.getString( C_PLYR_ROLE_TYPE_CODE );
listRoleType.add( ODSConstraintDecoder.decodeRoleType( roleType ) );
}
}
catch ( SQLException e )
{
throw new UnexpectedException( e.getErrorCode(),
C_ERROR_EXECUTING_STATEMENT, e );
}
finally
{
closeStatement( preparedStatement );
closeConnection( connection );
}
return listRoleType;
}
/**
* Consulta dos produtos
*/
public ArrayList listProduct( String prodCode_, String prodName_ )
{
DataSetRow row;
TplProductEntity tplProductEntity;
TplProductEntityVO tplProductEntityVO;
ArrayList result = new ArrayList();
BigDecimal sysSegCode;
//Cria uma instancia do DAO de produto para acessar a lista existente
TplProductDAO tplProductDAO = ODSDAOFactory.getInstance().getTplProductDAO();
//Passa os resultado da consulta para um arraylist de entities.
DataSet rds = tplProductDAO.list( prodCode_, null, prodName_, null, null,
null,"" );
for ( int indexRow = 0; indexRow < rds.size(); indexRow++ )
{
row = rds.getRow( indexRow );
tplProductEntity = new TplProductEntity();
tplProductEntityVO = ( TplProductEntityVO ) tplProductEntity.getData();
sysSegCode = row.getBigDecimalByName( C_SYS_SEG_CODE );
tplProductEntityVO.setProdCode( row.getStringByName( C_PROD_CODE ) );
tplProductEntityVO.setProdName( row.getStringByName( C_PROD_NAME ) );
tplProductEntityVO.setSysCode( row.getStringByName( C_SYS_CODE ) );
tplProductEntityVO.setSysSegCode( BigInteger.valueOf( sysSegCode.longValue() ) );
tplProductEntityVO.setLastUpdUserId( row.getStringByName( C_LAST_UPD_USER_ID ) );
tplProductEntityVO.setLastAuthDate( row.getDateByName( C_LAST_AUTH_DATE ) );
tplProductEntityVO.setLastAuthUserId( row.getStringByName( C_LAST_AUTH_USER_ID ) );
tplProductEntityVO.setRecStatCode( row.getStringByName( C_REC_STAT_CODE ) );
result.add( tplProductEntity );
}
return result;
}
} |
package com.jzl;
import lombok.Data;
import org.apache.hadoop.io.WritableComparable;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
@Data
public class Entity implements WritableComparable<Entity> {
private int id;//主键
private int cityId;//城市id
private String cityName;//城市名称
private String airportName;//机场名称
private String loccd;//机场三字码
private int locsubcd;//机场编号
private String airportLongitude;//机场经度
private String airportLatitude;//机场维度
private String address;//上下车地点
private String longitude;//经度
private String latitude;//维度
private double distance;//距离
private double price;
private String supplier;
private String car;
private String time;
private String usetime;
private int flag;
public String toString(){
return usetime+"\t"+cityName+"\t"+address+"\t"+airportName+"\t"+car+"\t"+supplier+"\t"+price+"\t"+time+"\t"+distance+"\t"+flag;
}
@Override
public int compareTo(Entity o) {
return 0;
}
@Override
public void write(DataOutput out) throws IOException {
//out.writeInt(id);
// out.writeInt(cityId);
out.writeUTF(cityName);
out.writeUTF(airportName);
// out.writeUTF(loccd);
// out.writeInt(locsubcd);
// out.writeUTF(airportLongitude);
// out.writeUTF(airportLatitude);
out.writeUTF(address);
//out.writeUTF(longitude);
// out.writeUTF(latitude);
out.writeDouble(distance);
out.writeUTF(car);
out.writeDouble(price);
out.writeUTF(supplier);
out.writeUTF(time);
out.writeInt(flag);
out.writeUTF(usetime);
}
@Override
public void readFields(DataInput in) throws IOException {
// this.id = in.readInt();
// this.cityId = in.readInt();
this.cityName = in.readUTF();
this.airportName = in.readUTF();
// this.loccd = in.readUTF();
// this.locsubcd = in.readInt();
// this.airportLongitude = in.readUTF();
// this.airportLatitude = in.readUTF();
this.address = in.readUTF();
// this.longitude = in.readUTF();
// this.latitude = in.readUTF();
this.distance = in.readDouble();
this.car = in.readUTF();
this.price = in.readDouble();
this.supplier = in.readUTF();
this.time = in.readUTF();
this.flag = in.readInt();
this.usetime = in.readUTF();
}
}
|
/*
* @(#) ErrorCodeAction.java
* Copyright (c) 2006 eSumTech Co., Ltd. All Rights Reserved.
*/
package com.esum.wp.ims.errorcode.struts.action;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.esum.appcommon.fileupload.DiskFileUpload;
import com.esum.appcommon.fileupload.FileItem;
import com.esum.appcommon.fileupload.FileUpload;
import com.esum.appcommon.resource.application.Config;
import com.esum.appcommon.session.SessionMgr;
import com.esum.appframework.struts.action.BaseDelegateAction;
import com.esum.appframework.struts.actionform.BeanUtilForm;
import com.esum.wp.ims.batchinfo.service.IBatchInfoService;
import com.esum.wp.ims.errorcategory.service.IErrorCategoryService;
import com.esum.wp.ims.errorcode.ErrorCode;
import com.esum.wp.ims.errorcode.service.IErrorCodeService;
/**
*
* @author heowon@esumtech.com
* @version $Revision: 1.2 $ $Date: 2009/01/15 09:23:12 $
*/
public class ErrorCodeAction extends BaseDelegateAction {
protected ActionForward doService(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
if (method.equals("uploadErrorCode")) {
boolean isMultipart = FileUpload.isMultipartContent(request);
if(!isMultipart)
throw new ServletException("Code regist error.");
Hashtable paramFields = new Hashtable();
DiskFileUpload upload = new DiskFileUpload();
List items = null;
items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
paramFields.put(item.getFieldName(), item.getString());
} else {
process(item);
}
}
ErrorCode errorCode = null;
BeanUtilForm beanUtilForm = (BeanUtilForm)form;
Object inputObject = null;
if (beanUtilForm != null) {
inputObject = beanUtilForm.getBean();
}else {
beanUtilForm = new BeanUtilForm();
}
if(inputObject == null) {
errorCode = new ErrorCode();
}else {
errorCode = (ErrorCode)inputObject;
}
beanUtilForm.setBean(errorCode);
request.setAttribute("inputObject", errorCode);
return super.doService(mapping, beanUtilForm, request, response);
}else if (method.equals("selectPageList")) {
ErrorCode errorCode = null;
BeanUtilForm beanUtilForm = (BeanUtilForm)form;
request.removeAttribute("inputObject");
request.removeAttribute("outputObject");
Object inputObject = null;
if (beanUtilForm != null) {
inputObject = beanUtilForm.getBean();
}else {
beanUtilForm = new BeanUtilForm();
}
int itemCountPerPage = Config.getInt("Common", "LIST.COUNT_PER_PAGE");
if(inputObject == null) {
errorCode = new ErrorCode();
errorCode.setCurrentPage(new Integer(1));
errorCode.setItemCountPerPage(new Integer(itemCountPerPage));
}else {
errorCode = (ErrorCode)inputObject;
if(errorCode.getCurrentPage() == null) {
errorCode.setCurrentPage(new Integer(1));
}
if(errorCode.getItemCountPerPage() == null) {
errorCode.setItemCountPerPage(new Integer(itemCountPerPage));
}
}
SessionMgr sessMgr = new SessionMgr(request);
errorCode.setDbType(sessMgr.getValue("dbType"));
if(errorCode.getCategory() != null){
if(errorCode.getCategory().equals("null") || errorCode.getCategory().equals("%")){
errorCode.setCategory("");
}
}else if(errorCode.getCategory() == null){
errorCode.setCategory("");
}
errorCode.setCategory(errorCode.getCategory() + "%");
if(errorCode.getErrorCode() != null){
if(errorCode.getErrorCode().equals("null") || errorCode.getErrorCode().equals("%")){
errorCode.setErrorCode("");
}
}else if(errorCode.getErrorCode() == null){
errorCode.setErrorCode("");
}
errorCode.setErrorCode(errorCode.getErrorCode() + "%");
beanUtilForm.setBean(errorCode);
request.setAttribute("inputObject",errorCode);
return super.doService(mapping, beanUtilForm, request, response);
} else if (method.equals("selectDetail")) {
ErrorCode errorCode = null;
BeanUtilForm beanUtilForm = (BeanUtilForm)form;
request.removeAttribute("inputObject");
request.removeAttribute("outputObject");
Object inputObject = null;
if (beanUtilForm != null) {
inputObject = beanUtilForm.getBean();
}else {
beanUtilForm = new BeanUtilForm();
}
if(inputObject == null) {
errorCode = new ErrorCode();
}else {
errorCode = (ErrorCode)inputObject;
}
SessionMgr sess = new SessionMgr(request);
errorCode.setLangType(sess.getValue("langType"));
List category = (List) ((IErrorCodeService)iBaseService).selectCategoryList(errorCode);
errorCode.setCategoryList(category);
beanUtilForm.setBean(errorCode);
request.setAttribute("inputObject", errorCode);
return super.doService(mapping, beanUtilForm, request, response);
} else if(method.equals("saveErrorCodeExcel")){
ErrorCode errorCode = null;
BeanUtilForm beanUtilForm = (BeanUtilForm) form;
request.removeAttribute("inputObject");
request.removeAttribute("outputObject");
Object inputObject = null;
if (beanUtilForm != null) {
inputObject = beanUtilForm.getBean();
}else {
beanUtilForm = new BeanUtilForm();
}
if(inputObject == null) {
errorCode = new ErrorCode();
}else {
errorCode = (ErrorCode)inputObject;
}
SessionMgr sessMgr = new SessionMgr(request);
errorCode.setDbType(sessMgr.getValue("dbType"));
errorCode.setLangTypeS(sessMgr.getValue("langType"));
errorCode.setRootPath(getServlet().getServletContext().getRealPath("/"));
IErrorCodeService service = (IErrorCodeService)iBaseService;
service.saveErrorCodeExcel(errorCode, request, response);
return null;
} else if (method.equals("selectCategoryList")) {
SessionMgr sess = new SessionMgr(request);
ErrorCode errorCode = new ErrorCode();
errorCode.setLangType(sess.getValue("langType"));
List category = (List) ((IErrorCodeService)iBaseService).selectCategoryList(errorCode);
request.setAttribute("outputObject", category);
return mapping.findForward("success");
}else {
return super.doService(mapping, form, request, response);
}
}
protected void process(FileItem item) throws Exception{
BufferedReader reader = new BufferedReader(new InputStreamReader(item.getInputStream()));
ErrorCode errCodeObj = null;
while(true){
try{
errCodeObj = new ErrorCode();
String line = reader.readLine();
if(line==null)
break;
String[] array = parseString(line);
errCodeObj.setErrorCode(array[0]);
errCodeObj.setLangType(array[1]);
errCodeObj.setReason(array[2]);
errCodeObj.setAction(array[3]);
errCodeObj.setCategory(array[4]);
errCodeObj.setSeverity(array[5]);
Object insertErrorCode = (Object) ((IErrorCodeService)iBaseService).insertErrorCode(errCodeObj);
}catch(Exception e){
throw new Exception(e);
}
}
}
protected String[] parseString(String line){
String[] array = new String[]{"", "", "", "", "", ""};
int fidx = 0;
int length = line.length();
for(int i=0;i<6;i++){
int idx = line.indexOf(",", fidx);
if(idx==-1)
idx = length;
String sub = line.substring(fidx, idx);
array[i] = sub.equals("")?array[i] = " ":sub.trim();
fidx = idx+1;
}
return array;
}
}
|
package com.example.projet_makbal_mounir;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Detailcours extends AppCompatActivity {
TextView tv1;
TextView tvid;
TextView tvsem;
TextView tvfil;
TextView tvcoef;
String id;
String semestre;
int coeff;
String filiere;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailcours);
tvid = (TextView) findViewById(R.id.tvid);
tvsem = (TextView) findViewById(R.id.tvsem);
tvfil = (TextView) findViewById(R.id.tvfil);
tvcoef = (TextView)findViewById(R.id.tvcoeff);
new RetrieveFeedTask().execute(tvid,tvsem,tvfil,tvcoef);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
public void Inscrire(View view) {
Intent intention = getIntent();
String s = intention.getStringExtra("cours");
Intent i=new Intent();
i.setAction("detailscours.inscrire");
i.putExtra("id", s);
i.putExtra("filière", tvfil.getText().toString());
startActivity(i);
}
public class RetrieveFeedTask extends AsyncTask<TextView, Void, Void> {
private Activity activity;
@Override
protected Void doInBackground(TextView... textViews) {
try {
Intent intention = getIntent();
String s = intention.getStringExtra("cours");
int idd=Integer.parseInt(s);
//tv1 = (TextView) findViewById(R.id.tv1);
//tv1.setText("Description du cours " + s);
Class.forName("com.mysql.jdbc.Driver");
Connection conex = DriverManager.getConnection("jdbc:mysql://192.168.1.112:3306/BD?characterEncoding=latin1", "root", "mysql");
String sql1 = "select * from cours where id ='" + idd + "'";
PreparedStatement prest = conex.prepareStatement(sql1);
ResultSet rs = prest.executeQuery();
while (rs.next()) {
id = rs.getString(2);//titre
semestre = rs.getString(4);
coeff = rs.getInt(3);
filiere = rs.getString(5);
}
conex.close();
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
Log.e("Dbtest", e.toString());
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
Log.e("Dbtest", String.valueOf(id));
tvid.setText(id);
tvsem.setText(semestre);
tvcoef.setText(String.valueOf(coeff));
tvfil.setText(filiere);
}
}
}
|
package br.com.drem.managebean.urlMb;
/**
* @author AndreMart
* @contacts: andremartins@outlook.com.br;andre.drem@gmail.com
* @tel: 63 8412 1921
* @site: drem.com.br
*/
import javax.faces.bean.ManagedBean;
@ManagedBean
public class MbHome {
public String redirecionaHome(){
return"index";
}
}
|
import java.io.*;
import java.util.Scanner;
class student{
private String stuName;
private Byte stuMarks[]=new Byte[5];
private long roll;
private String course;
public void read() throws IOException{
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
Scanner scan=new Scanner(System.in);
System.out.println("\nEnter the name of the student");
stuName=br.readLine();
System.out.println("\nEnter the roll number");
roll=Long.parseLong(br.readLine());
System.out.println("\nEnter the COURSE name");
course=br.readLine();
for(byte i=0;i<5;i++){
System.out.println("\nEnter the mark of " +i+" subject ");
stuMarks[i]=Byte.parseByte(br.readLine());
}
}
public double calculate(){
double average=0;
int total=0;
for(byte i=0;i<5;i++){
total+=stuMarks[i];
}
average=total/5;
//System.out.println("The average is " +average);
return average;
}
public double display(){
double avg=0;
avg=calculate();
System.out.println("The average = " +avg);
return avg;
}
public static void main(String args[]) throws IOException{
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
Scanner scan=new Scanner(System.in);
boolean ch=true;
byte opt=0;
student stu=new student();
while(ch){
System.out.println("\n1. Read Data");
// System.out.println("\n2. Calculate");
System.out.println("\n2. Display");
System.out.println("\n3. Exit");
System.out.println("\nEnter your choice");
opt=Byte.parseByte(br.readLine());
switch (opt) {
case 1:
stu.read();
break;
case 2:
stu.calculate();
stu.display();
case 3:
ch=false;
}
}
}
}
|
package javaapplication3;
/**
*
* @author Jayan
*/
public class MySqldb {
public static void main(String[] args) {
DbConnect connect= new DbConnect();
connect.getData();
}
}
|
package org.hadoop.praveen;
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
public class WritableMapper extends Mapper<LongWritable,Text,MyWritable,IntWritable>{
private final IntWritable one = new IntWritable(1);
@Override
protected void map(LongWritable key, Text val, Context c) throws IOException, InterruptedException{
String line = val.toString();
String[] words = line.split(",");
for(String word:words) {
c.write(new MyWritable(word), one);
}
}
}
|
package com.ymall.swagger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* http://localhost:8080/ymall/swagger/index.html#/
* 常用注解:
- @Api()用于类;
表示标识这个类是swagger的资源
- @ApiOperation()用于方法;
表示一个http请求的操作
- @ApiParam()用于方法,参数,字段说明;
表示对参数的添加元数据(说明或是否必填等)
- @ApiModel()用于类
表示对类进行说明,用于参数用实体类接收
- @ApiModelProperty()用于方法,字段
表示对model属性的说明或者数据操作更改
- @ApiIgnore()用于类,方法,方法参数
表示这个方法或者类被忽略
- @ApiImplicitParam() 用于方法
表示单独的请求参数
- @ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam
* @author Cherry
* @date 2019年5月17日
*/
//@Configuration //声明该类为配置类
@EnableSwagger2 //声明启动Swagger2
@EnableWebMvc //声明启动mvc
public class SwaggerConfig{
/*
* Docket可以配置多个
*/
@Bean
public Docket customDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.ymall.controller"))//扫描的包路径
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("接口测试")//文档说明
.version("1.0.0")//文档版本说明
.build();
}
}
|
package peropt.me.com.performaceoptimization;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.ViewTreeObserver;
import android.widget.TextView;
import java.lang.ref.WeakReference;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView=null;
textView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
}
});
textView.getViewTreeObserver().removeOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
}
});
MyHandler myHandler = new MyHandler(this);
}
private static class MyHandler extends Handler {
WeakReference<MainActivity> mMainActivityWeakReference;
private MyHandler(MainActivity mainActivity) {
mMainActivityWeakReference = new WeakReference<>(mainActivity);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 0:
MainActivity mainActivity = mMainActivityWeakReference.get();
if (mainActivity != null) {
System.out.println("不错哟");
}
break;
}
}
}
private static final Runnable RUNNABLE = new Runnable() {
@Override
public void run() {
}
};
/**
* GPU刷新:GPU帮我们将UI等组件计算出成纹理Textrue和三维图形Polygons
* 同时会使用OpenGL------会将纹理和polygons缓存在GPU内存里面
* Refresh rate
* viewTree:
*/
}
|
package jthrift;
import java.util.*;
public class TProgram extends TDoc {
private String path;
private String name;
private TScope scope;
private Map<Id, Id> namespaces = new HashMap<Id, Id>();
private List<Id> cppIncludes = new LinkedList<Id>();
private List<TProgram> includes = new LinkedList<TProgram>();
private List<TConst> consts = new LinkedList<TConst>();
private List<TTypedef> typedefs = new LinkedList<TTypedef>();
private List<TEnum> tenums = new LinkedList<TEnum>();
private List<TStruct> structs = new LinkedList<TStruct>();
private List<TStruct> xceptions = new LinkedList<TStruct>();
private List<TService> services = new LinkedList<TService>();
public TProgram(String path, String name) {
this.path = path;
this.name = name;
this.scope = new TScope();
}
public void setNamespace(Id lang, Id ns) {
namespaces.put(lang, ns);
}
public Map<Id, Id> getNamespaces() {
return namespaces;
}
public void addCppInclude(Id path) {
cppIncludes.add(path);
}
public List<Id> getCppIncludes() {
return cppIncludes;
}
public void addInclude(Id path, Id include_site) {
TProgram prog = new TProgram(path.toString(), this.name);
// TODO
//prog.setIncludePrefix(include_site)
includes.add(prog);
}
public List<TProgram> getIncludes() {
return includes;
}
public void addConst(TConst a) {
consts.add(a);
}
public List<TConst> getConsts() {
return consts;
}
public void addService(TService a) {
services.add(a);
}
public List<TService> getServices() {
return services;
}
public void addTypedef(TTypedef a) {
typedefs.add(a);
}
public List<TTypedef> getTypedefs() {
return typedefs;
}
public void addEnum(TEnum a) {
tenums.add(a);
}
public List<TEnum> getEnums() {
return tenums;
}
public void addStruct(TStruct a) {
structs.add(a);
}
public List<TStruct> getStructs() {
return structs;
}
public void addXception(TStruct a) {
xceptions.add(a);
}
public List<TStruct> getXceptions() {
return xceptions;
}
} |
import java.util.*;
class Question_1
{
static String str_operation(char[] chars)
{
char p = '\0';
int c = 0;
for (char ch: chars)
{
if (p != ch)
{
chars[c++] = ch;
p = ch;
}
}
return new String(chars).substring(0, c);
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the String : ");
String s = sc.next();
s = str_operation(s.toCharArray());
System.out.println(s);
}
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.htmlunit;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.WebResponse;
import com.gargoylesoftware.htmlunit.util.NameValuePair;
import jakarta.servlet.http.Cookie;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpServletResponse;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link MockWebResponseBuilder}.
*
* @author Rob Winch
* @since 4.2
*/
public class MockWebResponseBuilderTests {
private final MockHttpServletResponse response = new MockHttpServletResponse();
private WebRequest webRequest;
private MockWebResponseBuilder responseBuilder;
@BeforeEach
public void setup() throws Exception {
this.webRequest = new WebRequest(new URL("http://company.example:80/test/this/here"));
this.responseBuilder = new MockWebResponseBuilder(System.currentTimeMillis(), this.webRequest, this.response);
}
// --- constructor
@Test
public void constructorWithNullWebRequest() {
assertThatIllegalArgumentException().isThrownBy(() ->
new MockWebResponseBuilder(0L, null, this.response));
}
@Test
public void constructorWithNullResponse() throws Exception {
assertThatIllegalArgumentException().isThrownBy(() ->
new MockWebResponseBuilder(0L, new WebRequest(new URL("http://company.example:80/test/this/here")), null));
}
// --- build
@Test
public void buildContent() throws Exception {
this.response.getWriter().write("expected content");
WebResponse webResponse = this.responseBuilder.build();
assertThat(webResponse.getContentAsString()).isEqualTo("expected content");
}
@Test
public void buildContentCharset() throws Exception {
this.response.addHeader("Content-Type", "text/html; charset=UTF-8");
WebResponse webResponse = this.responseBuilder.build();
assertThat(webResponse.getContentCharset()).isEqualTo(StandardCharsets.UTF_8);
}
@Test
public void buildContentType() throws Exception {
this.response.addHeader("Content-Type", "text/html; charset-UTF-8");
WebResponse webResponse = this.responseBuilder.build();
assertThat(webResponse.getContentType()).isEqualTo("text/html");
}
@Test
public void buildResponseHeaders() throws Exception {
this.response.addHeader("Content-Type", "text/html");
this.response.addHeader("X-Test", "value");
Cookie cookie = new Cookie("cookieA", "valueA");
cookie.setDomain("domain");
cookie.setPath("/path");
cookie.setMaxAge(1800);
cookie.setSecure(true);
cookie.setHttpOnly(true);
this.response.addCookie(cookie);
WebResponse webResponse = this.responseBuilder.build();
List<NameValuePair> responseHeaders = webResponse.getResponseHeaders();
assertThat(responseHeaders).hasSize(3);
NameValuePair header = responseHeaders.get(0);
assertThat(header.getName()).isEqualTo("Content-Type");
assertThat(header.getValue()).isEqualTo("text/html");
header = responseHeaders.get(1);
assertThat(header.getName()).isEqualTo("X-Test");
assertThat(header.getValue()).isEqualTo("value");
header = responseHeaders.get(2);
assertThat(header.getName()).isEqualTo("Set-Cookie");
assertThat(header.getValue())
.startsWith("cookieA=valueA; Path=/path; Domain=domain; Max-Age=1800; Expires=")
.endsWith("; Secure; HttpOnly");
}
// SPR-14169
@Test
public void buildResponseHeadersNullDomainDefaulted() throws Exception {
Cookie cookie = new Cookie("cookieA", "valueA");
this.response.addCookie(cookie);
WebResponse webResponse = this.responseBuilder.build();
List<NameValuePair> responseHeaders = webResponse.getResponseHeaders();
assertThat(responseHeaders).hasSize(1);
NameValuePair header = responseHeaders.get(0);
assertThat(header.getName()).isEqualTo("Set-Cookie");
assertThat(header.getValue()).isEqualTo("cookieA=valueA");
}
@Test
public void buildStatus() throws Exception {
WebResponse webResponse = this.responseBuilder.build();
assertThat(webResponse.getStatusCode()).isEqualTo(200);
assertThat(webResponse.getStatusMessage()).isEqualTo("OK");
}
@Test
public void buildStatusNotOk() throws Exception {
this.response.setStatus(401);
WebResponse webResponse = this.responseBuilder.build();
assertThat(webResponse.getStatusCode()).isEqualTo(401);
assertThat(webResponse.getStatusMessage()).isEqualTo("Unauthorized");
}
@Test
public void buildStatusWithCustomMessage() throws Exception {
this.response.sendError(401, "Custom");
WebResponse webResponse = this.responseBuilder.build();
assertThat(webResponse.getStatusCode()).isEqualTo(401);
assertThat(webResponse.getStatusMessage()).isEqualTo("Custom");
}
@Test
public void buildWebRequest() throws Exception {
WebResponse webResponse = this.responseBuilder.build();
assertThat(webResponse.getWebRequest()).isEqualTo(this.webRequest);
}
}
|
package com.apon.taalmaatjes.backend.util;
public class ObjectUtil {
@SafeVarargs
public static <T> T coalesce(T ...items) {
for(T i : items) if(i != null) return i;
return null;
}
}
|
package be.mxs.common.util.pdf.general.oc.examinations;
import be.mxs.common.util.pdf.general.PDFGeneralBasic;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPCell;
/**
* User: ssm
* Date: 18-jul-2007
*/
public class PDFStomatologyOperationProtocol extends PDFGeneralBasic {
//--- ADD CONTENT -----------------------------------------------------------------------------
protected void addContent(){
try{
if(transactionVO.getItems().size() >= minNumberOfItems){
contentTable = new PdfPTable(1);
table = new PdfPTable(5);
// starthour
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPERATION_PROTOCOL_START");
if(itemValue.length() > 0){
addItemRow(table,getTran("openclinic.chuk","starthour"),itemValue);
}
// endhour
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPERATION_PROTOCOL_END");
if(itemValue.length() > 0){
addItemRow(table,getTran("openclinic.chuk","endhour"),itemValue);
}
// duration
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPERATION_PROTOCOL_DURATION");
if(itemValue.length() > 0){
addItemRow(table,getTran("openclinic.chuk","duration"),itemValue);
}
// diagnostic
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPERATION_PROTOCOL_DIAGNOSTIC");
if(itemValue.length() > 0){
addItemRow(table,getTran("openclinic.chuk","diagnostic"),itemValue);
}
// intervention
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPERATION_PROTOCOL_INTERVENTION");
if(itemValue.length() > 0){
addItemRow(table,getTran("openclinic.chuk","intervention"),itemValue);
}
//*** lochies *************************************************
PdfPTable compostitionTable = new PdfPTable(4);
// surgeons
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPERATION_PROTOCOL_SURGEONS");
if(itemValue.length() > 0){
compostitionTable.addCell(createValueCell(getTran("openclinic.chuk","surgeons"),1));
compostitionTable.addCell(createValueCell(itemValue,3));
}
// anasthesists
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPERATION_PROTOCOL_ANASTHESISTS");
if(itemValue.length() > 0){
compostitionTable.addCell(createValueCell(getTran("openclinic.chuk","anasthesists"),1));
compostitionTable.addCell(createValueCell(itemValue,3));
}
// nurses
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPERATION_PROTOCOL_NURSES");
if(itemValue.length() > 0){
compostitionTable.addCell(createValueCell(getTran("openclinic.chuk","nurses"),1));
compostitionTable.addCell(createValueCell(itemValue,3));
}
// add compostion table
if(compostitionTable.size() > 1){
table.addCell(createItemNameCell(getTran("openclinic.chuk","group.composition"),1));
table.addCell(createCell(new PdfPCell(compostitionTable),4,PdfPCell.ALIGN_CENTER,PdfPCell.BOX));
}
// patient.installation
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPERATION_PROTOCOL_PATIENT_INSTALLATION");
if(itemValue.length() > 0){
addItemRow(table,getTran("openclinic.chuk","patient.installation"),itemValue);
}
// aproval
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPERATION_PROTOCOL_APROVAL");
if(itemValue.length() > 0){
addItemRow(table,getTran("openclinic.chuk","aproval"),itemValue);
}
// observations
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPERATION_PROTOCOL_OBSERVATION");
if(itemValue.length() > 0){
addItemRow(table,getTran("openclinic.chuk","observations"),itemValue);
}
// surgical.act
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPERATION_PROTOCOL_SURGICAL_ACT");
if(itemValue.length() > 0){
addItemRow(table,getTran("openclinic.chuk","surgical.act"),itemValue);
}
// closure
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPERATION_PROTOCOL_CLOSURE");
if(itemValue.length() > 0){
addItemRow(table,getTran("openclinic.chuk","closure"),itemValue);
}
// care.post.op
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPERATION_PROTOCOL_CARE");
if(itemValue.length() > 0){
addItemRow(table,getTran("openclinic.chuk","care.post.op"),itemValue);
}
// remarks
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_OPERATION_PROTOCOL_REMARKS");
if(itemValue.length() > 0){
addItemRow(table,getTran("openclinic.chuk","remarks"),itemValue);
}
// add table
if(table.size() > 0){
if(contentTable.size() > 0) contentTable.addCell(emptyCell());
contentTable.addCell(createCell(new PdfPCell(table),1,PdfPCell.ALIGN_CENTER,PdfPCell.BOX));
tranTable.addCell(new PdfPCell(contentTable));
addTransactionToDoc();
}
// diagnoses
addDiagnosisEncoding();
addTransactionToDoc();
}
}
catch(Exception e){
e.printStackTrace();
}
}
} |
package stringtypes;
public class stringexple {
public static void main(String[] args) {
String name ="siran";
String name1 ="siran world";
System.out.println("string:");
int identityHashCode = System.identityHashCode(name);
System.out.println(identityHashCode);
int identityHashCode2 = System.identityHashCode(name1);
System.out.println(identityHashCode2);
String concat = name.concat(name1);
System.out.println(concat);
int identityHashCode3 = System.identityHashCode(concat);
//string buBuffer
System.out.println("stringbuffer");
StringBuffer a= new StringBuffer("siran");
StringBuffer b=new StringBuffer("sirangv");
int identityHashCode4 = System.identityHashCode(a);
System.out.println(identityHashCode4);
int identityHashCode5 = System.identityHashCode(b);
System.out.println(identityHashCode5);
StringBuffer append = a.append(b);
System.out.println(append);
int identityHashCode6 = System.identityHashCode(append);
System.out.println(identityHashCode6);
//string builder
StringBuilder c=new StringBuilder("siran");
StringBuilder t=new StringBuilder("sirangv");
int identityHashCode7 = System.identityHashCode(c);
System.out.println(identityHashCode7);
int identityHashCode8 = System.identityHashCode(t);
System.out.println(identityHashCode5);
StringBuilder append1= c.append(t);
System.out.println(append1);
int identityHashCode9= System.identityHashCode(append);
System.out.println(identityHashCode9);
}
}
|
package caris.framework.utilities;
import java.text.SimpleDateFormat;
import caris.framework.library.Constants;
import caris.framework.library.Variables;
import sx.blah.discord.handle.obj.IChannel;
import sx.blah.discord.handle.obj.IGuild;
import sx.blah.discord.handle.obj.IUser;
public class Logger {
public static SimpleDateFormat sdf = new SimpleDateFormat( Constants.DATEFORMAT );
public static void say(String message, IChannel channel) {
if( Constants.SAY ) {
String output = "(" + channel.getLongID() + ") <" + channel.getName() + ">: " + message;
consolePrint(output);
log(output);
}
}
public static void hear(String message, IUser user, IChannel channel) {
if( Constants.HEAR ) {
String output = "(" + channel.getLongID() + ") <";
output += channel.getName() + "> [";
output += user.getName() + "]: ";
output += message;
consolePrint(output);
log(output);
}
}
public static void error(String message) {
error(message, Constants.DEFAULT_INDENT_LEVEL);
}
public static void error(String message, int level) {
String output = "[ERROR]";
for( int f=0; f<level*Constants.DEFAULT_INDENT_INCREMENT; f++ ) {
output += Constants.ERROR_INDENT;
}
output += Constants.HEADER;
output += message;
System.err.println(output);
if( Constants.LOG ) {
log(output);
}
}
public static void debug(String message) {
debug(message, Constants.DEFAULT_INDENT_LEVEL, false);
}
public static void debug(String message, boolean verbose) {
debug(message, Constants.DEFAULT_INDENT_LEVEL, verbose);
}
public static void debug(String message, int level) {
debug(message, level, false);
}
public static void debug(String message, int level, boolean verbose) {
if( (Constants.DEBUG_LEVEL == -1 || Constants.DEBUG_LEVEL >= level) && (!verbose || Constants.VERBOSE) ) {
String output = "[DEBUG]";
if( Constants.DEBUG ) {
for( int f=0; f<level*Constants.DEFAULT_INDENT_INCREMENT; f++ ) {
output += Constants.DEBUG_INDENT;
}
output += Constants.HEADER;
output += message;
consolePrint(output);
if( Constants.LOG && ( Constants.LOG_LEVEL == -1 || Constants.LOG_LEVEL >= level )) {
log(output);
}
}
}
}
public static void print(String message) {
print(message, Constants.DEFAULT_INDENT_LEVEL);
}
public static void print(String message, boolean verbose) {
print(message, Constants.DEFAULT_INDENT_LEVEL, verbose);
}
public static void print(String message, int level) {
print(message, level, false);
}
public static void print(String message, int level, boolean verbose) {
if( (Constants.PRINT_LEVEL == -1 || Constants.PRINT_LEVEL >= level) && (!verbose || Constants.VERBOSE)) {
String output = "[PRINT]";
if( Constants.PRINT ) {
for( int f=0; f<level*Constants.DEFAULT_INDENT_INCREMENT; f++ ) {
output += Constants.PRINT_INDENT;
}
output += Constants.HEADER;
output += message;
consolePrint(output);
if( Constants.LOG && ( Constants.LOG_LEVEL == -1 || Constants.LOG_LEVEL >= level )) {
log(output);
}
}
}
}
public static void log(String message) {
// BufferedWriter logWriter;
// try {
// logWriter = new BufferedWriter( new OutputStreamWriter( new FileOutputStream(
// new File( ( Constants.PREPENDDATE ? sdf.format( Calendar.getInstance().getTime() ) + "_" : "" ) + Constants.LOG_FILE_NAME + Constants.SAVEEXTENTION ) ), Constants.ENCODING));
// logWriter.write(message);
// } catch (IOException e) {
// e.printStackTrace();
// }
}
public static void consolePrint(String s) {
System.out.println(s);
for( IGuild guild : Variables.guildIndex.keySet() ) {
BotUtils.sendLog(guild, s);
}
}
}
|
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello world!!!!!");
System.out.println("Shweta");
System.out.println("yadav");
System.out.println("DONE!!!!! ");
}
}
|
package geekbrains.java_level_one.lesson_two;
import java.util.*;
public class HelloConstructs {
private static void change(int[] array){
for (int i = 0; i < array.length; i++)
array[i] = (array[i] == 1) ? 0 : 1;
}
private static void fillIn(int[] array){
for (int i = 0; i < array.length; i++)
array[i] = i * 3 + 1;
}
private static void doubling(int[] array){
for (int i = 0; i < array.length; i++)
if (array[i] < 6) array[i] *= 2;
}
private static int findMax(int[] array){
int max = array[0];
for (int i = 0; i < array.length; i++)
max = (array[i] > max) ? array[i] : max;
return max;
}
private static int findMin(int[] array){
int min = array[0];
for (int index : array) min = (index < min) ? index : min;
return min;
}
private static void crossFill(int[][] array){
int strght, bckwd;
for (strght = 0,
bckwd = array.length - 1;
strght < array.length;
strght++,
bckwd--) {
array[strght][bckwd] = 1;
array[strght][strght] = 1;
}
}
private static float power(float base, float significative){
float res = 1.0f;
for (int i = 0; i < significative; i++) {
res *= base;
}
return res;
}
private static void calculator() {
Scanner scanner = new Scanner(System.in);
boolean work = true;
float first = 0;
float second = 0;
int counter = 0;
String divZeroMessage;
String operator;
System.out.println("Here we put numbers, operator, and get the result");
do {
System.out.print("Enter the operator (ex. + / * - ^) or 'exit' without quotes to quit! >>> ");
operator = scanner.next();
if (!Objects.equals(operator, "exit")) {
System.out.print("Enter the first number, be sure not to input characters! >>> ");
first = scanner.nextFloat();
if (operator.equals("/")) {
do {
switch (counter) {
case 0:
divZeroMessage = "Enter the second number, should not be zero! >>> ";
break;
case 1:
divZeroMessage = "Come on, don't try zero here! >>> ";
break;
case 2:
divZeroMessage = "Seriously? O_o >>> ";
break;
case 3:
divZeroMessage = "I give up, do whatever you want... >>> ";
break;
default:
divZeroMessage = "No zeroes in divider allowed! >>> ";
break;
}
System.out.print(divZeroMessage);
second = scanner.nextFloat();
counter++;
} while (second == 0);
} else {
System.out.print("Enter the second number, rules are the same! >>> ");
second = scanner.nextFloat();
}
}
System.out.print("Your result is: ");
switch (operator) {
case "+":
System.out.println(first + second);
break;
case "-":
System.out.println(first - second);
break;
case "*":
System.out.println(first * second);
break;
case "/":
System.out.println(first / second);
break;
case "^":
System.out.println(power(first, second));
break;
case "exit":
System.out.println("getting outta here!");
work = false;
break;
}
} while (work);
}
private static boolean checkBalance(int[] array) {
int right = 0, left = 0;
for (int i = 0; i < array.length - 1; i++){
left += array[i];
for (int j = i + 1; j < array.length; j++)
right += array[j];
if (left == right) return true;
right = 0;
}
return false;
}
public static void main(String[] args) {
/**
* 1. Создать массив, состоящий из элементов 0 и 1,
* например, int[] arr = { 1, 1, 0, 0, 1, 0, 1, 1, 0, 0 };
*/
int[] bin = {1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0};
System.out.println(Arrays.toString(bin));
/**
* 2. В массиве из предыдущего пункта с помощью цикла
* заменить 0 на 1, 1 на 0;
*/
change(bin);
System.out.println(Arrays.toString(bin));
/**
* 3. Создать массив из 8 целых чисел.
* С помощью цикла заполнить его значениями
* 1 4 7 10 13 16 19 22;
*/
int[] arrInt = new int[8];
fillIn(arrInt);
System.out.println(Arrays.toString(arrInt));
/**
* 4. Задать массив int[] mas = { 1, 5, 3, 2, 11, 4, 5, 2, 4, 8, 9, 1 };
* пройти по нему циклом, и числа, которые меньше 6, умножить на 2.
*/
int[] mas = { 1, 5, 3, 2, 11, 4, 5, 2, 4, 8, 9, 1 };
doubling(mas);
System.out.println(Arrays.toString(mas));
/**
* 5. * Задать одномерный массив и найти в нем
* минимальный и максимальный элементы;
*/
System.out.println(findMax(mas));
System.out.println(findMin(mas));
/**
* 5. Создать квадратный двумерный целочисленный
* массив (количество строк и столбцов одинаковое),
* и с помощью цикла(-ов) заполнить его диагональные элементы единицами;
*/
final int side = 10;
int[][] dArr = new int[side][side];
crossFill(dArr);
for (int i = 0; i < dArr.length; i++) {
for (int j = 0; j < dArr[i].length; j++) {
System.out.print(dArr[i][j] + " ");
}
System.out.println();
}
/**
* 6. ** Написать простой консольный калькулятор.
* Пользователь вводит два числа и операцию,
* которую хочет выполнить, программа вычисляет результат
* и выводит в консоль;
*/
System.out.println("The Calculator.");
calculator();
/**
* 7. ** Написать метод, в который передается не пустой
* одномерный целочисленный массив, метод должен вернуть
* true если в массиве есть место, в котором сумма
* левой и правой части массива равны.
* Примеры: checkBalance([1, 1, 1, || 2, 1]) → true,
* checkBalance ([2, 1, 1, 2, 1]) → false,
* checkBalance ([10, || 10]) → true,
* граница показана символами ||, эти символы в массив не входят.
*/
int[] balance = {0,31,7,2,3};
System.out.println(checkBalance(balance));
}
}
/*
public static short[] changeZeroOne (short[] in_mas){
for (int inc = 0; inc < in_mas.length; inc++) {
if (in_mas[inc] == 0) in_mas[inc] = 1;
else in_mas[inc] = 0;
}
return in_mas;
}
for (int inc = 0, plus3 = 1; inc < in_mas.length; inc++, plus3+=3){
in_mas[inc] = (short) plus3;
}
public static int[] zeroToOne(int[] inArr) {
int l=inArr.length;
for (int i=0;i<l;i++) {
inArr[i]=1-inArr[i];
}
return inArr;
}
public static int[] mulToSix(int[] inArr) {
int mul;
int lArr=inArr.length;
for (int i=0;i<lArr;i++){
mul=2-((inArr[i]-6)/abs(inArr[i]-6)+1)/2;
inArr[i]=inArr[i]*mul;
}
return inArr;
}
*/
|
package com.tridevmc.movingworld.common.network.message;
import com.tridevmc.compound.network.message.Message;
import com.tridevmc.compound.network.message.RegisteredMessage;
import com.tridevmc.movingworld.common.chunk.mobilechunk.MobileChunkClient;
import com.tridevmc.movingworld.common.entity.EntityMovingWorld;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.nbt.ListNBT;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.fml.LogicalSide;
/**
* Sends tile entity data in a MobileChunk to clients.
*/
@RegisteredMessage(channel = "movingworld", destination = LogicalSide.CLIENT)
public class MovingWorldTileChangeMessage extends Message {
public EntityMovingWorld movingWorld;
public CompoundNBT tileData;
public MovingWorldTileChangeMessage() {
super();
}
public MovingWorldTileChangeMessage(EntityMovingWorld movingWorld, CompoundNBT tileData) {
super();
this.movingWorld = movingWorld;
this.tileData = tileData;
}
@Override
public void handle(PlayerEntity sender) {
if (movingWorld == null || tileData == null
|| movingWorld.getMobileChunk() == null || !(movingWorld.getMobileChunk() instanceof MobileChunkClient))
return;
ListNBT list = tileData.getList("list", 10);
for (int i = 0; i < list.size(); i++) {
CompoundNBT nbt = list.getCompound(i);
if (nbt == null) continue;
int x = nbt.getInt("x");
int y = nbt.getInt("y");
int z = nbt.getInt("z");
BlockPos pos = new BlockPos(x, y, z);
try {
TileEntity te = movingWorld.getMobileChunk().getTileEntity(pos);
if (te != null)
te.read(nbt);
} catch (Exception e) {
e.printStackTrace();
}
}
((MobileChunkClient) movingWorld.getMobileChunk()).getRenderer().markDirty();
}
}
|
package uk.ac.nott.cs.g53dia.simulator;
import uk.ac.nott.cs.g53dia.agent.*;
import uk.ac.nott.cs.g53dia.library.*;
import java.util.Random;
/**
* An example of how to simulate execution of a tanker agent in the sample
* (task) environment.
* <p>
* Creates a default {@link Environment}, a {@link DemoTanker} and a GUI window
* (a {@link TankerViewer}) and executes the Tanker for DURATION days in the
* environment.
*
* @author Julian Zappala
*/
/*
* Copyright (c) 2005 Neil Madden. Copyright (c) 2011 Julian Zappala
* (jxz@cs.nott.ac.uk)
*
* See the file "license.terms" for information on usage and redistribution of
* this file, and for a DISCLAIMER OF ALL WARRANTIES.
*/
public class Simulator {
/**
* Time for which execution pauses so that GUI can update. Reducing this
* value causes the simulation to run faster.
*/
private static int DELAY = 50; //og 100
/**
* Number of timesteps to execute.
*/
private static int DURATION = 10000;
/**
* Whether the action attempted at the last timestep failed.
*/
private static boolean actionFailed = false;
public static void main(String[] args) {
// Note: to obtain reproducible behaviour, you can set the Random seed
//Random r = new Random();
for(int i=1; i<11;i++) {
Random r = new Random();
r.setSeed(3*i);
// Create an environment
Environment env = new Environment(Tanker.MAX_FUEL/2, r);
// Create a tanker
Tanker tank = new DemoTanker(r);
// Create a GUI window to show the tanker
TankerViewer tv = new TankerViewer(tank);
tv.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
// Start executing the Tanker
while (env.getTimestep() < DURATION) {
// Advance the environment timestep
env.tick();
// Update the GUI
tv.tick(env);
// Get the current view of the tanker
Cell[][] view = env.getView(tank.getPosition(), Tanker.VIEW_RANGE);
// Let the tanker choose an action
Action act = tank.senseAndAct(view, actionFailed, env.getTimestep());
// Try to execute the action
try {
actionFailed = act.execute(env, tank);
} catch (OutOfFuelException ofe) {
System.err.println(ofe.getMessage());
System.exit(-1);
} catch (IllegalActionException afe) {
System.err.println(afe.getMessage());
actionFailed = false;
}
try {
Thread.sleep(DELAY);
} catch (Exception e) {
}
}
System.out.println("Simulation completed at timestep " + env.getTimestep() + " , score: " + tank.getScore());
}
}
}
|
package com.mod.loan.risk.pb;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mod.loan.common.enums.OrderSourceEnum;
import com.mod.loan.common.enums.PbResultEnum;
import com.mod.loan.common.message.RiskAuditMessage;
import com.mod.loan.config.rabbitmq.RabbitConst;
import com.mod.loan.model.DecisionPbDetail;
import com.mod.loan.model.Order;
import com.mod.loan.service.CallBackBengBengService;
import com.mod.loan.service.CallBackRongZeService;
import com.mod.loan.service.DecisionPbDetailService;
import com.mod.loan.service.OrderService;
import com.mod.loan.util.ConstantUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Date;
/**
* loan-pay 2019/4/20 huijin.shuailijie Init
*/
@Slf4j
@Component
public class PbRiskManageQueryConsumer {
@Autowired
private OrderService orderService;
@Autowired
private DecisionPbDetailService decisionPbDetailService;
@Autowired
private RabbitTemplate rabbitTemplate;
@Resource
private CallBackRongZeService callBackRongZeService;
@Resource
private CallBackBengBengService callBackBengBengService;
@RabbitListener(queues = "pb_queue_risk_order_result", containerFactory = "pb_risk_order_result")
@RabbitHandler
public void risk_order_query(Message mess) throws Exception {
RiskAuditMessage riskAuditMessage = JSONObject.parseObject(mess.getBody(), RiskAuditMessage.class);
Order order = null;
try {
log.info("===============十露盘分控订单,[result]:" + JSON.toJSONString(riskAuditMessage));
if (riskAuditMessage.getOrderId() != null) {
order = orderService.selectByPrimaryKey(riskAuditMessage.getOrderId());
if (order == null || order.getUid() == null || order.getOrderNo() == null) {
log.error("十露盘风控查询订单,订单不存在 message={}", JSON.toJSONString(riskAuditMessage));
return;
}
if (order.getStatus() != ConstantUtils.newOrderStatus) { // 没有完成订单才能进入风控查询模块
log.error("十露盘风控查询订单,订单已完成风控查询,message={}", JSON.toJSONString(riskAuditMessage));
return;
}
} else {
log.error("十露盘风控查询消息错误,message={}", JSON.toJSONString(riskAuditMessage));
return;
}
//开始主动查询2.3接口
DecisionPbDetail decisionPbDetail = decisionPbDetailService.selectByOrderNo(order.getOrderNo());
if (decisionPbDetail == null) {
log.error("十露盘风控表数据不存在[decisionPbDetail],message={}", JSON.toJSONString(riskAuditMessage));
order.setStatus(ConstantUtils.rejectOrderStatus);
orderService.updateOrderByRisk(order);
return;
}
decisionPbDetail = decisionPbDetailService.queryCreditResult(decisionPbDetail);
//风控通过全部转为人工审核
if (PbResultEnum.APPROVE.getCode().equals(decisionPbDetail.getResult())) {
order.setStatus(ConstantUtils.unsettledOrderStatus);
orderService.updateOrderByRisk(order);
} else if (PbResultEnum.MANUAL.getCode().equals(decisionPbDetail.getResult())) {
order.setStatus(ConstantUtils.rejectOrderStatus);
orderService.updateOrderByRisk(order);
} else if (PbResultEnum.DENY.getCode().equals(decisionPbDetail.getResult())) {
order.setStatus(ConstantUtils.rejectOrderStatus);
orderService.updateOrderByRisk(order);
} else {
if (riskAuditMessage.getTimes() < 6) {
riskAuditMessage.setTimes(riskAuditMessage.getTimes() + 1);
rabbitTemplate.convertAndSend(RabbitConst.pb_queue_risk_order_result_wait, riskAuditMessage);
return;
} else {
//超过次数直接拒绝
order.setStatus(ConstantUtils.rejectOrderStatus);
orderService.updateOrderByRisk(order);
}
}
if (riskAuditMessage.getSource() == ConstantUtils.ONE) {
if(OrderSourceEnum.isRongZe(order.getSource())) {
callBackRongZeService.pushOrderStatus(order);
}else if(OrderSourceEnum.isBengBeng(order.getSource())) {
callBackBengBengService.pushOrderStatus(order);
}
}
log.info("==============十露盘分控订单,[result]:结束==============");
} catch (Exception e) {
//风控异常重新提交订单或者进入人工审核
log.error("十露盘风控订单查询异常,相关信息{}", JSON.toJSONString(riskAuditMessage));
log.error("十露盘风控订单查询异常信息", e);
if (riskAuditMessage.getTimes() < 6) {
riskAuditMessage.setTimes(riskAuditMessage.getTimes() + 1);
rabbitTemplate.convertAndSend(RabbitConst.pb_queue_risk_order_result_wait, riskAuditMessage);
return;
}
try {
//风控查询异常直接返回失败 更新风控表
DecisionPbDetail query = decisionPbDetailService.selectByOrderNo(riskAuditMessage.getOrderNo());
order.setStatus(ConstantUtils.rejectOrderStatus);
orderService.updateOrderByRisk(order);
if (riskAuditMessage.getSource() == ConstantUtils.ONE) {
if(OrderSourceEnum.isRongZe(order.getSource())) {
callBackRongZeService.pushOrderStatus(order);
}else if(OrderSourceEnum.isBengBeng(order.getSource())) {
callBackBengBengService.pushOrderStatus(order);
}
}
if (query == null) {
log.error("十露盘风控表数据不存在[query],message={}", JSON.toJSONString(riskAuditMessage));
return;
}
DecisionPbDetail decisionPbDetail = new DecisionPbDetail();
decisionPbDetail.setId(query.getId());
decisionPbDetail.setResult(PbResultEnum.DENY.getCode());
decisionPbDetail.setDesc("拒绝");
decisionPbDetail.setOrderId(order.getId());
decisionPbDetail.setOrderNo(riskAuditMessage.getOrderNo());
decisionPbDetail.setUpdatetime(new Date());
decisionPbDetailService.updateByPrimaryKeySelective(decisionPbDetail);
} catch (Exception e1) {
log.error("十露盘风控订单查询异常信息[2]", e1);
}
}
}
@Bean("pb_risk_order_result")
public SimpleRabbitListenerContainerFactory pointTaskContainerFactoryLoan(ConnectionFactory connectionFactory) {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
factory.setConnectionFactory(connectionFactory);
factory.setPrefetchCount(1);
factory.setConcurrentConsumers(5);
return factory;
}
}
|
package com.sinodynamic.hkgta.dao.crm;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;
import com.sinodynamic.hkgta.dao.GenericDao;
import com.sinodynamic.hkgta.entity.crm.ServicePlanFacility;
@Repository
public class ServicePlanFacilityDaoImpl extends GenericDao<ServicePlanFacility>
implements ServicePlanFacilityDao {
@Override
public ServicePlanFacility getServicePlanFacilityByCompositeKey(int planNo,
String typeCode) {
Query query = getCurrentSession().createQuery("from ServicePlanFacility s where s.id.servicePlanId=? and s.id.facilityTypeCode=? ");
query.setInteger(0, planNo);
query.setString(1, typeCode);
return (ServicePlanFacility) query.list().get(0);
}
public List<ServicePlanFacility> getListByServicePlanNo(Long planNo){
List<Serializable> param = new ArrayList<Serializable>();
param.add(planNo);
return getByHql(" from ServicePlanFacility m where m.id.servicePlanId = ? ",param);
}
}
|
package com.itheima.day_10.demo_10;
import java.util.Random;
import java.util.Scanner;
class GuessNumber {
private static Random rd = new Random();
private static Scanner sc = new Scanner(System.in);
public void start() {
int num = rd.nextInt(10) + 1;
while (true) {
System.out.println("请输入你要猜的数字(1~10):");
int guess = sc.nextInt();
if (guess >= 1 && guess <= 10) {
if (guess > num) {
System.out.printf("您猜的数字%d大了,再猜一次吧。\n", guess);
} else if (guess < num) {
System.out.printf("您猜的数字%d小了,再猜一次吧。\n", guess);
} else {
System.out.println("恭喜你猜对了!");
break;
}
} else {
System.out.println("输入有误,请输入1~10之间的数字");
}
}
}
}
|
package com.xyz.dcl.bangladesh.earn;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;
import android.view.MenuItem;
import android.view.View;
import com.xyz.dcl.bangladesh.R;
import com.xyz.dcl.bangladesh.extras.BaseActivity;
public class IncomeFactory extends BaseActivity {
private static final String TAG = IncomeFactory.class.getSimpleName();
private Toolbar toolbar_income_factory;
private CardView ivVideoWall,ivLookEarn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_income_factory);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
initializeView();
ivVideoWall.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent in =new Intent(IncomeFactory.this, VideoWallActivity.class);
startActivity(in);
}
});
ivLookEarn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent in =new Intent(IncomeFactory.this, LookEarnActivity.class);
startActivity(in);
}
});
}
private void initializeView(){
toolbar_income_factory = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar_income_factory);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ivVideoWall = findViewById(R.id.ivVideoWall);
ivLookEarn = findViewById(R.id.ivLookandEarn);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
default:
break;
}
return true;
}
@Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
}
|
package com.rndapp.t.requests;
/**
* Created by ell on 4/13/15.
*/
public class ScheduleByStopRequest extends StopRequest{
private static final String ENDPOINT = "schedulebystop";
public void get(String station){
super.get(String.format(URL, ENDPOINT, station), false);
}
}
|
package com.example.prova;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class Tela2 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tela2);
TextView tvlpa = findViewById(R.id.tvlpa);
TextView tvpl =findViewById(R.id.tvpl);
TextView tvroe =findViewById(R.id.tvroe);
TextView tvvpa =findViewById(R.id.tvvpa);
TextView tvpvp =findViewById(R.id.tvpvp);
Bundle b = getIntent().getExtras();
if (b != null){
double lpa = b.getDouble("LPA");
double pl = b.getDouble("PL");
double roe = b.getDouble("ROE");
double vpa = b.getDouble("VPA");
double pvp = b.getDouble("PVP");
tvlpa.setText("R$"+ String.valueOf(lpa));
tvpl.setText("R$" + String.valueOf(pl));
tvroe.setText("R$"+ String.valueOf(roe));
tvvpa.setText("R$"+ String.valueOf(vpa));
tvpvp.setText("R$"+ String.valueOf(pvp));
}
}
}
|
/*
* Copyright 2016 Palantir Technologies, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.palantir.weblogger;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.util.Set;
import org.immutables.value.Value;
/**
* Configuration for {@link WebLoggerBundle}.
*/
@Value.Immutable
@JsonSerialize(as = ImmutableWebLoggerConfiguration.class)
@JsonDeserialize(as = ImmutableWebLoggerConfiguration.class)
@SuppressWarnings("checkstyle:designforextension")
public abstract class WebLoggerConfiguration {
@Value.Default
public boolean getEnabled() {
return true;
}
public abstract Set<String> getEventNames();
}
|
package com.lsjr.zizi.mvp.upload;
/**
* Created by admin on 2017/5/6.
*/
public interface IUploadView {
void onUploadSucceed(boolean isSucceeds);
}
|
package com.noethlich.tobias.mcrobektrainingsplaner;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class CodeFragment extends Fragment implements View.OnClickListener {
public CodeFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_code, container, false);
Button sc = (Button) v.findViewById(R.id.button_save_code);
sc.setOnClickListener(this);
return v;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_save_code:
EditText feld = (EditText) v.findViewById(R.id.codeField);
String code = feld.getText().toString();
SharedPreferences settings;
SharedPreferences.Editor editor;
settings = getContext().getSharedPreferences("MR_CODE", Context.MODE_PRIVATE);
editor = settings.edit();
editor.putString("code", code);
editor.commit();
break;
}
}
}
|
package org.firstinspires.ftc.teamcode.opmodes;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.util.ElapsedTime;
import org.firstinspires.ftc.teamcode.base_classes.CoordinateTestTeleBot;
import org.firstinspires.ftc.teamcode.base_classes.TeleBot;
/**
* This is a test opmode used for getting data from the webcam.
*/
@TeleOp(name = "TestTeleOp", group = "TeleOp")
@Disabled
public class TestTeleOp extends LinearOpMode {
public CoordinateTestTeleBot robot = new CoordinateTestTeleBot(this);
public ElapsedTime runtime = new ElapsedTime();
@Override
public void runOpMode() {
telemetry.addData("Status", "Initialized");
telemetry.update();
robot.init();
// Wait for the game to start (driver presses PLAY)
waitForStart();
runtime.reset();
// run until the end of the match (driver presses STOP)
while (opModeIsActive()) {
robot.getNav().updateView();
robot.controlledDrive();
}
}
}
|
package com.git.cloud.resmgt.common.model.po;
import java.util.List;
import com.git.cloud.common.model.base.BaseBO;
import com.git.cloud.resmgt.common.model.vo.RmResPoolVo;
public class RmDatacenterPo extends BaseBO implements java.io.Serializable{
// Fields
/**
*
*/
private static final long serialVersionUID = 4525905759544097323L;
private String id;
private String datacenterCode;
private String datacenterCname;
private String ename;
private String address;
private String status;
private String isActive;
private String remark;
private String queueIden;
//private String datacenterCName;
private String eName;
private String createUser;
private String updateUser;
private String sort;
private String url;
private String username;
private String password;
// Constructors
/** default constructor */
public RmDatacenterPo() {
}
/** minimal constructor */
public RmDatacenterPo(String id) {
this.id = id;
}
/** full constructor */
public RmDatacenterPo(String id, String datacenterCode,
String datacenterCname, String ename, String address,
String status, String isActive, String remark) {
this.id = id;
this.datacenterCode = datacenterCode;
this.datacenterCname = datacenterCname;
this.ename = ename;
this.address = address;
this.status = status;
this.isActive = isActive;
this.remark = remark;
}
// Property accessors
public String getId() {
return this.id;
}
/*public String getDatacenterCName() {
return ;
}
public void setDatacedatacenterCNamenterCName(String datacenterCName) {
this.datacenterCName = datacenterCName;
}*/
public String geteName() {
return eName;
}
public void seteName(String eName) {
this.eName = eName;
}
public String getCreateUser() {
return createUser;
}
public void setCreateUser(String createUser) {
this.createUser = createUser;
}
public String getUpdateUser() {
return updateUser;
}
public void setUpdateUser(String updateUser) {
this.updateUser = updateUser;
}
public String getSort() {
return sort;
}
public void setSort(String sort) {
this.sort = sort;
}
public void setId(String id) {
this.id = id;
}
public String getDatacenterCode() {
return this.datacenterCode;
}
public void setDatacenterCode(String datacenterCode) {
this.datacenterCode = datacenterCode;
}
public String getDatacenterCname() {
return this.datacenterCname;
}
public void setDatacenterCname(String datacenterCname) {
this.datacenterCname = datacenterCname;
}
public String getEname() {
return this.ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public String getStatus() {
return this.status;
}
public void setStatus(String status) {
this.status = status;
}
public String getIsActive() {
return this.isActive;
}
public void setIsActive(String isActive) {
this.isActive = isActive;
}
public String getRemark() {
return this.remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getQueueIden() {
return queueIden;
}
public void setQueueIden(String queueIden) {
this.queueIden = queueIden;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String getBizId() {
// TODO Auto-generated method stub
return null;
}
public List<RmResPoolVo> getPoolList() {
return poolList;
}
public void setPoolList(List<RmResPoolVo> poolList) {
this.poolList = poolList;
}
private List<RmResPoolVo> poolList;
}
|
package com.grocery.codenicely.vegworld_new.welcomeScreen.presenter;
import com.grocery.codenicely.vegworld_new.R;
import com.grocery.codenicely.vegworld_new.helper.MyApplication;
import com.grocery.codenicely.vegworld_new.welcomeScreen.Data.WelcomeData;
import com.grocery.codenicely.vegworld_new.welcomeScreen.SlidesRequestCallback;
import com.grocery.codenicely.vegworld_new.welcomeScreen.model.ScreenSliderHelper;
import com.grocery.codenicely.vegworld_new.welcomeScreen.view.WelcomeView;
/**
* Created by ramya on 12/10/16.
*/
public class SliderImp implements Slider {
private WelcomeView welcomeView;
private ScreenSliderHelper screenSliderHelper;
public SliderImp(WelcomeView welcomeView, ScreenSliderHelper screenSliderHelper) {
this.screenSliderHelper = screenSliderHelper;
this.welcomeView = welcomeView;
}
@Override
public void getSlides() {
welcomeView.showProgressBar(true);
screenSliderHelper.getSlides(new SlidesRequestCallback() {
@Override
public void onSuccess(WelcomeData welcomeData) {
if (welcomeData.isSuccess()) {
welcomeView.showProgressBar(false);
welcomeView.setSlides(welcomeData.getSlider_list());
} else {
welcomeView.showProgressBar(true);
welcomeView.showError("error loading pages");
}
}
@Override
public void onFailure() {
welcomeView.showProgressBar(false);
welcomeView.showError(MyApplication.getContext().getResources().getString(R.string.failure_message));
}
});
}
}
|
package com.galid.commerce.domains.catalog.service;
import lombok.*;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.Min;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@ToString
public class AddItemRequest {
@Length(min = 3)
private String name;
@Length(min = 3)
private String imagePath;
@Min(0)
private int price;
@Min(1)
private int stockQuantity;
private Long categoryId;
}
|
package proxypattern;
import java.util.ArrayList;
import java.util.Scanner;
/**
*
* @author LUT, OOPT
* Jere Kaplas, 0403105
* Oskari Jahkola, 0403082
* Eetu Heimala, 0388819
* Sakari Laine, 0418598
*/
public class ProxyPattern {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
ArrayList<String> studentList = new ArrayList<>();
studentList.add("John");
studentList.add("Jane");
ProxyIntranetAccess testProxy = new ProxyIntranetAccess("John", studentList);
testProxy.grantIntranetAccess();
testProxy = new ProxyIntranetAccess("Mary", studentList);
testProxy.grantIntranetAccess();
ProxyIntranetAccess tempProxy = null;
Scanner reader = new Scanner(System.in);
String input;
do {
System.out.println("===== Access Intranet =====");
System.out.println("1. Add student");
System.out.println("2. Login");
System.out.println("3. Get Student ID");
System.out.println("0. Exit");
System.out.print("Select an option: ");
input = reader.nextLine();
switch (Integer.parseInt(input)) {
case 1:
System.out.print("Student's name: ");
studentList.add(reader.nextLine());
break;
case 2:
System.out.print("Login name: ");
tempProxy = new ProxyIntranetAccess(reader.nextLine(), studentList);
tempProxy.grantIntranetAccess();
break;
case 3:
if (tempProxy != null) {
tempProxy.printStudentID();
} else {
System.out.println("You must login first.");
}
break;
case 0:
System.out.println("Exiting...");
System.exit(0);
break;
default:
System.out.println("Choose something from the menu.");
break;
}
} while (true);
}
}
|
package kz.greetgo.file_storage.errors;
public class FileStorageError extends RuntimeException {
public FileStorageError(String message) {
super(message);
}
public FileStorageError(Exception e) {
super(e);
}
}
|
package me.gleep.oreganized.items;
import me.gleep.oreganized.blocks.SilverBlock;
import net.minecraft.client.entity.player.ClientPlayerEntity;
import net.minecraft.command.arguments.NBTPathArgument;
import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemGroup;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.nbt.INBT;
import net.minecraft.nbt.IntNBT;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import org.jetbrains.annotations.Nullable;
import java.util.List;
public class SilverMirror extends Item {
boolean isUndeadNearby = false;
public SilverMirror() {
super(new Properties().group(ItemGroup.TOOLS)
.maxStackSize(1));
}
@Override
public void inventoryTick(ItemStack stack, World worldIn, Entity entityIn, int itemSlot, boolean isSelected) {
int dist = 4;
if (!(entityIn instanceof PlayerEntity)) return;
CompoundNBT nbt = new CompoundNBT();
PlayerEntity player = (PlayerEntity) entityIn;
BlockPos pos = player.getPosition();
List<Entity> list = player.getEntityWorld().getEntitiesInAABBexcluding(player,
new AxisAlignedBB(pos.getX() + SilverBlock.RANGE, pos.getY() + SilverBlock.RANGE, pos.getZ() + SilverBlock.RANGE,
pos.getX() - SilverBlock.RANGE, pos.getY() - SilverBlock.RANGE, pos.getZ() - SilverBlock.RANGE), (Entity entity) -> entity instanceof LivingEntity
);
isUndeadNearby = false;
for (Entity e : list) {
LivingEntity living = (LivingEntity) e;
if (living.isEntityUndead()) {
isUndeadNearby = true;
double distance = living.getDistance(player);
if (distance < SilverBlock.RANGE && ((int) Math.ceil(distance / (SilverBlock.RANGE / 4))) < dist) {
if (distance <= 6) {
dist = 1;
} else dist = Math.max((int) Math.ceil(distance / (SilverBlock.RANGE / 4)), 2);
if (dist > 3) {
dist = 3;
}
}
}
}
if (!isUndeadNearby) {
dist = 4;
}
nbt.putInt("Dist", dist);
stack.setTag(nbt);
}
}
|
package com.toda.consultant;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;
import com.toda.consultant.model.RequestParams;
import com.toda.consultant.model.ResultData;
import com.toda.consultant.statics.Task;
import com.toda.consultant.util.IConfig;
import com.toda.consultant.util.StringUtils;
import com.toda.consultant.view.UnitDescriptionLayout;
import com.toda.consultant.view.dialog.CommonInputDialog;
import com.toda.consultant.view.dialog.CommonInputNumDialog;
import com.toda.consultant.view.dialog.CommonInputRateDialog;
import com.toda.consultant.view.dialog.CommonSelectDialog;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
/**
* 小区户型资料
* Created by guugangzhu on 2016/12/29.
*/
public class CheckEstateInfoActivity extends BaseActivity {
@BindView(R.id.tv_estate_info)
TextView tvEstateInfo;
@BindView(R.id.ll_estate_info)
UnitDescriptionLayout llEstateInfo;
@BindView(R.id.tv_developer)
TextView tvDeveloper;
@BindView(R.id.ll_developer)
UnitDescriptionLayout llDeveloper;
@BindView(R.id.tv_manager)
TextView tvManager;
@BindView(R.id.ll_manager)
UnitDescriptionLayout llManager;
@BindView(R.id.tv_estate_name)
TextView tvEstateName;
@BindView(R.id.ll_estate_name)
UnitDescriptionLayout llEstateName;
@BindView(R.id.tv_average_price)
TextView tvAveragePrice;
@BindView(R.id.ll_average_price)
UnitDescriptionLayout llAveragePrice;
@BindView(R.id.tv_open_date)
TextView tvOpenDate;
@BindView(R.id.ll_open_date)
UnitDescriptionLayout llOpenDate;
@BindView(R.id.tv_give_date)
TextView tvGiveDate;
@BindView(R.id.ll_give_date)
UnitDescriptionLayout llGiveDate;
@BindView(R.id.tv_decorate_standard)
TextView tvDecorateStandard;
@BindView(R.id.ll_standard)
UnitDescriptionLayout llStandard;
@BindView(R.id.tv_construct_type)
TextView tvConstructType;
@BindView(R.id.ll_build_type)
UnitDescriptionLayout llBuildType;
@BindView(R.id.tv_manager_type)
TextView tvManagerType;
@BindView(R.id.ll_manager_type)
UnitDescriptionLayout llManagerType;
@BindView(R.id.tv_estate_period)
TextView tvEstatePeriod;
@BindView(R.id.ll_period)
UnitDescriptionLayout llPeriod;
@BindView(R.id.tv_estate_area)
TextView tvEstateArea;
@BindView(R.id.ll_area)
UnitDescriptionLayout llArea;
@BindView(R.id.tv_land_area)
TextView tvLandArea;
@BindView(R.id.ll_floor_area)
UnitDescriptionLayout llFloorArea;
@BindView(R.id.tv_green_ratio)
TextView tvGreenRatio;
@BindView(R.id.ll_greening_rate)
UnitDescriptionLayout llGreeningRate;
@BindView(R.id.tv_plot_ratio)
TextView tvPlotRatio;
@BindView(R.id.ll_inner_rate)
UnitDescriptionLayout llInnerRate;
@BindView(R.id.tv_manage_fee)
TextView tvManageFee;
@BindView(R.id.ll_management_price)
UnitDescriptionLayout llManagementPrice;
@BindView(R.id.tv_park_amount)
TextView tvParkAmount;
@BindView(R.id.ll_park_amount)
UnitDescriptionLayout llParkAmount;
@BindView(R.id.tv_house_amount)
TextView tvHouseAmount;
@BindView(R.id.ll_house_amount)
UnitDescriptionLayout llHouseAmount;
private String averagePrice; //均价
private String floorArea; //占地面积
private String constructArea;//建筑面积
private String greenRate; //绿化率
private String innerRate; //容积率
private String managePrice; //物业费
private String houseId;
private Calendar calendar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_estate_info);
ButterKnife.bind(this);
houseId = getBundleStr(KEY_HOUSE_ID);
initView();
}
@Override
public void initView() {
setTitle("小区资料");
calendar = Calendar.getInstance();
setTopBarRightText("提交");
}
@Override
public void onTopRightClick() {
super.onTopRightClick();
if(checkData()){
commitEstateInfo();
}
}
/***
* 完善小区资料
*/
private void commitEstateInfo() {
RequestParams params = new RequestParams(IConfig.URL_COMMIT_ESTATE_INFO);
params.add("developer", tvDeveloper.getText().toString());
params.add("houseCorp", tvManager.getText().toString());
params.add("buildingName", tvEstateName.getText().toString());
params.add("openTime", tvOpenDate.getText().toString());
params.add("inTime", tvGiveDate.getText().toString());
params.add("designStandard", tvDecorateStandard.getText().toString());
params.add("buidlingType", tvConstructType.getText().toString());
params.add("houseType", tvManagerType.getText().toString());
params.add("ownYear", tvEstatePeriod.getText().toString());
params.add("averagePrice", averagePrice);
params.add("buildingArea", constructArea);
params.add("landArea", floorArea);
params.add("greenPercent", greenRate);
params.add("volumeRatio", innerRate);
params.add("propertyFee ", managePrice);
params.add("carNum ", tvParkAmount.getText().toString());
params.add("peopleNum ", tvHouseAmount.getText().toString());
params.add("buildingDescription ", tvEstateInfo.getText().toString());
params.add("secondHousePersonalId ", houseId);
startRequest(Task.COMMIT_ESTATE_INFO, params, null, false);
}
@Override
public void onRefresh(Call call, int tag, ResultData data) {
super.onRefresh(call, tag, data);
switch (tag) {
case Task.GET_AGENT_HOUSE_LIST:
if (handlerRequestErr(data)) {
}
}
}
private boolean checkData(){
if(StringUtils.isEmpty(tvEstateInfo.getText().toString())){
toast("小区简介不能为空");
return false;
}
if(StringUtils.isEmpty(tvDeveloper.getText().toString())){
toast("开发商不能为空");
return false;
}
if(StringUtils.isEmpty(tvManager.getText().toString())){
toast("物业公司不能为空");
return false;
}
if(StringUtils.isEmpty(tvEstateName.getText().toString())){
toast("楼盘名称不能为空");
return false;
}
if(StringUtils.isEmpty(tvEstateName.getText().toString())){
toast("楼盘名称不能为空");
return false;
}
if(StringUtils.isEmpty(averagePrice)){
toast("均价不能为空");
return false;
}
if(StringUtils.isEmpty(tvOpenDate.getText().toString())){
toast("开盘日期不能为空");
return false;
}
if(StringUtils.isEmpty(tvGiveDate.getText().toString())){
toast("交房日期不能为空");
return false;
}
if(StringUtils.isEmpty(tvDecorateStandard.getText().toString())){
toast("装修标准不能为空");
return false;
}
if(StringUtils.isEmpty(tvConstructType.getText().toString())){
toast("建筑类型不能为空");
return false;
}
if(StringUtils.isEmpty(tvManagerType.getText().toString())){
toast("物业类型不能为空");
return false;
}
if(StringUtils.isEmpty(tvEstatePeriod.getText().toString())){
toast("产权年限不能为空");
return false;
}
if(StringUtils.isEmpty(floorArea)){
toast("占地面积不能为空");
return false;
}
if(StringUtils.isEmpty(constructArea)){
toast("建筑面积不能为空");
return false;
}
if(StringUtils.isEmpty(greenRate)){
toast("绿化率不能为空");
return false;
}
if(StringUtils.isEmpty(innerRate)){
toast("容积率不能为空");
return false;
}
if(StringUtils.isEmpty(managePrice)){
toast("物业费不能为空");
return false;
}
if(StringUtils.isEmpty(tvParkAmount.getText().toString())){
toast("车位不能为空");
return false;
}
if(StringUtils.isEmpty(tvHouseAmount.getText().toString())){
toast("户数不能为空");
return false;
}
return true;
}
@OnClick({R.id.ll_estate_info, R.id.ll_developer, R.id.ll_manager, R.id.ll_estate_name, R.id.ll_average_price, R.id.ll_open_date, R.id.ll_give_date, R.id.ll_standard, R.id.ll_build_type,
R.id.ll_manager_type, R.id.ll_period, R.id.ll_area, R.id.ll_floor_area, R.id.ll_greening_rate, R.id.ll_inner_rate, R.id.ll_management_price, R.id.ll_park_amount, R.id.ll_house_amount})
public void onClick(View view) {
switch (view.getId()) {
case R.id.ll_estate_info:
showEstateInfo();
break;
case R.id.ll_developer:
showDeveloper();
break;
case R.id.ll_manager:
showManager();
break;
case R.id.ll_estate_name:
showEstateName();
break;
case R.id.ll_average_price:
showAveragePriceDialog();
break;
case R.id.ll_open_date:
showOpenDate();
break;
case R.id.ll_give_date:
showGiveDate();
break;
case R.id.ll_standard:
showStandard();
break;
case R.id.ll_build_type:
showBuildType();
break;
case R.id.ll_manager_type:
showManagementType();
break;
case R.id.ll_period:
showYears();
break;
case R.id.ll_area:
showAreaDialog();
break;
case R.id.ll_floor_area:
showFloorAreaDialog();
break;
case R.id.ll_greening_rate:
showGreeningRateDialog();
break;
case R.id.ll_inner_rate:
showInnerRateDialog();
break;
case R.id.ll_management_price:
showManagementPriceDialog();
break;
case R.id.ll_park_amount:
showParkAmountDialog();
break;
case R.id.ll_house_amount:
showHouseDialog();
break;
}
}
/**
* 小区介绍
*/
private void showEstateInfo() {
CommonInputDialog dialog = new CommonInputDialog(this, "请输入小区简介", new CommonInputDialog.OnConfirmListener() {
@Override
public void onConfirm(String selectedString) {
tvEstateInfo.setText(selectedString);
}
});
dialog.show();
}
/**
* 开发商
*/
private void showDeveloper() {
CommonInputDialog dialog = new CommonInputDialog(this, "请输入开发商", new CommonInputDialog.OnConfirmListener() {
@Override
public void onConfirm(String selectedString) {
tvDeveloper.setText(selectedString);
}
});
dialog.show();
}
/**
* 物业公司
*/
private void showManager() {
CommonInputDialog dialog = new CommonInputDialog(this, "请输入物业公司", new CommonInputDialog.OnConfirmListener() {
@Override
public void onConfirm(String selectedString) {
tvManager.setText(selectedString);
}
});
dialog.show();
}
/**
* 楼盘名称
*/
private void showEstateName() {
CommonInputDialog dialog = new CommonInputDialog(this, "请输入楼盘名称", new CommonInputDialog.OnConfirmListener() {
@Override
public void onConfirm(String selectedString) {
tvEstateName.setText(selectedString);
}
});
dialog.show();
}
/**
* 均价
*/
private void showAveragePriceDialog() {
CommonInputNumDialog dialog = new CommonInputNumDialog(this, "元/㎡", new CommonInputNumDialog.OnConfirmListener() {
@Override
public void onConfirm(String selectedString) {
averagePrice=selectedString;
tvAveragePrice.setText(selectedString+" 元/㎡");
}
});
dialog.show();
}
/**
* 开盘日期
*/
private void showOpenDate(){
DatePickerDialog datePickerDialog= new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
tvOpenDate.setText(year+"-"+month+"-"+dayOfMonth);
}
}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
datePickerDialog.show();
}
/**
* 交房日期
*/
private void showGiveDate(){
DatePickerDialog datePickerDialog= new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
tvGiveDate.setText(year+"-"+month+"-"+dayOfMonth);
}
}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
datePickerDialog.show();
}
/**
* 装修标准
*/
private void showStandard() {
final List<String> list = new ArrayList<>();
list.add("毛坯");
list.add("简装");
list.add("精装");
CommonSelectDialog standardDialog = new CommonSelectDialog(this, list, new CommonSelectDialog.OnStringSelectListener() {
@Override
public void onStringSelect(String selectedString) {
tvDecorateStandard.setText(selectedString);
}
});
standardDialog.show();
}
/**
* 建筑类型
*/
private void showBuildType() {
final List<String> list = new ArrayList<>();
/**
* 多层,小高层,高层,超高层,花园洋房,独栋别墅,双拼别墅,四合院,板楼,塔楼,楼塔组合
*/
list.add("多层");
list.add("小高层");
list.add("高层");
list.add("超高层");
list.add("花园洋房");
list.add("独栋别墅");
list.add("双拼别墅");
list.add("四合院");
list.add("板楼");
list.add("楼塔组合");
CommonSelectDialog dialog = new CommonSelectDialog(this, list, new CommonSelectDialog.OnStringSelectListener() {
@Override
public void onStringSelect(String selectedString) {
tvConstructType.setText(selectedString);
}
});
dialog.show();
}
/**
* 物业类型
*/
private void showManagementType() {
final List<String> list = new ArrayList<>();
list.add("住宅用地");
list.add("商用地");
list.add("商住两用");
CommonSelectDialog dialog = new CommonSelectDialog(this, list, new CommonSelectDialog.OnStringSelectListener() {
@Override
public void onStringSelect(String selectedString) {
tvManagerType.setText(selectedString);
}
});
dialog.show();
}
/**
* 年限
*/
private void showYears() {
final List<String> list = new ArrayList<>();
list.add("住宅用地70年");
list.add("商用地40年");
list.add("商住两用40年");
CommonSelectDialog elevatorDialog = new CommonSelectDialog(this, list, new CommonSelectDialog.OnStringSelectListener() {
@Override
public void onStringSelect(String selectedString) {
tvEstatePeriod.setText(selectedString);
}
});
elevatorDialog.show();
}
/**
* 建筑面积
*/
private void showAreaDialog() {
CommonInputNumDialog dialog = new CommonInputNumDialog(this, "㎡", new CommonInputNumDialog.OnConfirmListener() {
@Override
public void onConfirm(String selectedString) {
constructArea=selectedString;
tvEstateArea.setText(selectedString+" ㎡");
}
});
dialog.show();
}
/**
* 占地面积
*/
private void showFloorAreaDialog() {
CommonInputNumDialog dialog = new CommonInputNumDialog(this, "㎡", new CommonInputNumDialog.OnConfirmListener() {
@Override
public void onConfirm(String selectedString) {
floorArea=selectedString;
tvLandArea.setText(selectedString+" ㎡");
}
});
dialog.show();
}
/**
* 绿化率
*/
private void showGreeningRateDialog() {
CommonInputRateDialog dialog = new CommonInputRateDialog(this, "%", new CommonInputRateDialog.OnConfirmListener() {
@Override
public void onConfirm(String selectedString) {
greenRate=selectedString;
tvGreenRatio.setText(selectedString+" %");
}
});
dialog.show();
}
/**
* 容积率
*/
private void showInnerRateDialog() {
CommonInputRateDialog dialog = new CommonInputRateDialog(this, "%", new CommonInputRateDialog.OnConfirmListener() {
@Override
public void onConfirm(String selectedString) {
innerRate=selectedString;
tvPlotRatio.setText(selectedString+" %");
}
});
dialog.show();
}
/**
* 物业费
*/
private void showManagementPriceDialog() {
CommonInputNumDialog dialog = new CommonInputNumDialog(this, "元", new CommonInputNumDialog.OnConfirmListener() {
@Override
public void onConfirm(String selectedString) {
managePrice=selectedString;
tvManageFee.setText(selectedString+" 元");
}
});
dialog.show();
}
/**
* 停车位
*/
private void showParkAmountDialog() {
CommonInputNumDialog dialog = new CommonInputNumDialog(this, "个", new CommonInputNumDialog.OnConfirmListener() {
@Override
public void onConfirm(String selectedString) {
tvParkAmount.setText(selectedString);
}
});
dialog.show();
}
/**
* 户数
*/
private void showHouseDialog() {
CommonInputNumDialog dialog = new CommonInputNumDialog(this, "户", new CommonInputNumDialog.OnConfirmListener() {
@Override
public void onConfirm(String selectedString) {
tvHouseAmount.setText(selectedString);
}
});
dialog.show();
}
}
|
package gov.nih.mipav.model;
public class GaussianKernel implements Kernel {
private float[][] data;
public GaussianKernel() {
}
public float[][] getData() {
return data;
}
public void setData(float[][] data){
this.data = data;
}
public int[] getExtents(){
if(data == null){
return null;
}
int[] extents = new int[data.length];
for(int i = 0; i < data.length; i++){
extents[i] = data[i].length;
}
return extents;
}
}
|
package JavaCompleteReference;
public class box3 {
int width;
int heigth;
int depth;
double volume()
{
double volume=width*heigth*depth;
return volume;
//System.out.println("The Volume is " +volume);
}
}
|
package my.pkg.app;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import my.pkg.app.R;
public class Main extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
public void onClick(View button) {
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText("Good Bye World!");
}
});
}
}
|
package io.rong.app.map;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.view.View;
import io.rong.imkit.RLog;
import io.rong.imkit.RongContext;
import io.rong.imkit.RongIM;
import io.rong.imkit.widget.provider.InputProvider;
import io.rong.imlib.RongIMClient.ResultCallback;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.MessageContent;
import io.rong.message.LocationMessage;
import io.rong.message.TextMessage;
public class NewLocationProvider extends InputProvider.ExtendProvider {
public NewLocationProvider(RongContext arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
@Override
public Drawable obtainPluginDrawable(Context context) {
// TODO Auto-generated method stub
return context.getResources().getDrawable(
io.rong.imkit.R.drawable.rc_ic_location);
}
@Override
public CharSequence obtainPluginTitle(Context context) {
// TODO Auto-generated method stub
return context.getString(io.rong.imkit.R.string.rc_plugins_location);
}
@Override
public void onPluginClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(arg0.getContext(),
ChooseLocationActivity.class);
startActivityForResult(intent, 10);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK)
return;
switch (requestCode) {
case 10:// 选择地理位置.
{
TextMessage msgMessage = TextMessage.obtain("这是一个定位消息.");
sendMessage(msgMessage);
}
break;
default:
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
private void sendMessage(MessageContent msg) {
if (RongIM.getInstance() == null
|| RongIM.getInstance().getRongIMClient() == null)
return;
Conversation conversation = getCurrentConversation();
RongIM.getInstance()
.getRongIMClient()
.insertMessage(conversation.getConversationType(),
conversation.getTargetId(), null, msg,
new ResultCallback<Message>() {
public void onSuccess(Message message) {
message.setSentStatus(io.rong.imlib.model.Message.SentStatus.SENT);
RongIM.getInstance()
.getRongIMClient()
.setMessageSentStatus(
message.getMessageId(),
io.rong.imlib.model.Message.SentStatus.SENT,
null);
}
public void onError(
io.rong.imlib.RongIMClient.ErrorCode e) {
}
});
}
} |
package com.codigo.smartstore.sdk.core.struct.iterate.array;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.jupiter.api.DisplayName;
import com.codigo.smartstore.sdk.core.structs.iterate.array.ArrayIterable;
import com.codigo.smartstore.sdk.core.structs.iterate.array.ArrayIteratorFactory;
public class TestArrayIteratorReadCount {
private static Logger log = Logger.getLogger(TestArrayIteratorReadCount.class);
static final Double[] array = { 0.9, 99.2, 09.3, 232343.09, 2321.0, 1231.2, 12D, .09, 12D, .0923D, .3D, 4.5D };
@Test
@DisplayName("Test oczekuje liczby odczytanych rekordów równej ilość elementów kolekcji danych")
public void testShouldBe_CountRead12() {
// ...Arrange
int itemsReadCount = 0;
final ArrayIterable<Double> iterator = ArrayIteratorFactory.of(array);
log.info(iterator);
// ...Act
while (iterator.hasNext())
iterator.next();
itemsReadCount = iterator.getCountVisited();
// ...Assert
assertThat(iterator.getCount(), equalTo(itemsReadCount));
assertThat(array.length, equalTo(itemsReadCount));
}
@Test
@DisplayName("Test oczekuje liczby odczytanych rekordów równej jeden(1)")
public void testShouldBe_CountRead1() {
// ...Arrange
int itemsReadCount = 0;
final ArrayIterable<Double> iterator = ArrayIteratorFactory.ofRange(array, 1, 1);
log.info(iterator);
// ...Act
while (iterator.hasNext())
iterator.next();
itemsReadCount = iterator.getCountVisited();
// ...Assert
assertThat(1, equalTo(itemsReadCount));
}
@Test
@DisplayName("Test oczekuje liczby odczytanych rekordów równej jeden(5)")
public void testShouldBe_CountRead2() {
// ...Arrange
int itemsReadCount = 0;
final ArrayIterable<Double> iterator = ArrayIteratorFactory.ofRange(array, 11, 11);
log.info(iterator);
// ...Act
while (iterator.hasNext())
iterator.next();
itemsReadCount = iterator.getCountVisited();
// ...Assert
assertThat(iterator.getCountFromRange(), equalTo(itemsReadCount));
}
}
|
package de.scads.gradoop_service.server.helper.edge_fusion;
import java.util.ArrayList;
import org.gradoop.common.model.impl.pojo.Edge;
public interface EdgeFusionFunction<T> {
T apply(ArrayList<Edge> edges, String edgeAttribute);
} |
// File : AnimalTest.java
//PIC : Nur Latifah Ulfah - 13514015
import org.junit.*;
import static org.junit.Assert.*;
/**
*
* @author Nur Latifah Ulfah - 13514015
*/
public class AnimalTest {
@Test
public void test_getX() {
System.out.println("Test apakah getX menghasilkan nilai dengan benar");
Animal kodok = new Animal(2,3,"frog");
assertTrue(kodok.getX()==2);
}
@Test
public void test_getY() {
System.out.println("Test apakah getY menghasilkan nilai dengan benar");
Animal kodok = new Animal(2,3,"frog");
assertTrue(kodok.getY()==3);
}
@Test
public void test_setX() {
System.out.println("Test apakah setX menghasilkan nilai dengan benar");
Animal kodok = new Animal(2,3,"frog");
kodok.setX(0);
assertTrue(kodok.getX()==0);
}
@Test
public void test_setY() {
System.out.println("Test apakah setY menghasilkan nilai dengan benar");
Animal kodok = new Animal(2,3,"frog");
kodok.setY(0);
assertTrue(kodok.getY()==0);
}
@Test
public void test_getBobot() {
System.out.println("Test apakah getBobot menghasilkan nilai dengan benar");
Animal kodok = new Animal(2,3,"frog");
assertTrue(kodok.getBobot()==5);
}
@Test
public void test_addBobot() {
System.out.println("Test apakah addBobot menghasilkan nilai dengan benar");
Animal kodok = new Animal(2,3,"frog");
kodok.addBobot();
assertTrue(kodok.getBobot()==6);
}
@Test
public void test_getNHabitat() {
System.out.println("Test apakah getNHabitat menghasilkan nilai dengan benar");
Animal kodok = new Animal(2,3,"frog");
assertTrue(kodok.getNHabitat()==2);
}
@Test
public void test_getTipeHabitat() {
System.out.println("Test apakah getTipeHabitat menghasilkan nilai dengan benar");
Animal kodok = new Animal(2,3,"frog");
assertTrue(kodok.getTipeHabitat(0).equals("land"));
}
@Test
public void test_getTipeAnimal() {
System.out.println("Test apakah getTipeAnimal menghasilkan nilai dengan benar");
Animal kodok = new Animal(2,3,"frog");
assertTrue(kodok.getTipeAnimal().equals("frog"));
}
@Test
public void test_getSimbol() {
System.out.println("Test apakah getSimbol menghasilkan nilai dengan benar");
Animal kodok = new Animal(2,3,"frog");
assertTrue(kodok.getSimbol() == 'f');
}
@Test
public void test_interact() {
System.out.println("Test apakah interact menghasilkan nilai dengan benar");
Animal kodok = new Animal(2,3,"frog");
assertTrue(kodok.interact().equals("ribbit"));
}
@Test
public void test_getMusuh() {
System.out.println("Test apakah getMusuh menghasilkan nilai dengan benar");
Animal kodok = new Animal(2,3,"frog");
assertTrue(kodok.getMusuh(0).equals("rhino"));
}
} |
/*
* Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.db.model;
import pl.edu.icm.unity.exceptions.WrongArgumentException;
/**
* DB has certain size limits on different objects. Those are available from this class.
* @author K. Benedyczak
*/
public class DBLimits
{
private int nameLimit;
private int contentsLimit;
public int getNameLimit()
{
return nameLimit;
}
public void setNameLimit(int nameLimit)
{
this.nameLimit = nameLimit;
}
public int getContentsLimit()
{
return contentsLimit;
}
public void setContentsLimit(int contentsLimit)
{
this.contentsLimit = contentsLimit;
}
public void checkNameLimit(String ofWhat) throws WrongArgumentException
{
if (ofWhat != null && ofWhat.length() > getNameLimit())
throw new WrongArgumentException("Name length must not exceed " +
getNameLimit() + " characters");
}
public void checkContentsLimit(byte[] ofWhat) throws IllegalArgumentException
{
if (ofWhat != null && ofWhat.length > getContentsLimit())
throw new IllegalArgumentException("Contents must not exceed " +
getContentsLimit() + " bytes");
}
}
|
package com.jam.jamoodle.service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
/**
* Created by Andrew on 2/23/2017.
*/
public class SmsReceiver extends BroadcastReceiver {
private final static String TAG = SmsReceiver.class.getSimpleName();
public final static String INTENT_ACTION = "SmsMessage.intent.MAIN";
public final static String INTENT_MESSAGE_KEY = "SmsMessage.intent.message";
public final static String INTENT_SENDER_KEY = "SmsMessage.intent.sender";
public SmsReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
// Get the data (SMS data) bound to intent
final Bundle bundle = intent.getExtras();
final StringBuilder sb = new StringBuilder();
if (bundle != null) {
// Retrieve the SMS Messages received
final Object[] pdus = (Object[]) bundle.get("pdus");
String sender = "";
// For every SMS message received
for (int i = 0; i < pdus.length; i++) {
// Convert Object array
final SmsMessage smsMessages = SmsMessage.createFromPdu((byte[]) pdus[i]);
// Fetch the text message
sb.append(smsMessages.getMessageBody().toString()).append("\n");
// Sender's phone number
sender = smsMessages.getOriginatingAddress();
}
final String message = sb.toString();
Log.d(TAG, sender + ": " + sb.toString());
final Intent in = new Intent(INTENT_ACTION);
in.putExtra(INTENT_MESSAGE_KEY, message);
in.putExtra(INTENT_SENDER_KEY, sender);
//You can place your check conditions here(on the SMS or the sender)
//and then send another broadcast
context.sendBroadcast(in);
}
}
}
|
package com.intricatech.topwatch;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.SystemClock;
import android.text.SpannableString;
import android.text.style.RelativeSizeSpan;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
/**
* Created by Bolgbolg on 16/05/2017.
*
* A timer's most important field is its elapsedTime.
*/
public class StopWatch {
private final String TAG;
/**
* A reference to the parent Activity, used for callbacks.
*/
private MainActivity callbackActivity;
/**
* A simplified interface for a DBHelper object (extends SQLiteOpenHelper)
*/
private DatabaseFacade databaseFacade;
/**
* The session currently held in memory.
*/
private Session session;
/**
* The current route, null if using stopwatch to record a new session.
*/
private Route route;
/**
* The current date;
*/
private Date currentDate;
/**
* The total time (nanoseconds) that the timer has been running.
*/
private long elapsedTime;
/**
* The time since the last start event.
*/
private long lastStartTime;
/**
* Flag showing status of StopWatch.
*/
private boolean isRunning;
/**
* The elapsed time since the start of the current split.
*/
private long currentSplitElapsedTime;
private double totalDistance;
/**
* The time the current split last restarted at.
*/
private long currentSplitLastStartTime;
private boolean newSessionReadyToStart;
private static final String COLON_SEPARATOR = " : ";
/**
* The SharedPreferences object for storing Stopwatch's persistent state, and its editor.
*/
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor sharedPreferencesEditor;
private RecordingType recordingType;
/**
* String fields for the SharedPreference Tags.
*/
private String SHARED_PREF_TAG, SPLIT_LIST_TAG, ELAPSED_TIME, LAST_START_TIME,
CURRENT_SPLIT_ELAPSED_TIME, CURRENT_SPLIT_LAST_START_TIME, IS_RUNNING,
RECORDING_TYPE, NEW_SESSION_READY_TO_START;
public StopWatch(MainActivity activity) {
TAG = getClass().getSimpleName();
this.callbackActivity = activity;
databaseFacade = DatabaseFacade.getInstance();
SHARED_PREF_TAG = activity.getResources().getString(R.string.shared_preferences_tag);
SPLIT_LIST_TAG = activity.getResources().getString(R.string.split_list_tag);
ELAPSED_TIME = activity.getResources().getString(R.string.elapsed_time);
LAST_START_TIME = activity.getResources().getString(R.string.last_start_time);
CURRENT_SPLIT_ELAPSED_TIME = activity.getResources().getString(R.string.current_split_elapsed_time);
CURRENT_SPLIT_LAST_START_TIME = activity.getResources().getString(R.string.current_split_last_start_time);
IS_RUNNING = activity.getResources().getString(R.string.is_running);
RECORDING_TYPE = "RECORDING_TYPE";
NEW_SESSION_READY_TO_START = "NEW_SESSION_READY_TO_START";
sharedPreferences = callbackActivity.getSharedPreferences(SHARED_PREF_TAG, Context.MODE_PRIVATE);
sharedPreferencesEditor = sharedPreferences.edit();
elapsedTime = 0;
currentSplitElapsedTime = 0;
lastStartTime = 0;
currentSplitLastStartTime = 0;
isRunning = false;
recordingType = RecordingType.NEW_RECORDING;
currentDate = getCurrentDateWithoutTime();
session = new Session(currentDate);
route = null;
}
public void onMainActivityDestroyed() {
callbackActivity = null;
}
/**
* Handles button press from the parent activity.
*/
public void onPlayButtonPressed() {
if(!isRunning()) {
startTimer();
} else {
pauseTimer();
}
}
/**
* Handles button press from the parent activity. Creates a new split, initializes its
* currentSplitElapsedTime to zero, and records the time this split was started at, in case the
* timer is paused during it.
*/
public void onLapButtonPressed() {
if (isRunning) {
createSplit();
currentSplitElapsedTime = 0;
currentSplitLastStartTime = getCurrentTime();
}
}
/**
* Save the current session wrapped in a new Route object to the database.
* @param name A string chosen by the user.
*/
public long saveNewRouteToDB(String name) {
long rowID = databaseFacade.saveNewRouteToDB(name, session, totalDistance);
return rowID;
}
/**
* Add the current session to the current Route in the database.
*/
public void saveNewSessionToDB() {
databaseFacade.saveSessionToDB(route.getRowID(), session);
}
/**
* Handles button press from the parent activity. Sets all relevant fields to zero, and creates
* a new empty splitList.
*/
public void onResetButtonPressed() {
elapsedTime = 0;
currentSplitElapsedTime = 0;
lastStartTime = 0;
currentSplitLastStartTime = 0;
isRunning = false;
session.resetSplitList();
newSessionReadyToStart = true;
}
/**
* Sets the timer running, and stores the time of invocation. Does nothing if timer is
* already running.
* @return true if already running, false if not.
*/
public boolean startTimer() {
if (isRunning) {
return true;
} else {
isRunning = true;
long currentTime = getCurrentTime();
lastStartTime = currentTime;
currentSplitLastStartTime = currentTime;
newSessionReadyToStart = false;
return false;
}
}
/**
* Pauses the timer, and adds the time since the last startTime to the elapsedTime.
* @return true if already paused, false if not.
*/
public boolean pauseTimer() {
if (!isRunning) {
return true;
} else {
isRunning = false;
long currentTime = getCurrentTime();
elapsedTime += currentTime - lastStartTime;
currentSplitElapsedTime += currentTime - currentSplitLastStartTime;
return false;
}
}
public boolean isNewSessionReadyToStart() {
return newSessionReadyToStart;
}
public void createSplit() {
long currentTime = getCurrentTime();
long nanos = currentSplitElapsedTime + currentTime - currentSplitLastStartTime;
double dist = calculateDistanceForCurrentSplit();
Split split = new Split(nanos, dist, session.getSplitList().size() + 1);
session.getSplitList().add(split);
SpannableString distSS = getSplitDistanceAsString(split);
callbackActivity.onNewSplitCreated(getMostRecentSplitTimeAsString(), distSS);
}
private double calculateDistanceForCurrentSplit() {
double distForAllPreviousSplits = 0;
for (Split split : session.getSplitList()) {
distForAllPreviousSplits += split.getDistance();
}
return totalDistance - distForAllPreviousSplits;
}
public SpannableString getTotalTimeAsString() {
if (isRunning()) {
return getTimeAsSpannableString(getTotalTimeInNanos());
} else {
return getTimeAsSpannableString(elapsedTime);
}
}
public SpannableString getTimeSinceLastSplitAsString() {
if (isRunning()) {
return getTimeAsSpannableString(getTimeSinceStartOfCurrentSplit());
} else {
return getTimeAsSpannableString(currentSplitElapsedTime);
}
}
public long getTotalTimeInNanos() {
return elapsedTime + (getCurrentTime() - lastStartTime);
}
private long getTimeSinceStartOfCurrentSplit() {
return currentSplitElapsedTime + (getCurrentTime() - currentSplitLastStartTime);
}
/**
* Gets the most recently added split from splitList and returns a SpannableString
* representation of it. Format as follows :
* Index : 2 digits + COLON_SEPARATOR (half-size)
* Hours - 1 digit + ":"
* Minutes - 2 digits + ":"
* Seconds - 2 digits + "."
* Hundredths - 2 digits (half-size).
* @return The SpannableString representation of the most recent split time, with index prefix,
* or null if splitList is empty.
*/
public SpannableString getMostRecentSplitTimeAsString() {
if (!session.getSplitList().isEmpty()) {
Split spl = session.getSplitList().getLast();
long splitTime = spl.getSplitTime();
int index = spl.getIndex();
String indexString = String.format("%02d", index);
String timeString = getTimeAsString(splitTime);
String fullString = indexString + COLON_SEPARATOR + timeString;
SpannableString spStr = new SpannableString(fullString);
spStr.setSpan(
new RelativeSizeSpan(2f),
indexString.length() + COLON_SEPARATOR.length(),
indexString.length() + COLON_SEPARATOR.length() + 8,
0);
return spStr;
} else {
return null;
}
}
public SpannableString getSplitTimeAsString(Split split) {
Split spl;
if (split == null) {
return new SpannableString("empty - split is null");
} else {
long splitTime = split.getSplitTime();
int index = split.getIndex();
String indexString = String.format("%02d", index);
String timeString = getTimeAsString(splitTime);
String fullString = indexString + COLON_SEPARATOR + timeString;
SpannableString spStr = new SpannableString(fullString);
spStr.setSpan(
new RelativeSizeSpan(2f),
indexString.length() + COLON_SEPARATOR.length(),
indexString.length() + COLON_SEPARATOR.length() + 8,
0);
return spStr;
}
}
public SpannableString getSplitDistanceAsString(Split split) {
if (split == null) {
return new SpannableString("empty - split is null");
} else {
SpannableString str = new SpannableString(String.format("%.2f", split.getDistance()) + "m");
return str;
}
}
/*
TODO - Overload this method as follows : getMostRecentSplitTimeAsString(split comparisonSplit) -
using the best previous split to compare and format accordingly. Colour RED/GREEN?
*/
/**
* Takes a time in nanoseconds and returns a SpannableString representation with the following
* layout :
* Hours - 1 digit + ":"
* Minutes - 2 digits + ":"
* Seconds - 2 digits + "."
* Hundredths - 2 digits (half the size of the other digits.
*
* @param nanos The time to display
* @return The SpannableString representation of the time.
*/
public static SpannableString getTimeAsSpannableString(long nanos) {
String s = getTimeAsString(nanos);
// Reduce hundredths in size to 50% of other digits.
SpannableString spannableString = new SpannableString(s);
spannableString.setSpan(new RelativeSizeSpan(2f), 0, 8, 0);
return spannableString;
}
/**
* Takes a time in nanoseconds and returns an ordinary String representation with the following
* layout :
* Hours - 1 digit + ":"
* Minutes - 2 digits + ":"
* Seconds - 2 digits + "."
* Hundredths - 2 digits
* @param nanos The time to display
* @return The String representation of the time.
*/
public static String getTimeAsString(long nanos) {
// Get hours/minutes/seconds String.
long timeInMilliSeconds = TimeUnit.MILLISECONDS.convert(nanos, TimeUnit.NANOSECONDS);
int hours = (int) ((timeInMilliSeconds / 1000 / 60 / 60) % 24);
int mins = (int) ((timeInMilliSeconds / 1000 / 60) % 60);
int seconds = (int) ((timeInMilliSeconds / 1000) % 60);
int hundredths = (int) ((timeInMilliSeconds / 10) % 100);
StringBuilder sb = new StringBuilder();
sb.append(String.format("%01d", hours) + ":");
sb.append(String.format("%02d", mins) + ":");
sb.append(String.format("%02d", seconds) + ".");
sb.append(String.format("%02d", hundredths));
return sb.toString();
}
public boolean isRunning() {
return isRunning;
}
public void saveSharedPreferencesOnStop() {
Gson gson = new Gson();
String jsonString = gson.toJson(session.getSplitList());
sharedPreferencesEditor.putLong(ELAPSED_TIME, elapsedTime);
sharedPreferencesEditor.putLong(LAST_START_TIME, lastStartTime);
sharedPreferencesEditor.putLong(CURRENT_SPLIT_ELAPSED_TIME, currentSplitElapsedTime);
sharedPreferencesEditor.putLong(CURRENT_SPLIT_LAST_START_TIME, currentSplitLastStartTime);
sharedPreferencesEditor.putString(SPLIT_LIST_TAG, jsonString);
sharedPreferencesEditor.putBoolean(IS_RUNNING, isRunning);
sharedPreferencesEditor.putInt(RECORDING_TYPE, recordingType.ordinal());
sharedPreferencesEditor.putBoolean(NEW_SESSION_READY_TO_START, newSessionReadyToStart);
Log.d(TAG, "saving stopwatch to SharedPrefs : newSessionReadyToStart = " + newSessionReadyToStart);
sharedPreferencesEditor.commit();
}
public void loadSharedPreferencesOnStart() {
Gson gson = new Gson();
LinkedList<Split> retrievedList;
String jsonString = sharedPreferences.getString(SPLIT_LIST_TAG, "");
Type type = new TypeToken<LinkedList<Split>>(){}.getType();
if (jsonString != "") {
retrievedList = gson.fromJson(jsonString, type);
session.setSplitList(retrievedList);
}
elapsedTime = sharedPreferences.getLong(ELAPSED_TIME, 0);
lastStartTime = sharedPreferences.getLong(LAST_START_TIME, 0);
currentSplitElapsedTime = sharedPreferences.getLong(CURRENT_SPLIT_ELAPSED_TIME, 0);
currentSplitLastStartTime = sharedPreferences.getLong(CURRENT_SPLIT_LAST_START_TIME, 0);
isRunning = sharedPreferences.getBoolean(IS_RUNNING, false);
recordingType = RecordingType.values()[sharedPreferences.getInt(RECORDING_TYPE, 0)];
newSessionReadyToStart = sharedPreferences.getBoolean(NEW_SESSION_READY_TO_START, true);
Log.d(TAG, "loading stopwatch from SharedPrefs : newSessionReadyToStart = " + newSessionReadyToStart);
}
public void rePostSavedSplits() {
for(Split s : session.getSplitList()) {
callbackActivity.onNewSplitCreated(getSplitTimeAsString(s), getSplitDistanceAsString(s));
}
}
private long getCurrentTime() {
return SystemClock.elapsedRealtimeNanos();
}
/**
* Utility method to remove the time information from a date.
* @return the date with zero time.
*/
public static Date getCurrentDateWithoutTime() {
Date dateWithTime = new Date();
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date dateWithoutTime = null;
try {
dateWithoutTime = formatter.parse(formatter.format(dateWithTime));
} catch (ParseException e) {
e.printStackTrace();
}
return dateWithoutTime;
}
public RecordingType getRecordingType() {
return recordingType;
}
public double getTotalDistance() {
return totalDistance;
}
public void setTotalDistance(double totalDistance) {
this.totalDistance = totalDistance;
}
}
|
package plugins.fmp.fmpTools;
import java.awt.Color;
import icy.image.IcyBufferedImage;
import icy.image.IcyBufferedImageUtil;
import icy.type.DataType;
import icy.type.collection.array.Array1DUtil;
import plugins.fmp.fmpSequence.SequenceVirtual;
public class ImageTransformTools {
private IcyBufferedImage referenceImage = null;
private int spanDiff = 3;
private SequenceVirtual vinputSequence = null;
// -------------------------------------
public void setReferenceImage(IcyBufferedImage img) {
referenceImage = IcyBufferedImageUtil.getCopy(img);
}
public void setSpanDiff(int spanDiff) {
this.spanDiff = spanDiff;
}
public int getSpanDiff () {
return spanDiff;
}
public void setSequence (SequenceVirtual vinputSeq) {
vinputSequence = vinputSeq;
referenceImage = vinputSequence.loadVImage(0);
}
public IcyBufferedImage transformImage (IcyBufferedImage inputImage, EnumImageOp transformop) {
IcyBufferedImage transformedImage = null;
switch (transformop) {
case NONE:
case COLORARRAY1: /*System.out.println("transform image - " + transformop);*/
transformedImage = inputImage;
break;
case R_RGB: transformedImage= functionRGB_keepOneChan(inputImage, 0); break;
case G_RGB: transformedImage= functionRGB_keepOneChan(inputImage, 1); break;
case B_RGB: transformedImage= functionRGB_keepOneChan(inputImage, 2); break;
case RGB: transformedImage= functionRGB_grey (inputImage);
case H_HSB: transformedImage= functionRGBtoHSB(inputImage, 0); break;
case S_HSB: transformedImage= functionRGBtoHSB(inputImage, 1); break;
case B_HSB: transformedImage= functionRGBtoHSB(inputImage, 2); break;
case R2MINUS_GB: transformedImage= functionRGB_2C3MinusC1C2 (inputImage, 1, 2, 0); break;
case G2MINUS_RB: transformedImage= functionRGB_2C3MinusC1C2 (inputImage, 0, 2, 1); break;
case B2MINUS_RG: transformedImage= functionRGB_2C3MinusC1C2 (inputImage, 0, 1, 2); break;
case GBMINUS_2R: transformedImage= functionRGB_C1C2minus2C3 (inputImage, 1, 2, 0); break;
case RBMINUS_2G: transformedImage= functionRGB_C1C2minus2C3 (inputImage, 0, 2, 1); break;
case RGMINUS_2B: transformedImage= functionRGB_C1C2minus2C3 (inputImage, 0, 1, 2); break;
case NORM_BRMINUSG: transformedImage= functionNormRGB_sumC1C2Minus2C3(inputImage, 1, 2, 0); break;
case RTOGB: transformedImage= functionTransferRedToGreenAndBlue(inputImage); break;
case REF_T0: transformedImage= functionSubtractRef(inputImage); break;
case REF: transformedImage= functionSubtractRef(inputImage); break;
case REF_PREVIOUS:
int t = vinputSequence.currentFrame;
if (t>0){
referenceImage = vinputSequence.loadVImage(t-1);
transformedImage= functionSubtractRef(inputImage);}
break;
case XDIFFN: transformedImage= computeXDiffn (inputImage); break;
case YDIFFN: transformedImage= computeYDiffn (inputImage); break;
case XYDIFFN: transformedImage= computeXYDiffn (inputImage); break;
case RGB_TO_HSV: transformedImage= functionRGBtoHSV(inputImage); break;
case RGB_TO_H1H2H3: transformedImage= functionRGBtoH1H2H3(inputImage); break;
}
return transformedImage;
}
public IcyBufferedImage transformImageFromVirtualSequence (int t, EnumImageOp transformop) {
return transformImage(vinputSequence.loadVImage(t), transformop);
}
// function proposed by François Rebaudo
private IcyBufferedImage functionNormRGB_sumC1C2Minus2C3 (IcyBufferedImage sourceImage, int Rlayer, int Glayer, int Blayer) {
double[] Rn = Array1DUtil.arrayToDoubleArray(sourceImage.getDataXY(Rlayer), sourceImage.isSignedDataType());
double[] Gn = Array1DUtil.arrayToDoubleArray(sourceImage.getDataXY(Glayer), sourceImage.isSignedDataType());
double[] Bn = Array1DUtil.arrayToDoubleArray(sourceImage.getDataXY(Blayer), sourceImage.isSignedDataType());
double[] ExG = (double[]) Array1DUtil.createArray(DataType.DOUBLE, Rn.length);
for (int i=0; i< Rn.length; i++) {
double sum = (Rn[i] / 255) + (Gn[i] / 255) + (Bn [i] / 255);
ExG[i] = ((Gn[i] *2 / 255 / sum) - (Rn[i] / 255/sum) - (Bn [i] / 255/sum)) * 255;
}
IcyBufferedImage img2 = new IcyBufferedImage (sourceImage.getWidth(), sourceImage.getHeight(), 1, sourceImage.getDataType_());
Array1DUtil.doubleArrayToSafeArray(ExG, img2.getDataXY(0), false); //true);
img2.setDataXY(0, img2.getDataXY(0));
return img2;
}
private IcyBufferedImage functionTransferRedToGreenAndBlue(IcyBufferedImage sourceImage) {
IcyBufferedImage img2 = new IcyBufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), 3, sourceImage.getDataType_());
img2.copyData(sourceImage, 0, 0);
img2.copyData(sourceImage, 0, 1);
img2.copyData(sourceImage, 0, 2);
return img2;
}
private IcyBufferedImage functionRGB_2C3MinusC1C2 (IcyBufferedImage sourceImage, int addchan1, int addchan2, int subtractchan3) {
IcyBufferedImage img2 = new IcyBufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), 1, sourceImage.getDataType_());
double[] tabSubtract = Array1DUtil.arrayToDoubleArray(sourceImage.getDataXY(subtractchan3), sourceImage.isSignedDataType());
double[] tabAdd1 = Array1DUtil.arrayToDoubleArray(sourceImage.getDataXY(addchan1), sourceImage.isSignedDataType());
double[] tabAdd2 = Array1DUtil.arrayToDoubleArray(sourceImage.getDataXY(addchan2), sourceImage.isSignedDataType());
double[] tabResult = (double[]) Array1DUtil.createArray(DataType.DOUBLE, tabSubtract.length);
for (int i = 0; i < tabResult.length; i++) {
double val = tabSubtract[i]* 2 - tabAdd1[i] - tabAdd2[i] ;
tabResult [i] = val;
}
Array1DUtil.doubleArrayToSafeArray(tabResult, img2.getDataXY(0), false); // true);
img2.setDataXY(0, img2.getDataXY(0));
return img2;
}
private IcyBufferedImage functionRGB_C1C2minus2C3 (IcyBufferedImage sourceImage, int addchan1, int addchan2, int subtractchan3) {
IcyBufferedImage img2 = new IcyBufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), 1, sourceImage.getDataType_());
if (sourceImage.getSizeC() < 3)
return null;
double[] tabSubtract = Array1DUtil.arrayToDoubleArray(sourceImage.getDataXY(subtractchan3), sourceImage.isSignedDataType());
double[] tabAdd1 = Array1DUtil.arrayToDoubleArray(sourceImage.getDataXY(addchan1), sourceImage.isSignedDataType());
double[] tabAdd2 = Array1DUtil.arrayToDoubleArray(sourceImage.getDataXY(addchan2), sourceImage.isSignedDataType());
double[] tabResult = (double[]) Array1DUtil.createArray(DataType.DOUBLE, tabSubtract.length);
for (int i = 0; i < tabResult.length; i++) {
tabResult [i] = tabAdd1[i] + tabAdd2[i] - tabSubtract[i]* 2;
}
Array1DUtil.doubleArrayToSafeArray(tabResult, img2.getDataXY(0), false); // true);
img2.setDataXY(0, img2.getDataXY(0));
return img2;
}
private IcyBufferedImage computeXDiffn(IcyBufferedImage sourceImage) {
int chan0 = 0;
int chan1 = sourceImage.getSizeC();
int imageSizeX = sourceImage.getSizeX();
int imageSizeY = sourceImage.getSizeY();
IcyBufferedImage img2 = new IcyBufferedImage(imageSizeX, imageSizeY, 3, sourceImage.getDataType_());
for (int c=chan0; c < chan1; c++) {
double[] tabValues = Array1DUtil.arrayToDoubleArray(sourceImage.getDataXY(c), sourceImage.isSignedDataType());
double[] outValues = Array1DUtil.arrayToDoubleArray(img2.getDataXY(c), img2.isSignedDataType());
for (int iy = 0; iy < imageSizeY; iy++) {
// erase border values
for (int ix = 0; ix < spanDiff; ix++) {
outValues[ix + iy* imageSizeX] = 0;
}
// compute values
int deltay = iy* imageSizeX;
for (int ix =spanDiff; ix < imageSizeX -spanDiff; ix++) {
int kx = ix + deltay;
int deltax = 0;
double outVal = 0;
for (int ispan = 1; ispan < spanDiff; ispan++) {
deltax += 1;
outVal += tabValues [kx+deltax] - tabValues[kx-deltax];
}
outValues [kx] = (int) Math.abs(outVal);
}
// erase border values
for (int ix = imageSizeX-spanDiff; ix < imageSizeX; ix++) {
outValues[ix + iy* imageSizeX] = 0;
}
}
Array1DUtil.doubleArrayToSafeArray(outValues, img2.getDataXY(c), false); // true);
img2.setDataXY(c, img2.getDataXY(c));
}
return img2;
}
private IcyBufferedImage computeYDiffn(IcyBufferedImage sourceImage) {
int chan0 = 0;
int chan1 = sourceImage.getSizeC();
int imageSizeX = sourceImage.getSizeX();
int imageSizeY = sourceImage.getSizeY();
IcyBufferedImage img2 = new IcyBufferedImage(imageSizeX, imageSizeY, 1, sourceImage.getDataType_());
for (int c=chan0; c < chan1; c++) {
double[] tabValues = Array1DUtil.arrayToDoubleArray(sourceImage.getDataXY(c), sourceImage.isSignedDataType());
double[] outValues = Array1DUtil.arrayToDoubleArray(img2.getDataXY(c), img2.isSignedDataType());
for (int ix = spanDiff; ix < imageSizeX - spanDiff; ix++) {
// // erase border values
// for (int iy = 0; iy < spanDiff; iy++) {
// outValues[ix + iy* imageSizeX] = 0;
// }
// compute values
for (int iy =spanDiff; iy < imageSizeY -spanDiff; iy++) {
int kx = ix + iy* imageSizeX;
int deltax = 0;
double outVal = 0;
for (int ispan = 1; ispan < spanDiff; ispan++) {
deltax += imageSizeX;
outVal += tabValues [kx+deltax] - tabValues[kx-deltax];
}
outValues [kx] = (int) Math.abs(outVal);
}
// // erase border values
// for (int iy = imageSizeY-spanDiff; iy < imageSizeY; iy++) {
// outValues[ix + iy* imageSizeX] = 0;
// }
}
Array1DUtil.doubleArrayToSafeArray(outValues, img2.getDataXY(c), false); // true);
img2.setDataXY(c, img2.getDataXY(c));
}
return img2;
}
private IcyBufferedImage computeXYDiffn(IcyBufferedImage sourceImage) {
int chan0 = 0;
int chan1 = sourceImage.getSizeC();
int imageSizeX = sourceImage.getSizeX();
int imageSizeY = sourceImage.getSizeY();
IcyBufferedImage img2 = new IcyBufferedImage(imageSizeX, imageSizeY, 1, sourceImage.getDataType_());
for (int c=chan0; c < chan1; c++) {
double[] tabValues = Array1DUtil.arrayToDoubleArray(sourceImage.getDataXY(c), sourceImage.isSignedDataType());
double[] outValues = Array1DUtil.arrayToDoubleArray(img2.getDataXY(c), img2.isSignedDataType());
for (int ix =0; ix < imageSizeX; ix++) {
for (int iy = spanDiff; iy < imageSizeY-spanDiff; iy++) {
int ky = ix + iy* imageSizeX;
int deltay = 0;
double outVal = 0;
// loop vertically
for (int ispan = 1; ispan < spanDiff; ispan++) {
deltay += imageSizeX;
outVal += tabValues [ky+deltay] - tabValues[ky-deltay];
}
// loop horizontally
int deltax = 0;
int yspan2 = 10;
if (ix >yspan2 && ix < imageSizeX - yspan2) {
for (int ispan = 1; ispan < yspan2; ispan++) {
deltax += 1;
outVal += tabValues [ky+deltax] - tabValues[ky-deltax];
}
}
outValues [ky] = (int) Math.abs(outVal);
}
// erase out-of-bounds points
for (int iy = 0; iy < spanDiff; iy++)
outValues[ix + iy* imageSizeX] = 0;
for (int iy = imageSizeY-spanDiff; iy < imageSizeY; iy++)
outValues[ix + iy* imageSizeX] = 0;
}
Array1DUtil.doubleArrayToSafeArray(outValues, img2.getDataXY(c), false); // img2.isSignedDataType());
img2.setDataXY(c, img2.getDataXY(c));
}
return img2;
}
private IcyBufferedImage functionRGB_keepOneChan (IcyBufferedImage sourceImage, int keepChan) {
IcyBufferedImage img2 = new IcyBufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), 1, sourceImage.getDataType_());
img2.copyData(sourceImage, keepChan, 0);
return img2;
}
private IcyBufferedImage functionRGB_grey (IcyBufferedImage sourceImage) {
IcyBufferedImage img2 = new IcyBufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), 1, sourceImage.getDataType_());
int[] tabValuesR = Array1DUtil.arrayToIntArray(sourceImage.getDataXY(0), sourceImage.isSignedDataType());
int[] tabValuesG = Array1DUtil.arrayToIntArray(sourceImage.getDataXY(1), sourceImage.isSignedDataType());
int[] tabValuesB = Array1DUtil.arrayToIntArray(sourceImage.getDataXY(2), sourceImage.isSignedDataType());
int[] outValues0 = Array1DUtil.arrayToIntArray(img2.getDataXY(0), sourceImage.isSignedDataType());
for (int ky =0; ky < outValues0.length; ky++) {
outValues0 [ky] = (tabValuesR[ky]+tabValuesG[ky]+tabValuesB[ky])/3;
}
Object dataArray = img2.getDataXY(0);
Array1DUtil.intArrayToSafeArray(outValues0, dataArray, sourceImage.isSignedDataType(), false); //image.isSignedDataType());
img2.setDataXY(0, dataArray);
return img2;
}
private IcyBufferedImage functionRGBtoHSB(IcyBufferedImage sourceImage, int xHSB) {
IcyBufferedImage img2 = new IcyBufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), 3, sourceImage.getDataType_());
double[] tabValuesR = Array1DUtil.arrayToDoubleArray(sourceImage.getDataXY(0), sourceImage.isSignedDataType());
double[] tabValuesG = Array1DUtil.arrayToDoubleArray(sourceImage.getDataXY(1), sourceImage.isSignedDataType());
double[] tabValuesB = Array1DUtil.arrayToDoubleArray(sourceImage.getDataXY(2), sourceImage.isSignedDataType());
double[] outValues0 = Array1DUtil.arrayToDoubleArray(img2.getDataXY(0), img2.isSignedDataType());
double[] outValues1 = Array1DUtil.arrayToDoubleArray(img2.getDataXY(1), img2.isSignedDataType());
double[] outValues2 = Array1DUtil.arrayToDoubleArray(img2.getDataXY(2), img2.isSignedDataType());
// compute values
for (int ky = 0; ky < tabValuesR.length; ky++) {
int R = (int) tabValuesR[ky];
int G = (int) tabValuesG[ky];
int B = (int) tabValuesB[ky];
float[] hsb = Color.RGBtoHSB(R, G, B, null) ;
double val = (double) hsb[xHSB] * 100;
outValues0 [ky] = val;
outValues1 [ky] = val;
outValues2 [ky] = val;
}
Array1DUtil.doubleArrayToSafeArray(outValues0, img2.getDataXY(0), false); // img2.isSignedDataType());
img2.setDataXY(0, img2.getDataXY(0));
Array1DUtil.doubleArrayToSafeArray(outValues1, img2.getDataXY(1), false); // img2.isSignedDataType());
img2.setDataXY(1, img2.getDataXY(1));
Array1DUtil.doubleArrayToSafeArray(outValues2, img2.getDataXY(2), false); // img2.isSignedDataType());
img2.setDataXY(2, img2.getDataXY(2));
return img2;
}
private IcyBufferedImage functionSubtractRef(IcyBufferedImage sourceImage) {
/* algorithm borrowed from Perrine.Paul-Gilloteaux@univ-nantes.fr in EC-CLEM
* original function: private IcyBufferedImage substractbg(Sequence ori, Sequence bg,int t, int z)
*/
if (referenceImage == null)
referenceImage = vinputSequence.loadVImage(0);
IcyBufferedImage img2 = new IcyBufferedImage(sourceImage.getSizeX(), sourceImage.getSizeY(),sourceImage.getSizeC(), sourceImage.getDataType_());
for (int c=0; c<sourceImage.getSizeC(); c++) {
int [] imgSourceInt = Array1DUtil.arrayToIntArray(sourceImage.getDataXY(0), sourceImage.isSignedDataType());
int [] img2Int = Array1DUtil.arrayToIntArray(img2.getDataXY(0), img2.isSignedDataType());
int [] imgReferenceInt = Array1DUtil.arrayToIntArray(referenceImage.getDataXY(0), referenceImage.isSignedDataType());
for (int i=0; i< imgSourceInt.length; i++) {
int val = imgSourceInt[i] - imgReferenceInt[i];
if (val < 0)
val = -val;
img2Int[i] = 0xFF - val;
}
Array1DUtil.intArrayToSafeArray(img2Int, img2.getDataXY(c), true, false); // img2.isSignedDataType());
img2.setDataXY(c, img2.getDataXY(c));
}
return img2;
}
private IcyBufferedImage functionRGBtoHSV (IcyBufferedImage sourceImage) {
IcyBufferedImage img2 = new IcyBufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), 3, sourceImage.getDataType_());
double[] tabValuesR = Array1DUtil.arrayToDoubleArray(sourceImage.getDataXY(0), sourceImage.isSignedDataType());
double[] tabValuesG = Array1DUtil.arrayToDoubleArray(sourceImage.getDataXY(1), sourceImage.isSignedDataType());
double[] tabValuesB = Array1DUtil.arrayToDoubleArray(sourceImage.getDataXY(2), sourceImage.isSignedDataType());
double[] outValues0 = Array1DUtil.arrayToDoubleArray(img2.getDataXY(0), img2.isSignedDataType());
double[] outValues1 = Array1DUtil.arrayToDoubleArray(img2.getDataXY(1), img2.isSignedDataType());
double[] outValues2 = Array1DUtil.arrayToDoubleArray(img2.getDataXY(2), img2.isSignedDataType());
// compute values
float [] hsb = new float [3];
for (int ky = 0; ky < tabValuesR.length; ky++) {
int R = (int) tabValuesR[ky];
int G = (int) tabValuesG[ky];
int B = (int) tabValuesB[ky];
hsb = Color.RGBtoHSB(R, G, B, hsb) ;
outValues0 [ky] = (double) hsb[0] ;
outValues1 [ky] = (double) hsb[1] ;
outValues2 [ky] = (double) hsb[2] ;
}
Array1DUtil.doubleArrayToSafeArray(outValues0, img2.getDataXY(0), false); // img2.isSignedDataType());
img2.setDataXY(0, img2.getDataXY(0));
Array1DUtil.doubleArrayToSafeArray(outValues1, img2.getDataXY(1), false); // img2.isSignedDataType());
img2.setDataXY(1, img2.getDataXY(1));
Array1DUtil.doubleArrayToSafeArray(outValues2, img2.getDataXY(2), false); // img2.isSignedDataType());
img2.setDataXY(2, img2.getDataXY(2));
return img2;
}
private IcyBufferedImage functionRGBtoH1H2H3 (IcyBufferedImage sourceImage) {
IcyBufferedImage img2 = new IcyBufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), 3, sourceImage.getDataType_());
double[] tabValuesR = Array1DUtil.arrayToDoubleArray(sourceImage.getDataXY(0), sourceImage.isSignedDataType());
double[] tabValuesG = Array1DUtil.arrayToDoubleArray(sourceImage.getDataXY(1), sourceImage.isSignedDataType());
double[] tabValuesB = Array1DUtil.arrayToDoubleArray(sourceImage.getDataXY(2), sourceImage.isSignedDataType());
double[] outValues0 = Array1DUtil.arrayToDoubleArray(img2.getDataXY(0), img2.isSignedDataType());
double[] outValues1 = Array1DUtil.arrayToDoubleArray(img2.getDataXY(1), img2.isSignedDataType());
double[] outValues2 = Array1DUtil.arrayToDoubleArray(img2.getDataXY(2), img2.isSignedDataType());
// compute values
final double VMAX = 255.0;
for (int ky = 0; ky < tabValuesR.length; ky++) {
int r = (int) tabValuesR[ky];
int g = (int) tabValuesG[ky];
int b = (int) tabValuesB[ky];
outValues0 [ky] = (r + g) / 2.0;
outValues1 [ky] = (VMAX + r - g) / 2.0;
outValues2 [ky] = (VMAX + b - (r + g) / 2.0) / 2.0;
}
Array1DUtil.doubleArrayToSafeArray(outValues0, img2.getDataXY(0), false); // img2.isSignedDataType());
img2.setDataXY(0, img2.getDataXY(0));
Array1DUtil.doubleArrayToSafeArray(outValues1, img2.getDataXY(1), false); // img2.isSignedDataType());
img2.setDataXY(1, img2.getDataXY(1));
Array1DUtil.doubleArrayToSafeArray(outValues2, img2.getDataXY(2), false); // img2.isSignedDataType());
img2.setDataXY(2, img2.getDataXY(2));
return img2;
}
}
|
package com.example.qunxin.erp.fragment;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.qunxin.erp.R;
import com.example.qunxin.erp.activity.AddShangpinActivity;
import com.example.qunxin.erp.activity.ShangpinliebiaoActivity;
import com.example.qunxin.erp.util.Constant;
import com.google.zxing.activity.CaptureActivity;
import static android.app.Activity.RESULT_OK;
/**
* Created by qunxin on 2019/8/15.
*/
public class ShangpinliebiaoSearchFragment extends Fragment {
EditText editText;
View view;
View shangpinliebiao_search_back;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view=inflater.inflate(R.layout.fragment_shangpinliebiao_search,container,false);
initView();
return view;
}
void initView(){
shangpinliebiao_search_back=view.findViewById(R.id.shangpinliebiao_search_back);
shangpinliebiao_search_back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// ((ShangpinliebiaoActivity)(getActivity())).addShangpinliebiaoPaixuFragmentt();
// ((ShangpinliebiaoActivity)(getActivity())).search("");
}
});
editText=view.findViewById(R.id.shangpinliebiao_search_serch);
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH){
Log.d("search", "onEditorAction: search");
((ShangpinliebiaoActivity)(getActivity())).search(editText.getText().toString());
return true;
}
return false;
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
((ShangpinliebiaoActivity)(getActivity())).search(editText.getText().toString());
}
});
//点击editText右边图标
editText.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// getCompoundDrawables获取是一个数组,数组0,1,2,3,对应着左,上,右,下 这4个位置的图片,如果没有就为null
Drawable drawable = editText.getCompoundDrawables()[2];
//如果右边没有图片,不再处理
if (drawable == null){
return false;
}
//如果不是按下事件,不再处理
if (event.getAction() != MotionEvent.ACTION_DOWN) {
return false;
}
if (event.getX() > editText.getWidth()
- editText.getPaddingRight()
- drawable.getIntrinsicWidth()){
//具体操作
startQrCode();
Log.d("touch", "onTouch: touch");
}
return false;
}
});
}
// 开始扫码
private void startQrCode() {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
// 申请权限
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
return;
}
// 二维码扫码
Intent intent = new Intent(((ShangpinliebiaoActivity)(getActivity())), CaptureActivity.class);
startActivityForResult(intent, Constant.REQ_QR_CODE);
}
//申请访问权限回调结果
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case Constant.REQ_PERM_CAMERA:
// 摄像头权限申请
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// 获得授权
startQrCode();
} else {
// 被禁止授权
Toast.makeText(getActivity(), "请至权限中心打开本应用的相机访问权限", Toast.LENGTH_LONG).show();
}
break;
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {
Bundle bundle = data.getExtras();
String scanResult = bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN);
//将扫描出的信息显示出来
editText.setText(scanResult);
}
}
}
|
package com.beike.common.exception;
/**
* @title: DiscountCouponException.java
* @package com.beike.common.exception
* @description:
* @author wangweijie
* @date 2012-7-11 下午09:36:34
* @version v1.0
*/
public class DiscountCouponException extends BaseException {
/**
* @fields serialVersionUID :
*/
private static final long serialVersionUID = 658441052768973882L;
// public DiscountCouponException(){
// super();
// }
public DiscountCouponException(int code){
super(code);
}
}
|
package com.lab.shopCart.shopcartms.application.internal.service;
import com.lab.shopCart.shopcartms.interfaces.rest.dto.order.OrderResDto;
import com.lab.shopCart.shopcartms.interfaces.rest.dto.shopcart.ShopCartReqDto;
import com.lab.shopCart.shopcartms.interfaces.rest.dto.shopcart.ShopCartResDto;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
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;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
//@Testcontainers
public class ShopCartServiceTest {
@Autowired
ShopCartService shopCartService;
// @Container
// private static final PostgreSQLContainer database =
// (PostgreSQLContainer) new PostgreSQLContainer("postgres:9.6")
// .withDatabaseName("shopcart")
// .withUsername("postgres")
// .withPassword("1qaz1qaz")
// .withInitScript("init_postgres.sql");
@Test
public void createShopCartTest(){
//Arrange
ShopCartReqDto shopCartReqDto = new ShopCartReqDto("Hank");
ShopCartResDto expectShopCartResDto = new ShopCartResDto(0,"Hank");
//Act
ShopCartResDto actalShopCartResDto = shopCartService.createShopCart(shopCartReqDto);
//Assert
Assertions.assertEquals(expectShopCartResDto,actalShopCartResDto);
}
@Test
public void createOrderTest(){
//Arrange
Integer cartId = 1;
String expectCustomerName = "Hank";
//Act
OrderResDto actaulOrder = shopCartService.createOrder(cartId);
//Assert
Assertions.assertEquals(expectCustomerName,actaulOrder.getCustomerName());
}
}
|
package org.hpin.common.util;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
/**
* 字符串工具类
*
* @author thinkpad
*
*/
public class StrUtils {
/**
* 判断字符串是否不为空或者不为空字符
*
* @param str
* 允许为NULL
* @return
*/
public static boolean isNotNullOrBlank(Object o) {
if (null == o) {
return false;
} else {
String str = o.toString();
if ("".equals(str.trim())) {
return false;
} else {
return true;
}
}
}
/**
* 两个数组做对比
* @param a
* @param b
* @return
*/
public static boolean compareArgs(String[] a, String b[]) {
String[] aa = {};
if (a != null && a.length > 0) {
aa = new String[a.length-1];
for (int i = 0; i < a.length; i++) {
if(i != a.length-1){
aa[i] = a[i];
}
}
}
String[] bb = {};
if (b != null && b.length > 0) {
bb = new String[b.length-1];
for (int i = 0; i < b.length; i++) {
if(i != b.length-1) {
bb[i] = b[i];
}
}
}
if (aa.length != bb.length) {
return false;
}
else {
Arrays.sort(aa);
Arrays.sort(bb);
return Arrays.equals(aa, bb);
}
}
public static boolean compareArgsLength(String[] a, String b[]) {
boolean flag = false;
if(a.length==b.length) flag = true;
return flag;
}
/**
* 将null转化为空白
* @param str
* @return
*/
public static String toStr(Object str) {
return (str == null) ? "" : String.valueOf(str).trim();
}
/**
* 判断字符串是否为空或者不为空字符
*
* @param str
* 允许为NULL
* @return
*/
public static boolean isNullOrBlank(Object o) {
return !isNotNullOrBlank(o);
}
/**
* 将sourceObject转换为字符串后与compareStr对象比较,如果相等就返回afterIsEqualToObject对象,
* 不相等就返回sourceObject
*
* @param sourceObject
* 被比较的对象
* @param compareStr
* 比较的对象
* @param object
* 如果相等,则返回afterIsEqualToObject对象
*/
public static Object toStringForCompare(Object sourceObject,
String compareStr, Object afterIsEqualToObject) {
if (null == sourceObject) {
return sourceObject;
} else if (sourceObject.toString().equals(compareStr)) {
return compareStr;
} else {
return null;
}
}
/**
* 如果对象为空,则返回空字符串
*
* @param str
* @return
*/
public static String isNullToBank(Object str) {
if (null == str) {
return "";
} else {
return str.toString();
}
}
/**
* 将对象转换为String类型
*
* @param str
* @return
*/
public static String ObjectToStr(Object o, String defaultValue) {
if (null == o) {
return defaultValue;
} else {
return o.toString().trim();
}
}
public static String ObjectToStr(Object o) {
if (null == o) {
return null;
} else {
return o.toString().trim();
}
}
public static String doubleChange(double money) {
DecimalFormat df = new DecimalFormat("######0.00");
return df.format(money);
}
public static void main(String arg[]) {
double a = 12.658;
double b = 12;
String x = doubleChange(b);
}
/**
* 将对象转换为String类型
*
* @param str
* @return
*/
public static String ObjectToString(Object o) {
if (null == o) {
return null;
} else {
return o.toString();
}
}
/**
* 将对象转换为Long类型
*
* @param str
* @return
*/
public static Long ObjectToLong(Object o, Long defaultValue) {
if (null == o) {
return defaultValue;
} else {
return (Long) o;
}
}
/**
* 将对象转换为Long类型
*
* @param str
* @return
*/
public static Long ObjectToLong(Object o) {
if (null == o) {
return null;
} else {
return new Long(o.toString());
}
}
/**
* 将对象转换为Double类型
*
* @param str
* @return
*/
public static Double ObjectToDouble(Object o) {
if (null == o || "" == o) {
return null;
} else {
return new Double(o.toString());
}
}
/**
* 将对象转换为Integer类型
*
* @param str
* @return
*/
public static Integer ObjectToInteger(Object o) {
if (null == o|| ""==o) {
return null;
} else {
return Integer.parseInt(o.toString());
}
}
/**
* 集合转换成字符串
*
* @param collection
* 集合
* @param separator
* 分隔符
* @return
*/
public static String CollectionToStr(Collection collection,
String separator, boolean all) {
Iterator it = collection.iterator();
Object object = null;
String str = "";
while (it.hasNext()) {
object = it.next();
str = str + object.toString() + separator;
}
if (collection.size() > 0) {
if (all) {
str = "," + str;
} else {
str = str.substring(0, str.length() - (separator.length()));
}
}
return str;
}
}
|
package dao;
import table.Status;
import java.sql.SQLException;
import java.util.List;
public interface StatusDao {
public void addStatus(Status status) throws SQLException;
public void deleteStatus(Integer statusId) throws SQLException;
public Status getStatusById(Integer statusId) throws SQLException;
public List<Status> getStatusesByStudentIdAndThemeId(Integer studentId, Integer themeId) throws SQLException;
public void updateMessage(Integer statusId, String message) throws SQLException;
public void updateDone(Integer statusId, Boolean done) throws SQLException;
public void updateMark(Integer statusId, Integer mark) throws SQLException;
}
|
package com.flipkart.DAO;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import com.flipkart.constants.SQLConstantsQuery;
import com.flipkart.exceptions.CourseNotFoundException;
import com.flipkart.model.Course;
import com.flipkart.model.Report;
import com.flipkart.utils.DBUtil;
import com.flipkart.utils.DateTimeUtil;
public class StudentCoursesDaoImpl implements StudentCoursesDao{
private static Logger logger= Logger.getLogger(StudentCoursesDaoImpl.class);
//View Enrolled Courses
@Override
public List<Course> viewEnrolledCourses(int studentId) {
// TODO Auto-generated method stub
List <Course> enrolledList=new ArrayList<>();
Connection connect=DBUtil.getConnection();
try {
String sql=SQLConstantsQuery.VIEW_ENROLLED_COURSES;
PreparedStatement stmt = connect.prepareStatement(sql);
stmt.setInt(1, studentId);
ResultSet rs = stmt.executeQuery();
while(rs.next()){
int courseId= rs.getInt("courseId");
String courseName=rs.getString("courseName");
Course course=new Course();
course.courseId=courseId;
course.courseName=courseName;
enrolledList.add(course);
}
return enrolledList;
} catch (SQLException e) {
logger.error(e.getMessage());
}
return null;
}
//Add course in student List
@Override
public void addCourse(int studentId, int courseId) throws CourseNotFoundException{
// TODO Auto-generated method stub
Connection connect=DBUtil.getConnection();
try {
String sql=SQLConstantsQuery.ADD_STUDENT_COURSE;
PreparedStatement stmt = connect.prepareStatement(sql);
stmt.setInt(1, studentId);
stmt.setInt(2, courseId);
stmt.setString(3,null);
stmt.executeUpdate();
} catch (SQLException e) {
throw new CourseNotFoundException();
//logger.error(e.getMessage());
}
}
//Drop Course from student List
@Override
public void deleteCourse(int studentId, int courseId) throws CourseNotFoundException {
// TODO Auto-generated method stub
Connection connect=DBUtil.getConnection();
String query = SQLConstantsQuery.DELETE_STUDENT_COURSE;
try {
PreparedStatement stmt = connect.prepareStatement(query);
stmt.setInt(1, courseId);
stmt.setInt(2, studentId);
int row=stmt.executeUpdate();
if(row==0) {
throw new CourseNotFoundException();
}
} catch (SQLException e) {
logger.error(e.getMessage());
}
}
//Calculate fees for registration
@Override
public double calculateFees(int studentId) {
Connection connect=DBUtil.getConnection();
String query = SQLConstantsQuery.CALCULATE_FEE;
double fee=0;
try {
PreparedStatement stmt = connect.prepareStatement(query);
stmt.setInt(1,studentId);
ResultSet rs = stmt.executeQuery();
while(rs.next()){
fee= rs.getDouble("fee");
}
return fee;
} catch (SQLException e) {
logger.error(e.getMessage());
}
return 0;
}
//Upload Grades to report Card
@Override
public void uploadGrades(int studentId, int cid, String grades) {
Connection connect=DBUtil.getConnection();
String query = SQLConstantsQuery.UPLOAD_GRADES;
try {
PreparedStatement stmt = connect.prepareStatement(query);
stmt.setString(1,grades);
stmt.setInt(2, studentId);
stmt.setInt(3, cid);
stmt.executeUpdate();
} catch (SQLException e) {
logger.error(e.getMessage());
}
}
//View Report Card
@Override
public List<Report> viewReport(int studentId) {
List <Report> reportList=new ArrayList<>();
Connection connect=DBUtil.getConnection();
String query = "Select courseId,grades from course where studentId=?";
double fee=0;
try {
PreparedStatement stmt = connect.prepareStatement(query);
stmt.setInt(1, studentId);
ResultSet rs = stmt.executeQuery();
while(rs.next()){
int courseId= rs.getInt("courseId");
String grades=rs.getString("grades");
Report report =new Report();
report.courseId=courseId;
report.grades=grades;
reportList.add(report);
}
return reportList;
} catch (SQLException e) {
logger.error(e.getMessage());
}
return null;
}
}
|
package OnTap;
import java.util.ArrayList;
import java.util.Scanner;
public class QuanLy {
Scanner scanner = new Scanner(System.in);
public void menu() {
while(true) {
System.out.println("---------------------------------");
System.out.println("1.Nhap thong tin hoc sinh ");
System.out.println("2.Hien thi thong tin hoc sinh ");
System.out.println("3.Hien thi hoc sinh can tim ");
System.out.println("4.Hien thi hoc sinh lop 10A1 ");
System.out.println("0.Ket thuc ");
System.out.println("---------------------------------");
System.out.println("Lua chon menu");
String chon = scanner.nextLine();
switch (chon) {
case "1":
nhap();
break;
case "2":
xuat();
break;
case "3":
tim();
break;
case "4":
lop();
break;
case "0":
scanner.close();
System.exit(0);
break;
default:
break;
}
}
}
HSHocSinh hsHocSinh;
int n;
ArrayList<HSHocSinh> hshs = new ArrayList<>();
public void nhap() {
System.out.println("Nhap so luong hoc sinh: ");
n = Integer.parseInt(scanner.nextLine());
for(int i = 0; i < n; i++) {
hsHocSinh = new HSHocSinh();
System.out.println("Nhap thong tin hoc sinh thu: " + (i+1) + " : ");
hsHocSinh.nhap();
hshs.add(hsHocSinh);
}
}
public void xuat() {
for (int i = 0; i < hshs.size(); i++) {
System.out.println("\nThong tin hoc sinh thu: " + (i+1) + " : ");
hshs.get(i).xuat();
}
}
public void tim() {
for (HSHocSinh x : hshs) {
if(x.ngaySinh==1985 && x.queQuan.equals("Thai Nguyen")) {
x.xuat();
}
}
}
public void lop() {
for (HSHocSinh y : hshs) {
if(y.lop.equals("10A1")) {
y.xuat();
}
}
}
}
|
package learnBasics;
public class NullExample {
public static void main(String[] args) {
// Null refers to classes or object not primitive types
// int a=null; gives an error
String s=null;
if(s==null) {
System.out.println("s is null");
}
// below code will give null pointer exception
if(s.equals(null)) {
System.out.println("S is also null");
}
}
}
|
package com.lenovohit.ssm.payment.model;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.lenovohit.core.model.BaseIdModel;
import com.lenovohit.ssm.base.model.Machine;
//现金打印批次
@Entity
@Table(name="SSM_CASH_BATCH")
public class CashBatch extends BaseIdModel{
private static final long serialVersionUID = 5578125996822876373L;
public static final String PRINT_STAT_INIT = "0";//已清钞
public static final String PRINT_STAT_PRINTED = "1";//已打印
private String batchNo;
private Date createTime;
private String status;
private Date printTime;
private long count;
private BigDecimal amt;
private Machine machine;
private String machineCode;
private String machineName;
private String machineMac;
private String batchDay;
private long bankCount;
private BigDecimal bankAmt;
private Date importTime;
public String getBatchDay() {
return batchDay;
}
public void setBatchDay(String batchDay) {
this.batchDay = batchDay;
}
@ManyToOne
@JoinColumn(name="MACHINE_ID")
public Machine getMachine() {
return machine;
}
public void setMachine(Machine machine) {
this.machine = machine;
}
public String getMachineCode() {
return machineCode;
}
public void setMachineCode(String machineCode) {
this.machineCode = machineCode;
}
public String getMachineName() {
return machineName;
}
public void setMachineName(String machineName) {
this.machineName = machineName;
}
public String getMachineMac() {
return machineMac;
}
public void setMachineMac(String machineMac) {
this.machineMac = machineMac;
}
public BigDecimal getAmt() {
return amt;
}
public void setAmt(BigDecimal amt) {
this.amt = amt;
}
public String getBatchNo() {
return batchNo;
}
public void setBatchNo(String batchNo) {
this.batchNo = batchNo;
}
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
public Date getPrintTime() {
return printTime;
}
public void setPrintTime(Date printTime) {
this.printTime = printTime;
}
public long getCount() {
return count;
}
public void setCount(long count) {
this.count = count;
}
public long getBankCount() {
return bankCount;
}
public void setBankCount(long bankCount) {
this.bankCount = bankCount;
}
public BigDecimal getBankAmt() {
return bankAmt;
}
public void setBankAmt(BigDecimal bankAmt) {
this.bankAmt = bankAmt;
}
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
public Date getImportTime() {
return importTime;
}
public void setImportTime(Date importTime) {
this.importTime = importTime;
}
}
|
package me.deepak.code.ib.arrays;
import java.util.ArrayList;
import java.util.List;
/**
* <a href="https://www.interviewbit.com/problems/max-distance/">Click here</a> for problem description
*
* @author Deepak Soni
*/
public class BucketingP5MD {
/**
* List copy to startIndex, stopIndex both inclusive.
*
* @param copyTo
* @param copyFrom
* @param startIndex
*/
private void listRangeCopy(List<Integer> copyTo, List<Integer> copyFrom, int startIndex) {
int i = startIndex;
for (Integer item : copyFrom) {
copyTo.set(i, item);
i++;
}
}
/**
* Sort the array.
*
* @param arr
* @param indices
* @param startIndex
* @param stopIndex
*/
private void sort(List<Integer> arr, List<Integer> indices, int startIndex, int stopIndex) {
if (startIndex >= stopIndex) {
return;
}
int middleIndex = (startIndex + stopIndex) / 2;
sort(arr, indices, startIndex, middleIndex);
sort(arr, indices, middleIndex + 1, stopIndex);
List<Integer> tempArr = new ArrayList<Integer>(stopIndex - startIndex + 1);
List<Integer> tempIndices = new ArrayList<Integer>(stopIndex - startIndex + 1);
int i = startIndex;
int j = middleIndex + 1;
while (i <= middleIndex && j <= stopIndex) {
if (arr.get(i) <= arr.get(j)) {
tempArr.add(arr.get(i));
tempIndices.add(indices.get(i));
i++;
} else {
tempArr.add(arr.get(j));
tempIndices.add(indices.get(j));
j++;
}
}
while (i <= middleIndex) {
tempArr.add(arr.get(i));
tempIndices.add(indices.get(i));
i++;
}
while (j <= stopIndex) {
tempArr.add(arr.get(j));
tempIndices.add(indices.get(j));
j++;
}
listRangeCopy(arr, tempArr, startIndex);
listRangeCopy(indices, tempIndices, startIndex);
}
/**
* Starts here.
*
* @param a
* @return
*/
public int maximumGap(final List<Integer> a) {
if (a.size() == 0) {
return -1;
}
List<Integer> arr = new ArrayList<Integer>(a);
List<Integer> indices = new ArrayList<Integer>(a.size());
List<Integer> maxIndices = new ArrayList<Integer>(a.size());
for (int i = 0; i < a.size(); i++) {
indices.add(i);
maxIndices.add(0);
}
sort(arr, indices, 0, arr.size() - 1);
int maxIndex = -1;
for (int i = arr.size() - 1; i >= 0; i--) {
maxIndex = Math.max(maxIndex, indices.get(i));
maxIndices.set(i, maxIndex);
}
int maxGap = 0;
for (int i = arr.size() - 1; i >= 0; i--) {
int gap = maxIndices.get(i) - indices.get(i);
if (gap > maxGap) {
maxGap = gap;
}
}
return maxGap;
}
}
|
/* ====================================================================
*
* Copyright (c) Atos Origin INFORMATION TECHNOLOGY All rights reserved.
*
* ==================================================================== *
*/
package com.aof.webapp.action.prm.expense;
import java.io.FileInputStream;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Query;
import net.sf.hibernate.Transaction;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;
import com.aof.component.domain.party.Party;
import com.aof.component.domain.party.PartyHelper;
import com.aof.component.domain.party.UserLogin;
import com.aof.component.prm.Bill.TransactionServices;
import com.aof.component.prm.expense.ExpenseMaster;
import com.aof.component.prm.expense.ProjectAirFareCost;
import com.aof.component.prm.expense.ProjectCostMaster;
import com.aof.component.prm.util.EmailService;
import com.aof.core.persistence.hibernate.Hibernate2Session;
import com.aof.core.persistence.jdbc.SQLResults;
import com.aof.util.Constants;
import com.aof.util.UtilDateTime;
import com.aof.webapp.action.BaseAction;
import com.aof.webapp.action.prm.report.ReportBaseAction;
/**
* @author Jeffrey Liang
* @version 2004-10-30
*
*/
public class FindCostSelfPageAction extends ReportBaseAction {
public ActionForward perform(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) {
// Extract attributes we will need
Locale locale = getLocale(request);
MessageResources messages = getResources();
String action = request.getParameter("FormAction");
UserLogin ul = (UserLogin)request.getSession().getAttribute(Constants.USERLOGIN_KEY);
if(action == null) action = "QueryForList";
if (action.equals("QueryForList")) {
List result = findQueryResult(request);
request.setAttribute("QryList", result);
}
if (action.equals("PAConfirm")) {
String chk[] =request.getParameterValues("chk");
TransactionServices ts = new TransactionServices();
if (chk != null) {
try {
net.sf.hibernate.Session hs =Hibernate2Session.currentSession();
Transaction tx = hs.beginTransaction();
int RowSize = java.lang.reflect.Array.getLength(chk);
for (int i = 0; i < RowSize; i++) {
ProjectCostMaster pcm = (ProjectCostMaster)hs.load(ProjectCostMaster.class, new Integer(chk[i]));
if (pcm.getPAConfirm() == null) {
pcm.setPAConfirm(UtilDateTime.nowTimestamp());
hs.update(pcm);
}
ts.insert(pcm, ul);
}
tx.commit();
hs.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
List result = findQueryResult(request);
request.setAttribute("QryList", result);
}
if (action.equals("PAUNConfirm")) {
String chk[] =request.getParameterValues("chk");
TransactionServices ts = new TransactionServices();
if (chk != null) {
try {
net.sf.hibernate.Session hs =Hibernate2Session.currentSession();
Transaction tx = hs.beginTransaction();
int RowSize = java.lang.reflect.Array.getLength(chk);
for (int i = 0; i < RowSize; i++) {
ProjectCostMaster pcm = (ProjectCostMaster)hs.load(ProjectCostMaster.class, new Integer(chk[i]));
if (pcm.getPAConfirm() != null) {
pcm.setPAConfirm(null);
hs.update(pcm);
}
ts.remove(pcm);
}
tx.commit();
hs.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
List result = findQueryResult(request);
request.setAttribute("QryList", result);
}
if (action.equals("Confirm")) {
String chk[] =request.getParameterValues("chk");
TransactionServices ts = new TransactionServices();
if (chk != null) {
try {
net.sf.hibernate.Session hs =Hibernate2Session.currentSession();
Transaction tx = hs.beginTransaction();
int RowSize = java.lang.reflect.Array.getLength(chk);
for (int i = 0; i < RowSize; i++) {
ProjectCostMaster pcm = (ProjectCostMaster)hs.load(ProjectCostMaster.class, new Integer(chk[i]));
if (pcm.getApprovalDate() == null) {
pcm.setApprovalDate(UtilDateTime.nowTimestamp());
pcm.setPayStatus("confirmed");
hs.update(pcm);
}
// ts.remove(pcm);
}
tx.commit();
hs.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
List result = findQueryResult(request);
request.setAttribute("QryList", result);
}
if (action.equals("PostToFA")) {
String chk[] =request.getParameterValues("chk");
if (chk != null) {
try {
net.sf.hibernate.Session hs =Hibernate2Session.currentSession();
// Transaction tx = hs.beginTransaction();
int RowSize = java.lang.reflect.Array.getLength(chk);
for (int i = 0; i < RowSize; i++) {
ProjectCostMaster pcm = (ProjectCostMaster)hs.load(ProjectCostMaster.class, new Integer(chk[i]));
ProjectAirFareCost pac = (ProjectAirFareCost)hs.load(ProjectAirFareCost.class, new Integer(chk[i]));
// if(pac.getReturnDate()!=null){
pcm.setPayStatus("Posted");
hs.save(pcm);
// }
}
// tx.commit();
hs.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
List result = findQueryResult(request);
request.setAttribute("QryList", result);
}
if (action.equals("ExcelPrint")) {
String chk[] =request.getParameterValues("chk");
if (chk != null) {
try {
// Get Excel Template Path =============================================
net.sf.hibernate.Session hs =Hibernate2Session.currentSession();
String TemplatePath = GetTemplateFolder();
if (TemplatePath == null) return null;
int RowSize = java.lang.reflect.Array.getLength(chk);
//Start to output the excel file
response.reset();
response.setHeader("Content-Disposition", "attachment;filename=\""+ SaveToFileName + "\"");
response.setContentType("application/octet-stream");
//Use POI to read the selected Excel Spreadsheet
HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(TemplatePath+"\\"+ExcelTemplate));
//Select the first worksheet
HSSFSheet sheet = wb.getSheet(FormSheetName);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
String status ="";
HSSFCell cell = null;
//List
HSSFCellStyle boldTextStyle = sheet.getRow(ListStartRow).getCell((short)0).getCellStyle();
HSSFCellStyle dateStyle = sheet.getRow(1).getCell((short)7).getCellStyle();
HSSFCellStyle numberFormatStyle = sheet.getRow(ListStartRow).getCell((short)6).getCellStyle();
int ExcelRow = ListStartRow;
HSSFRow HRow = null;
HRow = sheet.createRow(1);
cell = HRow.createCell((short)7);
cell.setCellValue(new Date());
cell.setCellStyle(dateStyle);
//in order to make groups
short cellNumber = 0;
//write the titles
HRow = sheet.createRow(titleRow);
cell = HRow.createCell(cellNumber++);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断
cell.setCellValue("Ticket Code");
cell.setCellStyle(boldTextStyle);
cell = HRow.createCell(cellNumber++);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断
cell.setCellValue("Project ID");
cell.setCellStyle(boldTextStyle);
cell = HRow.createCell(cellNumber++);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断
cell.setCellValue("Staff Name");
cell.setCellStyle(boldTextStyle);
cell = HRow.createCell(cellNumber++);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断
cell.setCellValue("Description");
cell.setCellStyle(boldTextStyle);
cell = HRow.createCell(cellNumber++);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断
cell.setCellValue("Bill To");
cell.setCellStyle(boldTextStyle);
cell = HRow.createCell(cellNumber++);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断
cell.setCellValue("Create Date");
cell.setCellStyle(boldTextStyle);
cell = HRow.createCell(cellNumber++);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断
cell.setCellValue("Flight No.");
cell.setCellStyle(boldTextStyle);
cell = HRow.createCell(cellNumber++);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断
cell.setCellValue("Paid By");
cell.setCellStyle(boldTextStyle);
cell = HRow.createCell(cellNumber++);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断
cell.setCellValue("Flight Date");
cell.setCellStyle(boldTextStyle);
cell = HRow.createCell(cellNumber++);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断
cell.setCellValue("Confirm Date");
cell.setCellStyle(boldTextStyle);
cell = HRow.createCell(cellNumber++);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断
cell.setCellValue("Price");
cell.setCellStyle(boldTextStyle);
cell = HRow.createCell(cellNumber++);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断
cell.setCellValue("Vendor");
cell.setCellStyle(boldTextStyle);
//write contents
for (int i = 0; i < RowSize; i++) {
ProjectCostMaster pcm = (ProjectCostMaster)hs.load(ProjectCostMaster.class, new Integer(chk[i]));
ProjectAirFareCost pac = (ProjectAirFareCost)hs.load(ProjectAirFareCost.class, new Integer(chk[i]));
cellNumber = 0;
HRow = sheet.createRow(ExcelRow);
cell = HRow.createCell(cellNumber++);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断
cell.setCellValue(pcm.getFormCode());
cell.setCellStyle(boldTextStyle);
cell = HRow.createCell(cellNumber++);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断
cell.setCellValue(pcm.getProjectMaster()==null ? "" : pcm.getProjectMaster().getProjId());
cell.setCellStyle(boldTextStyle);
cell = HRow.createCell(cellNumber++);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断
cell.setCellValue(pcm.getUserLogin().getName());
cell.setCellStyle(boldTextStyle);
cell = HRow.createCell(cellNumber++);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断
cell.setCellValue(pcm.getPayType()== null? pcm.getProjectMaster().getProjName() : pcm.getPayType());
cell.setCellStyle(boldTextStyle);
cell = HRow.createCell(cellNumber++);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断
cell.setCellValue(pcm.getProjectMaster().getBillTo() == null ? "" : pcm.getProjectMaster().getBillTo().getDescription());
cell.setCellStyle(boldTextStyle);
cell = HRow.createCell(cellNumber++);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断
cell.setCellValue(df.format(pcm.getCreatedate()));
cell.setCellStyle(boldTextStyle);
cell = HRow.createCell(cellNumber++);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断
cell.setCellValue(pcm.getRefno());
cell.setCellStyle(boldTextStyle);
cell = HRow.createCell(cellNumber++);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断
cell.setCellValue(pcm.getClaimType().equals("CN") ? "Company" : "Customer");
cell.setCellStyle(boldTextStyle);
cell = HRow.createCell(cellNumber++);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断
cell.setCellValue(df.format(pcm.getCostdate()));
cell.setCellStyle(boldTextStyle);
cell = HRow.createCell(cellNumber++);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断
cell.setCellValue(pcm.getApprovalDate()==null? "" : df.format(pcm.getApprovalDate()));
cell.setCellStyle(boldTextStyle);
cell = HRow.createCell(cellNumber++);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断
cell.setCellValue(pcm.getTotalvalue());
cell.setCellStyle(numberFormatStyle);
cell = HRow.createCell(cellNumber++);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断
cell.setCellValue(pcm.getVendor()==null?"":pcm.getVendor().getDescription());
cell.setCellStyle(boldTextStyle);
pcm.setExportDate(UtilDateTime.nowTimestamp());
ExcelRow++;
}
// writeExportDate(sr);
// writeExportDate(sr);
//写入Excel工作表
wb.write(response.getOutputStream());
//关闭Excel工作薄对象
response.getOutputStream().close();
response.setStatus( HttpServletResponse.SC_OK );
response.flushBuffer();
//------------------------------------------
// Transaction tx = hs.beginTransaction();
hs.flush();
} catch (Exception e) {
e.printStackTrace();
}
}else{
return null;
}
// List result = findQueryResult(request);
// request.setAttribute("QryList", result);
}
return (mapping.findForward("success"));
}
private List findQueryResult (HttpServletRequest request) {
Logger log = Logger.getLogger(FindCostSelfPageAction.class.getName());
List result = new ArrayList();
try {
SimpleDateFormat Date_formater = new SimpleDateFormat("yyyy-MM-dd");
Date nowDate = (java.util.Date)UtilDateTime.nowTimestamp();
String textsrc = request.getParameter("textsrc");
String texttype = request.getParameter("texttype");
String departmentId = request.getParameter("departmentId");
String DateStart = request.getParameter("DateStart");
String DateEnd = request.getParameter("DateEnd");
String textProj = request.getParameter("textProj");
String textUser = request.getParameter("textUser");
String textStatus = request.getParameter("textStatus");
String textPAConfirm = request.getParameter("textPAConfirm");
if (textStatus==null) textStatus="";
String textPaid = request.getParameter("textPaid");
if (textPaid==null) textPaid="";
if (textPAConfirm==null) textPAConfirm="";
if (textProj==null) textProj="";
if (textUser==null) textUser="";
if (textsrc==null) textsrc="";
if (texttype==null) texttype="";
if (departmentId == null) departmentId = "";
if (DateStart==null) DateStart=Date_formater.format(UtilDateTime.getDiffDay(nowDate,-30));
if (DateEnd==null) DateEnd=Date_formater.format(nowDate);
String Type = request.getParameter("Type");
String costType = request.getParameter("CostType");
if (costType != null && costType.trim().length() != 0) {
texttype = costType;
}
if (Type == null) Type = "";
net.sf.hibernate.Session hs = Hibernate2Session.currentSession();
String QryStr = "select pcm from ProjectCostMaster as pcm ";
if (departmentId.trim().equals("")) {
UserLogin ul = (UserLogin)request.getSession().getAttribute(Constants.USERLOGIN_KEY);
QryStr = QryStr + " where (pcm.createuser ='"+ul.getUserLoginId()+"' or pcm.modifyuser ='"+ul.getUserLoginId()+"')";
} else {
PartyHelper ph = new PartyHelper();
String PartyListStr = "''";
if (!departmentId.trim().equals("")) {
List partyList_dep=ph.getAllSubPartysByPartyId(hs,departmentId);
Iterator itdep = partyList_dep.iterator();
PartyListStr = "'"+departmentId+"'";
while (itdep.hasNext()) {
Party p =(Party)itdep.next();
PartyListStr = PartyListStr +", '"+p.getPartyId()+"'";
}
}
QryStr = QryStr + " where pcm.projectMaster.department.partyId in ("+PartyListStr+")";
}
QryStr = QryStr + " and (pcm.costdate between '"+DateStart+"' and '"+DateEnd+"')";
if(!textsrc.trim().equals("")){
QryStr = QryStr +" and (pcm.FormCode like '%"+ textsrc.trim() +"%' )";
}
if(!texttype.trim().equals("")){
QryStr = QryStr +" and (pcm.projectCostType.typeid = '"+ texttype +"')";
} else {
QryStr = QryStr +" and (pcm.projectCostType.typeid != 'EAF')";
}
if(!textProj.trim().equals("")){
QryStr = QryStr +" and (pcm.projectMaster.projId like '%"+ textProj.trim() +"%')";
}
if(!textUser.trim().equals("")){
QryStr = QryStr +" and (pcm.userLogin.userLoginId like '%"+ textUser.trim() +"%' or pcm.userLogin.name like '%"+ textUser.trim() +"%')";
}
if(!textStatus.trim().equals("")){
if (textStatus.trim().equals("confirmed")){
QryStr = QryStr +" and (pcm.payStatus = 'confirmed' )";
}else if(textStatus.trim().equals("unconfirmed")){
QryStr = QryStr +" and (pcm.payStatus = 'unconfirmed' )";
}else if(textStatus.trim().equals("posted")){
QryStr = QryStr +" and (pcm.payStatus = 'posted' )";
}else if(textStatus.trim().equals("paid")){
QryStr = QryStr +" and (pcm.payStatus = 'paid' )";
}
}
if(!textPAConfirm.trim().equals("")){
if (textPAConfirm.trim().equals("confirmed")){
QryStr = QryStr +" and (pcm.PAConfirm is not null )";
}else if(textPAConfirm.trim().equals("unconfirmed")){
QryStr = QryStr +" and (pcm.PAConfirm is null )";
}
}
if(!textPaid.trim().equals("")){
QryStr = QryStr +" and (pcm.ClaimType = '"+textPaid.trim() +"' )";
}
QryStr = QryStr +" and pcm.projectCostType.typeaccount='"+Type+"'";
Query q = hs.createQuery(QryStr);
result = q.list();
} catch (Exception e) {
log.error(e.getMessage());
} finally {
try {
Hibernate2Session.closeSession();
} catch (HibernateException e1) {
log.error(e1.getMessage());
e1.printStackTrace();
} catch (SQLException e1) {
log.error(e1.getMessage());
e1.printStackTrace();
}
}
return result;
}
private final static String ExcelTemplate="AirfareCostReport.xls";
private final static String FormSheetName="Form";
private final static String SaveToFileName="Airfare Cost Report.xls";
private final int ListStartRow = 4;
private final int titleRow = 3;
}
|
//javaEE 개발패턴 중 mvc패턴을 적용한 개발 방법을 가리켜 model2 방식이라 일컫는다.
//특히 jsp가 디자인에 사용되고 있으므로, 웹상의 요청을 받고 응답이 가능한 서블릿이 컨트롤러로서
//역할을 수행하게 된다..
package com.webapp1216.board.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.webapp1216.board.model.NoticeDAO;
//클라이언트의 목록 요청을 처리하는 서블릿 정의
public class ListServlet extends HttpServlet{
NoticeDAO noticeDAO = new NoticeDAO();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List list = noticeDAO.selectAll();
//뭔가 저장할 방법??
//세션? 클라이언트가 브라우저 프로세스를 닫지 않거나, 일정 시작내에 재접속할 때 서버측의 메모리에
//담겨진 정보를 사용할 수 있는 기술..(새로운 접속인 경우 세션객체를 새로 생성되고, 세션아이디가 새롭게 발급됨..)
//jsp 에서의 session 내장객체는 자료형이 HttpSession이다!!
HttpSession session = request.getSession(); //이 요청과 관련한 세션을 얻는다!!
session.setAttribute("noticeList", list); //세션 객체에 보관!!
//결과 페이지 선택
response.sendRedirect("/board/list.jsp");
}
} |
package de.phantomcreations.backend.rest.impl;
import com.amihaiemil.docker.Docker;
import com.amihaiemil.docker.LocalDocker;
import org.springframework.stereotype.Component;
import org.springframework.web.context.annotation.ApplicationScope;
import java.io.File;
@Component
@ApplicationScope
public class DockerSercive {
public Docker docker;
public DockerSercive(){
docker = new LocalDocker(new File("/var/run/docker.sock"));
}
}
|
package com.durgesh.schoolassist;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class QuizActivity extends AppCompatActivity implements View.OnClickListener {
Button button1,button2,button3;
Bundle bundle;
String username;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
init();
}
@Override
public boolean onSupportNavigateUp() {
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
onBackPressed();
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.logout,menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id==R.id.log_out)
{
startActivity(new Intent(QuizActivity.this,MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
finish();
}
return super.onOptionsItemSelected(item);
}
void init()
{
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
button1=findViewById(R.id.quiz_seminar);
button2=findViewById(R.id.quiz_club);
button3=findViewById(R.id.quiz_case);
bundle=getIntent().getExtras();
username = bundle.getString("username");
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int id = v.getId();
switch (id)
{
case R.id.quiz_seminar:
startActivity(new Intent(QuizActivity.this,SeminarEvaluation.class).putExtra("username",username));
break;
case R.id.quiz_club:
startActivity(new Intent(QuizActivity.this,JournalClub.class).putExtra("username",username));
break;
case R.id.quiz_case:
startActivity(new Intent(QuizActivity.this,CasePresentationForTheoryRubrics.class).putExtra("username",username));
break;
}
}
}
|
package com.designurway.idlidosa.a.model;
public class OrderHistoryModel {
private String orderId;
private String amount;
private String orderedDate;
private String orderStatus;
public OrderHistoryModel(String orderId, String amount, String orderedDate,String orderStatus) {
this.orderId = orderId;
this.amount = amount;
this.orderedDate = orderedDate;
this.orderStatus = orderStatus;
}
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getOrderedDate() {
return orderedDate;
}
public void setOrderedDate(String orderedDate) {
this.orderedDate = orderedDate;
}
public String getOrderStatus() {
return orderStatus;
}
public void setOrderStatus(String orderStatus) {
this.orderStatus = orderStatus;
}
}
|
import model.PointAndClick;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
/**
* Created by RENT on 2017-05-29.
*/
public class SmileyServlet extends HttpServlet{
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
HttpSession session = req.getSession(true);
PointAndClick pointAndClick = (PointAndClick) session.getAttribute("tabela");
if (pointAndClick == null) {
pointAndClick = new PointAndClick();
session.setAttribute("tabela", pointAndClick);
}
if (req.getParameter("x") != null && req.getParameter("y") != null) {
int x = Integer.parseInt(req.getParameter("x"));
int y = Integer.parseInt(req.getParameter("y"));
pointAndClick.setField(x, y);
}
req.setAttribute("tabela", pointAndClick);
req.getRequestDispatcher("/kotki.jsp").forward(req, resp);
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.annotation;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.annotation.Lookup;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.index.CandidateComponentsIndex;
import org.springframework.context.index.CandidateComponentsIndexLoader;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.env.Environment;
import org.springframework.core.env.EnvironmentCapable;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.core.type.filter.AssignableTypeFilter;
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Indexed;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
/**
* A component provider that scans for candidate components starting from a
* specified base package. Can use the {@linkplain CandidateComponentsIndex component
* index}, if it is available, and scans the classpath otherwise.
*
* <p>Candidate components are identified by applying exclude and include filters.
* {@link AnnotationTypeFilter} and {@link AssignableTypeFilter} include filters
* for an annotation/target-type that is annotated with {@link Indexed} are
* supported: if any other include filter is specified, the index is ignored and
* classpath scanning is used instead.
*
* <p>This implementation is based on Spring's
* {@link org.springframework.core.type.classreading.MetadataReader MetadataReader}
* facility, backed by an ASM {@link org.springframework.asm.ClassReader ClassReader}.
*
* @author Mark Fisher
* @author Juergen Hoeller
* @author Ramnivas Laddad
* @author Chris Beams
* @author Stephane Nicoll
* @author Sam Brannen
* @since 2.5
* @see org.springframework.core.type.classreading.MetadataReaderFactory
* @see org.springframework.core.type.AnnotationMetadata
* @see ScannedGenericBeanDefinition
* @see CandidateComponentsIndex
*/
@SuppressWarnings("removal") // components index
public class ClassPathScanningCandidateComponentProvider implements EnvironmentCapable, ResourceLoaderAware {
static final String DEFAULT_RESOURCE_PATTERN = "**/*.class";
protected final Log logger = LogFactory.getLog(getClass());
private String resourcePattern = DEFAULT_RESOURCE_PATTERN;
private final List<TypeFilter> includeFilters = new ArrayList<>();
private final List<TypeFilter> excludeFilters = new ArrayList<>();
@Nullable
private Environment environment;
@Nullable
private ConditionEvaluator conditionEvaluator;
@Nullable
private ResourcePatternResolver resourcePatternResolver;
@Nullable
private MetadataReaderFactory metadataReaderFactory;
@Nullable
private CandidateComponentsIndex componentsIndex;
/**
* Protected constructor for flexible subclass initialization.
* @since 4.3.6
*/
protected ClassPathScanningCandidateComponentProvider() {
}
/**
* Create a ClassPathScanningCandidateComponentProvider with a {@link StandardEnvironment}.
* @param useDefaultFilters whether to register the default filters for the
* {@link Component @Component}, {@link Repository @Repository},
* {@link Service @Service}, and {@link Controller @Controller}
* stereotype annotations
* @see #registerDefaultFilters()
*/
public ClassPathScanningCandidateComponentProvider(boolean useDefaultFilters) {
this(useDefaultFilters, new StandardEnvironment());
}
/**
* Create a ClassPathScanningCandidateComponentProvider with the given {@link Environment}.
* @param useDefaultFilters whether to register the default filters for the
* {@link Component @Component}, {@link Repository @Repository},
* {@link Service @Service}, and {@link Controller @Controller}
* stereotype annotations
* @param environment the Environment to use
* @see #registerDefaultFilters()
*/
public ClassPathScanningCandidateComponentProvider(boolean useDefaultFilters, Environment environment) {
if (useDefaultFilters) {
registerDefaultFilters();
}
setEnvironment(environment);
setResourceLoader(null);
}
/**
* Set the resource pattern to use when scanning the classpath.
* This value will be appended to each base package name.
* @see #findCandidateComponents(String)
* @see #DEFAULT_RESOURCE_PATTERN
*/
public void setResourcePattern(String resourcePattern) {
Assert.notNull(resourcePattern, "'resourcePattern' must not be null");
this.resourcePattern = resourcePattern;
}
/**
* Add an include type filter to the <i>end</i> of the inclusion list.
*/
public void addIncludeFilter(TypeFilter includeFilter) {
this.includeFilters.add(includeFilter);
}
/**
* Add an exclude type filter to the <i>front</i> of the exclusion list.
*/
public void addExcludeFilter(TypeFilter excludeFilter) {
this.excludeFilters.add(0, excludeFilter);
}
/**
* Reset the configured type filters.
* @param useDefaultFilters whether to re-register the default filters for
* the {@link Component @Component}, {@link Repository @Repository},
* {@link Service @Service}, and {@link Controller @Controller}
* stereotype annotations
* @see #registerDefaultFilters()
*/
public void resetFilters(boolean useDefaultFilters) {
this.includeFilters.clear();
this.excludeFilters.clear();
if (useDefaultFilters) {
registerDefaultFilters();
}
}
/**
* Register the default filter for {@link Component @Component}.
* <p>This will implicitly register all annotations that have the
* {@link Component @Component} meta-annotation including the
* {@link Repository @Repository}, {@link Service @Service}, and
* {@link Controller @Controller} stereotype annotations.
* <p>Also supports Jakarta EE's {@link jakarta.annotation.ManagedBean} and
* JSR-330's {@link jakarta.inject.Named} annotations (as well as their
* pre-Jakarta {@code javax.annotation.ManagedBean} and {@code javax.inject.Named}
* equivalents), if available.
*/
@SuppressWarnings("unchecked")
protected void registerDefaultFilters() {
this.includeFilters.add(new AnnotationTypeFilter(Component.class));
ClassLoader cl = ClassPathScanningCandidateComponentProvider.class.getClassLoader();
try {
this.includeFilters.add(new AnnotationTypeFilter(
((Class<? extends Annotation>) ClassUtils.forName("jakarta.annotation.ManagedBean", cl)), false));
logger.trace("JSR-250 'jakarta.annotation.ManagedBean' found and supported for component scanning");
}
catch (ClassNotFoundException ex) {
// JSR-250 1.1 API (as included in Jakarta EE) not available - simply skip.
}
try {
this.includeFilters.add(new AnnotationTypeFilter(
((Class<? extends Annotation>) ClassUtils.forName("javax.annotation.ManagedBean", cl)), false));
logger.trace("JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning");
}
catch (ClassNotFoundException ex) {
// JSR-250 1.1 API not available - simply skip.
}
try {
this.includeFilters.add(new AnnotationTypeFilter(
((Class<? extends Annotation>) ClassUtils.forName("jakarta.inject.Named", cl)), false));
logger.trace("JSR-330 'jakarta.inject.Named' annotation found and supported for component scanning");
}
catch (ClassNotFoundException ex) {
// JSR-330 API (as included in Jakarta EE) not available - simply skip.
}
try {
this.includeFilters.add(new AnnotationTypeFilter(
((Class<? extends Annotation>) ClassUtils.forName("javax.inject.Named", cl)), false));
logger.trace("JSR-330 'javax.inject.Named' annotation found and supported for component scanning");
}
catch (ClassNotFoundException ex) {
// JSR-330 API not available - simply skip.
}
}
/**
* Set the Environment to use when resolving placeholders and evaluating
* {@link Conditional @Conditional}-annotated component classes.
* <p>The default is a {@link StandardEnvironment}.
* @param environment the Environment to use
*/
public void setEnvironment(Environment environment) {
Assert.notNull(environment, "Environment must not be null");
this.environment = environment;
this.conditionEvaluator = null;
}
@Override
public final Environment getEnvironment() {
if (this.environment == null) {
this.environment = new StandardEnvironment();
}
return this.environment;
}
/**
* Return the {@link BeanDefinitionRegistry} used by this scanner, if any.
*/
@Nullable
protected BeanDefinitionRegistry getRegistry() {
return null;
}
/**
* Set the {@link ResourceLoader} to use for resource locations.
* This will typically be a {@link ResourcePatternResolver} implementation.
* <p>Default is a {@code PathMatchingResourcePatternResolver}, also capable of
* resource pattern resolving through the {@code ResourcePatternResolver} interface.
* @see org.springframework.core.io.support.ResourcePatternResolver
* @see org.springframework.core.io.support.PathMatchingResourcePatternResolver
*/
@Override
public void setResourceLoader(@Nullable ResourceLoader resourceLoader) {
this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
this.metadataReaderFactory = new CachingMetadataReaderFactory(resourceLoader);
this.componentsIndex = CandidateComponentsIndexLoader.loadIndex(this.resourcePatternResolver.getClassLoader());
}
/**
* Return the ResourceLoader that this component provider uses.
*/
public final ResourceLoader getResourceLoader() {
return getResourcePatternResolver();
}
private ResourcePatternResolver getResourcePatternResolver() {
if (this.resourcePatternResolver == null) {
this.resourcePatternResolver = new PathMatchingResourcePatternResolver();
}
return this.resourcePatternResolver;
}
/**
* Set the {@link MetadataReaderFactory} to use.
* <p>Default is a {@link CachingMetadataReaderFactory} for the specified
* {@linkplain #setResourceLoader resource loader}.
* <p>Call this setter method <i>after</i> {@link #setResourceLoader} in order
* for the given MetadataReaderFactory to override the default factory.
*/
public void setMetadataReaderFactory(MetadataReaderFactory metadataReaderFactory) {
this.metadataReaderFactory = metadataReaderFactory;
}
/**
* Return the MetadataReaderFactory used by this component provider.
*/
public final MetadataReaderFactory getMetadataReaderFactory() {
if (this.metadataReaderFactory == null) {
this.metadataReaderFactory = new CachingMetadataReaderFactory();
}
return this.metadataReaderFactory;
}
/**
* Scan the component index or class path for candidate components.
* @param basePackage the package to check for annotated classes
* @return a corresponding Set of autodetected bean definitions
*/
public Set<BeanDefinition> findCandidateComponents(String basePackage) {
if (this.componentsIndex != null && indexSupportsIncludeFilters()) {
return addCandidateComponentsFromIndex(this.componentsIndex, basePackage);
}
else {
return scanCandidateComponents(basePackage);
}
}
/**
* Determine if the component index can be used by this instance.
* @return {@code true} if the index is available and the configuration of this
* instance is supported by it, {@code false} otherwise
* @since 5.0
*/
private boolean indexSupportsIncludeFilters() {
for (TypeFilter includeFilter : this.includeFilters) {
if (!indexSupportsIncludeFilter(includeFilter)) {
return false;
}
}
return true;
}
/**
* Determine if the specified include {@link TypeFilter} is supported by the index.
* @param filter the filter to check
* @return whether the index supports this include filter
* @since 5.0
* @see #extractStereotype(TypeFilter)
*/
private boolean indexSupportsIncludeFilter(TypeFilter filter) {
if (filter instanceof AnnotationTypeFilter annotationTypeFilter) {
Class<? extends Annotation> annotationType = annotationTypeFilter.getAnnotationType();
return (AnnotationUtils.isAnnotationDeclaredLocally(Indexed.class, annotationType) ||
annotationType.getName().startsWith("jakarta.") ||
annotationType.getName().startsWith("javax."));
}
if (filter instanceof AssignableTypeFilter assignableTypeFilter) {
Class<?> target = assignableTypeFilter.getTargetType();
return AnnotationUtils.isAnnotationDeclaredLocally(Indexed.class, target);
}
return false;
}
/**
* Extract the stereotype to use for the specified compatible filter.
* @param filter the filter to handle
* @return the stereotype in the index matching this filter
* @since 5.0
* @see #indexSupportsIncludeFilter(TypeFilter)
*/
@Nullable
private String extractStereotype(TypeFilter filter) {
if (filter instanceof AnnotationTypeFilter annotationTypeFilter) {
return annotationTypeFilter.getAnnotationType().getName();
}
if (filter instanceof AssignableTypeFilter assignableTypeFilter) {
return assignableTypeFilter.getTargetType().getName();
}
return null;
}
private Set<BeanDefinition> addCandidateComponentsFromIndex(CandidateComponentsIndex index, String basePackage) {
Set<BeanDefinition> candidates = new LinkedHashSet<>();
try {
Set<String> types = new HashSet<>();
for (TypeFilter filter : this.includeFilters) {
String stereotype = extractStereotype(filter);
if (stereotype == null) {
throw new IllegalArgumentException("Failed to extract stereotype from " + filter);
}
types.addAll(index.getCandidateTypes(basePackage, stereotype));
}
boolean traceEnabled = logger.isTraceEnabled();
boolean debugEnabled = logger.isDebugEnabled();
for (String type : types) {
MetadataReader metadataReader = getMetadataReaderFactory().getMetadataReader(type);
if (isCandidateComponent(metadataReader)) {
ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);
sbd.setSource(metadataReader.getResource());
if (isCandidateComponent(sbd)) {
if (debugEnabled) {
logger.debug("Using candidate component class from index: " + type);
}
candidates.add(sbd);
}
else {
if (debugEnabled) {
logger.debug("Ignored because not a concrete top-level class: " + type);
}
}
}
else {
if (traceEnabled) {
logger.trace("Ignored because matching an exclude filter: " + type);
}
}
}
}
catch (IOException ex) {
throw new BeanDefinitionStoreException("I/O failure during classpath scanning", ex);
}
return candidates;
}
private Set<BeanDefinition> scanCandidateComponents(String basePackage) {
Set<BeanDefinition> candidates = new LinkedHashSet<>();
try {
String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
resolveBasePackage(basePackage) + '/' + this.resourcePattern;
Resource[] resources = getResourcePatternResolver().getResources(packageSearchPath);
boolean traceEnabled = logger.isTraceEnabled();
boolean debugEnabled = logger.isDebugEnabled();
for (Resource resource : resources) {
String filename = resource.getFilename();
if (filename != null && filename.contains(ClassUtils.CGLIB_CLASS_SEPARATOR)) {
// Ignore CGLIB-generated classes in the classpath
continue;
}
if (traceEnabled) {
logger.trace("Scanning " + resource);
}
try {
MetadataReader metadataReader = getMetadataReaderFactory().getMetadataReader(resource);
if (isCandidateComponent(metadataReader)) {
ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);
sbd.setSource(resource);
if (isCandidateComponent(sbd)) {
if (debugEnabled) {
logger.debug("Identified candidate component class: " + resource);
}
candidates.add(sbd);
}
else {
if (debugEnabled) {
logger.debug("Ignored because not a concrete top-level class: " + resource);
}
}
}
else {
if (traceEnabled) {
logger.trace("Ignored because not matching any filter: " + resource);
}
}
}
catch (FileNotFoundException ex) {
if (traceEnabled) {
logger.trace("Ignored non-readable " + resource + ": " + ex.getMessage());
}
}
catch (Throwable ex) {
throw new BeanDefinitionStoreException(
"Failed to read candidate component class: " + resource, ex);
}
}
}
catch (IOException ex) {
throw new BeanDefinitionStoreException("I/O failure during classpath scanning", ex);
}
return candidates;
}
/**
* Resolve the specified base package into a pattern specification for
* the package search path.
* <p>The default implementation resolves placeholders against system properties,
* and converts a "."-based package path to a "/"-based resource path.
* @param basePackage the base package as specified by the user
* @return the pattern specification to be used for package searching
*/
protected String resolveBasePackage(String basePackage) {
return ClassUtils.convertClassNameToResourcePath(getEnvironment().resolveRequiredPlaceholders(basePackage));
}
/**
* Determine whether the given class does not match any exclude filter
* and does match at least one include filter.
* @param metadataReader the ASM ClassReader for the class
* @return whether the class qualifies as a candidate component
*/
protected boolean isCandidateComponent(MetadataReader metadataReader) throws IOException {
for (TypeFilter tf : this.excludeFilters) {
if (tf.match(metadataReader, getMetadataReaderFactory())) {
return false;
}
}
for (TypeFilter tf : this.includeFilters) {
if (tf.match(metadataReader, getMetadataReaderFactory())) {
return isConditionMatch(metadataReader);
}
}
return false;
}
/**
* Determine whether the given class is a candidate component based on any
* {@code @Conditional} annotations.
* @param metadataReader the ASM ClassReader for the class
* @return whether the class qualifies as a candidate component
*/
private boolean isConditionMatch(MetadataReader metadataReader) {
if (this.conditionEvaluator == null) {
this.conditionEvaluator =
new ConditionEvaluator(getRegistry(), this.environment, this.resourcePatternResolver);
}
return !this.conditionEvaluator.shouldSkip(metadataReader.getAnnotationMetadata());
}
/**
* Determine whether the given bean definition qualifies as candidate.
* <p>The default implementation checks whether the class is not an interface
* and not dependent on an enclosing class.
* <p>Can be overridden in subclasses.
* @param beanDefinition the bean definition to check
* @return whether the bean definition qualifies as a candidate component
*/
protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
AnnotationMetadata metadata = beanDefinition.getMetadata();
return (metadata.isIndependent() && (metadata.isConcrete() ||
(metadata.isAbstract() && metadata.hasAnnotatedMethods(Lookup.class.getName()))));
}
/**
* Clear the local metadata cache, if any, removing all cached class metadata.
*/
public void clearCache() {
if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory cmrf) {
// Clear cache in externally provided MetadataReaderFactory; this is a no-op
// for a shared cache since it'll be cleared by the ApplicationContext.
cmrf.clearCache();
}
}
}
|
package chap11.y;
import chap11.x.Maruyama;
class Ishizaki {
void func(Maruyama m){
m.maru1(); // OK! (publicしか呼べません)
// m.maru2(); // ERROR! (proteced 呼べない)
// m.maru3(); // ERROR! (default 呼べない)
// m.maru4(); // ERROR! (private 呼べない)
}
}
|
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
public class testFlipAndInvertImageTest {
@Test
public void testFlipAndInvertImageTest(){
FlipAndInvertImage flipAndInvertImage
= new FlipAndInvertImage();
assertThat(flipAndInvertImage.flipAndInvertImage(
new int[][]{{1,1,0},{1,0,1},{0,0,0}}),
is(equalTo(new int[] {{0,0,1},{0,1,0},{1,1,1}})));
}
//Input: [[1,1,0],[1,0,1],[0,0,0]]
//Output: [[1,0,0],[0,1,0],[1,1,1]]
} |
package com.company;
public class Main {
public static void main(String[] args) {
MyFloat a = new MyFloat(123320002,3);
MyFloat b = new MyFloat(232400003,3);
a.sub(b);
a.sum(b);
}
}
|
/*
* 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 vectores_ejercicio2;
import javax.swing.JOptionPane;
/**
*
* @author GABRIEL
*/
public class Principal extends javax.swing.JFrame {
/**
* Creates new form Principal
*/
double v[];
public Principal() {
initComponents();
cmdManual.setEnabled(false);
cmdAuto.setEnabled(false);
cmdCalcular.setEnabled(false);
cmdBorrar.setEnabled(false);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
txtLongitud = new javax.swing.JTextField();
jPanel3 = new javax.swing.JPanel();
cmbOperaciones = new javax.swing.JComboBox<>();
jPanel4 = new javax.swing.JPanel();
cmdBorrar = new javax.swing.JButton();
cmdCrear = new javax.swing.JButton();
cmdManual = new javax.swing.JButton();
cmdAuto = new javax.swing.JButton();
cmdCalcular = new javax.swing.JButton();
jPanel5 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
txtVector = new javax.swing.JTextArea();
jPanel6 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
txtResultado = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel1.setText("VECTOR - CANTIDAD DE PARES, IMPARES, y PRIMOS");
jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 20, -1, -1));
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Datos iniciales"));
jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel2.setText("Longitud:");
jPanel2.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 30, -1, -1));
txtLongitud.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txtLongitudKeyTyped(evt);
}
});
jPanel2.add(txtLongitud, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 24, 70, 30));
jPanel1.add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 70, 180, 70));
jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Seleccione una operación:"));
jPanel3.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
cmbOperaciones.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Elementos pares", "Elementos impares", "Elementos primos" }));
jPanel3.add(cmbOperaciones, new org.netbeans.lib.awtextra.AbsoluteConstraints(15, 25, 160, 30));
jPanel1.add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 70, 190, 70));
jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Opciones"));
jPanel4.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
cmdBorrar.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
cmdBorrar.setText("Borrar");
cmdBorrar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmdBorrarActionPerformed(evt);
}
});
jPanel4.add(cmdBorrar, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 230, 130, 30));
cmdCrear.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
cmdCrear.setText("Crear");
cmdCrear.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmdCrearActionPerformed(evt);
}
});
jPanel4.add(cmdCrear, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 30, 130, 30));
cmdManual.setText("Llenado Manual");
cmdManual.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmdManualActionPerformed(evt);
}
});
jPanel4.add(cmdManual, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 70, 130, 30));
cmdAuto.setText("Llenado Autom.");
cmdAuto.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmdAutoActionPerformed(evt);
}
});
jPanel4.add(cmdAuto, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 110, 130, 30));
cmdCalcular.setText("CALCULAR");
cmdCalcular.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmdCalcularActionPerformed(evt);
}
});
jPanel4.add(cmdCalcular, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 150, 130, 30));
jPanel1.add(jPanel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 160, 180, 280));
jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Su vector es:"));
jPanel5.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
txtVector.setEditable(false);
txtVector.setColumns(20);
txtVector.setRows(5);
jScrollPane1.setViewportView(txtVector);
jPanel5.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 20, 170, 100));
jPanel1.add(jPanel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 160, 190, 130));
jPanel6.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "RESULTADO:"));
jPanel6.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
txtResultado.setEditable(false);
txtResultado.setColumns(20);
txtResultado.setRows(5);
jScrollPane2.setViewportView(txtResultado);
jPanel6.add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 20, 170, 100));
jPanel1.add(jPanel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 310, 190, 130));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 462, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 472, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void txtLongitudKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtLongitudKeyTyped
// TODO add your handling code here:
char c = evt.getKeyChar();
if (!Character.isDigit(c)) {
getToolkit().beep();
evt.consume();
}
}//GEN-LAST:event_txtLongitudKeyTyped
private void cmdCrearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdCrearActionPerformed
// TODO add your handling code here:
if (txtLongitud.getText().isEmpty()) {
JOptionPane.showMessageDialog(this, "Campo vacío. Por favor llénelo", "ERROR", JOptionPane.ERROR_MESSAGE);
txtLongitud.requestFocusInWindow();
} else if (Integer.parseInt(txtLongitud.getText()) == 0) {
JOptionPane.showMessageDialog(this, "La longitud no puede ser cero", "ERROR", JOptionPane.ERROR_MESSAGE);
txtLongitud.requestFocusInWindow();
txtLongitud.selectAll();
} else {
int longitud;
longitud = Integer.parseInt(txtLongitud.getText());
v = new double[longitud];
JOptionPane.showMessageDialog(this, "Vector creado satisfactoriamente");
txtLongitud.setEditable(false);
cmdManual.setEnabled(true);
cmdAuto.setEnabled(true);
cmdCrear.setEnabled(false);
cmdCalcular.setEnabled(false);
cmdBorrar.setEnabled(true);
}
}//GEN-LAST:event_cmdCrearActionPerformed
private void cmdBorrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdBorrarActionPerformed
// TODO add your handling code here:
v = null;
txtLongitud.setText("");
txtResultado.setText("");
txtVector.setText("");
txtLongitud.requestFocusInWindow();
cmbOperaciones.setSelectedIndex(0);
txtLongitud.setEditable(true);
cmdCrear.setEnabled(true);
cmdManual.setEnabled(false);
cmdAuto.setEnabled(false);
cmdCalcular.setEnabled(false);
cmdBorrar.setEnabled(false);
}//GEN-LAST:event_cmdBorrarActionPerformed
private void cmdManualActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdManualActionPerformed
// TODO add your handling code here:
double n;
for (int i = 0; i < v.length; i++) {
n = Double.parseDouble(JOptionPane.showInputDialog(this, "Digite el elemento No " + (i + 1)));
v[i] = n;
}
cmdManual.setEnabled(false);
cmdAuto.setEnabled(false);
cmdCalcular.setEnabled(true);
cmdBorrar.setEnabled(true);
for (int i = 0; i < v.length; i++) {
txtVector.append(v[i] + "\n");
}
}//GEN-LAST:event_cmdManualActionPerformed
private void cmdAutoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdAutoActionPerformed
// TODO add your handling code here:
double n;
for (int i = 0; i < v.length; i++) {
n = (int) (Math.random() * 50 + 1);
v[i] = n;
}
cmdManual.setEnabled(false);
cmdAuto.setEnabled(false);
cmdCalcular.setEnabled(true);
cmdBorrar.setEnabled(true);
for (int i = 0; i < v.length; i++) {
txtVector.append(v[i] + "\n");
}
}//GEN-LAST:event_cmdAutoActionPerformed
private void cmdCalcularActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdCalcularActionPerformed
// TODO add your handling code here:
int op, contPar = 0, contImpar = 0, contDiv, contPrimos = 0;
op = cmbOperaciones.getSelectedIndex();
switch (op) {
case 0:
for (int i = 0; i < v.length; i++) {
if (v[i] % 2 == 0) {
contPar = contPar + 1;
}
}
txtResultado.setText("Hay " +contPar+ " elemento(s) par(es)");
break;
case 1:
for (int i = 0; i < v.length; i++) {
if (v[i] % 2 != 0) {
contImpar = contImpar + 1;
}
}
txtResultado.setText("Hay " +contImpar+ " elemento(s) impar(es)");
break;
case 2:
for (int i = 0; i < v.length; i++) {
contDiv = 0;
for (int j = 1; j <= v[i]; j++) {
if (v[i] % j == 0){
contDiv = contDiv + 1;
}
}
if (contDiv == 2){
contPrimos = contPrimos + 1;
}
}
txtResultado.setText("Hay " +contPrimos+ " elemento(s) primo(s)");
break;
}
}//GEN-LAST:event_cmdCalcularActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Principal().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JComboBox<String> cmbOperaciones;
private javax.swing.JButton cmdAuto;
private javax.swing.JButton cmdBorrar;
private javax.swing.JButton cmdCalcular;
private javax.swing.JButton cmdCrear;
private javax.swing.JButton cmdManual;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextField txtLongitud;
private javax.swing.JTextArea txtResultado;
private javax.swing.JTextArea txtVector;
// End of variables declaration//GEN-END:variables
}
|
import java.util.LinkedList;
// This class has a list, producer (adds items to list
// and the consumer (removes items).
public class ConsumerProducer
{
// Create a list shared by producer and consumer
// Size of list is 2
LinkedList<Integer> list = new LinkedList<Integer>();
int capacity = 2;
// Function called by the producer thread in
//cons_prod_multhread class
public void produce() throws InterruptedException
{
int value = 0;
while (true)
{
//no more than one thread can access the code
//inside this block (synchonized)
synchronized (this)
{
// the producer thread waits while list
// is full
while (list.size()==capacity)
wait();
System.out.println("The Producer produced-"
+ value);
// insert the jobs in the list
list.add(value++);
// notifies the consumer thread that
// now it can start consuming
notify();
// so you can see what the program is doing
// and not printed everything at once
Thread.sleep(1000);
}
}
}
// Function called by the consumer thread
public void consume() throws InterruptedException
{
while (true)
{
synchronized (this)
{
// consumer thread waits while list
// is empty
while (list.size()==0)
wait();
//to consume the first job in the list
int val = list.removeFirst();
System.out.println("The Consumer consumed-"
+ val);
// Wake up the producer thread
notify();
// and sleep like in the produce() function
Thread.sleep(1000);
}
}
}
} |
package tree;
import java.util.ArrayList;
import java.util.List;
/**
* 95. 不同的二叉搜索树 II
*
* 给定一个整数 n,生成所有由 1 ... n 为节点所组成的 二叉搜索树 。
*/
public class C95 {
public static void main(String[] args) {
int n = 3;
Solution_1 solution = new Solution_1();
List<TreeNode> res = solution.generateTrees(n);
for (TreeNode i : res) {
System.out.println(i);
}
}
/** 递归 */
static class Solution_1 {
public List<TreeNode> generateTrees(int n) {
if (n == 0) {
return new ArrayList<TreeNode>();
}
return generateTree(1, n);
}
public List<TreeNode> generateTree(int start, int end) {
List<TreeNode> allTrees = new ArrayList<TreeNode>();
if (start > end) {
allTrees.add(null);
return allTrees;
}
for (int i = start; i <= end; i++) {
List<TreeNode> node_l = generateTree(start, i - 1);
List<TreeNode> node_r = generateTree(i + 1, end);
for (TreeNode ll : node_l) {
for (TreeNode rr : node_r) {
TreeNode cur = new TreeNode(i);
cur.left = ll;
cur.right = rr;
allTrees.add(cur);
}
}
}
return allTrees;
}
}
}
|
package rabbitmq.mq;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import rabbitmq.mq.entity.ContractRabbitmq;
import rabbitmq.mq.entity.TenantRabbitmq;
import rabbitmq.mq.producer.ContractRabbitmqService;
@RestController
@RequestMapping(value = "/rabbitmq")
public class RabbitMqController{
@Autowired
private ContractRabbitmqService contractRabbitmqService;
@RequestMapping(value = "contract/direct", method = RequestMethod.GET)
public void contractDirect(String content) {
ContractRabbitmq contract = new ContractRabbitmq();
contract.setDateCreated(new Date());
contract.setId(12L);
contract.setName("liuhan");
List<String> strList = new ArrayList<>();
strList.add("liu");
strList.add("test str");
contract.setTestStrList(strList);
contractRabbitmqService.sendContractRabbitmqDirect(contract);
}
@RequestMapping(value = "contract/topic", method = RequestMethod.GET)
public void contractTopic(String content) {
ContractRabbitmq contract = new ContractRabbitmq();
contract.setDateCreated(new Date());
contract.setId(12L);
contract.setName("liuhan");
List<String> strList = new ArrayList<>();
strList.add("liu");
strList.add("test str");
contract.setTestStrList(strList);
contractRabbitmqService.sendContractRabbitmqTopic(contract);
}
@RequestMapping(value = "tenant/direct", method = RequestMethod.GET)
public void tenantDirect(String content) {
TenantRabbitmq tenant = new TenantRabbitmq();
tenant.setId(12L);
tenant.setName("liuhan");
contractRabbitmqService.sendTenantRabbitmqDirect(tenant);
}
@RequestMapping(value = "tenant/topic", method = RequestMethod.GET)
public void tenantTopic(String content) {
TenantRabbitmq tenant = new TenantRabbitmq();
tenant.setId(12L);
tenant.setName("liuhan");
contractRabbitmqService.sendTenantRabbitmqTopic(tenant);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.