text stringlengths 10 2.72M |
|---|
package com.legado.grupo.dao;
// librerias
import com.legado.grupo.dao.I.Crud;
import com.legado.grupo.dao.I.GrupoRepositorio;
import com.legado.grupo.dom.Asignatura;
import com.legado.grupo.dom.Grupo;
import com.legado.grupo.dom.Periodo;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
// fin librerias
@Repository
public class GrupoDAO implements Crud<Grupo> {
//instancia repositorio
@Autowired
private GrupoRepositorio repositorio;
//Agregar grupo a base de datos
public void agregar(Grupo grupo, Asignatura asignatura, Periodo periodo) throws Exception {
//control de campos repetidos
if (asignatura == null) {//control de asignaturas
throw new Exception("No se ha indicado la asignatura del grupo " + grupo.getNombre());
}
if (periodo == null) {//control de periodos
throw new Exception("No se ha indicado el periodo del grupo " + grupo.getNombre());
}
if (existe(grupo, asignatura, periodo)) {//control de grupo + periodo
throw new Exception("Ya existe un grupo " + grupo.getNombre() + " para la asignatura " + asignatura.getNombre() + " en el período " + periodo.getFechaInicio() + "!.");
}
//fin control de campos repetidos
//Bidireccional: Un Grupo tiene una Asinatura
grupo.setAsignatura(asignatura);
asignatura.addGrupo(grupo);
//Bidireccional: Un Grupo tiene un periodo
grupo.setPeriodo(periodo);
periodo.addGrupo(grupo);
repositorio.save(grupo);//guardamos el grupo en la base de datos
}
@Override
public Grupo buscarPorID(int id) {
return repositorio.findOne(id);//devuelve el grupo mediante el id de grupo
}
public Grupo buscarPorNombre(String nombre) {
return repositorio.findByNombre(nombre);//devuelve el grupo mediante el nombre del grupo
}
@Override
public void actualizar(Grupo o) {
repositorio.save(o);//actualiza el grupo
//guarda el grupo enviado por parametro
}
//elimina el grupo mediante el id enviado por parametro
@Override
public void eliminarPorId(int id) {
if (existe(id)) {
repositorio.delete(id);
}
}
//borra todos los grupos existente de la base de datos
@Override
public void eliminarTodo() {
repositorio.deleteAll();
}
//devuelve un listado de los grupos existentes
@Override
public List<Grupo> listar() {
return (List<Grupo>) repositorio.findAll();
}
//en caso de existir un grupo devolvera el valor de verdadero
@Override
public boolean existe(int id) {
return repositorio.exists(id);
}
//en caso de existir un grupo devolvera el valor de verdadero
private boolean existe(Grupo grupo, Asignatura asignatura, Periodo periodo) {
for (Grupo g : asignatura.getGrupos()) {
if (g.getNombre().equals(grupo.getNombre()) && g.getPeriodo().getFechaInicio().equals(periodo.getFechaInicio())) {
return true;//devuelve verdadero si existen coincidencias en la base de datos en la tabla grupo
}
}
return false;//devuelve falso si no encuentra coincidencias en la base de datos en la tabla grupo
}
}
|
package org.sermig.sermigapp.activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import org.sermig.sermigapp.R;
public class GestioneEventiActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gestione_eventi);
initButtonLinks();
}
public Button nuovo;
public void initButtonLinks() {
nuovo = (Button) findViewById(R.id.Bottone_nuovo_GestioneEventi);
nuovo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent nuovoIntent = new Intent(GestioneEventiActivity.this, NuovoActivity.class);
GestioneEventiActivity.this.startActivity(nuovoIntent);
}
});
}
}
|
package com.contentstack.sdk;
import com.contentstack.sdk.utilities.CSAppUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
public class SyncStack {
private static final String TAG = SyncStack.class.getSimpleName();
private JSONObject receiveJson;
private int skip;
private int limit;
private int count;
private String URL;
private String pagination_token;
private String sync_token;
private ArrayList<JSONObject> syncItems;
public String getURL() { return this.URL; }
public JSONObject getJSONResponse(){ return this.receiveJson; }
public int getCount() {
return this.count;
}
public int getLimit() {
return this.limit;
}
public int getSkip() {
return this.skip;
}
public String getPaginationToken(){ return this.pagination_token; }
public String getSyncToken(){
return this.sync_token;
}
public ArrayList<JSONObject> getItems() { return this.syncItems; }
protected void setJSON(JSONObject jsonobject) {
if (jsonobject != null){
receiveJson = jsonobject;
try{
if(receiveJson != null){
URL = "";
if(receiveJson.has("items")) {
JSONArray jsonarray = receiveJson.getJSONArray("items");
if (jsonarray != null) {
syncItems = new ArrayList<>();
for (int position = 0; position < jsonarray.length(); position++){
syncItems.add(jsonarray.optJSONObject(position));
}
}
}
if(receiveJson.has("skip")){
this.skip = receiveJson.optInt("skip");
}
if(receiveJson.has("total_count")){
this.count = receiveJson.optInt("total_count");
}
if(receiveJson.has("limit")){
this.limit = receiveJson.optInt("limit");
}
if (receiveJson.has("pagination_token")){
this.pagination_token = receiveJson.optString("pagination_token");
}else {
this.sync_token = null;
}
if (receiveJson.has("sync_token")){
this.sync_token = receiveJson.optString("sync_token");
}else {
this.sync_token = null;
}
}
}catch(Exception e){
CSAppUtils.showLog(TAG, "---------QueryResult--setJSON--"+e.toString());
}
}
}
}
|
package com.capgemini.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.capgemini.entity.AssociatePersonal;
@Repository
public interface AssociateRepository extends JpaRepository<AssociatePersonal, Integer>
{
}
|
package com.citibank.ods.persistence.pl.dao.rdb.oracle;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.citibank.ods.common.connection.rdb.ManagedRdbConnection;
import com.citibank.ods.common.dataset.DataSet;
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.entity.bg.BaseTbgSegmentEntity;
import com.citibank.ods.entity.bg.TbgSegmentEntity;
import com.citibank.ods.entity.pl.TbgOfficerEntity;
import com.citibank.ods.persistence.pl.dao.TbgSegmentDAO;
import com.citibank.ods.persistence.pl.dao.rdb.oracle.factory.OracleODSDAOFactory;
import com.citibank.ods.persistence.util.CitiStatement;
//
//©2002-2007 Accenture. All rights reserved.
//
/**
* [Class description]
*
* @see package com.citibank.ods.persistence.pl.dao.rdb.oracle;
* @version 1.0
* @author acacio.domingos,Apr 24, 2007
*
* <PRE>
*
* <U>Updated by: </U> <U>Description: </U>
*
* </PRE>
*/
public class OracleTbgSegmentDAO extends BaseOracleTbgSegmentDAO implements
TbgSegmentDAO
{
private static final String C_TBG_SEGMENT = C_BG_SCHEMA + "TBG_SEGMENT";
/*
* (non-Javadoc)
* @see com.citibank.ods.persistence.pl.dao.TbgSegmentDAO#update(com.citibank.ods.entity.bg.TbgSegmentEntity)
*/
public void update( TbgSegmentEntity segmentEntity_ )
{
/**
* "[Method description]"
*
* @param
* @return
* @exception
* @see
*/
}
/*
* (non-Javadoc)
* @see com.citibank.ods.persistence.pl.dao.TbgSegmentDAO#delete(com.citibank.ods.entity.bg.TbgSegmentEntity)
*/
public void delete( TbgSegmentEntity segmentEntity_ )
{
/**
* "[Method description]"
*
* @param
* @return
* @exception
* @see
*/
}
/*
* (non-Javadoc)
* @see com.citibank.ods.persistence.pl.dao.TbgSegmentDAO#insert(com.citibank.ods.entity.bg.TbgSegmentEntity)
*/
public TbgOfficerEntity insert( TbgSegmentEntity segmentEntity_ )
{
/**
* "[Method description]"
*
* @param
* @return
* @exception
* @see
*/
return null;
}
/*
* (non-Javadoc)
* @see com.citibank.ods.persistence.pl.dao.TbgSegmentDAO#list(java.lang.String)
*/
public DataSet list( String segNameCode_ )
{
/**
* "[Method description]"
*
* @param
* @return
* @exception
* @see
*/
return null;
}
/*
* (non-Javadoc)
* @see com.citibank.ods.persistence.pl.dao.TbgSegmentDAO#exists(com.citibank.ods.entity.bg.TbgSegmentEntity)
*/
public boolean exists( TbgSegmentEntity segmentEntity_ )
{
/**
* "[Method description]"
*
* @param
* @return
* @exception
* @see
*/
return false;
}
/*
* (non-Javadoc)
* @see com.citibank.ods.persistence.pl.dao.TbgSegmentDAO#loadDomain(com.citibank.ods.entity.bg.TbgSegmentEntity)
*/
public DataSet loadDomain()
{
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( " TRIM( " + C_SEG_NAME_CODE + ") AS " + C_SEG_NAME_CODE
+ ", " );
query.append( C_SEG_NAME_TEXT );
query.append( " FROM " );
query.append( C_TBG_SEGMENT );
preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() ));
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;
}
/*
* (non-Javadoc)
* @see com.citibank.ods.persistence.pl.dao.BaseTbgSegmentDAO#find(com.citibank.ods.entity.bg.BaseTbgSegmentEntity)
*/
public BaseTbgSegmentEntity find( BaseTbgSegmentEntity segmentEntity_ )
{
/**
* "[Method description]"
*
* @param
* @return
* @exception
* @see
*/
return null;
}
} |
package ru.otus.sua.L11.entity;
import lombok.*;
import javax.persistence.*;
import java.util.List;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString(callSuper = true)
@Entity
@Table(name = "users")
public class UserDataSet extends DataSet {
@Basic
private String name;
@Basic
private int age;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "user")
private List<PhoneDataSet> phones;
@OneToOne(optional = false, cascade = CascadeType.ALL, mappedBy = "user")
@JoinColumn(name = "address_id")
private AddressDataSet address;
}
|
package org.giddap.dreamfactory.mitbbs.google;
/**
* [google面试题] API流量控制
* <p/>
* Implement rate limiting for an API so that we rate limit if the same
* developer makes > 10K req/sec. What would the logic be? What would the
* structure be? Where would you store this structure?
* <p/>
* http://en.wikipedia.org/wiki/Leaky_bucket
* http://stackoverflow.com/questions/1407113/throttling-method-calls-to-m-requests-in-n-seconds
*/
public class ApiRequestRateLimit {
}
|
//package com.vivek.sampleapp.networktask;
//
//import com.android.volley.Request;
//import com.android.volley.Response;
//import com.google.gson.reflect.TypeToken;
//import com.vivek.sampleapp.basetask.BaseNetworkTask;
//import com.vivek.sampleapp.modal.StaffInformation;
//import com.vivek.sampleapp.volley.VolleyRequest;
//import com.vivek.sampleapp.volley.VolleyRequestQueue;
//
//import java.lang.reflect.Type;
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
///**
// * Created by v.vekariya on 12/9/2015.
// */
//public class FetchStaff extends BaseNetworkTask<List<StaffInformation>> {
// public FetchStaff() {
// super();
// }
//
// public FetchStaff(Response.Listener<List<StaffInformation>> successListener) {
// super(Request.Method.POST, successListener);
// Type listType = new TypeToken<ArrayList<StaffInformation>>() {
// }.getType();
// super.setResponseClassType(listType);
// }
//
// @Override
// public void executeNetworkRequest(int type, String uri, Map<String, String> header, Map<String, String> params, Type clazz, Response.Listener succListener, Response.ErrorListener errorListener) {
// VolleyRequestQueue.getInstance().getRequestQueue().add(
// new VolleyRequest<List<StaffInformation>>(type, uri, getRequestBody(), header, params, clazz, succListener, errorListener));
// }
//
// @Override
// public String provideUri() {
// return "http://107.110.77.237/ipdweb/patient/get_staff";
// }
//
// @Override
// public Map<String, String> provideHeader(int type) {
// return null;
// }
//
// @Override
// public Map<String, String> getParams() {
// Map<String, String> params = new HashMap<>();
// params.put("patient_id", "p101");
// return params;
// }
//
// @Override
// public String getRequestBody() {
// return null;
// }
//}
|
package c.c.quadraticfunction.solvers;
import java.util.ArrayList;
import java.util.List;
/**
* Klasa rozwiązująca równania liniowe
*/
public class Linear implements PolynomialEquation {
private double a,b;
Linear(double b, double a) {
this.a = a;
this.b = b;
}
/**
* Funkcja do obliczania rozwiązania równania liniowego
* @return Wyniki w List≤Double≥
* @throws Exception
*/
@Override
public List<Double> compute() throws Exception{
if(a == 0){ // równanie 0 stopnia
if(b == 0) { // wyraz wolny = 0
throw new Exception("InconsistentEquationException"); // równanie nieoznaczone
}
throw new Exception("NoSolutionException"); // równanie sprzeczne
}
List<Double> results = new ArrayList<>(1);
results.add((0-b)/a);
return results;
}
}
|
package org.jetlang.remote.example.chat;
import org.jetlang.core.Callback;
import org.jetlang.core.SynchronousDisposingExecutor;
import org.jetlang.fibers.ThreadFiber;
import org.jetlang.remote.client.CloseEvent;
import org.jetlang.remote.client.ConnectEvent;
import org.jetlang.remote.client.JetlangClientConfig;
import org.jetlang.remote.client.JetlangTcpClient;
import org.jetlang.remote.client.SocketConnector;
import org.jetlang.remote.core.ByteMessageWriter;
import org.jetlang.remote.core.ErrorHandler;
import org.jetlang.remote.core.ObjectByteReader;
import org.jetlang.remote.core.ObjectByteWriter;
import org.jetlang.remote.core.Serializer;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
* User: mrettig
* Date: 4/26/11
* Time: 4:00 PM
*/
public class LatencyPing {
private static volatile CountDownLatch latch;
public static void main(String[] args) throws InterruptedException {
String host = "localhost";
int port = 8081;
if (args.length >= 2) {
host = args[0];
port = Integer.parseInt(args[1]);
}
final int iteration = 50000;
System.out.println("iterations = " + iteration);
latch = new CountDownLatch(1);
SocketConnector conn = new SocketConnector(host, port);
JetlangClientConfig clientConfig = new JetlangClientConfig();
JetlangTcpClient tcpClient = new JetlangTcpClient(conn, new ThreadFiber(), clientConfig, new LongSerializer(), new ErrorHandler.SysOut());
SynchronousDisposingExecutor executor = new SynchronousDisposingExecutor();
tcpClient.getConnectChannel().subscribe(executor, Client.<ConnectEvent>print("Connect"));
tcpClient.getCloseChannel().subscribe(executor, Client.<CloseEvent>print("Closed"));
tcpClient.start();
Callback<Long> onMsg = new Callback<Long>() {
int count = 0;
long latency = 0;
long min = Long.MAX_VALUE;
long max = 0;
public void onMessage(Long message) {
long duration = System.nanoTime() - message;
min = Math.min(duration, min);
max = Math.max(duration, max);
count++;
latency+= duration;
if(count == iteration){
System.out.println("Min: " + min + " Max: " + max);
System.out.println("Count: " + count);
System.out.println("AvgNanos: " + (latency/count));
latch.countDown();
}
}
};
tcpClient.subscribe("t", new SynchronousDisposingExecutor(), onMsg);
int sleepTime = 1;
for (int i = 0; i < iteration; i++) {
tcpClient.publish("t", System.nanoTime());
Thread.sleep(sleepTime);
}
System.out.println("executor = " + latch.await(10, TimeUnit.SECONDS));
tcpClient.close(true).await(1, TimeUnit.SECONDS);
}
public static class LongSerializer implements Serializer<Long, Long> {
public ObjectByteWriter<Long> getWriter() {
return new ObjectByteWriter<Long>() {
byte[] bytes = new byte[8];
ByteBuffer buffer = ByteBuffer.wrap(bytes);
public void write(String topic, Long msg, ByteMessageWriter writer) {
buffer.clear();
buffer.putLong(msg);
writer.writeObjectAsBytes(bytes, 0, bytes.length);
}
};
}
public ObjectByteReader<Long> getReader() {
return new ObjectByteReader<Long>() {
public Long readObject(String fromTopic, byte[] buffer, int offset, int length) {
final ByteBuffer wrap = ByteBuffer.wrap(buffer);
if(offset > 0){
wrap.position(offset);
}
return wrap.getLong();
}
};
}
}
}
|
package com.fhate.studyhelper.ui;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import com.fhate.studyhelper.R;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
import butterknife.BindView;
import butterknife.ButterKnife;
public class VideoActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
private Context context;
private String link;
private final String apiKey = "AIzaSyBnjKKzRYVi2eyTG3sxE48kN2Z8FinWwvQ";
@BindView(R.id.videoView)
YouTubePlayerView videoView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
ButterKnife.bind(this);
context = this;
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
link = bundle.getString("link");
}
videoView.initialize(apiKey, this);
}
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
if (!b) youTubePlayer.cueVideo(link);
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
}
|
package de.varylab.discreteconformal.unwrapper;
import java.awt.Color;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.junit.Ignore;
import org.junit.Test;
import de.jreality.math.Rn;
import de.jreality.plugin.JRViewer;
import de.jreality.reader.Readers;
import de.jreality.scene.Appearance;
import de.jreality.scene.IndexedFaceSet;
import de.jreality.scene.SceneGraphComponent;
import de.jreality.scene.data.Attribute;
import de.jreality.shader.CommonAttributes;
import de.jreality.util.Input;
import de.jreality.util.NativePathUtility;
import de.jreality.util.SceneGraphUtility;
public class TwoHoleExample {
static {
NativePathUtility.set("native");
}
static double rt = Math.PI/2,
triangleArea = .005;
static boolean letter = true, doholes = true, originalAngles = false;
@Test@Ignore
public void testLetterB() {
SceneGraphComponent triangulation = null;
try {
triangulation = Readers.read(new Input(EuclideanUnwrapProblem.class.getResource("letterB-TA01.off")));
} catch (IOException e) {
e.printStackTrace();
}
IndexedFaceSet triang2 = (IndexedFaceSet) SceneGraphUtility.getFirstGeometry(triangulation);
SceneGraphComponent origSgc = SceneGraphUtility.createFullSceneGraphComponent("sgc");
origSgc.setGeometry(triang2);
Appearance ap = origSgc.getAppearance();
ap.setAttribute("polygonShader.diffuseColor", Color.white);
ap.setAttribute(CommonAttributes.FACE_DRAW, false);
ap.setAttribute(CommonAttributes.EDGE_DRAW, true);
ap.setAttribute(CommonAttributes.VERTEX_DRAW, false);
HashMap<Integer, Double> indexToAngle = new HashMap<Integer, Double>();
int[] inds = new int[]{0,5,45,47};
for (int i = 0; i<inds.length; ++i) {
indexToAngle.put(inds[i], Math.PI/2);
}
List<Integer> holes = new ArrayList<Integer>();
if (doholes) {
holes.add(51);
holes.add(80);
}
try {
EuclideanUnwrapperPETSc.unwrapcg(triang2, 1, indexToAngle, doholes ? holes : null, 1E-4);
double[][] tv = triang2.getVertexAttributes(Attribute.TEXTURE_COORDINATES).toDoubleArrayArray(null);
System.err.println("unwrapped verts = "+Rn.toString(tv));
triang2.setVertexAttributes(Attribute.COORDINATES, null);
triang2.setVertexAttributes(Attribute.COORDINATES, triang2.getVertexAttributes(Attribute.TEXTURE_COORDINATES));
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
JRViewer.display(origSgc);
}
}
|
/*
* throw_JIF.java
*
* Created on __DATE__, __TIME__
*/
package zzt.view;
import global.dao.Fileselection;
import global.dao.Majoraccess;
import global.model.Major;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import zxx.dao.PrintObjectExcel;
/**
*
* @author __USER__
*/
public class throw_JIF extends javax.swing.JInternalFrame {
/** Creates new form throw_JIF */
public throw_JIF() {
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.
*/
//GEN-BEGIN:initComponents
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton1 = new javax.swing.JButton();
jButton1.setText("\u5bfc\u51fa\u9519\u8bef\u5230excel\u8868\u4e2d");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
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(117, 117, 117)
.addComponent(jButton1)
.addContainerGap(133, Short.MAX_VALUE)));
layout.setVerticalGroup(layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING).addGroup(
javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addContainerGap(496, Short.MAX_VALUE)
.addComponent(jButton1,
javax.swing.GroupLayout.PREFERRED_SIZE, 45,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap()));
pack();
}// </editor-fold>
//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
// TODO add your handling code here:
// TODO add your handling code here:
//调用导出方法把文件的路径存放在tabletwo变量里
File Filename = Fileselection.exportselect();
File filenametow = new File(Filename + ".xls");
String filetable = filenametow.toString();
// System.out.println(Filename+".xls");
String o_id = null;
//实例化部门列表,把部门信息存放在calist变量中
List<Major> caList = Majoraccess.getMajor(o_id);
List<Major> list = new ArrayList<Major>();
//设置excel表头信息
String[] header = { "错误信息" };
// File Filename =new File() ;
// System.out.println(Filename);
//
JFileChooser fDialog = new JFileChooser();
if (Filename == null) {
// System.out.println("文件名为null");
return;
}
//怎么拿到导出之后的文件名
if (filenametow.exists()) {
System.out.println(filenametow.exists());
int overwriteSelect = JOptionPane.showConfirmDialog(this,
"<html><font size=3>文件" + filenametow.getName()
+ "已存在,是否覆盖?</font><html>", "是否覆盖?",
JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
System.out.println(overwriteSelect);
if (overwriteSelect == JOptionPane.YES_OPTION) {
List<String> aList = PrintObjectExcel.printExcel(caList,
filetable, header);
if (aList.size() == 0) {
JOptionPane.showMessageDialog(this, "导出成功", "提示信息",
JOptionPane.INFORMATION_MESSAGE);
} else {
String str = "";
for (String item : aList) {
str += item + "\n";
}
JOptionPane.showMessageDialog(this, str, "错误信息",
JOptionPane.ERROR_MESSAGE);
}
} else {
return;
}
}
List<String> aList = PrintObjectExcel.printExcel(caList, filetable,
header);
if (aList.size() == 0) {
JOptionPane.showMessageDialog(this, "导出成功", "提示信息",
JOptionPane.INFORMATION_MESSAGE);
} else {
String str = "";
for (String item : aList) {
str += item + "\n";
}
JOptionPane.showMessageDialog(this, str, "错误信息",
JOptionPane.ERROR_MESSAGE);
}
}
//GEN-BEGIN:variables
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
// End of variables declaration//GEN-END:variables
public static void CONTENT_PANE_PROPERTY() {
// TODO Auto-generated method stub
}
} |
package ru.pattern.builder.var2;
public class Main {
public static void main(String[] args) {
System.out.println("bulder -> var 2: ");
Account account = new Account.Builder().setUserId("habr").setToken("hello").build();
}
}
|
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int d = in.nextInt();
int[] expenditures = new int[n];
for (int i = 0; i < n; i++) {
expenditures[i] = in.nextInt();
}
System.out.print(fraudulentNotifications(expenditures, d));
in.close();
}
private static long fraudulentNotifications(int[] expenditures, int d) {
int[] counter = new int[201];
int i = 0, j = d;
for (; i < j; i++) {
counter[expenditures[i]] += 1;
}
i = 0;
long notifications = 0;
int medianPosition = (d % 2 != 0) ? (d / 2) + 1 : d / 2;
while (j < expenditures.length) {
double median = getMedian(counter, d, medianPosition);
if (expenditures[j] >= (median * 2)) {
notifications += 1;
}
counter[expenditures[i]] -= 1;
counter[expenditures[j]] += 1;
i++; j++;
}
return notifications;
}
private static double getMedian(int[] countSort, int d, int medianPosition) {
int count = 0, i = 0, j = 0;
for (; count < medianPosition; i++) {
count += countSort[i];
}
j = i;
i -= 1;
if (count > medianPosition || d % 2 != 0)
return i;
for (; countSort[j] == 0; j++);
return (i + j) / 2d;
}
}
|
package WebShop.services;
import java.util.List;
import javax.annotation.security.DeclareRoles;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import WebShop.model.Basket;
import WebShop.model.Comment;
import WebShop.model.Product;
@Stateless
@LocalBean
@PermitAll
public class CommentService extends AbstractService<Comment> {
@PersistenceContext
EntityManager em;
public CommentService() {
super(Comment.class);
}
@Override
protected EntityManager em() {
return em;
}
@PermitAll
public List<Comment> findByProductId(int id) {
List<Comment> comments = em.createQuery("SELECT c FROM Comment c WHERE c.product.id LIKE :id", Comment.class)
.setParameter("id", id).getResultList();
return comments;
}
/*public List<Basket> filterWithUser(String userName){
List<Basket> orders = em.createQuery("SELECT b FROM Basket b WHERE b.clientId LIKE :user", Basket.class)
.setParameter("user", userName).getResultList();
return orders;
}*/
}
|
//package com.union.express.commons.bean.redis.cache;
//
//import org.springframework.stereotype.Component;
//
///**
// * @author linaz
// * @created 2016.08.10 9:17
// */
//@Component
//public class OrgKeySchema extends KeySchema {
//
// private String Table = "org";
//
// private String Name = "name";
//
// public String name(String code){
// return makeKey(Table, code, Name);
// }
//}
|
package com.yunhetong.sdk.base;
/**
*/
public class YhtContractParter {
private int sdkUserId;
private long contractId;
/**
* 能否签名的权限
*/
private boolean sign; //
/**
* 是否能作废权限
*/
private boolean invalid;
/**
* 用户是否含有签名
*/
private boolean hasSign;
public boolean isHasSign() {
return hasSign;
}
public void setHasSign(boolean hasSign) {
this.hasSign = hasSign;
}
public boolean isSign() {
return sign;
}
public void setSign(boolean sign) {
this.sign = sign;
}
public int getSdkUserId() {
return sdkUserId;
}
public void setSdkUserId(int sdkUserId) {
this.sdkUserId = sdkUserId;
}
public long getContractId() {
return contractId;
}
public void setContractId(long contractId) {
this.contractId = contractId;
}
public boolean isInvalid() {
return invalid;
}
public void setInvalid(boolean invalid) {
this.invalid = invalid;
}
}
|
/*
* Copyright 2016 TeddySoft Technology. All rights reserved.
*
*/
package tw.teddysoft.gof.Adapter;
public class Contact extends ConfigObject {
private String email;
public Contact() {
}
public void setEmail(String email){
this.email = email;
}
public String getEmail() {
return email;
}
}
|
package org.giddap.dreamfactory.geeksforgeeks.dynamicprogramming;
/**
* http://www.geeksforgeeks.org/dynamic-programming-set-4-longest-common-subsequence/
*/
public class Set04LongestCommonSubsequence {
}
|
package org.reactome.web.nursa.client.details.tabs.dataset.widgets;
import org.reactome.web.nursa.model.Comparison;
import org.reactome.web.nursa.model.Comparison.Operand;
import org.reactome.web.nursa.model.ComparisonDataPoint;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Widget;
public class ComparisonSections extends DataSetSections {
private static final String OVERVIEW_TITLE = "Compare To:";
private Comparison comparison;
public ComparisonSections(Comparison comparison, EventBus eventBus) {
super(eventBus);
this.comparison = comparison;
}
@Override
protected Widget createOverviewPanel() {
HorizontalPanel overview = new HorizontalPanel();
Operand other = comparison.operands[1];
Widget name = new HTMLPanel(other.dataset.getName());
name.setStyleName("elv-Details-Title-Wrap");
overview.add(name);
Widget doi = new HTMLPanel("DOI: " + other.dataset.getDoi());
doi.setStyleName(DataSetPanel.RESOURCES.getCSS().doi());
overview.add(doi);
Widget exp = new HTMLPanel("Experiment: " + other.experiment.getName());
exp.setStyleName(DataSetPanel.RESOURCES.getCSS().experiment());
overview.add(exp);
return overview;
}
@Override
protected String overviewTitle() {
return OVERVIEW_TITLE;
}
@Override
protected Widget createDataPointsPanel() {
DataPanel<ComparisonDataPoint> panel = new ComparisonDataPointsPanel(comparison);
return panel.asWidget();
}
@Override
protected Widget createAnalysisPanel(EventBus eventBus) {
return new ComparisonAnalysisDisplay(comparison, eventBus);
}
}
|
package com.csc.capturetool.myapplication.http;
import com.csc.capturetool.myapplication.BuildConfig;
/**
* Created by SirdarYangK on 2018/11/2
* des:
*/
public class BaseUrls {
public static final int RELEASE = 0;//正式环境
private static final int DEV = 1;//测试环境
public static final String CSC_BASE_URL = getCscBaseUrl();
public static String getCscBaseUrl() {
switch (BuildConfig.HTTP_TYPE) {
case RELEASE:
return "https://m.csc33.cn";
case DEV:
return "https://mj.7i1.cn/";
default:
return "https://mj.7i1.cn/";
}
}
}
|
package zhangxiangyu.conn;
import java.sql.Connection;
import java.sql.DriverManager;
public class Conn {
public Connection getConnection ()
{
Connection zhangxiangyu_conn=null;
try {
Class.forName("org.gjt.mm.mysql.Driver");
zhangxiangyu_conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/jsp?characterEncoding=utf8", "root", "zxy54321");
}catch (Exception e) {
System.out.println(e);
}
return zhangxiangyu_conn;
}
}
|
package com.stanislavmachel.shop.services;
import com.stanislavmachel.shop.api.v1.mappers.CustomerMapper;
import com.stanislavmachel.shop.api.v1.model.CustomerDto;
import com.stanislavmachel.shop.repositories.CustomerRepository;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
@Service
public class CustomerServiceImpl implements CustomerService {
private final CustomerRepository customerRepository;
private final CustomerMapper customerMapper;
public CustomerServiceImpl(CustomerRepository customerRepository, CustomerMapper customerMapper) {
this.customerRepository = customerRepository;
this.customerMapper = customerMapper;
}
@Override
public List<CustomerDto> getAll() {
return customerRepository.findAll()
.stream()
.map(customerMapper::customerToCustomerDto)
.collect(Collectors.toList());
}
@Override
public CustomerDto getById(UUID id) {
return customerRepository.findById(id)
.map(customerMapper::customerToCustomerDto)
.orElseThrow(() -> new ResourceNotFoundException("Customer with id: " + id + " not found"));
}
@Override
public CustomerDto create(CustomerDto customerDto) {
return customerMapper.customerToCustomerDto(
customerRepository.save(
customerMapper.customerDtoToCustomer(customerDto)));
}
@Override
public CustomerDto update(UUID id, CustomerDto customerDto) {
return customerRepository.findById(id)
.map(customer -> {
customer.setFirstName(customerDto.getFirstName());
customer.setLastName(customerDto.getLastName());
return customerMapper.customerToCustomerDto(customerRepository.save(customer));
}).orElseThrow(() -> new ResourceNotFoundException("Customer with id: " + id + " not exist"));
}
@Override
public CustomerDto patch(UUID id, CustomerDto customerDto) {
return customerRepository.findById(id).map(customer -> {
if (customerDto.getFirstName() != null) {
customer.setFirstName(customerDto.getFirstName());
}
if (customerDto.getLastName() != null) {
customer.setLastName(customerDto.getLastName());
}
return customerMapper.customerToCustomerDto(customerRepository.save(customer));
}).orElseThrow(() -> new ResourceNotFoundException("Customer with id: " + id + " not exist"));
}
@Override
public void deleteById(UUID id) {
customerRepository.deleteById(id);
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.Unipago.Bean;
import Entity.EntidadCiudadano;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.*;
@Stateless
public class SessionBeanCiudadano implements SessionBeanCiudadanoLocal {
private EntityManagerFactory emFactory = null;
private EntityManager entityManaged = null;
private EntityTransaction EntityTransaction;
public SessionBeanCiudadano() {
}
@Override
public boolean AddCiudadano(EntidadCiudadano ciudadano) {
boolean Exito = false;
try {
emFactory = Persistence.createEntityManagerFactory("Ciudadano");
entityManaged = emFactory.createEntityManager();
EntityTransaction = entityManaged.getTransaction();
EntityTransaction.begin();
entityManaged.persist(ciudadano);
entityManaged.getTransaction().commit();
Exito = true;
} catch (Exception ex) {
if (EntityTransaction != null) {
System.out.println("Eror ingresar" + ex.getMessage());
EntityTransaction.rollback();
Exito = false;
}
} finally {
if (emFactory != null) {
emFactory.close();
emFactory = null;
}
if (entityManaged != null) {
entityManaged = null;
}
}
return Exito;
}
@Override
public boolean DeleteCiudadano(int ID) {
boolean Exito = false;
try {
emFactory = Persistence.createEntityManagerFactory("Ciudadano");
entityManaged = emFactory.createEntityManager();
EntityTransaction = entityManaged.getTransaction();
EntityTransaction.begin();
EntidadCiudadano entidaE = entityManaged.find(EntidadCiudadano.class, ID);
entityManaged.remove(entidaE);
EntityTransaction.commit();
Exito = true;
} catch (Exception ex) {
if (EntityTransaction != null) {
System.out.println("Error Eliminar" + ex.getMessage());
EntityTransaction.rollback();
Exito = false;
}
} finally {
if (emFactory != null) {
emFactory.close();
emFactory = null;
}
if (entityManaged != null) {
entityManaged = null;
}
}
return Exito;
}
@Override
public boolean UpdateCiudadano(EntidadCiudadano ciudadano, int ID) {
boolean Exito = false;
try {
emFactory = Persistence.createEntityManagerFactory("Ciudadano");
entityManaged = emFactory.createEntityManager();
EntityTransaction = entityManaged.getTransaction();
EntityTransaction.begin();
EntidadCiudadano ciudadanoUpdate = entityManaged.find(EntidadCiudadano.class, ID);
ciudadanoUpdate.setNombre(ciudadano.getNombre());
ciudadanoUpdate.setApellido(ciudadano.getApellido());
ciudadanoUpdate.setSexo(ciudadano.getSexo());
ciudadanoUpdate.setFecha(ciudadano.getFecha());
ciudadanoUpdate.setDireccion(ciudadano.getDireccion());
ciudadanoUpdate.setCorreo(ciudadano.getCorreo());
ciudadanoUpdate.setTelefono(ciudadano.getTelefono());
EntityTransaction.commit();
Exito = true;
} catch (Exception ex) {
if (EntityTransaction != null) {
System.out.println("Eror ingresar" + ex.getMessage());
EntityTransaction.rollback();
Exito = false;
}
} finally {
if (emFactory != null) {
emFactory.close();
emFactory = null;
}
if (entityManaged != null) {
entityManaged = null;
}
}
return Exito;
}
@Override
public ArrayList<EntidadCiudadano> ListaCiudadanos() {
ArrayList<EntidadCiudadano> ArrayLista = new ArrayList<EntidadCiudadano>();
try {
emFactory = Persistence.createEntityManagerFactory("Ciudadano");
entityManaged = emFactory.createEntityManager();
Query ListTodos = entityManaged.createNamedQuery("Ciudadano.findAll");
List<EntidadCiudadano> lista = ListTodos.getResultList();
ArrayLista.addAll(lista);
} catch (Exception ex) {
System.out.println("Error " + ex.getMessage());
} finally {
if (emFactory != null) {
emFactory.close();
emFactory = null;
}
if (entityManaged != null) {
entityManaged = null;
}
}
return ArrayLista;
}
@Override
public EntidadCiudadano BuscarCiudadano(int ID) {
EntidadCiudadano entity = null;
try{
emFactory = Persistence.createEntityManagerFactory("Ciudadano");
entityManaged = emFactory.createEntityManager();
EntityTransaction = entityManaged.getTransaction();
EntityTransaction.begin();
entity = entityManaged.find(EntidadCiudadano.class, ID);
}catch(Exception ex){
System.out.println("Error " + ex.getMessage());
}finally{
if (emFactory != null) {
emFactory.close();
emFactory = null;
}
if (entityManaged != null) {
entityManaged = null;
}
}
return entity;
}
}
|
/**
* https://www.hackerearth.com/practice/data-structures/trees/binary-search-tree/practice-problems/algorithm/monk-and-his-friends/description/
* #binary-search-tree #map
*/
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class MonkAndFriends {
public static void main(String[] args) throws IOException {
MyScanner sc = new MyScanner(System.in);
OutputStream out = new BufferedOutputStream(System.out);
int t = sc.nextInt();
int n, m;
long tmp;
for (int k = 0; k < t; k++) {
n = sc.nextInt();
m = sc.nextInt();
TreeSet<Long> ts = new TreeSet<>();
for (int i = 0; i < n; i++) {
tmp = sc.nextLong();
ts.add(tmp);
}
for (int i = 0; i < m; i++) {
tmp = sc.nextLong();
if (ts.contains(tmp)) {
out.write("YES \n".getBytes());
} else {
ts.add(tmp);
out.write("NO \n".getBytes());
}
}
out.flush();
}
}
}
class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
|
package fudan.database.project.controller;
import fudan.database.project.entity.ChiefNurse;
import fudan.database.project.entity.Doctor;
import fudan.database.project.entity.EmergencyNurse;
import fudan.database.project.entity.WardNurse;
import fudan.database.project.service.AccountService;
import net.sf.json.JSONObject;
import javax.servlet.RequestDispatcher;
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;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class AccountServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final AccountService accountService = new AccountService();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
String requestURI = request.getRequestURI();
String methodName = requestURI.substring(requestURI.lastIndexOf("/") + 1);
try {
Method method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
method.invoke(this, request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
private void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String name = request.getParameter("name");
String password = request.getParameter("password");
String type = request.getParameter("type");
HttpSession session = request.getSession();
switch (type) {
case "doctor":
Doctor doctor = accountService.checkDoctor(name, password);
session.setAttribute("user", doctor);
break;
case "chief nurse":
ChiefNurse chiefNurse = accountService.checkChiefNurse(name, password);
session.setAttribute("user", chiefNurse);
break;
case "ward nurse":
WardNurse wardNurse = accountService.checkWardNurse(name, password);
session.setAttribute("user", wardNurse);
break;
case "emergency nurse":
EmergencyNurse emergencyNurse = accountService.checkEmergencyNurse(name, password);
session.setAttribute("user", emergencyNurse);
break;
}
if(session.getAttribute("user") == null){
request.setAttribute("loginStatus", "false");
request.setAttribute("message", "There is something wrong with your <b>username or password</b>, please check and try again!");
request.getRequestDispatcher("/jsp/login.jsp").forward(request, response);
return;
}else{
session.setAttribute("userType", type);
request.setAttribute("loginStatus", "true");
request.setAttribute("message", "Success!");
}
switch (type){
case "doctor":
request.getRequestDispatcher("/jsp/doctor.jsp").forward(request, response);
break;
case "chief nurse":
request.getRequestDispatcher("/jsp/chiefNurse.jsp").forward(request, response);
break;
case "ward nurse":
request.getRequestDispatcher("/jsp/wardNurse.jsp").forward(request, response);
break;
case "emergency nurse":
request.getRequestDispatcher("/jsp/emergencyNurse.jsp").forward(request, response);
break;
}
}
private void changeInfo(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String name = request.getParameter("name");
String password = request.getParameter("password");
HttpSession session = request.getSession();
accountService.changeInfo(session, name, password);
Map<String, Object> map = new HashMap<String, Object>();
map.put("message", "success");
JSONObject mapJson = JSONObject.fromObject(map);
response.getWriter().print(mapJson);
}
private void jumpToHome(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
HttpSession session = request.getSession();
String type = (String) session.getAttribute("userType");
switch (type){
case "doctor":
request.getRequestDispatcher("/jsp/doctor.jsp").forward(request, response);
break;
case "chief nurse":
request.getRequestDispatcher("/jsp/chiefNurse.jsp").forward(request, response);
break;
case "ward nurse":
request.getRequestDispatcher("/jsp/wardNurse.jsp").forward(request, response);
break;
case "emergency nurse":
request.getRequestDispatcher("/jsp/emergencyNurse.jsp").forward(request, response);
break;
}
}
private void logout(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
HttpSession session = request.getSession();
session.removeAttribute("userType");
session.removeAttribute("user");
request.getRequestDispatcher("/jsp/login.jsp").forward(request, response);
}
}
|
package com.servlets;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.beans.EmailService;
import com.classes.EmailOrder;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
/**
* Servlet implementation class SupplyProduct
*/
@WebServlet("/SupplyProduct")
public class SupplyProduct extends HttpServlet {
private static final long serialVersionUID = 1L;
@EJB
EmailService bean;
/**
* @see HttpServlet#HttpServlet()
*/
public SupplyProduct() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Supply product!");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Gson gson = new Gson();
EmailOrder emailOrder = gson.fromJson(request.getReader(), EmailOrder.class);
System.out.println("Post email");
bean.supplyProduct(emailOrder.getEmail(), emailOrder.getName() , emailOrder.getProducts());
doGet(request, response);
}
}
|
package com.rubic.demo.trade;
import com.lmax.disruptor.ExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author rubic
*/
public class IntEventExceptionHandler implements ExceptionHandler {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
public void handleEventException(Throwable ex, long sequence, Object event) {
logger.error("handleEventException", ex);
}
public void handleOnStartException(Throwable ex) {
logger.error("handleOnStartException", ex);
}
public void handleOnShutdownException(Throwable ex) {
logger.error("handleOnShutdownException", ex);
}
}
|
package temperaturasfamilias;
import java.util.ArrayList;
import java.util.Scanner;
public class TemperaturasFamilias {
public static void main(String[] args) {
Scanner entrada=new Scanner(System.in);
short caso=0,tamañolista=0;
ArrayList<Persona> familia=new ArrayList<>();
while(caso!=4)
{
String nombre,parentesco;
int edad,CantT=0;
Float temperatura;
System.out.println("*********Menu************");
System.out.println("1.Registrar nueva persona");
System.out.println("2.Registrar temperatura");
System.out.println("3.Generrar reporte");
System.out.println("4.Cerrar programa");
caso=entrada.nextShort();
switch(caso)
{
case 1:
System.out.println("digite el nombre de la persona");
nombre=entrada.next();
System.out.println("digite el parentesco");
parentesco=entrada.next();
System.out.println("digte la edad");
edad=entrada.nextInt();
familia.add(new Persona(nombre,parentesco,edad));
tamañolista++;
familia.get((familia.size()-1)).agragartemperaturas();
break;
case 2:
short Npersona;
System.out.println("las personas registradas son:");
for(int i=0;i<familia.size();i++)
{
System.out.println((i+1)+"."+familia.get(i).Nombre);
}
System.out.println("\n");
System.out.println("digite el numero de quien quiere agregar una emperatura");
Npersona=entrada.nextShort();
familia.get((Npersona-1)).agragartemperaturas();
break;
case 3:
String nombreReport;
boolean estara = false;
int indice=0;
System.out.println("digite el nombre de la persona de quien quiere el reporte");
nombreReport=entrada.next();
for(int i=0;i<familia.size();i++)
{
if(nombreReport.equals(familia.get(i).Nombre))
{
estara=true;
indice=i;
}
}
if(estara==true)
{
int largo=familia.get(indice).Temperaturas.size();
System.out.println("nombre:"+familia.get(indice).Nombre);
System.out.println("edad:"+familia.get(indice).Edad);
System.out.println("parentesco:"+familia.get(indice).Parentesco);
for(int i=0;i<largo;i++)
{
System.out.println(familia.get(indice).Temperaturas.get(i));
}
}else
{
System.out.println("la persona no se encuentra");
}
break;
case 4:
break;
default: System.out.println("la opcion ingresada no esta en el menu");
}
}
}
}
|
package com.infoworks.lab.util.states.client.states;
import com.infoworks.lab.util.states.client.users.User;
import com.infoworks.lab.util.states.context.State;
public interface iDocState extends State {
void setUser(User user);
void publish();
void render();
}
|
package airHockey;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.font.TextAttribute;
import java.io.File;
import java.io.IOException;
import java.text.AttributedString;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class AirHockey extends JFrame implements KeyListener {
Image img=null;
int xb=700,yb=250;
int xl=650,yl=0;
int xh=650,yh=60;
int d=2;
int a=1,b=1;
JLabel image =null;
int xhg=0;
int yhg=0;
int xlg=0;
int ylg=0;
int scoreh=0;
int scorel=0;
//AttributedString as0=null,as1,as2,as3,as4,as5,as6,as7,as8,as9,as10;
public AirHockey()
{
Toolkit toolkit = Toolkit.getDefaultToolkit ();
Dimension dim = toolkit.getScreenSize();
dim.height=dim.height -40;
System.out.println("Width of Screen Size is "+dim.width+" pixels");
System.out.println("Height of Screen Size is "+dim.height+" pixels");
setSize(dim);
setLayout(new BorderLayout());
JLabel background=new JLabel(new ImageIcon("C:\\Users\\AKA\\Desktop\\Libraries\\Pictures\\airh"));
add(background);
// background.setLayout(new FlowLayout());
setVisible(true);
setBackground(Color.CYAN);
pause=1;
addKeyListener(this);
}
int i=0;
public void run(){
try{
Thread.sleep(4);
}
catch(Exception e){ }
repaint();
}
public void paint(Graphics g)
{
xhg=getBounds().width/2-250;
yhg=20;
xlg=getBounds().width/2-250;
ylg=getBounds().height-20;
yl=getBounds().height-60;
// image =new JLabel();
// image.setIcon(new ImageIcon("e://image.jpg"));
// add(image);
// try {
// Image img = ImageIO.read(new File("e://image.jpg"));
// } catch (IOException e1) {
// // TODO Auto-generated catch block
// e1.printStackTrace();
// }
// g.drawImage(img, 0, 0, null);
if(pause!=1)
{
xb+=a*d;
yb+=b*d;
}
if(xb>getBounds().width-15||xb<10)
a=a*-1;
if(yb==yl-20&& (xb>xl-10)&&xb<xl+85)
{
if(xb<=xl+26)
{b=-1;
a=-1;
}
else if(xb>xl+26&&xb<=xl+52)
{
a=0;
b=-1;
}
else if (xb>xl+52)
{
a=1;
b=-1;
}
}
if(yb==yh+30&& (xb>xh-10)&&xb<xh+85)
{
if(xb<=xh+26)
{b=1;
a=-1;
}
else if(xb>xh+26&&xb<=xh+52)
{
a=0;
b=1;
}
else if (xb>xh+52)
{
a=1;
b=1;
}
}
// try {
// Thread.sleep(2);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
if((yb>getBounds().height-20||yb<30))
{
if (xb<getBounds().width/2-250 || xb > getBounds().width/2+250 )
{ b=b*-1;
}
else
{
if(yb<100)
{
scorel++;
xb=600;
yb=500;
}
else if(yb>100)
{
scoreh++;
xb=600;
yb=500;
}
// a=a*-1;
// b=b*-1;
}
}
//For stopping paddles from going outside
if(xl<5)
xl=5;
if(xl>getBounds().width-85)
xl=getBounds().width-85;
if(xh<5)
xh=5;
if(xh>getBounds().width-85)
xh=getBounds().width-85;
g.clearRect(0, 0, getBounds().width, getBounds().height);
g.setColor(Color.LIGHT_GRAY);
// g.fillRect(xlg, ylg-100, 180, 100);
// g.fillRect(xhg, yhg+15, 180, 100);
g.fillOval(xlg,ylg-80 , 500, 200);
g.fillOval(xhg,yhg-100 , 500, 200);
g.setColor(Color.DARK_GRAY);
g.fillRect(xhg, yhg, 500, 20);
g.fillRect(xlg, ylg, 500, 20);
// try {
// Thread.sleep(2);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
g.setColor(Color.YELLOW);
g.fillOval(xb, yb, 15, 15);
g.fillRect(xl, yl, 80, 20);
g.fillRect(xh, yh, 80, 20);
//
// Graphics2D g2d = (Graphics2D) g;
// g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//
// AttributedString as0 = new AttributedString("0");
// AttributedString as1 = new AttributedString("1");
// AttributedString as2 = new AttributedString("2");
// AttributedString as3 = new AttributedString("3");
// AttributedString as4 = new AttributedString("4");
// AttributedString as5 = new AttributedString("5");
// AttributedString as6 = new AttributedString("6");
// AttributedString as7 = new AttributedString("7");
// AttributedString as8 = new AttributedString("8");
// AttributedString as9 = new AttributedString("9");
// AttributedString as10 = new AttributedString("10");
//
// as0.addAttribute(TextAttribute.SIZE, 40);
// as1.addAttribute(TextAttribute.SIZE, 40);
// as2.addAttribute(TextAttribute.SIZE, 40);
// as3.addAttribute(TextAttribute.SIZE, 40);
// as4.addAttribute(TextAttribute.SIZE, 40);
// as5.addAttribute(TextAttribute.SIZE, 40);
// as6.addAttribute(TextAttribute.SIZE, 40);
// as7.addAttribute(TextAttribute.SIZE, 40);
// as8.addAttribute(TextAttribute.SIZE, 40);
// as9.addAttribute(TextAttribute.SIZE, 40);
// as10.addAttribute(TextAttribute.SIZE, 40);
//
//
g.setColor(Color.blue);
g.drawString(""+scorel, 40, 80);
g.fillRect(xl, yl+5, 80, 10);
// if(scorel==0)
// g2d.drawString(as0.getIterator(), 40, 60);
// else if(scorel==1)
// g2d.drawString(as1.getIterator(), 40, 60);
//
// else if(scorel==2)
// g2d.drawString(as2.getIterator(), 40, 60);
//
// else if(scorel==3)
// g2d.drawString(as3.getIterator(), 40, 60);
// else if(scorel==4)
// g2d.drawString(as4.getIterator(), 40, 60);
// else if(scorel==5)
// g2d.drawString(as5.getIterator(), 40, 60);
// else if(scorel==6)
// g2d.drawString(as6.getIterator(), 40, 60);
// else if(scorel==7)
// g2d.drawString(as7.getIterator(), 40, 60);
// else if(scorel==8)
// g2d.drawString(as8.getIterator(), 40, 60);
// else if(scorel==9)
// g2d.drawString(as9.getIterator(), 40, 60);
// else if(scorel==10)
// {
// g2d.drawString(as10.getIterator(), 40, 60);
// pause=1;
// }
g.setColor(Color.red);
g.drawString(""+scoreh, 15, 80);
g.fillRect(xh, yh+5, 80, 10);
Font font =new Font("Arial",1,40);
g.setFont(font);
g.setColor(Color.PINK);
if(scoreh==5)
{
pause=1;
g.drawString("RED WINS", getBounds().width/2-100, getBounds().height/2);
}
if(scorel==5)
{
pause=1;
g.drawString("BLUE WINS", getBounds().width/2-100, getBounds().height/2);
}
run();
// if(scoreh==0)
// g2d.drawString(as0.getIterator(), 15, 60);
// else if(scoreh==1)
// g2d.drawString(as1.getIterator(), 15, 60);
//
// else if(scoreh==2)
// g2d.drawString(as2.getIterator(), 15, 60);
//
// else if(scoreh==3)
// g2d.drawString(as3.getIterator(), 15, 60);
// else if(scoreh==4)
// g2d.drawString(as4.getIterator(), 15, 60);
// else if(scoreh==5)
// g2d.drawString(as5.getIterator(), 15, 60);
// else if(scoreh==6)
// g2d.drawString(as6.getIterator(), 15, 60);
// else if(scoreh==7)
// g2d.drawString(as7.getIterator(), 15, 60);
// else if(scoreh==8)
// g2d.drawString(as8.getIterator(), 15, 60);
// else if(scoreh==9)
// g2d.drawString(as9.getIterator(), 15, 60);
// else if(scoreh==10)
// {
// g2d.drawString(as10.getIterator(), 15, 60);
// pause=1;
// }
// try {
// Thread.sleep(2);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// repaint();
}
int pause=-1;
int k=KeyEvent.VK_S;
@Override
public void keyPressed(KeyEvent et) {
// TODO Auto-generated method stub
int code=et.getKeyCode();
// System.out.println(code);
if(code == KeyEvent.VK_P||code==k)
{pause*=-1;
k=-1;
repaint();
}
if(pause!=1)
{
if (code == KeyEvent.VK_LEFT) {
xl-=20;
// repaint();
}
else if (code == KeyEvent.VK_RIGHT) {
xl+=20;
// repaint();
}
if (code == KeyEvent.VK_A) {
xh-=20;
// repaint();
}
else if (code == KeyEvent.VK_D) {
xh+=20;
// repaint();
}
}
}
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
|
package cdp.factorys;
import java.io.IOException;
import java.io.Serializable;
import cdp.controllers.PessoaController;
import cdp.controllers.ProjetoController;
import cdp.exception.CadastroException;
import cdp.exception.ValidacaoException;
import cdp.participacao.AlunoGraduando;
import cdp.participacao.AlunoPosGraduando;
import cdp.participacao.Participacao;
import cdp.participacao.Professor;
import cdp.participacao.Profissional;
/**
* Classe responsavel pelo encapsulamento da criacao de uma participacao.
*
* @author Yuri Silva
* @author Tiberio Gadelha
* @author Matheus Henrique
* @author Gustavo Victor
*/
public class FactoryDeParticipacao implements Serializable {
private PessoaController pessoaController;
private ProjetoController projetoController;
public FactoryDeParticipacao(PessoaController pessoaController, ProjetoController projetoController) {
this.pessoaController = pessoaController;
this.projetoController = projetoController;
}
public Participacao criaAssociacaoProfessor(String cpf, int codigoProjeto, boolean coordenador, double valorHora, int qtdHoras) throws ValidacaoException, CadastroException {
this.projetoController.validaHoraProfessor(valorHora, codigoProjeto);
Professor participacao = new Professor(valorHora, qtdHoras, coordenador);
this.pessoaController.associaPessoa(participacao, cpf);
this.projetoController.associaProjeto(participacao, codigoProjeto);
this.projetoController.adicionaParticipacao(participacao, codigoProjeto);
this.pessoaController.adicionaParticipacao(participacao, cpf);
return participacao;
}
public Participacao criaAssociacaoGraduando(String cpf, int codigoProjeto, double valorHora, int qtdHoras) throws CadastroException, ValidacaoException {
AlunoGraduando participacao = new AlunoGraduando(valorHora, qtdHoras);
this.pessoaController.associaPessoa(participacao, cpf);
this.projetoController.associaProjeto(participacao, codigoProjeto);
this.projetoController.adicionaParticipacao(participacao, codigoProjeto);
this.pessoaController.adicionaParticipacao(participacao, cpf);
return participacao;
}
public Participacao criaAssociacaoProfissional(String cpf, int codigoProjeto, String cargo, double valorHora, int qtdHoras) throws CadastroException, ValidacaoException {
Profissional participacao = new Profissional(cargo.toLowerCase(), valorHora, qtdHoras);
this.pessoaController.associaPessoa(participacao, cpf);
this.projetoController.associaProjeto(participacao, codigoProjeto);
this.projetoController.adicionaParticipacao(participacao, codigoProjeto);
this.pessoaController.adicionaParticipacao(participacao, cpf);
return participacao;
}
public Participacao criaAssociacaoPosGraduando(String cpf, int codigoProjeto, String associacao, double valorHora, int qtdHoras) throws CadastroException, ValidacaoException {
AlunoPosGraduando participacao = new AlunoPosGraduando( valorHora, qtdHoras, associacao);
this.pessoaController.associaPessoa(participacao, cpf);
this.projetoController.associaProjeto(participacao, codigoProjeto);
this.projetoController.adicionaParticipacao(participacao, codigoProjeto);
this.pessoaController.adicionaParticipacao(participacao, cpf);
return participacao;
}
}
|
package exam.iz0_803;
public class Exam_090 {
}
/*
Which action will improve the encapsulation of a class?
A. Changing the access modifier of a field from public to private
B. Removing the public modifier from at a class declaration
C. Changing the return type of a method to void
D. Returning a copy of the contents of an array or ArrayList of a direct reference
Answer: A
*/
|
package novemberChallenge2017;
import java.util.ArrayList;
import java.util.Scanner;
public class ChefGoesLeftRightLeft {
public static void main(String[] args) {
int no = 0;
Scanner src = new Scanner(System.in);
no = src.nextInt();
int n = 0;
long rating = 0, right_baricate = -1, left_baricate = -1, othrppl_rank = 0;
ArrayList<Long> ppl_rank = new ArrayList<Long>();
for (int i = 0; i < no; i++) {
right_baricate = -1;
left_baricate = -1;
ppl_rank.clear();
n = src.nextInt();
rating = src.nextLong();
for (int j = 0; j < n; j++)
ppl_rank.add(src.nextLong());
for (int j = 0; j < n; j++) {
othrppl_rank = ppl_rank.get(j);
if (rating < othrppl_rank) {
// move left
if (right_baricate == -1) {
right_baricate = othrppl_rank;
// System.out.println("Move left");
continue;
} else {
if (othrppl_rank > right_baricate) {
System.out.println("NO");
break;
} else if (right_baricate > othrppl_rank) {
right_baricate = othrppl_rank;
continue;
}
}
} else if (rating > othrppl_rank) {
// move right
if (left_baricate == -1) {
left_baricate = othrppl_rank;
continue;
} else {
if (othrppl_rank < left_baricate) {
System.out.println("NO");
break;
} else if (othrppl_rank > left_baricate) {
left_baricate = othrppl_rank;
continue;
}
}
} else
System.out.println("YES");
break;
}
}
}
} |
package com.gaoshin.coupon.dao.impl;
import java.util.Collections;
import org.springframework.stereotype.Repository;
import com.gaoshin.coupon.dao.ConfigDao;
import com.gaoshin.coupon.entity.Configuration;
@Repository
public class ConfigDaoImpl extends GenericDaoImpl implements ConfigDao {
@Override
public String get(String name) {
Configuration conf = getUniqueResult(Configuration.class, Collections.singletonMap("name", name));
return conf == null ? null : conf.getValue();
}
@Override
public int getInt(String name, int defaultValue) {
return Integer.parseInt(get(name, defaultValue));
}
@Override
public long getLong(String name, long defaultValue) {
return Long.parseLong(get(name, defaultValue));
}
@Override
public float getFloat(String name, float defaultValue) {
return Float.parseFloat(get(name, defaultValue));
}
@Override
public void set(String name, Object value) {
update(Configuration.class, Collections.singletonMap("value", value.toString()), Collections.singletonMap("name", name));
}
@Override
public String get(String name, Object defaultValue) {
String value = get(name);
return value == null ? defaultValue.toString() : value;
}
}
|
package com.ufcg.virtualmusicbox.Model;
/**
* Created by Victor on 5/9/2016.
*/
public interface Searchable {
public Changeable getRecyclerAdapter();
}
|
package com.aragon.gift;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class GiftCenterApplication {
public static void main(String[] args) {
SpringApplication.run(GiftCenterApplication.class, args);
}
}
|
package com.aca.swap;
public class IntegerWrapper {
private int number;
public IntegerWrapper(int number) {
this.number = number;
}
int getNumber() {
return number;
}
void setNumber(int number) {
this.number = number;
}
public static void swap(IntegerWrapper number1, IntegerWrapper number2) {
int a = number1.number;
number1.number = number2.number;
number2.number = a;
}
}
|
package ivge;
public class PlayStationGame implements Game {
}
|
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.Huurder;
import model.KamerVerhuur;
import model.User;
import model.Verhuurder;
/**
* Servlet implementation class RegisterServlet
*/
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private KamerVerhuur kamerVerhuur;
/**
* @see HttpServlet#HttpServlet()
*/
public RegisterServlet() {
super();
}
@Override
public void init() throws ServletException {
super.init();
kamerVerhuur = (KamerVerhuur) getServletContext().getAttribute("KamerVerhuur");
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.sendRedirect("registeer.html");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context = request.getServletContext();
KamerVerhuur kamerVerhuur = (KamerVerhuur) context.getAttribute("KamerVerhuur");
String username = request.getParameter("username");
String password = request.getParameter("password");
String type = request.getParameter("type");
if(kamerVerhuur.userExists(username)){
getServletContext().getRequestDispatcher("/WEB-INF/usernameExists.html").forward(request, response);
return;
}
if(username.isEmpty() || password.isEmpty() || type == null){
getServletContext().getRequestDispatcher("/WEB-INF/emptyFields.html").forward(request, response);
return;
}
User user = null;
if(type.equals("huurder")){
user = new Huurder(username, password);
}else if(type.equals("verhuurder")){
user = new Verhuurder(username, password);
}
kamerVerhuur.addUser(user);
response.sendRedirect("login.html");
}
}
|
package com.example.sergiosiniy.beeradvicer.activities;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.app.ShareCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Spinner;
import com.example.sergiosiniy.beeradvicer.R;
public class AdviceNewBeer extends Activity {
private String shareBody;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_new_beer);
}
/**
* Sending new beer to my mail
* @param view
*/
public void sendMessage(View view){
Spinner beerType = (Spinner) findViewById(R.id.beer_type_spinner_sendto);
EditText beerBrand = (EditText)findViewById(R.id.brand_edit_text);
shareBody = beerType.getSelectedItem().toString()+" - "+beerBrand.getText().toString();
Uri adminMail = Uri.parse("mailto:sergio.siniy@gmail.com");
Intent sendMsg = new Intent (Intent.ACTION_SENDTO)
.setData(adminMail)
.putExtra(Intent.EXTRA_SUBJECT, "Beer advice from user")
.putExtra(Intent.EXTRA_TEXT, shareBody);
startActivity(sendMsg);
}
}
|
package cn.itcast.core.service.temp;
import cn.itcast.core.dao.specification.SpecificationOptionDao;
import cn.itcast.core.dao.template.TypeTemplateDao;
import cn.itcast.core.entity.PageResult;
import cn.itcast.core.pojo.specification.SpecificationOption;
import cn.itcast.core.pojo.specification.SpecificationOptionQuery;
import cn.itcast.core.pojo.template.TypeTemplate;
import cn.itcast.core.pojo.template.TypeTemplateQuery;
import cn.itcast.core.service.template.TypeTemplateService;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
@Service
public class TypeTemplateServiceImpl implements TypeTemplateService{
@Resource
private TypeTemplateDao typeTemplateDao;
@Resource
private SpecificationOptionDao specificationOptionDao;
@Resource
private RedisTemplate<String,Object> redisTemplate;
/**
* 模板列表查询
* @param page
* @param rows
* @param typeTemplate
* @return
*/
@Override
public PageResult search(Integer page, Integer rows, TypeTemplate typeTemplate) {
//列表查询过程中将数据同步到redis中
List<TypeTemplate> list = typeTemplateDao.selectByExample(null);
if (list != null && list.size()>0){
for (TypeTemplate template : list) {
//将品牌结果集存储到内存中
String brandIds = template.getBrandIds();
List<Map> brandList = JSON.parseArray(brandIds, Map.class);
redisTemplate.boundHashOps("brandList").put(template.getId(),brandList);
//将规格结果集存储到内存中
List<Map> specList = findBySpecList(template.getId());
redisTemplate.boundHashOps("specList").put(template.getId(),specList);
}
}
// 1、设置分页条件
PageHelper.startPage(page, rows);
// 2、设置查询条件
TypeTemplateQuery query = new TypeTemplateQuery();
if(typeTemplate.getName() != null && !"".equals(typeTemplate.getName().trim())){
query.createCriteria().andNameLike("%" + typeTemplate.getName().trim() + "%");
}
query.setOrderByClause("id desc");
// 3、根据条件查询
Page<TypeTemplate> p = (Page<TypeTemplate>) typeTemplateDao.selectByExample(query);
// 4、封装结果集
return new PageResult(p.getTotal(), p.getResult());
}
/**
* 保存模板
* @param typeTemplate
*/
@Transactional
@Override
public void add(TypeTemplate typeTemplate) {
typeTemplateDao.insertSelective(typeTemplate);
}
/**
* 新增商品:回显品牌以及扩展属性
* @param id
* @return
*/
@Override
public TypeTemplate findOne(Long id) {
return typeTemplateDao.selectByPrimaryKey(id);
}
/**
* 新增商品:回显规格以及规格选项
* @param id
* @return
*/
@Override
public List<Map> findBySpecList(Long id) {
//通过id 获取到模板
TypeTemplate typeTemplate = typeTemplateDao.selectByPrimaryKey(id);
//通过模板获取规格
//[{"id":27,"text":"网络"},{"id":32,"text":"机身内存"}]
String specids = typeTemplate.getSpecIds();
//将json串 转成对象
List<Map> specList = JSON.parseArray(specids, Map.class);
//设置规格选项
if (specList != null && specList.size()>0){
for (Map map : specList) {
//获取规格id
long specId =Long.parseLong(map.get("id").toString());
//获取对应的规格选项
SpecificationOptionQuery query = new SpecificationOptionQuery();
query.createCriteria().andSpecIdEqualTo(specId);
List<SpecificationOption> options = specificationOptionDao.selectByExample(query);
//将规格选项设置到map中
map.put("options",options);
}
}
return specList;
}
/*
* 模板审核
* */
@Override
public void updateStatus(Long[] ids, String status) {
TypeTemplate typeTemplate = new TypeTemplate();
if (ids != null && ids.length > 0) {
typeTemplate.setStatus(status);
for ( final Long id : ids) {
typeTemplate.setId(id);
}
typeTemplateDao.updateByPrimaryKeySelective(typeTemplate);
}
}
}
|
/*
* 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 dilema_3;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
/**
*
* @author Dipta Mahardhika
*/
public class Dilema_3 {
static final int ITERATION = 100;
//this values are for csv tokenizer
public static final int AGENT_NAMEX = 0;
public static final int AGENT_INTENTIONX = 1;
public static final int AGENT_JUDGEMENTX = 2;
public static final int AGENT_COMMUNICATIVEX = 3;
//treshold for whether the lower layers will be taken into account or not
public static final double CONSIDER_L3THEY_TRESH = 1;
public static final double CONSIDER_L3ME_TRESH = 1;
public static final double CONSIDER_L2_TRESH = 1;
public static final String fileName = "population.csv";
public static final String POPULATION_FILE = "population_auto.csv";
public static final String NETWORK_FILE_NAME = "network_default.csv";
// public static final int NO_OF_PARTNER =3; //this is turned off because in the interface, user will be asked directly
public static List<Agent> population = new ArrayList<>();
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner task = new Scanner(System.in);
String taskNum;
System.out.println("Task list");
System.out.println("1. experiment ground");
System.out.println("2. build population file");
System.out.println("3. build network file");
System.out.println("4. simulate");
System.out.print("which task do you want to do?");
taskNum = task.next();
if (taskNum.equals("1")) {
System.out.println("EXPERIMENT GROUND");
//put something here to try / test
}
else if (taskNum.equals("2")) {
System.out.println("BUILDING POPULATION-FILE");
generatePopulation();
}
else if (taskNum.equals("3")) {
System.out.println("BUILDING NETWORK-FILE");
Scanner networkGeneratorScan = new Scanner(System.in);
System.out.print("what is the name of the population file that you want to use?");
String popFileName = networkGeneratorScan.next();
System.out.println("how many partners for one agent?");
int numOfPartners = Integer.parseInt(networkGeneratorScan.next());
generateNetworkFile(popFileName, numOfPartners);
System.out.println("Network file DONE");
}
else {
System.out.println("MAIN SIMULATION");
System.out.println("Working Directory = " + System.getProperty("user.dir"));
File resultFile = SupportTool.notOverwriteFileName("result.csv");
// File networkFile = SupportTool.notOverwriteFileName("network.csv");
Scanner simScan = new Scanner(System.in);
System.out.print("what is the name of the population file that you want to use?");
String popFileName = simScan.next();
loadPopulationFromFile(popFileName);
System.out.print("what is the name of the network file that you want to use?");
String networkFileName = simScan.next();
loadPartnerFromfile(networkFileName);
//TODO blm ada sistem untuk mengecek apakah populasi dan network yg dipakai sinkron apa engga
printMetadata(resultFile);
printPopulation(resultFile, popFileName);
printNetwork(resultFile, networkFileName);
SupportTool.writeToCsv(resultFile, "Result:");
SupportTool.writeToCsv(resultFile, "agent,iteration,layer1,layer2,layer3me,layer3they, judgement rate, payoff");
for (int i = 0; i < ITERATION; i++) {
for (Agent agent: population) {
agent.decide();
}
for (Agent agent: population) {
agent.updateJudgOblValue(agent.didTheyCooperate());
}
for (Agent agent: population) {
double payoff = Payoff.countPayoff(agent, population);
SupportTool.writeToCsv(resultFile, agent.name + "," + i + "," + agent.layer1 + "," + agent.layer2 + "," + agent.layer3me + "," + agent.layer3they + "," + agent.judgingTreshold + "," + payoff);
}
}
}
}
private static void generatePopulation() {
Random rand = new Random();
File outFile =SupportTool.notOverwriteFileName(POPULATION_FILE);
String agentData;
final Double POP_INTENT_RATIO = 0.75;
final Double POP_COM_RATIO = 0.75;
final int POP_SIZE = 50;
// final Double MEAN_JUDG = 0.5; //this is used only if the distribution of agentJudg is wanted to be continuous
// final Double STD_JUDG = 0.3;
final Double POP_POST_THINKER_RATIO = 0.75;
SupportTool.writeToCsv(outFile,"Name,Intention,Judgement,Communicative");
for (int i = 0; i < POP_SIZE; i++) {
int agentInt = rand.nextDouble()<POP_INTENT_RATIO ? 1: 0;
// double agentJudg = SupportTool.round(rand.nextGaussian()*STD_JUDG+MEAN_JUDG,1); //use this if the distribution of agentJudg is wanted to be continuous
double agentJudg = rand.nextDouble()<POP_POST_THINKER_RATIO ? 0.75 : 0.25;
int agentCom = rand.nextDouble()<POP_COM_RATIO ? 1:0;
agentData = SupportTool.threeDigitHex(i)+","+agentInt+","+SupportTool.alwaysZeroOne(agentJudg)+","+agentCom;
SupportTool.writeToCsv(outFile, agentData);}
}
public static void generateNetworkFile(String popFileName, int numOfPartners) {
loadPopulationFromFile(popFileName);
String networkFileHeader ="agent";
for (int i = 1; i <= numOfPartners; i++) {
networkFileHeader += ",partner"+i;
}
File networkFile = SupportTool.notOverwriteFileName("network_for_"+popFileName.substring(0, popFileName.length()-4)+"_.csv");
SupportTool.writeToCsv(networkFile, networkFileHeader);
for (Agent agent: population) {
agent.setNRandomPartners(population, numOfPartners);
String partnerList = agent.name;
for (Agent partner: agent.partners) {
partnerList += ","+partner.name;
}
SupportTool.writeToCsv(networkFile, partnerList);
}
}
public static void loadPopulationFromFile(String popFileName) {
BufferedReader fileReader = null;
try {
String line;
fileReader = new BufferedReader(new FileReader(popFileName));
//Read the CSV file header to skip it
fileReader.readLine();
//Read the file line by line starting from the second line
while ((line = fileReader.readLine()) != null) {
String[] tokens = line.split(",");
if (tokens.length > 0) {
Agent agent = new Agent(
tokens[AGENT_NAMEX],
Integer.parseInt(tokens[AGENT_INTENTIONX]),
Double.parseDouble(tokens[AGENT_JUDGEMENTX]),
Integer.parseInt(tokens[AGENT_COMMUNICATIVEX])
);
population.add(agent);
}
}
//Print the new student list
for (Agent agent: population) {
System.out.println(agent.toString());
}
} catch (Exception e) {
System.out.println("Error in CsvFileReader !!!");
e.printStackTrace();
} finally {
try {
fileReader.close();
} catch (IOException e) {
System.out.println("Error while closing fileReader !!!");
e.printStackTrace();
}
}
}
public static void loadPartnerFromfile(String networkFileName) {
BufferedReader fileReader = null;
try {
String line;
fileReader = new BufferedReader(new FileReader(networkFileName));
//Read the CSV file header to skip it
fileReader.readLine();
//Read the file line by line starting from the second line
while ((line = fileReader.readLine()) != null) {
String[] tokens = line.split(",");
// System.out.println("tokens size = " + tokens.length);
if (tokens.length > 0) {
for (Agent agent : population) {
// System.out.println("agent.name = " + agent.name);
if (agent.name.equals(tokens[0])){
for (Agent partner : population) {
boolean match=false;
for (int i = 1; i <= tokens.length-1; i++) {
match = partner.name.equals(tokens[i]);
// System.out.println("partner.name = " + partner.name);
// System.out.println("tokens["+i+"] = " + tokens[i]);
if (match) {break;}
}
if (match)
{ System.out.println("partner.name for " + agent.name+"="+partner.name);
agent.partners.add(partner);}
}
break;
}
}
}
}
//Print the new student list
for (Agent agent: population) {
System.out.println(agent.toString());
}
} catch (Exception e) {
System.out.println("Error in CsvFileReader !!!");
e.printStackTrace();
} finally {
try {
fileReader.close();
} catch (IOException e) {
System.out.println("Error while closing fileReader !!!");
e.printStackTrace();
}
}
}
public static void printNetwork(File resultFile, String networkFileName) {
BufferedReader fileReader = null;
SupportTool.writeToCsv(resultFile, "Network Data:");
try {
String line;
fileReader = new BufferedReader(new FileReader(networkFileName));
//Read the CSV file header to skip it
//Read the file line by line starting from the second line
while ((line = fileReader.readLine()) != null) {
SupportTool.writeToCsv(resultFile, line);
}
//Print a line
SupportTool.writeToCsv(resultFile, "");
} catch (Exception e) {
System.out.println("Error in CsvFileReader !!!");
e.printStackTrace();
} finally {
try {
fileReader.close();
} catch (IOException e) {
System.out.println("Error while closing fileReader !!!");
e.printStackTrace();
}
}
}
public static void printPopulation(File resultFile, String popFileName){
BufferedReader fileReader = null;
SupportTool.writeToCsv(resultFile, "Population Data:");
try {
String line;
fileReader = new BufferedReader(new FileReader(popFileName));
//Read the CSV file header to skip it
//Read the file line by line starting from the second line
while ((line = fileReader.readLine()) != null) {
SupportTool.writeToCsv(resultFile, line);
}
//Print a line
SupportTool.writeToCsv(resultFile, "");
} catch (Exception e) {
System.out.println("Error in CsvFileReader !!!");
e.printStackTrace();
} finally {
try {
fileReader.close();
} catch (IOException e) {
System.out.println("Error while closing fileReader !!!");
e.printStackTrace();
}
}
}
public static void printMetadata(File resultFile){
SupportTool.writeToCsv(resultFile, "Layer 3-me active? "+CONSIDER_L3THEY_TRESH);
SupportTool.writeToCsv(resultFile, "Layer 3-they active? "+CONSIDER_L3ME_TRESH);
SupportTool.writeToCsv(resultFile, "Layer 2 active? "+CONSIDER_L2_TRESH);
SupportTool.writeToCsv(resultFile, "");
}
}
|
package com.pb.android.pages;
public class QuickTest {
}
|
package org.wuxinshui.boosters.designPatterns.factorymethod;
/**
* Created with IntelliJ IDEA.
* User: FujiRen
* Date: 2016/10/31
* Time: 10:55
* To change this template use File | Settings | File Templates.
*/
public interface Sender {
public void send();
}
|
package com.expedia.www.haystack.dropwizard.example;
import com.expedia.www.haystack.dropwizard.example.client.ClientApplication;
import com.expedia.www.haystack.dropwizard.example.server.ServerApplication;
public class ExampleApplication {
public static void main(String[] args) throws Exception {
if (args == null)
throw new Exception("Arguments not provided");
if ("client".equalsIgnoreCase(args[0])) {
new ClientApplication().run("server", args[1]);
} else if ("server".equalsIgnoreCase(args[0])) {
new ServerApplication().run("server", args[1]);
} else {
throw new Exception("unexpected argument".concat(" ").concat(args[0]));
}
}
}
|
package structures;
public interface List<xType> {
public void insertFront (xType data);
public void insertBack (xType data);
public void insertAt (int index, xType data);
public boolean deleteAtIndex ( int index);
public boolean contains( xType data);
public void print();
};
|
/*
* Copyright (C) 2011 The Baremaps 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
*
* 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.baremaps.osm.geometry;
import java.util.stream.Stream;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.CoordinateSequence;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.impl.CoordinateArraySequence;
import org.locationtech.jts.geom.util.GeometryTransformer;
import org.locationtech.proj4j.CoordinateTransform;
import org.locationtech.proj4j.ProjCoordinate;
public class ProjectionTransformer extends GeometryTransformer {
private final CoordinateTransform coordinateTransform;
public ProjectionTransformer(CoordinateTransform coordinateTransform) {
this.coordinateTransform = coordinateTransform;
}
@Override
protected CoordinateSequence transformCoordinates(CoordinateSequence coords, Geometry parent) {
Coordinate[] coordinates = Stream.of(coords.toCoordinateArray())
.map(this::transformCoordinate)
.toArray(Coordinate[]::new);
return new CoordinateArraySequence(coordinates);
}
private Coordinate transformCoordinate(Coordinate coordinate) {
ProjCoordinate c1 = new ProjCoordinate(coordinate.x, coordinate.y);
ProjCoordinate c2 = coordinateTransform.transform(c1, new ProjCoordinate());
return new Coordinate(c2.x, c2.y);
}
}
|
package io.chark.food.app.thread;
import io.chark.food.app.account.AccountService;
import io.chark.food.app.administrate.audit.AuditService;
import io.chark.food.app.comment.CommentService;
import io.chark.food.app.thread.categories.ThreadCategoryService;
import io.chark.food.domain.authentication.account.Account;
import io.chark.food.domain.comment.Comment;
import io.chark.food.domain.thread.Thread;
import io.chark.food.domain.thread.ThreadRepository;
import io.chark.food.domain.thread.category.ThreadCategory;
import io.chark.food.domain.thread.category.ThreadCategoryRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import java.util.Optional;
@Service
public class ThreadService {
private static final Logger LOGGER = LoggerFactory.getLogger(ThreadService.class);
private final ThreadRepository threadRepository;
private final ThreadCategoryService threadCategoryService;
private final AccountService accountService;
private final CommentService commentService;
private final AuditService auditService;
@Autowired
public ThreadService(ThreadRepository threadRepository, AuditService auditService, CommentService commentService, ThreadCategoryService threadCategoryService, AccountService accountService) {
this.threadRepository = threadRepository;
this.auditService = auditService;
this.commentService = commentService;
this.threadCategoryService = threadCategoryService;
this.accountService = accountService;
}
public Optional<Thread> update(Thread thread, Thread threadDetails) {
// Update other stuff.
thread.setTitle(threadDetails.getTitle());
thread.setDescription(threadDetails.getDescription());
thread.setAccount(threadDetails.getAccount());
thread.setRegistrationRequired(threadDetails.isRegistrationRequired());
thread.setThreadLink(threadDetails.getThreadLink());
try {
LOGGER.debug("Updating Thread{id={}} details", thread.getId());
return Optional.ofNullable(threadRepository.save(thread));
} catch (DataIntegrityViolationException e) {
LOGGER.error("Could not update thread", e);
auditService.error("Failed to update thread details");
return Optional.empty();
}
}
public void incrementView(Thread t){
t.setViewCount(t.incremenetViewCount());
threadRepository.save(t);
}
public List<Comment> getComments(long id){
return threadRepository.findOne(id).getComments();
}
public Optional<Thread> register(Account account, String title, String description, boolean registrationRequired, ThreadCategory threadCategory) {
Thread thread = new Thread(account,
title,
description,
registrationRequired,
threadCategory);
//TODO remove from live
for (int i = 0; i < 10; i++) {
thread.addComment(commentService.register(account, "Long text is really long not much lol " + i, false).get());
}
try {
thread = threadRepository.save(thread);
LOGGER.debug("Created new Thread{title='{}'}", title);
auditService.info("Created a new Thread using title: %s", title);
} catch (DataIntegrityViolationException e) {
LOGGER.error("Failed while creating new Thread{title='{}'}", title, e);
auditService.error("Failed to create a Thread using title: %s", title);
return Optional.empty();
}
return Optional.of(thread);
}
public Optional<Thread> addComment(Optional<Thread> t, Comment comment) {
try {
t.get().addComment(comment);
} catch (DataIntegrityViolationException e) {
LOGGER.error("Failed while creating new Comment");
auditService.error("Failed to create a new Comment");
return Optional.empty();
}
return t;
}
public void addComment(long id, Comment comment){
Thread t = threadRepository.findOne(id);
t.addComment(comment);
}
public Thread getThread(long id) {
return threadRepository.findOne(id);
}
public void delete(long id){
Thread thread = threadRepository.findOne(id);
threadRepository.delete(thread);
auditService.info("Deleted Thread with id: %d", id);
}
public Optional<Thread> saveThread(long id, long cid, Thread threadDetails) {
Optional<Thread> optional;
Account currentAccount = accountService.getAccount();
if(currentAccount == null){
LOGGER.error("Could not save thread. User not found");
auditService.error("Failed to save Thread. User not found.");
return Optional.empty();
}
if (id <= 0) {
ThreadCategory threadCategory = threadCategoryService.getThreadCategory(cid);
optional = register(currentAccount,
threadDetails.getTitle(),
threadDetails.getDescription(),
threadDetails.isRegistrationRequired(),
threadCategory
);
} else {
optional = Optional.of(threadRepository.findOne(id));
}
if (!optional.isPresent()) {
return Optional.empty();
}
optional = update(optional.get(), threadDetails);
Thread thread = optional.get();
thread.setTitle(threadDetails.getTitle());
thread.setDescription(threadDetails.getDescription());
thread.setAccount(currentAccount);
thread.setThreadLink(threadDetails.getThreadLink());
try {
thread = threadRepository.save(thread);
LOGGER.debug("Saved Thread{id={}}", thread.getId());
auditService.debug("%s Thread with id: %d via front user",
id <= 0 ? "Created new" : "Updated", thread.getId());
return Optional.of(thread);
} catch (DataIntegrityViolationException e) {
LOGGER.error("Could not save thread", e);
auditService.error("Failed to save Thread");
return Optional.empty();
}
}
public List<Thread> getThreads() {
return threadRepository.findAll(new Sort(Sort.Direction.ASC, "title"));
}
} |
package com.softserveinc.uschedule.entity;
public enum NotificationType {
EMAIL, SMS, APPLICATION
}
|
package com.hfjy.framework.common.util;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base32;
import org.apache.commons.codec.binary.Base64;
public class EncryptUtil {
public static KeyPair getKeyPair(int keysize) throws Exception {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(keysize);
return keyPairGen.generateKeyPair();
}
public static byte[] RSAEncrypt(byte[] bytes, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(bytes);
}
public static byte[] RSADecrypt(byte[] bytes, PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(bytes);
}
public static PublicKey getPublicKey(String key) throws Exception {
byte[] keyBytes = base32Decrypt(key.getBytes());
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
}
public static PrivateKey getPrivateKey(String key) throws Exception {
byte[] keyBytes = base32Decrypt(key.getBytes());
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
}
public static String getKeyString(Key key) throws Exception {
byte[] keyBytes = base32Encrypt(key.getEncoded());
return new String(keyBytes);
}
public static byte[] AESEncrypt(byte[] bytes, byte[] key) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(key));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
return cipher.doFinal(bytes);
}
public static byte[] AESDecrypt(byte[] content, byte[] key) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(key));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
return cipher.doFinal(content);
}
public static byte[] DESEncrypt(byte[] bytes, byte[] key) throws Exception {
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
DESKeySpec desKeySpec = new DESKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(key);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
return cipher.doFinal(bytes);
}
public static byte[] DESDecrypt(byte[] bytes, byte[] key) throws Exception {
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
DESKeySpec desKeySpec = new DESKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(key);
cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
return cipher.doFinal(bytes);
}
public static String md5(String inputText) throws Exception {
MessageDigest m = MessageDigest.getInstance("md5");
m.update(inputText.getBytes());
return hex(m.digest());
}
public static byte[] md5(byte[] bytes) throws Exception {
MessageDigest m = MessageDigest.getInstance("md5");
m.update(bytes);
return m.digest();
}
public static String md5String(byte[] bytes) throws Exception {
MessageDigest m = MessageDigest.getInstance("md5");
m.update(bytes);
return hex(m.digest());
}
public static String sha(String inputText) throws Exception {
MessageDigest m = MessageDigest.getInstance("sha-1");
m.update(inputText.getBytes());
return hex(m.digest());
}
public static byte[] sha(byte[] bytes) throws Exception {
MessageDigest m = MessageDigest.getInstance("sha-1");
m.update(bytes);
return m.digest();
}
public static String shaString(byte[] bytes) throws Exception {
MessageDigest m = MessageDigest.getInstance("sha-1");
m.update(bytes);
return hex(m.digest());
}
public static byte[] base32Encrypt(byte[] bytes) {
Base32 base32 = new Base32();
return base32.encode(bytes);
}
public static byte[] base32Decrypt(byte[] bytes) {
Base32 base32 = new Base32();
return base32.decode(bytes);
}
public static byte[] base64Encrypt(byte[] bytes) {
return Base64.encodeBase64(bytes);
}
public static byte[] base64Decrypt(byte[] bytes) {
return Base64.decodeBase64(bytes);
}
private static String hex(byte[] arr) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < arr.length; ++i) {
sb.append(Integer.toHexString((arr[i] & 0xFF) | 0x100).substring(1, 3));
}
return sb.toString();
}
} |
package com.siicanada.article.service;
import com.siicanada.article.model.ArticleModel;
import java.util.List;
import org.springframework.stereotype.Service;
/**
* Business Logic Layer interface.
*/
@Service
public interface ArticleService {
/**
* Get all articles.
*
* @return List list of articles.
*/
List<ArticleModel> getArticles();
/**
* Get one article by id.
*
* @param id article id
* @return Article article
*/
ArticleModel getArticleById(Integer id);
/**
* Get articles by tag descriptions.
*
* @param description tag description
* @return List list of articles.
*/
List<ArticleModel> getArticlesByTagDescription(String description);
}
|
package prog2.examen.entities;
import java.time.LocalDateTime;
public class PartidaVacuna implements Comparable<PartidaVacuna> {
private LocalDateTime fecha;
private TipoVacuna tipo;
private int cantidad;
private LocalDateTime vencimiento;
public PartidaVacuna(LocalDateTime fecha, TipoVacuna tipo, int cantidad, LocalDateTime vencimiento) {
this.fecha = fecha;
this.tipo = tipo;
this.cantidad = cantidad;
this.vencimiento = vencimiento;
}
public void vacunar() {
this.cantidad--;
}
public LocalDateTime getFecha() {
return fecha;
}
public TipoVacuna getTipo() {
return tipo;
}
public int getCantidad() {
return cantidad;
}
public void setCantidad(int cantidad) {
this.cantidad = cantidad;
}
public LocalDateTime getVencimiento() {
return vencimiento;
}
@Override
public int compareTo(PartidaVacuna o) {
return this.vencimiento.compareTo(o.getVencimiento());
}
}
|
package aspectj.examples.services;
import org.springframework.stereotype.Service;
/**
* Created by aziring on 8/29/17.
*/
@Service
public class DemoServices {
public void processData() {
// dummy method to test logging entry statement
}
}
|
package ca.girardprogramming.buggedout;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockListFragment;
public class IssuesFragmentTab extends SherlockListFragment {
TextView issueId;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.issues_fragment_tab, container,
false);
return view;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public boolean onOptionsItemSelected(
com.actionbarsherlock.view.MenuItem item) {
if (item.getTitle().equals(getString(R.string.action_refresh))) {
updateList();
Toast.makeText(getActivity(), "Refreshing the Issues list...",
Toast.LENGTH_SHORT).show();
return super.onOptionsItemSelected(item);
}
return false;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!updateList()) {
// add click listener for refresh button
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
DBMethods dbMethods = new DBMethods(getActivity());
dbMethods.insertDemoData();
updateList();
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(
"No issues found,Would you like to populate with demo Demo issues?")
.setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
}
}
// updates list view with appropriate data
private Boolean updateList() {
DBMethods dbMethods = new DBMethods(getActivity());
ArrayList<HashMap<String, String>> issuesList = dbMethods
.getAllIssues();
if (issuesList.size() != 0) {
ListView listView = getListView();
ListAdapter adapter = new CustomSimpleAdapter(getActivity(),
issuesList, R.layout.issue_row,
new String[] { "issueId", "issueTitle", "projectName",
"priority", "category" }, new int[] {
R.id.issueIdRowTextView,
R.id.issueTitleRowTextView,
R.id.projectNameRowTextView,
R.id.priorityRowTextView,
R.id.issueCategoryRowTextView });
setListAdapter(adapter);
}
if (issuesList.size() == 0) {
return false;
}
return true;
}
}
|
package com.karya.model;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name="recruitopening001mb")
public class RecruitOpening001MB implements Serializable {
private static final long serialVersionUID = -723583058586873479L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "jobId")
private int jobId;
@Column(name="jobName")
private String jobName;
@Column(name="status")
private String status;
@OneToMany(mappedBy="recruitopening001mb")
private Set<RecruitApplicant001MB> recruitapplicant001mb;
public Set<RecruitApplicant001MB> getRecruitapplicant001mb() {
return recruitapplicant001mb;
}
public void setRecruitapplicant001mb(Set<RecruitApplicant001MB> recruitapplicant001mb) {
this.recruitapplicant001mb = recruitapplicant001mb;
}
public int getJobId() {
return jobId;
}
public void setJobId(int jobId) {
this.jobId = jobId;
}
public String getJobName() {
return jobName;
}
public void setJobName(String jobName) {
this.jobName = jobName;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
|
/*
Copyright 2013 Andrew Joiner
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 uk.co.tekkies.readings.adapter;
import java.util.ArrayList;
import java.util.List;
import uk.co.tekkies.readings.R;
import uk.co.tekkies.readings.ReadingsApplication;
import uk.co.tekkies.readings.activity.PassageActivity;
import uk.co.tekkies.readings.activity.ReadingsActivity;
import uk.co.tekkies.readings.day.DayFragment;
import uk.co.tekkies.readings.model.ParcelableReadings;
import uk.co.tekkies.readings.model.Passage;
import uk.co.tekkies.readings.model.Prefs;
import uk.co.tekkies.readings.util.Analytics;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class PortionArrayAdapter extends ArrayAdapter<Passage> implements OnClickListener {
private ReadingsActivity readingsActivity;
private ArrayList<Passage> passages;
Prefs prefs;
public PortionArrayAdapter(Activity activity, ArrayList<Passage> values) {
super(activity, R.layout.listitem_portion, values);
this.readingsActivity = (ReadingsActivity) activity;
this.passages = values;
prefs = new Prefs(activity);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) readingsActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewGroup view = (ViewGroup) inflater.inflate(R.layout.listitem_portion, parent, false);
TextView textViewPassageTitle = (TextView) view.findViewById(R.id.passage_title);
TextView textViewSummary = (TextView) view.findViewById(R.id.textViewSummary);
textViewPassageTitle.setText(passages.get(position).getTitle());
view.setTag(passages.get(position).getTitle());
textViewPassageTitle.setOnClickListener(this);
view.findViewById(R.id.imageViewReadOffline).setOnClickListener(this);
view.findViewById(R.id.imageViewReadOnline).setOnClickListener(this);
textViewSummary.setOnClickListener(this);
if (ReadingsApplication.getMp3Installed()) {
View listenView = view.findViewById(R.id.imageListen);
listenView.setVisibility(View.VISIBLE);
listenView.setOnClickListener(this);
}
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(readingsActivity);
Boolean showSummary = settings.getBoolean(Prefs.PREF_SHOW_SUMMARY, true);
if (showSummary) {
textViewSummary.setText(passages.get(position).getSummary());
} else {
textViewSummary.setVisibility(View.GONE);
}
return view;
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.passage_title:
Analytics.UIClick(readingsActivity, "passage_title");
tryOpenIntegratedReader(((View) v.getParent().getParent()).getTag().toString());
break;
case R.id.textViewSummary:
Analytics.UIClick(readingsActivity, "passage_summay");
tryOpenIntegratedReader(((View) v.getParent()).getTag().toString());
break;
case R.id.imageViewReadOffline:
Analytics.UIClick(readingsActivity, "passage_read_offline");
tryOpenIntegratedReader(((View) v.getParent().getParent()).getTag().toString());
break;
case R.id.imageListen:
Analytics.UIClick(readingsActivity, "passage_listen");
openMp3(((View) v.getParent().getParent()).getTag().toString());
break;
case R.id.imageViewReadOnline:
Analytics.UIClick(readingsActivity, "passage_read_online");
openPositiveWord(((View) v.getParent().getParent()).getTag().toString());
break;
}
}
private void tryOpenIntegratedReader(String passage) {
PackageInfo packageInfo = getOfflineKgvPackageInfo();
if(packageInfo == null){
askUserToInstallKjvPlugin();
} else {
if(packageInfo.versionCode < 103030000) {
//openOfflineBible(passage);
upgradeKjvBiblePlugin(passage);
} else {
openIntegratedReader(passage);
}
}
}
private void upgradeKjvBiblePlugin(String passage) {
final String finalPassage = passage;
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(readingsActivity);
dlgAlert.setMessage(readingsActivity.getString(R.string.please_upgrade_the_kjv_bible_plugin));
dlgAlert.setTitle(readingsActivity.getString(R.string.upgrade_plugin));
dlgAlert.setCancelable(true);
dlgAlert.setPositiveButton("Download update",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
installKjvPlugin();
}
});
dlgAlert.setNegativeButton("Use old version",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
openOfflineBible(finalPassage);
}
});
dlgAlert.create().show();
}
private PackageInfo getOfflineKgvPackageInfo() {
PackageInfo packageInfo=null;
try {
packageInfo = readingsActivity.getPackageManager().getPackageInfo("uk.co.tekkies.plugin.kjv", 0);
} catch (NameNotFoundException e) {
//swallow it
}
return packageInfo;
}
private void openOfflineBible(String passage) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setType("vnd.android.cursor.item/vnd.uk.co.tekkies.bible.passage");
intent.putExtra("passage", passage);
//Look for plugin in packages
PackageManager pm = readingsActivity.getPackageManager();
List<ResolveInfo> list = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
if (list.size() > 0) {
// Intent can be serviced, try it.
readingsActivity.startActivity(intent);
} else {
// install the off-line Bible
Toast.makeText(readingsActivity, "The offline bible must be installed from Google Play.", Toast.LENGTH_LONG).show();
installKjvPlugin();
}
}
private void askUserToInstallKjvPlugin() {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(readingsActivity);
dlgAlert.setMessage(R.string.install_kjv_bible_plugin);
dlgAlert.setTitle(R.string.title_install);
dlgAlert.setCancelable(true);
dlgAlert.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
installKjvPlugin();
}
});
dlgAlert.create().show();
}
private boolean installKjvPlugin() {
boolean installed = false;
Uri marketUri = Uri.parse("market://details?id=uk.co.tekkies.plugin.kjv");
Intent marketIntent = new Intent(Intent.ACTION_VIEW).setData(marketUri);
PackageManager pm = readingsActivity.getPackageManager();
List<ResolveInfo> list = pm.queryIntentActivities(marketIntent, PackageManager.MATCH_DEFAULT_ONLY);
if (list.size() > 0)
readingsActivity.startActivity(marketIntent);
else {
Toast.makeText(readingsActivity, R.string.sorry_no_market_installed, Toast.LENGTH_LONG).show();
}
return installed;
}
private void openPositiveWord(String passage) {
String url = "http://read.thepositiveword.com/index.php?ref=" + Uri.encode(passage);
Intent webIntent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.parse(url);
webIntent.setData(uri);
readingsActivity.startActivity(webIntent);
}
private void openIntegratedReader(String selectedPassage) {
Intent intent = new Intent(readingsActivity, PassageActivity.class);
ParcelableReadings passableReadings = new ParcelableReadings(passages, selectedPassage, readingsActivity.getSelectedDate());
intent.putExtra(ParcelableReadings.PARCEL_NAME, passableReadings);
readingsActivity.startActivity(intent);
}
private void openMp3(String passage) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setType("vnd.android.cursor.item/vnd.uk.co.tekkies.mp3bible.passage");
intent.putExtra("passage", passage);
//Look for plugin in packages
PackageManager pm = readingsActivity.getPackageManager();
List<ResolveInfo> list = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
if (list.size() > 0) {
// Intent can be serviced, try it.
readingsActivity.startActivity(intent);
} else {
// install the off-line Bible
Toast.makeText(readingsActivity, "The MP3 plugin must be installed from Google Play.", Toast.LENGTH_LONG).show();
installKjvPlugin();
}
}
}
|
package com.jcodecraeer.xrecyclerview;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.jcodecraeer.xrecyclerview.touch.OnSwipeMenuItemClickListener;
import com.jcodecraeer.xrecyclerview.touch.SwipeMenu;
import com.jcodecraeer.xrecyclerview.touch.SwipeMenuCreator;
import com.jcodecraeer.xrecyclerview.touch.SwipeMenuLayout;
import com.jcodecraeer.xrecyclerview.touch.SwipeMenuView;
import java.util.ArrayList;
import java.util.List;
/**
* 基类adapter
*
* @author Sandy
* create at 16/6/2 下午2:14
*/
public abstract class BaseAdapter<ItemDataType> extends
RecyclerView.Adapter<BaseRecyclerViewHolder> implements View.OnClickListener {
private OnRecyclerViewItemClickListener mOnItemClickListener = null;
private ArrayList<ItemDataType> mItemDataList = new ArrayList<>();
/**
* Swipe menu click listener。
*/
private OnSwipeMenuItemClickListener mSwipeMenuItemClickListener = null;
private SwipeMenuCreator mSwipeMenuCreator = null;
/**
* 动态增加一条数据
*
* @param itemDataType 数据实体类对象
*/
public void append(ItemDataType itemDataType) {
if (itemDataType != null) {
mItemDataList.add(itemDataType);
notifyDataSetChanged();
}
}
/**
* 动态增加一组数据集合
*
* @param itemDataTypes 数据实体类集合
*/
public void append(List<ItemDataType> itemDataTypes) {
if (itemDataTypes.size() > 0) {
mItemDataList.addAll(itemDataTypes);
notifyDataSetChanged();
}
}
/**
* 替换全部数据
*
* @param itemDataTypes 数据实体类集合
*/
public void replace(List<ItemDataType> itemDataTypes) {
if (!mItemDataList.isEmpty()) mItemDataList.clear();
mItemDataList.addAll(itemDataTypes);
notifyDataSetChanged();
}
/**
* 移除一条数据集合
*
* @param position
*/
public void remove(int position) {
mItemDataList.remove(position);
notifyDataSetChanged();
}
public ArrayList<ItemDataType> getAll() {
return mItemDataList;
}
/**
* 移除一条数据
*
* @param item
*/
public void remove(ItemDataType item) {
if (mItemDataList != null) mItemDataList.remove(item);
notifyDataSetChanged();
}
/**
* 移除所有数据
*/
public void removeAll() {
if (mItemDataList != null) mItemDataList.clear();
notifyDataSetChanged();
}
public void cleanListData() {
if (mItemDataList != null) mItemDataList.clear();
}
@Override
public int getItemCount() {
return mItemDataList.size();
}
@Override
public BaseRecyclerViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View contentView = createView(viewGroup, viewType);
if (mSwipeMenuCreator != null) {
SwipeMenuLayout swipeMenuLayout = (SwipeMenuLayout) LayoutInflater.from(
viewGroup.getContext()).inflate(R.layout.item_swipe_menu_default, viewGroup, false);
SwipeMenu swipeLeftMenu = new SwipeMenu(swipeMenuLayout, viewType);
SwipeMenu swipeRightMenu = new SwipeMenu(swipeMenuLayout, viewType);
mSwipeMenuCreator.onCreateMenu(swipeLeftMenu, swipeRightMenu, viewType);
int leftMenuCount = swipeLeftMenu.getMenuItems().size();
if (leftMenuCount > 0) {
SwipeMenuView swipeLeftMenuView = (SwipeMenuView) swipeMenuLayout.findViewById(R.id.lv_swipe_left);
// noinspection WrongConstant
swipeLeftMenuView.setOrientation(swipeLeftMenu.getOrientation());
swipeLeftMenuView.bindMenu(swipeLeftMenu, XRecyclerView.LEFT_DIRECTION);
swipeLeftMenuView.bindMenuItemClickListener(mSwipeMenuItemClickListener, swipeMenuLayout);
}
int rightMenuCount = swipeRightMenu.getMenuItems().size();
if (rightMenuCount > 0) {
SwipeMenuView swipeRightMenuView = (SwipeMenuView) swipeMenuLayout.findViewById(R.id.lv_swipe_right);
// noinspection WrongConstant
swipeRightMenuView.setOrientation(swipeRightMenu.getOrientation());
swipeRightMenuView.bindMenu(swipeRightMenu, XRecyclerView.RIGHT_DIRECTION);
swipeRightMenuView.bindMenuItemClickListener(mSwipeMenuItemClickListener, swipeMenuLayout);
}
if (leftMenuCount > 0 ||rightMenuCount > 0) {
ViewGroup viewById = (ViewGroup) swipeMenuLayout.findViewById(R.id.lv_swipe_content);
viewById.addView(contentView);
contentView = swipeMenuLayout;
}
}
//将创建的View注册点击事件
contentView.setOnClickListener(this);
return createViewHolder(contentView, viewType);
}
@Override
public void onBindViewHolder(BaseRecyclerViewHolder viewHolder, int position) {
View itemView = viewHolder.itemView;
if (itemView instanceof SwipeMenuLayout) {
SwipeMenuLayout swipeMenuLayout = (SwipeMenuLayout) itemView;
int childCount = swipeMenuLayout.getChildCount();
for (int i = 0; i < childCount; i++) {
View childView = swipeMenuLayout.getChildAt(i);
if (childView instanceof SwipeMenuView) {
((SwipeMenuView) childView).bindAdapterViewHolder(viewHolder);
}
}
}
showData(viewHolder, position, mItemDataList.get(position));
viewHolder.itemView.setTag(mItemDataList.get(position));
}
/**
* 加载item的view,直接返回加载的view即可
*
* @param viewGroup 如果需要Context,可以viewGroup.getContext()获取
* @param i
* @return item 的 view
*/
public abstract View createView(ViewGroup viewGroup, int i);
/**
* 加载两个个ViewHolder,为BaseRecyclerViewHolder子类,直接返回子类的对象即可
*
* @param view item 的view
* @return BaseRecyclerViewHolder 基类ViewHolder
*/
public abstract BaseRecyclerViewHolder createViewHolder(View view, int itemType);
/**
* 显示数据抽象函数
*
* @param viewHolder 基类ViewHolder,需要向下转型为对应的ViewHolder(example:MainRecyclerViewHolder mainRecyclerViewHolder=(MainRecyclerViewHolder) viewHolder;)
* @param position 位置
* @param data 数据集合
*/
public abstract void showData(BaseRecyclerViewHolder viewHolder, int position, ItemDataType data);
@Override
public void onClick(View v) {
if (mOnItemClickListener != null) {
//注意这里使用getTag方法获取数据
mOnItemClickListener.onItemClick(v, v.getTag());
}
}
public void setOnItemClickListener(OnRecyclerViewItemClickListener listener) {
this.mOnItemClickListener = listener;
}
//默认接口
public interface OnRecyclerViewItemClickListener {
void onItemClick(View view, Object data);
}
/**
* 侧滑用添加
*/
void setSwipeMenuCreator(SwipeMenuCreator swipeMenuCreator) {
this.mSwipeMenuCreator = swipeMenuCreator;
}
/**
* Set to click menu listener.
*/
void setSwipeMenuItemClickListener(OnSwipeMenuItemClickListener swipeMenuItemClickListener) {
this.mSwipeMenuItemClickListener = swipeMenuItemClickListener;
}
} |
package ch.brickwork.mockapi.services;
import ch.brickwork.mockapi.Main;
import javax.print.attribute.standard.Media;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
/**
* index.html - is it best practice and beautiful? no. does it need to be? no.
*/
@Path("/")
public class Index {
@GET
@Produces(MediaType.TEXT_HTML)
public String getIndexHTML()
{
String tables = "<ul>";
for (String tableName : Main.db.getTableNames()) {
tables += "<li><a href=\"" + Main.BASE_URI + "tables/" + tableName + "\">" + tableName + "</a></li>";
}
tables += "</ul>";
String uploadForm = " <h1>File Upload</h1>\n" + "\n"
+ " <form action=\"" + Main.BASE_URI + "upload/\" method=\"post\" enctype=\"multipart/form-data\">\n" + "\n"
+ " <p>Select a file : <input type=\"file\" name=\"file\" size=\"45\" /></p>\n"
+ " <input type=\"submit\" value=\"Upload CSV\" />\n" + "\n" + " </form>";
return "<?xml version=\"1.0\"?><html>" + "<head><title>Mockapi</title></head>" + "<body>" + "<h1>Welcome to Mockapi</h1>" + "<h2>Tables</h2>" + tables
+ uploadForm + "</body>" + "</html>" + "" + "";
}
}
|
package com.example.john.monitor.phonerecorder;
import java.util.List;
public class VoiceFile
{
public static int selectedFilesCount = 0;
private String fullName;
private boolean selected;
private String showName;
private String showTime;
private long size;
public static void reverseAllCheckedState(List<VoiceFile> paramList)
{
int i = paramList.size();
int j = 0;
if (j >= i) {
return;
}
VoiceFile localVoiceFile = (VoiceFile)paramList.get(j);
if (((VoiceFile)paramList.get(j)).isSelected()) {}
for (boolean bool = false;; bool = true)
{
localVoiceFile.setSelected(bool);
j++;
break;
}
}
public static List<VoiceFile> search(String[] paramArrayOfString)
{
return null;
}
public static void setAllToCheckedState(List<VoiceFile> paramList)
{
int i = paramList.size();
for (int j = 0;; j++)
{
if (j >= i) {
return;
}
((VoiceFile)paramList.get(j)).setSelected(true);
}
}
public static void setAllToUnCheckedState(List<VoiceFile> paramList)
{
int i = paramList.size();
for (int j = 0;; j++)
{
if (j >= i) {
return;
}
((VoiceFile)paramList.get(j)).setSelected(false);
}
}
public static void sortByFileSizeAsc(List<VoiceFile> paramList) {}
public static void sortByFileSizeDesc(List<VoiceFile> paramList) {}
public static void sortByTimeAsc(List<VoiceFile> paramList) {}
public static void sortByTimeDesc(List<VoiceFile> paramList) {}
public String getFullName()
{
return this.fullName;
}
public String getShowName()
{
return this.showName;
}
public String getShowTime()
{
return this.showTime;
}
public long getSize()
{
return this.size;
}
public boolean isSelected()
{
return this.selected;
}
public void setFullName(String paramString)
{
this.fullName = paramString;
}
public void setSelected(boolean paramBoolean)
{
if ((paramBoolean ^ this.selected))
{
this.selected = paramBoolean;
if (this.selected) {
selectedFilesCount = 1 + selectedFilesCount;
}
}
else
{
return;
}
selectedFilesCount = -1 + selectedFilesCount;
}
public void setShowName(String paramString)
{
this.showName = paramString;
}
public void setShowTime(String paramString)
{
this.showTime = paramString;
}
public void setSize(long paramLong)
{
this.size = paramLong;
}
}
/* Location: H:\baiduyundownload\android\反编译\record_dex2jar.jar!\com\sdvdxl\phonerecorder\VoiceFile.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ |
package com.nantian.foo.web.auth.entity;
import java.io.Serializable;
import javax.persistence.*;
@Entity
@Table(name = "role_info")
public class RoleInfo implements Serializable {
protected Long roleId;
protected String roleName;
protected String roleDesc;
protected String roleCreator;
public RoleInfo() {
}
public RoleInfo(Long roleId,String roleName,String roleDesc,String roleCreator)
{
this.roleId = roleId;
this.roleName = roleName;
this.roleDesc = roleDesc;
this.roleCreator = roleCreator;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getRoleId() {
return roleId;
}
public void setRoleId(Long roleId) {
this.roleId = roleId;
}
@Basic
@Column(name = "role_name")
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
@Basic
@Column(name = "role_desc")
public String getRoleDesc() {
return roleDesc;
}
public void setRoleDesc(String roleDesc) {
this.roleDesc = roleDesc;
}
@Basic
@Column(name = "role_creator")
public String getRoleCreator() {
return roleCreator;
}
public void setRoleCreator(String roleCreator) {
this.roleCreator = roleCreator;
}
}
|
package presentation.websalesman.model;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import vo.WebPromotionVO.LevelVO;
/**
* Created by 曹利航 on 2016/12/11 14:14.
*/
public class LevelPromotion {
final private StringProperty level;
final private StringProperty credit;
final private StringProperty discount;
public LevelPromotion(LevelVO levelVO) {
level = new SimpleStringProperty(String.format("%02d", levelVO.getLevel()));
credit = new SimpleStringProperty(String.format("%.2f", levelVO.getCredit()));
discount = new SimpleStringProperty(String.format("%.2f", levelVO.getDiscount()));
}
public LevelVO toLevelVO() {
return new LevelVO(Integer.valueOf(level.get()), Double.valueOf(credit.get()), Double.valueOf(discount.get()));
}
public String getLevel() {
return level.get();
}
public StringProperty levelProperty() {
return level;
}
public void setLevel(String level) {
this.level.set(level);
}
public String getCredit() {
return credit.get();
}
public StringProperty creditProperty() {
return credit;
}
public void setCredit(String credit) {
this.credit.set(credit);
}
public String getDiscount() {
return discount.get();
}
public StringProperty discountProperty() {
return discount;
}
public void setDiscount(String discount) {
this.discount.set(discount);
}
}
|
package com.evan.demo.yizhu.yuding;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import com.evan.demo.yizhu.R;
public class yuding_hotel_more extends AppCompatActivity {
private int flag = 1;
private Button back;
private ImageButton shangla;
private LinearLayout hotel_more;
private Button yuyue1;
private Button yuyue2;
private Button yuyue3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yuding_hotel_more);
back = (Button)findViewById(R.id.hotel_more_back);
shangla = (ImageButton)findViewById(R.id.hotel_shangla);
hotel_more = (LinearLayout)findViewById(R.id.hotel_more);
yuyue1 = (Button)findViewById(R.id.hotel_yuyue1);
yuyue2 = (Button)findViewById(R.id.hotel_yuyue2);
yuyue3 = (Button)findViewById(R.id.hotel_yuyue3);
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
yuding_hotel_more.this.finish();
}
});
shangla.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(flag == 1){
shangla.setImageDrawable(getResources().getDrawable(R.drawable.yuding_xiala));
hotel_more.setVisibility(View.GONE);
flag=0;
}
else {
shangla.setImageDrawable(getResources().getDrawable(R.drawable.hotel_more_jiantou));
hotel_more.setVisibility(View.VISIBLE);
flag=1;
}
}
});
yuyue1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(yuding_hotel_more.this,com.evan.demo.yizhu.yuding.yuding_yuyue.class);
startActivity(i);
}
});
yuyue2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(yuding_hotel_more.this,com.evan.demo.yizhu.yuding.yuding_yuyue.class);
startActivity(i);
}
});
yuyue3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(yuding_hotel_more.this,com.evan.demo.yizhu.yuding.yuding_yuyue.class);
startActivity(i);
}
});
}
}
|
package name.stojanok.dzone.scripteddataset;
public class Person {
private String firstName;
private String lastName;
private OtherPersonData otherPersonData;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public OtherPersonData getOtherPersonData() {
return otherPersonData;
}
public void setOtherPersonData(OtherPersonData otherPersonData) {
this.otherPersonData = otherPersonData;
}
}
|
package com.gxtc.huchuan.bean.event;
import java.io.Serializable;
/**
* Created by Steven on 17/5/3.
*/
public class EventJPushMessgeBean implements Serializable {
public String userPic ;
public String userName;
public String unReadNum;
public String userCode;
public EventJPushMessgeBean(String userPic, String userName, String unReadNum, String userCode) {
this.userPic = userPic;
this.userName = userName;
this.unReadNum = unReadNum;
this.userCode = userCode;
}
}
|
package com.lior.AdoptMe.repo;
import com.lior.AdoptMe.entitiy.ContactRequest;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface IContactRequestRepo extends JpaRepository<ContactRequest, Long> {
void deleteContactRequestById(Long id);
Optional<ContactRequest> findContactRequestById(Long id);
}
|
package org.squonk.camel.chemaxon.dataformat;
import chemaxon.formats.MolExporter;
import chemaxon.struc.Molecule;
import org.squonk.chemaxon.molecule.MoleculeUtils;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collections;
import java.util.Iterator;
import org.apache.camel.Exchange;
import org.apache.camel.spi.DataFormat;
/**
*
* @author timbo
*/
public class MoleculeIteratorDataFormat implements DataFormat {
@Override
public void marshal(Exchange exchange, Object o, OutputStream out) throws Exception {
Iterator<Molecule> mols = null;
if (o instanceof Iterator) {
mols = (Iterator<Molecule>) o;
} else if (o instanceof Iterable) {
mols = ((Iterable) o).iterator();
} else if (o instanceof Molecule) {
mols = Collections.singletonList((Molecule)o).iterator();
}
MolExporter exporter = new MolExporter(out, "sdf");
try {
while (mols.hasNext()) {
exporter.write(mols.next());
}
} finally {
exporter.close();
}
}
@Override
public Object unmarshal(Exchange exchange, InputStream in) throws Exception {
Iterator it = MoleculeUtils.createIterable(in).iterator();
return it;
}
}
|
/*
* 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.test.context.cache;
import java.util.Set;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.test.context.CacheAwareContextLoaderDelegate;
import org.springframework.test.context.ContextLoader;
import org.springframework.test.context.MergedContextConfiguration;
import org.springframework.test.context.support.DelegatingSmartContextLoader;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link AotMergedContextConfiguration}.
*
* @author Sam Brannen
* @since 6.0
*/
class AotMergedContextConfigurationTests {
private final CacheAwareContextLoaderDelegate delegate =
new DefaultCacheAwareContextLoaderDelegate(mock());
private final ContextLoader contextLoader = new DelegatingSmartContextLoader();
private final MergedContextConfiguration mergedConfig = new MergedContextConfiguration(getClass(), null, null,
Set.of(DemoApplicationContextInitializer.class), null, contextLoader);
private final AotMergedContextConfiguration aotMergedConfig1 = new AotMergedContextConfiguration(getClass(),
DemoApplicationContextInitializer.class, mergedConfig, delegate);
private final AotMergedContextConfiguration aotMergedConfig2 = new AotMergedContextConfiguration(getClass(),
DemoApplicationContextInitializer.class, mergedConfig, delegate);
@Test
void testEquals() {
assertThat(aotMergedConfig1).isEqualTo(aotMergedConfig1);
assertThat(aotMergedConfig1).isEqualTo(aotMergedConfig2);
assertThat(mergedConfig).isNotEqualTo(aotMergedConfig1);
assertThat(aotMergedConfig1).isNotEqualTo(mergedConfig);
}
@Test
void testHashCode() {
assertThat(aotMergedConfig1).hasSameHashCodeAs(aotMergedConfig2);
assertThat(aotMergedConfig1).doesNotHaveSameHashCodeAs(mergedConfig);
}
static class DemoApplicationContextInitializer implements ApplicationContextInitializer<GenericApplicationContext> {
@Override
public void initialize(GenericApplicationContext applicationContext) {
}
}
}
|
package utils;
public class LOGGER {
public static void info(String msg) {
System.out.print("Info: " + msg);
System.out.println();
}
public static void error(String msg) {
System.out.println();
System.out.print("Error: " + msg);
System.out.println();
}
}
|
package com.ict.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.ict.service.DAO;
import com.ict.service.VO;
@Controller
public class MyController {
@Autowired
private DAO dao;
public DAO getDao() {
return dao;
}
public void setDao(DAO dao) {
this.dao = dao;
}
@RequestMapping("/")
public ModelAndView getList() {
ModelAndView mv = new ModelAndView();
mv.setViewName("list");
// DB 처리 후 저장
List<VO> list = dao.getList();
mv.addObject("list", list);
return mv;
}
@RequestMapping("add.do")
public ModelAndView getAdd(VO vo) {
ModelAndView mv = new ModelAndView();
mv.setViewName("redirect:/");
// DB 처리 후 저장
dao.getInsert(vo);
return mv;
}
@RequestMapping("onelist.do")
public ModelAndView getOneList(VO vo) {
ModelAndView mv = new ModelAndView();
mv.setViewName("onelist");
// DB 처리 후 저장
VO one_vo = dao.getOneList(vo);
mv.addObject("vo", one_vo);
return mv;
}
@RequestMapping("delete.do")
public ModelAndView getDelete(VO vo) {
ModelAndView mv = new ModelAndView();
mv.setViewName("redirect:/");
// DB 처리 후 저장
mv.addObject("ok",dao.getDelete(vo));
return mv;
}
@RequestMapping("update.do")
public ModelAndView getUpdate(VO vo) {
ModelAndView mv = new ModelAndView();
mv.setViewName("update");
// DB 처리 후 저장
VO one_vo = dao.getOneList(vo);
mv.addObject("onevo", one_vo);
return mv;
}
@RequestMapping("update_ok.do")
public ModelAndView getUpdate_ok(VO vo) {
ModelAndView mv = new ModelAndView();
mv.setViewName("redirect:/onelist.do?id="+vo.getId());
// DB 처리 후 저장
dao.getUpdate(vo);
return mv;
}
}
|
package physics;
import java.util.ArrayList;
import java.util.List;
public class PhysicsHandeler {
private List<Collideable> collideables = new ArrayList<>();
public void update() {
for (int i = 0; i < collideables.size()-1; i++) {
//for (int j = i+1)
}
}
public void addCollideable(Collideable unit) {
collideables.add(unit);
}
public void removeCollideable(Collideable unit) {
collideables.remove(unit);
}
public static boolean isCollision(Collideable coll1, Collideable coll2) {
return isCollision(coll1.getPhShape(), coll2.getPhShape());
}
public static boolean isCollision( PhShape shape1, PhShape shape2 ) {
if (shape1 instanceof PhCircle && shape2 instanceof PhCircle) {
return isCollision((PhCircle)shape1, (PhCircle)shape2);
}
else if (shape1 instanceof PhCircle && shape2 instanceof PhRectangle) {
return isCollision((PhCircle)shape1, (PhRectangle)shape2);
}
else if (shape1 instanceof PhRectangle && shape2 instanceof PhCircle) {
return isCollision((PhCircle)shape2, (PhRectangle)shape1);
}
else if (shape1 instanceof PhRectangle && shape2 instanceof PhRectangle) {
return isCollision((PhRectangle)shape1, (PhRectangle)shape2);
}
throw new UnsupportedOperationException("Cannot check collision between given shapes");
}
public static boolean isCollision(PhCircle circ1, PhCircle circ2) {
float r1 = circ1.getRadius();
float x1 = circ1.getX();
float y1 = circ1.getY();
float r2 = circ2.getRadius();
float x2 = circ2.getX();
float y2 = circ2.getY();
float maxDistSquared = r1 + r2;
float distSquared = (float)( Math.pow((float)(y2-y1), 2) + Math.pow((float)(x2-x1), 2) );
return distSquared < maxDistSquared;
}
public static boolean isCollision(PhCircle circ1, PhRectangle rect2) {
//throw new UnsupportedOperationException("Circ-rect collision not supported yet");
float r1 = circ1.getRadius();
float cx = circ1.getX();
float cy = circ1.getY();
float x2 = rect2.getX();
float y2 = rect2.getY();
float w2 = rect2.getWidth();
float h2 = rect2.getHeight();
// float bx = cx-r1;
// float by = cy-r1;
// float bWidth = 2*r1;
// float bHeigth = 2*r1;
// if (!(isCollision(rect2, new PhRectangle(bx, by, bWidth, bHeigth)))){
// return false;
// }
if (!isCollision(rect2, circ1.getBoundingBox())){
return false;
}
float r2 = r1*r1;
if (y2>cy){
if (x2>cx){
return (r2>(x2-cx)*(x2-cx) + (y2-cy)*(y2-cy));
}
else if (cx>x2+w2){
return (r2>(x2+w2-cx)*(x2+w2-cx) + (y2-cy)*(y2-cy));
}
}
else if (y2+h2<cy) {
if (x2>cx){
return (r2>(x2-cx)*(x2-cx) + (y2+h2-cy)*(y2+h2-cy));
}
else if (cx>x2+w2){
return (r2>(x2+w2-cx)*(x2+w2-cx) + (y2+h2-cy)*(y2+h2-cy));
}
}
return true;
}
public static boolean isCollision(PhRectangle rect1, PhRectangle rect2) {
float x1 = rect1.getX();
float y1 = rect1.getY();
float w1 = rect1.getWidth();
float h1 = rect1.getHeight();
float x2 = rect2.getX();
float y2 = rect2.getY();
float w2 = rect2.getWidth();
float h2 = rect2.getHeight();
return ( (x2 < x1+w1 && x2+w2 > x1) && (y2 < y1+h1 && y2+h2 >y1) );
}
}
|
package roombook.dao;
import roombook.guest.Guest;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
public class GuestsDAO
{
public void insertGuest(Guest guest) throws Exception
{
EntityManager entityManager= DatabaseUtils.getEMFactory().createEntityManager();
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
try
{
entityManager.persist(guest);
transaction.commit();
}
catch (Exception e)
{
transaction.rollback();
throw e;
}
finally
{
entityManager.close();
}
}
}
|
package frc;
/**
* For when you're too lazy to make a class to return multiple values.
*/
public class Tuples {
private Tuples() {
}
/**
* A 2-tuple. Also known as a twople.
*/
public static class Two<A, B> {
public final A first;
public final B second;
public Two(A first, B second) {
this.first = first;
this.second = second;
}
}
/**
* A 3-tuple. Also known as a threeple.
*/
public static class Three<A, B, C> extends Two<A, B> {
public final C third;
public Three(A first, B second, C third) {
super(first, second);
this.third = third;
}
}
/**
* A 4-tuple. Also known as a fourple.
*/
public static class Four<A, B, C, D> extends Three<A, B, C> {
public final D fourth;
public Four(A first, B second, C third, D fourth) {
super(first, second, third);
this.fourth = fourth;
}
}
/**
* A 5-tuple. Also known as a fiveple.
*/
public static class Five<A, B, C, D, E> extends Four<A, B, C, D> {
public final E fifth;
public Five(A first, B second, C third, D fourth, E fifth) {
super(first, second, third, fourth);
this.fifth = fifth;
}
}
/**
* A 6-tuple. Also known as a sixple.
*/
public static class Six<A, B, C, D, E, F> extends Five<A, B, C, D, E> {
public final F sixth;
public Six(A first, B second, C third, D fourth, E fifth, F sixth) {
super(first, second, third, fourth, fifth);
this.sixth = sixth;
}
}
/**
* A 7-tuple. Also known as a sevenple.
*/
public static class Seven<A, B, C, D, E, F, G> extends Six<A, B, C, D, E, F> {
public final G seventh;
public Seven(A first, B second, C third, D fourth, E fifth, F sixth, G seventh) {
super(first, second, third, fourth, fifth, sixth);
this.seventh = seventh;
}
}
/**
* An 8-tuple. Also known as an eightple.
*/
public static class Eight<A, B, C, D, E, F, G, H> extends Seven<A, B, C, D, E, F, G> {
public final H eighth;
public Eight(A first, B second, C third, D fourth, E fifth, F sixth, G seventh, H eighth) {
super(first, second, third, fourth, fifth, sixth, seventh);
this.eighth = eighth;
}
}
/**
* A 9-tuple. Also known as a nineple.
*/
public static class Nine<A, B, C, D, E, F, G, H, I> extends Eight<A, B, C, D, E, F, G, H> {
public final I ninth;
public Nine(A first, B second, C third, D fourth, E fifth, F sixth, G seventh, H eighth, I ninth) {
super(first, second, third, fourth, fifth, sixth, seventh, eighth);
this.ninth = ninth;
}
}
/**
* A 10-tuple. Also known as a tenple.
*/
public static class Ten<A, B, C, D, E, F, G, H, I, J> extends Nine<A, B, C, D, E, F, G, H, I> {
public final J tenth;
public Ten(A first, B second, C third, D fourth, E fifth, F sixth, G seventh, H eighth, I ninth, J tenth) {
super(first, second, third, fourth, fifth, sixth, seventh, eighth, ninth);
this.tenth = tenth;
}
}
/**
* An 11-tuple. Also known as an elevenple.
*/
public static class Eleven<A, B, C, D, E, F, G, H, I, J, K> extends Ten<A, B, C, D, E, F, G, H, I, J> {
public final K eleventh;
public Eleven(A first, B second, C third, D fourth, E fifth, F sixth, G seventh, H eighth, I ninth, J tenth,
K eleventh) {
super(first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth);
this.eleventh = eleventh;
}
}
/**
* A 12-tuple. Also known as a twelveple.
*/
public static class Twelve<A, B, C, D, E, F, G, H, I, J, K, L> extends Eleven<A, B, C, D, E, F, G, H, I, J, K> {
public final L twelfth;
public Twelve(A first, B second, C third, D fourth, E fifth, F sixth, G seventh, H eighth, I ninth, J tenth,
K eleventh, L twelfth) {
super(first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh);
this.twelfth = twelfth;
}
}
/**
* A 13-tuple. Also known as a thirteenple.
*/
public static class Thirteen<A, B, C, D, E, F, G, H, I, J, K, L, M>
extends Twelve<A, B, C, D, E, F, G, H, I, J, K, L> {
public final M thirteenth;
public Thirteen(A first, B second, C third, D fourth, E fifth, F sixth, G seventh, H eighth, I ninth, J tenth,
K eleventh, L twelfth, M thirteenth) {
super(first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth);
this.thirteenth = thirteenth;
}
}
/**
* A 14-tuple. Also known as a fourteenple.
*/
public static class Fourteen<A, B, C, D, E, F, G, H, I, J, K, L, M, N>
extends Thirteen<A, B, C, D, E, F, G, H, I, J, K, L, M> {
public final N fourteenth;
public Fourteen(A first, B second, C third, D fourth, E fifth, F sixth, G seventh, H eighth, I ninth, J tenth,
K eleventh, L twelfth, M thirteenth, N fourteenth) {
super(first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth,
thirteenth);
this.fourteenth = fourteenth;
}
}
/**
* A 15-tuple. Also known as a fifteenple.
*/
public static class Fifteen<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O>
extends Fourteen<A, B, C, D, E, F, G, H, I, J, K, L, M, N> {
public final O fifteenth;
public Fifteen(A first, B second, C third, D fourth, E fifth, F sixth, G seventh, H eighth, I ninth, J tenth,
K eleventh, L twelfth, M thirteenth, N fourteenth, O fifteenth) {
super(first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth,
thirteenth, fourteenth);
this.fifteenth = fifteenth;
}
}
/**
* A 16-tuple. Also known as a sixteenple.
*/
public static class Sixteen<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P>
extends Fifteen<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O> {
public final P sixteenth;
public Sixteen(A first, B second, C third, D fourth, E fifth, F sixth, G seventh, H eighth, I ninth, J tenth,
K eleventh, L twelfth, M thirteenth, N fourteenth, O fifteenth, P sixteenth) {
super(first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth,
thirteenth, fourteenth, fifteenth);
this.sixteenth = sixteenth;
}
}
/**
* A 17-tuple. Also known as a seventeenple.
*/
public static class Seventeen<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q>
extends Sixteen<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P> {
public final Q seventeenth;
public Seventeen(A first, B second, C third, D fourth, E fifth, F sixth, G seventh, H eighth, I ninth, J tenth,
K eleventh, L twelfth, M thirteenth, N fourteenth, O fifteenth, P sixteenth, Q seventeenth) {
super(first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth,
thirteenth, fourteenth, fifteenth, sixteenth);
this.seventeenth = seventeenth;
}
}
/**
* An 18-tuple. Also known as an eighteenple.
*/
public static class Eighteen<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R>
extends Seventeen<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q> {
public final R eighteenth;
public Eighteen(A first, B second, C third, D fourth, E fifth, F sixth, G seventh, H eighth, I ninth, J tenth,
K eleventh, L twelfth, M thirteenth, N fourteenth, O fifteenth, P sixteenth, Q seventeenth,
R eighteenth) {
super(first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth,
thirteenth, fourteenth, fifteenth, sixteenth, seventeenth);
this.eighteenth = eighteenth;
}
}
/**
* A 19-tuple. Also known as a nineteenple.
*/
public static class Nineteen<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S>
extends Eighteen<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R> {
public final S nineteenth;
public Nineteen(A first, B second, C third, D fourth, E fifth, F sixth, G seventh, H eighth, I ninth, J tenth,
K eleventh, L twelfth, M thirteenth, N fourteenth, O fifteenth, P sixteenth, Q seventeenth,
R eighteenth, S nineteenth) {
super(first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth,
thirteenth, fourteenth, fifteenth, sixteenth, seventeenth, eighteenth);
this.nineteenth = nineteenth;
}
}
/**
* A 20-tuple. Also known as a twentyple.
*/
public static class Twenty<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T>
extends Nineteen<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S> {
public final T twentieth;
public Twenty(A first, B second, C third, D fourth, E fifth, F sixth, G seventh, H eighth, I ninth, J tenth,
K eleventh, L twelfth, M thirteenth, N fourteenth, O fifteenth, P sixteenth, Q seventeenth,
R eighteenth, S nineteenth, T twentieth) {
super(first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth,
thirteenth, fourteenth, fifteenth, sixteenth, seventeenth, eighteenth, nineteenth);
this.twentieth = twentieth;
}
}
/**
* A 21-tuple. Also known as a twenty-oneple.
*/
public static class TwentyOne<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U>
extends Twenty<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T> {
public final U twentyFirst;
public TwentyOne(A first, B second, C third, D fourth, E fifth, F sixth, G seventh, H eighth, I ninth, J tenth,
K eleventh, L twelfth, M thirteenth, N fourteenth, O fifteenth, P sixteenth, Q seventeenth,
R eighteenth, S nineteenth, T twentieth, U twentyFirst) {
super(first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth,
thirteenth, fourteenth, fifteenth, sixteenth, seventeenth, eighteenth, nineteenth, twentieth);
this.twentyFirst = twentyFirst;
}
}
/**
* A 22-tuple. Also known as a twenty-twople.
*/
public static class TwentyTwo<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V>
extends TwentyOne<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U> {
public final V twentySecond;
public TwentyTwo(A first, B second, C third, D fourth, E fifth, F sixth, G seventh, H eighth, I ninth, J tenth,
K eleventh, L twelfth, M thirteenth, N fourteenth, O fifteenth, P sixteenth, Q seventeenth,
R eighteenth, S nineteenth, T twentieth, U twentyFirst, V twentySecond) {
super(first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth,
thirteenth, fourteenth, fifteenth, sixteenth, seventeenth, eighteenth, nineteenth, twentieth,
twentyFirst);
this.twentySecond = twentySecond;
}
}
/**
* A 23-tuple. Also known as a twenty-threeple.
*/
public static class TwentyThree<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W>
extends TwentyTwo<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V> {
public final W twentyThird;
public TwentyThree(A first, B second, C third, D fourth, E fifth, F sixth, G seventh, H eighth, I ninth,
J tenth, K eleventh, L twelfth, M thirteenth, N fourteenth, O fifteenth, P sixteenth, Q seventeenth,
R eighteenth, S nineteenth, T twentieth, U twentyFirst, V twentySecond, W twentyThird) {
super(first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth,
thirteenth, fourteenth, fifteenth, sixteenth, seventeenth, eighteenth, nineteenth, twentieth,
twentyFirst, twentySecond);
this.twentyThird = twentyThird;
}
}
/**
* A 24-tuple. Also known as a twenty-fourple.
*/
public static class TwentyFour<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X>
extends TwentyThree<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W> {
public final X twentyFourth;
public TwentyFour(A first, B second, C third, D fourth, E fifth, F sixth, G seventh, H eighth, I ninth, J tenth,
K eleventh, L twelfth, M thirteenth, N fourteenth, O fifteenth, P sixteenth, Q seventeenth,
R eighteenth, S nineteenth, T twentieth, U twentyFirst, V twentySecond, W twentyThird, X twentyFourth) {
super(first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth,
thirteenth, fourteenth, fifteenth, sixteenth, seventeenth, eighteenth, nineteenth, twentieth,
twentyFirst, twentySecond, twentyThird);
this.twentyFourth = twentyFourth;
}
}
/**
* A 25-tuple. Also known as a twenty-fiveple.
*/
public static class TwentyFive<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y>
extends TwentyFour<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X> {
public final Y twentyFifth;
public TwentyFive(A first, B second, C third, D fourth, E fifth, F sixth, G seventh, H eighth, I ninth, J tenth,
K eleventh, L twelfth, M thirteenth, N fourteenth, O fifteenth, P sixteenth, Q seventeenth,
R eighteenth, S nineteenth, T twentieth, U twentyFirst, V twentySecond, W twentyThird, X twentyFourth,
Y twentyFifth) {
super(first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth,
thirteenth, fourteenth, fifteenth, sixteenth, seventeenth, eighteenth, nineteenth, twentieth,
twentyFirst, twentySecond, twentyThird, twentyFourth);
this.twentyFifth = twentyFifth;
}
}
/**
* A 26-tuple. Also known as a twenty-sixple.
*/
public static class TwentySix<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z>
extends TwentyFive<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y> {
public final Z twentySixth;
public TwentySix(A first, B second, C third, D fourth, E fifth, F sixth, G seventh, H eighth, I ninth, J tenth,
K eleventh, L twelfth, M thirteenth, N fourteenth, O fifteenth, P sixteenth, Q seventeenth,
R eighteenth, S nineteenth, T twentieth, U twentyFirst, V twentySecond, W twentyThird, X twentyFourth,
Y twentyFifth, Z twentySixth) {
super(first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth,
thirteenth, fourteenth, fifteenth, sixteenth, seventeenth, eighteenth, nineteenth, twentieth,
twentyFirst, twentySecond, twentyThird, twentyFourth, twentyFifth);
this.twentySixth = twentySixth;
}
}
// i guess i'll let running out of alphabet stop me... for now
} |
import java.io.PrintStream;
import java.util.HashMap;
import java.util.HashSet;
abstract class Tree {
public Tree left;
public Tree right;
public PrintStream out;
public Integer result = null;
abstract public void print(Integer nrTabs);
abstract public boolean interpret();
public void printTabs(Integer nrTabs) {
for (int i = 0; i < nrTabs; ++i) {
out.print("\t");
}
}
}
class MainNode extends Tree{
@Override
public void print(Integer nrTabs) {
printTabs(nrTabs);
out.println("<MainNode>");
left.out = out;
left.print(nrTabs + 1);
}
@Override
public boolean interpret() {
left.out = out;
return left.interpret();
}
}
class IntNode extends Tree {
public Integer data;
public IntNode(Integer data) {
this.data = data;
}
@Override
public void print(Integer nrTabs) {
printTabs(nrTabs);
out.println("<IntNode> " + data);
}
@Override
public boolean interpret() {
result = data;
return true;
}
}
class BoolNode extends Tree {
public String data;
public BoolNode(String data) {
this.data = data;
if (data.equals("true")) result = 1;
else result = 0;
}
@Override
public void print(Integer nrTabs) {
printTabs(nrTabs);
out.println("<BoolNode> " + data);
}
@Override
public boolean interpret() {
return true;
}
}
class VarNode extends Tree {
public String data;
public HashSet<String> vars;
public HashMap<String, Integer> varToValue;
public VarNode(String data, HashSet<String> vars, HashMap<String, Integer> varToValue) {
this.data = data;
this.vars = vars;
this.varToValue = varToValue;
}
@Override
public void print(Integer nrTabs) {
printTabs(nrTabs);
out.println("<VariableNode> " + data);
}
@Override
public boolean interpret() {
if (!vars.contains(data)) {
out.println("UnassignedVar 6");
return false;
}
result = varToValue.get(data);
return true;
}
}
class PlusNode extends Tree {
@Override
public void print(Integer nrTabs) {
printTabs(nrTabs);
out.println("<PlusNode> +" );
left.out = out;
left.print(nrTabs + 1);
right.out = out;
right.print(nrTabs + 1);
}
@Override
public boolean interpret() {
left.out = out;
right.out = out;
boolean ok = left.interpret();
if (!ok) {
return false;
} else {
ok = right.interpret();
if (!ok ) {
return false;
}
if (left.result == null || right.result == null) {
out.println("UnassignedVar 6");
return false;
}
result = left.result + right.result;
}
return true;
}
}
class DivNode extends Tree {
@Override
public void print(Integer nrTabs) {
printTabs(nrTabs);
out.println("<DivNode> /");
left.out = out;
left.print(nrTabs + 1);
right.out = out;
right.print(nrTabs + 1);
}
@Override
public boolean interpret() {
left.out = out;
right.out = out;
boolean ok = left.interpret();
if (!ok) {
return false;
} else {
ok = right.interpret();
if (!ok ) {
return false;
}
if (left.result == null || right.result == null) {
out.println("UnassignedVar 6");
return false;
}
if (right.result == 0) {
out.println("DivideByZero 4");
return false;
}
result = left.result / right.result;
}
return true;
}
}
class BracketNode extends Tree {
@Override
public void print(Integer nrTabs) {
printTabs(nrTabs);
out.println("<BracketNode> ()");
left.out = out;
left.print(nrTabs + 1);
}
@Override
public boolean interpret() {
left.out = out;
boolean ok = left.interpret();
result = left.result;
return ok;
}
}
class AndNode extends Tree {
@Override
public void print(Integer nrTabs) {
printTabs(nrTabs);
out.println("<AndNode> &&");
left.out = out;
left.print(nrTabs + 1);
right.out = out;
right.print(nrTabs + 1);
}
@Override
public boolean interpret() {
left.out = out;
right.out = out;
boolean ok = left.interpret();
if (!ok) {
return false;
} else {
ok = right.interpret();
if (!ok ) {
return false;
}
if (left.result == null || right.result == null) {
out.println("UnassignedVar 6");
return false;
}
if (left.result == 0 || right.result == 0) result = 0;
else result = 1;
}
return true;
}
}
class GreaterNode extends Tree {
@Override
public void print(Integer nrTabs) {
printTabs(nrTabs);
out.println("<GreaterNode> >");
left.out = out;
left.print(nrTabs + 1);
right.out = out;
right.print(nrTabs + 1);
}
@Override
public boolean interpret() {
left.out = out;
right.out = out;
boolean ok = left.interpret();
if (!ok) {
return false;
} else {
ok = right.interpret();
if (!ok ) {
return false;
}
if (left.result == null || right.result == null) {
out.println("UnassignedVar 6");
return false;
}
if (left.result > right.result) result = 1;
else result = 0;
}
return true;
}
}
class NotNode extends Tree {
@Override
public void print(Integer nrTabs) {
printTabs(nrTabs);
out.println("<NotNode> !");
left.out = out;
left.print(nrTabs + 1);
}
@Override
public boolean interpret() {
left.out = out;
boolean ok = left.interpret();
if (ok) {
if (left.result == null) {
out.println("UnassignedVar 6");
return false;
}
if (left.result == 0) result = 1;
else result = 0;
}
return ok;
}
}
class AssignmentNode extends Tree {
@Override
public void print(Integer nrTabs) {
printTabs(nrTabs);
out.println("<AssignmentNode> =");
left.out = out;
left.print(nrTabs + 1);
right.out = out;
right.print(nrTabs + 1);
}
@Override
public boolean interpret() {
left.out = out;
right.out = out;
boolean ok = left.interpret();
if (ok) {
ok = right.interpret();
if (ok) {
if (right.result == null) {
out.println("UnassignedVar 6");
return false;
}
VarNode aux = (VarNode) left;
aux.varToValue.put(aux.data, right.result);
aux.result = right.result;
}
}
return ok;
}
}
class BlockNode extends Tree {
@Override
public void print(Integer nrTabs) {
printTabs(nrTabs);
out.println("<BlockNode> {}");
if (left != null) {
left.out = out;
left.print(nrTabs + 1);
}
}
@Override
public boolean interpret() {
left.out = out;
boolean ok = left.interpret();
if (ok) {
result = left.result;
}
return ok;
}
}
class IfNode extends Tree {
Tree nodeElse;
@Override
public void print(Integer nrTabs) {
printTabs(nrTabs);
out.println("<IfNode> if");
left.out = out;
left.print(nrTabs + 1);
right.out = out;
right.print(nrTabs + 1);
nodeElse.out = out;
nodeElse.print(nrTabs + 1);
}
@Override
public boolean interpret() {
left.out = out;
right.out = out;
nodeElse.out = out;
boolean ok = left.interpret();
if (ok) {
if (left.result == 1) {
ok = right.interpret();
} else {
ok = nodeElse.interpret();
}
}
return ok;
}
}
class WhileNode extends Tree {
@Override
public void print(Integer nrTabs) {
printTabs(nrTabs);
out.println("<WhileNode> while");
left.out = out;
left.print(nrTabs + 1);
right.out = out;
right.print(nrTabs + 1);
}
@Override
public boolean interpret() {
left.out = out;
right.out = out;
boolean ok = left.interpret();
if (ok) {
if (left.result == null) {
out.println("UnassignedVar 6");
return false;
}
while (left.result == 1) {
ok = right.interpret();
if (!ok) break;
left.interpret();
}
}
return ok;
}
}
class SequenceNode extends Tree {
@Override
public void print(Integer nrTabs) {
if (left != null) {
if (left.left == null && left.right == null) {
left = null;
}
}
if (right != null) {
if (right.left == null && right.right == null) {
right = null;
}
}
if (left == null && right == null) return;
if (left != null && right != null) {
printTabs(nrTabs);
out.println("<SequenceNode>");
++nrTabs;
}
left.out = out;
left.print(nrTabs);
if (right != null) {
right.out = out;
right.print(nrTabs);
}
}
@Override
public boolean interpret() {
boolean ok = true;
if (left != null) {
left.out = out;
ok = left.interpret();
if (ok && right != null) {
right.out = out;
ok = right.interpret();
}
}
return ok;
}
}
|
package com.itheima.bos.web.action;
import java.io.IOException;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.itheima.bos.domain.Function;
import com.itheima.bos.domain.User;
import com.itheima.bos.utils.BOSContext;
import com.itheima.bos.utils.MD5Utils;
import com.itheima.bos.web.action.base.BaseAction;
import com.opensymphony.xwork2.ActionContext;
@Controller//("abc")
@Scope("prototype")
public class UserAction extends BaseAction<User>{
//提供属性接收验证码
private String checkcode;
/**
* 使用shiro方式进行认证
*/
public String login(){
//从session中获取自动生成的验证码
String key = (String) ActionContext.getContext().getSession().get("key");
if(StringUtils.isNotBlank(checkcode) && checkcode.equals(key)){
//使用shiro方式进行认证
String username = model.getUsername();
String password = model.getPassword();
password = MD5Utils.md5(password);
Subject subject = SecurityUtils.getSubject();//主体,当前状态为“未认证”状态
AuthenticationToken token = new UsernamePasswordToken(username, password);//用户名密码令牌
try{
subject.login(token);//使用subject调用SecurityManager,安全管理器调用Realm
User user = (User) subject.getPrincipal();
//登录成功,将User对象放入session
//ActionContext.getContext().getSession().put("loginUser", user);
ServletActionContext.getRequest().getSession().setAttribute("loginUser", user);
}catch (UnknownAccountException e) {//用户名不存在异常
e.printStackTrace();
return "login";
}catch (IncorrectCredentialsException e) {//密码错误异常
e.printStackTrace();
return "login";
}
return "home";
}else{
//验证码有误,添加错误信息,跳转到登录页面
this.addActionError(this.getText("checkcodeError"));
return "login";
}
}
public String login_bak(){
//从session中获取自动生成的验证码
String key = (String) ActionContext.getContext().getSession().get("key");
if(StringUtils.isNotBlank(checkcode) && checkcode.equals(key)){
//验证码正确
User user = userService.login(model);
if(user != null){
//登录成功,将User对象放入session
ActionContext.getContext().getSession().put("loginUser", user);
return "home";
}else{
//登录失败,添加错误信息,跳转到登录页面
this.addActionError(this.getText("loginError"));
return "login";
}
}else{
//验证码有误,添加错误信息,跳转到登录页面
this.addActionError(this.getText("checkcodeError"));
return "login";
}
}
/**
* 注销
*/
public String logout(){
ServletActionContext.getRequest().getSession().invalidate();
return "login";
}
/**
* 修改密码
* @throws IOException
*/
public String editPassword() throws IOException{
//Subject subject = SecurityUtils.getSubject();
//subject.checkPermission("abc");
String password = model.getPassword();
User user = BOSContext.getLoginUser();
String id = user.getId();
String flag = "1";
try{
userService.editPassword(password,id);
}catch (Exception e) {
flag = "0";
}
ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8");
ServletActionContext.getResponse().getWriter().print(flag);
return NONE;
}
//接受角色ID数组
private String[] roleIds;
/**
* 添加用户
*/
public String add(){
userService.save(model,roleIds);
return "list";
}
/**
* 分页查询
*/
public String pageQuery(){
userService.pageQuery(pageBean);
String[] excludes = new String[]{ "currentPage",
"pageSize","detachedCriteria","noticebills","roles"};
this.writePageBean2Json(pageBean, excludes );
return NONE;
}
/**
* 根据登录人查询对应的权限菜单数据
*/
public String findMenu(){
User user = BOSContext.getLoginUser();
List<Function> list = null;
if(user.getUsername().equals("admin")){
//超级管理员,加载所有的菜单数据
list = functionService.findAllMenu();
}else{
//根据用户ID查询菜单数据
list = functionService.findMenuByUserId(user.getId());
}
String[] excludes = new String[]{"parentFunction","children","roles"};
this.writeListBean2Json(list, excludes );
return NONE;
}
public void setCheckcode(String checkcode) {
this.checkcode = checkcode;
}
public String[] getRoleIds() {
return roleIds;
}
public void setRoleIds(String[] roleIds) {
this.roleIds = roleIds;
}
}
|
package exam03;
public enum CruiseClass {
LUXURY(3), FIRST(1.8), SECOND(1);
private final double priceMultiplier;
CruiseClass(double priceMultiplier) {
this.priceMultiplier = priceMultiplier;
}
public double getPriceMultiplier() {
return priceMultiplier;
}
}
|
package Problem_1697;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
/*2019-07-29 완료 */
/* N과 K가 같을때의 경우도 고려해야한다. */
class data {
int location;
int time;
public data(int location, int time) {
this.location = location;
this.time = time;
}
}
public class Main_bfs {
static int isvisited[] = new int[100001];
public static void bfs(int n, int k) {
Queue<data> q = new LinkedList<data>();
q.add(new data(n,0));
while(!q.isEmpty()) {
data d_ = q.poll();
// +1, -1, *2 의 방문여부를 판단하고 범위내에 존재하면, queue에 삽입
if(d_.location - 1 >= 0 && d_.location -1 <= 100000 && isvisited[d_.location-1] == 0) { // 방문 x
q.add(new data(d_.location-1, d_.time+1));
isvisited[d_.location-1] = d_.time+1;
}
if(d_.location + 1 >= 0 && d_.location + 1 <= 100000 && isvisited[d_.location+1] == 0) { // 방문 x
q.add(new data(d_.location+1, d_.time+1));
isvisited[d_.location+1] = d_.time+1;
}
if(d_.location * 2 >= 0 && d_.location * 2 <= 100000 && isvisited[d_.location * 2] == 0) { // 방문 x
q.add(new data(d_.location*2, d_.time+1));
isvisited[d_.location*2] = d_.time+1;
}
}
System.out.println(isvisited[k]);
return;
}
public static void main(String[] args) throws IOException {
// subin's location : N
// brother's location : K
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] temp = br.readLine().split(" ");
int N = Integer.parseInt(temp[0]);
int K = Integer.parseInt(temp[1]);
if(N == K) { System.out.println("0");}
else {bfs(N,K);}
}
}
|
package jianzhioffer;
import jianzhioffer.utils.ListNode;
/**
* @ClassName : Solution18
* @Description : O(1)时间删除链表节点
* 将删除当前节点,转换为删除下一节点,把指针指向改变。
* @Date : 2019/9/16 11:12
*/
public class Solution18 {
public void deleteNode(ListNode head, ListNode deListNode) {
if (head==null || deListNode==null)
return;
if (head==deListNode)
head=null;
if (deListNode.next==null){
ListNode tmp=head;
while (tmp.next!=deListNode)
tmp=tmp.next;
tmp.next=null;
}else{
deListNode.val=deListNode.next.val;
deListNode.next=deListNode.next.next;
}
}
}
|
package uz.zako.example.payload;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CategoryRequest {
private Long id;
private String categoryNameUz;
private String categoryNameRu;
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package network;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.PriorityQueue;
import simulator.Simulator;
/**
*
* @author dimitriv
*/
public class Lyui extends DRAND {
public Lyui(Network network, Simulator simulator, double slotTime) {
super(network, simulator, slotTime);
execLyui();
// network.dumpSlots();
}
final Map<Node, Integer> defaultColor = new HashMap<>();
final void execLyui() {
// Create defaultColor table and remove slot assignments (from DRAND)
for (Node node : network.nodes) {
defaultColor.put(node, network.slots.indexOf(node.reservations.peek().slot));
}
for (Node node : network.nodes) {
node.reservations.remove();
}
network.slots.clear();
// Calculate p_k for each node
Map<Node, Integer> p_ck = new HashMap<>();
int max_p = 0;
for (Entry<Node, Integer> entry : defaultColor.entrySet()) {
int p = calcP_k(entry.getValue());
max_p = p > max_p ? p : max_p;
p_ck.put(entry.getKey(), p);
}
// Set 2*map_p for te Lobats extension... Should not affect the Lyui one
for (int t = 0; t < 2 * max_p; t++) {
// List of candidate nodes for slot t
PriorityQueue<Node> queue = new PriorityQueue<>(network.nodes.size(), new Comparator<Node>() {
@Override
public int compare(Node o1, Node o2) {
return -defaultColor.get(o1).compareTo(defaultColor.get(o2));
}
});
// Add the node to list according to Lyui's criterion
for (Node node : network.nodes) {
if (t % p_ck.get(node) == (defaultColor.get(node) % p_ck.get(node))) {
queue.offer(node);
}
}
// Create a slot and add it to the network
Slot slot = new Slot();
network.slots.add(slot);
// Add the nodes to the slot ordered by defaultColor.
while (queue.size() > 0) {
slot.addNode(queue.poll());
}
}
}
int calcP_k(int color) {
int p = 1;
while (p < color) {
p *= 2;
}
return p;
}
}
|
/*
* 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.web;
import java.net.URI;
import java.util.Locale;
import java.util.function.Consumer;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ProblemDetail;
import org.springframework.lang.Nullable;
/**
* Representation of a complete RFC 7807 error response including status,
* headers, and an RFC 7807 formatted {@link ProblemDetail} body. Allows any
* exception to expose HTTP error response information.
*
* <p>{@link ErrorResponseException} is a default implementation of this
* interface and a convenient base class for other exceptions to use.
*
* <p>{@code ErrorResponse} is supported as a return value from
* {@code @ExceptionHandler} methods that render directly to the response, e.g.
* by being marked {@code @ResponseBody}, or declared in an
* {@code @RestController} or {@code RestControllerAdvice} class.
*
* @author Rossen Stoyanchev
* @since 6.0
* @see ErrorResponseException
*/
public interface ErrorResponse {
/**
* Return the HTTP status code to use for the response.
*/
HttpStatusCode getStatusCode();
/**
* Return headers to use for the response.
*/
default HttpHeaders getHeaders() {
return HttpHeaders.EMPTY;
}
/**
* Return the body for the response, formatted as an RFC 7807
* {@link ProblemDetail} whose {@link ProblemDetail#getStatus() status}
* should match the response status.
*/
ProblemDetail getBody();
// MessageSource codes and arguments
/**
* Return a code to use to resolve the problem "type" for this exception
* through a {@link MessageSource}. The type resolved through the
* {@code MessageSource} will be passed into {@link URI#create(String)}
* and therefore must be an encoded URI String.
* <p>By default this is initialized via {@link #getDefaultTypeMessageCode(Class)}.
* @since 6.1
*/
default String getTypeMessageCode() {
return getDefaultTypeMessageCode(getClass());
}
/**
* Return a code to use to resolve the problem "title" for this exception
* through a {@link MessageSource}.
* <p>By default this is initialized via {@link #getDefaultTitleMessageCode(Class)}.
*/
default String getTitleMessageCode() {
return getDefaultTitleMessageCode(getClass());
}
/**
* Return a code to use to resolve the problem "detail" for this exception
* through a {@link MessageSource}.
* <p>By default this is initialized via
* {@link #getDefaultDetailMessageCode(Class, String)}.
*/
default String getDetailMessageCode() {
return getDefaultDetailMessageCode(getClass(), null);
}
/**
* Return arguments to use along with a {@link #getDetailMessageCode()
* message code} to resolve the problem "detail" for this exception
* through a {@link MessageSource}. The arguments are expanded
* into placeholders of the message value, e.g. "Invalid content type {0}".
*/
@Nullable
default Object[] getDetailMessageArguments() {
return null;
}
/**
* Variant of {@link #getDetailMessageArguments()} that uses the given
* {@link MessageSource} for resolving the message argument values.
* <p>This is useful for example to expand message codes from validation errors.
* <p>The default implementation delegates to {@link #getDetailMessageArguments()},
* ignoring the supplied {@code MessageSource} and {@code Locale}.
* @param messageSource the {@code MessageSource} to use for the lookup
* @param locale the {@code Locale} to use for the lookup
*/
@Nullable
default Object[] getDetailMessageArguments(MessageSource messageSource, Locale locale) {
return getDetailMessageArguments();
}
/**
* Use the given {@link MessageSource} to resolve the
* {@link #getTypeMessageCode() type}, {@link #getTitleMessageCode() title},
* and {@link #getDetailMessageCode() detail} message codes, and then use the
* resolved values to update the corresponding fields in {@link #getBody()}.
* @param messageSource the {@code MessageSource} to use for the lookup
* @param locale the {@code Locale} to use for the lookup
*/
default ProblemDetail updateAndGetBody(@Nullable MessageSource messageSource, Locale locale) {
if (messageSource != null) {
String type = messageSource.getMessage(getTypeMessageCode(), null, null, locale);
if (type != null) {
getBody().setType(URI.create(type));
}
Object[] arguments = getDetailMessageArguments(messageSource, locale);
String detail = messageSource.getMessage(getDetailMessageCode(), arguments, null, locale);
if (detail != null) {
getBody().setDetail(detail);
}
String title = messageSource.getMessage(getTitleMessageCode(), null, null, locale);
if (title != null) {
getBody().setTitle(title);
}
}
return getBody();
}
/**
* Build a message code for the "type" field, for the given exception type.
* @param exceptionType the exception type associated with the problem
* @return {@code "problemDetail.type."} followed by the fully qualified
* {@link Class#getName() class name}
* @since 6.1
*/
static String getDefaultTypeMessageCode(Class<?> exceptionType) {
return "problemDetail.type." + exceptionType.getName();
}
/**
* Build a message code for the "title" field, for the given exception type.
* @param exceptionType the exception type associated with the problem
* @return {@code "problemDetail.title."} followed by the fully qualified
* {@link Class#getName() class name}
*/
static String getDefaultTitleMessageCode(Class<?> exceptionType) {
return "problemDetail.title." + exceptionType.getName();
}
/**
* Build a message code for the "detail" field, for the given exception type.
* @param exceptionType the exception type associated with the problem
* @param suffix an optional suffix, e.g. for exceptions that may have multiple
* error message with different arguments
* @return {@code "problemDetail."} followed by the fully qualified
* {@link Class#getName() class name} and an optional suffix
*/
static String getDefaultDetailMessageCode(Class<?> exceptionType, @Nullable String suffix) {
return "problemDetail." + exceptionType.getName() + (suffix != null ? "." + suffix : "");
}
/**
* Static factory method to build an instance via
* {@link #builder(Throwable, HttpStatusCode, String)}.
*/
static ErrorResponse create(Throwable ex, HttpStatusCode statusCode, String detail) {
return builder(ex, statusCode, detail).build();
}
/**
* Return a builder to create an {@code ErrorResponse} instance.
* @param ex the underlying exception that lead to the error response;
* mainly to derive default values for the
* {@linkplain #getDetailMessageCode() detail message code} and for the
* {@linkplain #getTitleMessageCode() title message code}.
* @param statusCode the status code to set in the response
* @param detail the default value for the
* {@link ProblemDetail#setDetail(String) detail} field, unless overridden
* by a {@link MessageSource} lookup with {@link #getDetailMessageCode()}
*/
static Builder builder(Throwable ex, HttpStatusCode statusCode, String detail) {
return builder(ex, ProblemDetail.forStatusAndDetail(statusCode, detail));
}
/**
* Variant of {@link #builder(Throwable, HttpStatusCode, String)} for use
* with a custom {@link ProblemDetail} instance.
* @since 6.1
*/
static Builder builder(Throwable ex, ProblemDetail problemDetail) {
return new DefaultErrorResponseBuilder(ex, problemDetail);
}
/**
* Builder for an {@code ErrorResponse}.
*/
interface Builder {
/**
* Add the given header value(s) under the given name.
* @param headerName the header name
* @param headerValues the header value(s)
* @return the same builder instance
* @see HttpHeaders#add(String, String)
*/
Builder header(String headerName, String... headerValues);
/**
* Manipulate this response's headers with the given consumer. This is
* useful to {@linkplain HttpHeaders#set(String, String) overwrite} or
* {@linkplain HttpHeaders#remove(Object) remove} existing values, or
* use any other {@link HttpHeaders} methods.
* @param headersConsumer a function that consumes the {@code HttpHeaders}
* @return the same builder instance
*/
Builder headers(Consumer<HttpHeaders> headersConsumer);
/**
* Set the underlying {@link ProblemDetail#setType(URI) type} field.
* @return the same builder instance
*/
Builder type(URI type);
/**
* Customize the {@link MessageSource} code to use to resolve the value
* for {@link ProblemDetail#setType(URI)}.
* <p>By default, set from {@link ErrorResponse#getDefaultTypeMessageCode(Class)}.
* @param messageCode the message code to use
* @return the same builder instance
* @since 6.1
* @see ErrorResponse#getTypeMessageCode()
*/
Builder typeMessageCode(String messageCode);
/**
* Set the underlying {@link ProblemDetail#setTitle(String) title} field.
* @return the same builder instance
*/
Builder title(@Nullable String title);
/**
* Customize the {@link MessageSource} code to use to resolve the value
* for {@link ProblemDetail#setTitle(String)}.
* <p>By default, set from {@link ErrorResponse#getDefaultTitleMessageCode(Class)}.
* @param messageCode the message code to use
* @return the same builder instance
* @see ErrorResponse#getTitleMessageCode()
*/
Builder titleMessageCode(String messageCode);
/**
* Set the underlying {@link ProblemDetail#setInstance(URI) instance} field.
* @return the same builder instance
*/
Builder instance(@Nullable URI instance);
/**
* Set the underlying {@link ProblemDetail#setDetail(String) detail}.
* @return the same builder instance
*/
Builder detail(String detail);
/**
* Customize the {@link MessageSource} code to use to resolve the value
* for the {@link #detail(String)}.
* <p>By default, set from {@link ErrorResponse#getDefaultDetailMessageCode(Class, String)}.
* @param messageCode the message code to use
* @return the same builder instance
* @see ErrorResponse#getDetailMessageCode()
*/
Builder detailMessageCode(String messageCode);
/**
* Set the arguments to provide to the {@link MessageSource} lookup for
* {@link #detailMessageCode(String)}.
* @param messageArguments the arguments to provide
* @return the same builder instance
* @see ErrorResponse#getDetailMessageArguments()
*/
Builder detailMessageArguments(Object... messageArguments);
/**
* Set a "dynamic" {@link ProblemDetail#setProperty(String, Object)
* property} on the underlying {@code ProblemDetail}.
* @return the same builder instance
*/
Builder property(String name, @Nullable Object value);
/**
* Build the {@code ErrorResponse} instance.
*/
ErrorResponse build();
/**
* Build the {@code ErrorResponse} instance and also resolve the "detail"
* and "title" through the given {@link MessageSource}. Effectively a
* shortcut for calling {@link #build()} and then
* {@link ErrorResponse#updateAndGetBody(MessageSource, Locale)}.
* @since 6.0.3
*/
default ErrorResponse build(@Nullable MessageSource messageSource, Locale locale) {
ErrorResponse response = build();
response.updateAndGetBody(messageSource, locale);
return response;
}
}
}
|
package FirstProject.DataStructures;
public class StringTest {
public static void main(String[] args) {
//Methods
//length()
// concat
//equals
//equalsIgnoreCase
//toLowerCase
//toUpperCase
//charAt(int index)
// substring(int beginIndex, endIndex)
//containct(CharSequence s)
// replace(char old, char new)
}
}
|
/*
* Copyright 2014-2023 JKOOL, LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jkoolcloud.jesl.net.socket;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
import javax.net.ssl.SSLContext;
import org.apache.commons.lang3.StringUtils;
import com.jkoolcloud.jesl.net.JKStream;
import com.jkoolcloud.jesl.net.security.AuthUtils;
import com.jkoolcloud.tnt4j.core.OpLevel;
import com.jkoolcloud.tnt4j.sink.DefaultEventSinkFactory;
import com.jkoolcloud.tnt4j.sink.EventSink;
import com.jkoolcloud.tnt4j.utils.Utils;
/**
* This class provides TCP/SSL connection to the specified JESL server based on given URL. tcp[s]://host:port
* <p>
* In case your SOCKS proxy requires authentication, use system properties to define credentials:
* <ul>
* <li>{@code java.net.socks.username} - proxy user name</li>
* <li>{@code java.net.socks.password} - proxy user password</li>
* </ul>
*
* @version $Revision: 4 $
*/
public class SocketClient implements JKStream {
protected EventSink logger;
protected InetSocketAddress proxyAddr;
protected Proxy proxy = Proxy.NO_PROXY; // default to direct connection
protected String host;
protected int port;
protected boolean secure;
protected Socket socket;
protected DataOutputStream out;
protected BufferedReader in;
/**
* Create JESL HTTP[S} client stream with given attributes
*
* @param host
* JESL host server
* @param port
* JESL host port number
* @param secure
* use SSL if secure, standard sockets if false
* @param logger
* event sink used for logging, null if none
*
*/
public SocketClient(String host, int port, boolean secure, EventSink logger) {
this.host = host;
this.port = port;
this.secure = secure;
this.logger = (logger != null ? logger : DefaultEventSinkFactory.defaultEventSink(SocketClient.class));
}
/**
* Create JESL HTTP[S} client stream with given attributes
*
* @param host
* JESL host server
* @param port
* JESL host port number
* @param secure
* use SSL if secure, standard sockets if false
* @param proxyHost
* proxy host name if any, null if none
* @param proxyPort
* proxy port number if any, 0 of none
* @param logger
* event sink used for logging, null if none
*
*/
public SocketClient(String host, int port, boolean secure, String proxyHost, int proxyPort, EventSink logger) {
this(host, port, secure, logger);
if (!StringUtils.isEmpty(proxyHost)) {
proxyAddr = new InetSocketAddress(proxyHost, proxyPort);
proxy = new Proxy(Proxy.Type.SOCKS, proxyAddr);
}
}
@Override
public synchronized void connect() throws IOException {
long startTime = System.currentTimeMillis();
try {
if (isConnected()) {
return;
}
socket = new Socket(proxy);
socket.connect(new InetSocketAddress(host, port));
if (secure) {
SSLContext sslContext = SSLContext.getInstance(AuthUtils.SSL_PROTOCOL);
sslContext.init(null, null, null);
socket = sslContext.getSocketFactory().createSocket(socket, proxyAddr.getHostName(),
proxyAddr.getPort(), true);
}
out = new DataOutputStream(socket.getOutputStream());
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (Throwable exc) {
String errMsg = "Failed to connect to host=" + host //
+ ", port=" + port //
+ ", elapsed.ms=" + (System.currentTimeMillis() - startTime) //
+ ", reason=" + exc.getMessage();
logger.log(OpLevel.ERROR, errMsg, exc);
close();
throw new IOException(errMsg, exc);
}
}
@Override
public synchronized void connect(String token) throws IOException {
connect();
if (!StringUtils.isEmpty(token)) {
try {
logger.log(OpLevel.DEBUG, "Authenticating connection={0} with token={1}", this,
Utils.hide(token, "x", 4));
AuthUtils.authenticate(this, token);
logger.log(OpLevel.DEBUG, "Authenticated connection={0} with token={1}", this,
Utils.hide(token, "x", 4));
} catch (SecurityException exc) {
close();
throw new IOException("Connect failed to complete", exc);
}
}
}
@Override
public synchronized void send(String token, String msg, boolean wantResponse) throws IOException {
if (wantResponse) {
throw new UnsupportedOperationException("Responses are not supported for TCP connections");
}
String lineMsg = msg.endsWith("\n") ? msg : msg + "\n";
byte[] bytes = lineMsg.getBytes();
checkState(token);
out.write(bytes, 0, bytes.length);
out.flush();
}
@Override
public synchronized void close() {
Utils.close(out);
Utils.close(in);
Utils.close(socket);
socket = null;
}
@Override
public String getHost() {
return host;
}
@Override
public int getPort() {
return port;
}
@Override
public boolean isSecure() {
return secure;
}
@Override
public String getProxyHost() {
return (proxyAddr != null ? proxyAddr.getHostName() : null);
}
@Override
public int getProxyPort() {
return (proxyAddr != null ? proxyAddr.getPort() : 0);
}
@Override
public boolean isConnected() {
return (socket != null && socket.isConnected());
}
@Override
public synchronized String read() throws IOException {
checkState();
return in.readLine();
}
@Override
public String toString() {
return "tcp" + (isSecure() ? "s" : "") + "://" + host + ":" + port;
}
@Override
public URI getURI() {
try {
return new URI("tcp" + (isSecure() ? "s" : "") + "://" + host + ":" + port);
} catch (URISyntaxException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
}
|
package kr.or.ddit.freeboard.controller;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import kr.or.ddit.fileitem.service.IFileItemService;
import kr.or.ddit.freeboard.service.IFreeboardService;
import kr.or.ddit.utiles.CryptoGenerator;
import kr.or.ddit.utiles.RolePaginationUtil;
import kr.or.ddit.vo.FileItemVO;
import kr.or.ddit.vo.FreeboardVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
@RequestMapping("/user/freeboard/")
public class FreeboardController {
@Autowired
private CryptoGenerator cryptoGen;
@Autowired
private IFreeboardService freeboardService;
@Autowired
private RolePaginationUtil rolePagination;
// http://localhost/user/freeboard/freeboardList.do
@Autowired
private IFileItemService fileItemService;
@RequestMapping("freeboardList")
public ModelAndView freeboardList(Map<String, String> params,
String search_keycode, String search_keyword,
HttpServletRequest request, ModelAndView modelView,
HttpSession session, String currentPage,
// @RequestHeader("취득하려는 키값")
@RequestHeader("User-Agent") String agent,
@RequestHeader("accept-Language") String language,
// @CookieValue("전송되려는쿠키값")
@CookieValue("JSESSIONID") String sessionID) throws Exception {
Map<String, String> publicKeyMap = this.cryptoGen.generatePairKey(session);
// String currentPage = request.getParameter("currentPage");
if (currentPage == null) {
currentPage = "1";
}
params.put("search_keycode", search_keycode);
params.put("search_keyword", search_keyword);
String totalCount = this.freeboardService.totalCount(params);
this.rolePagination.RolePaginationUtilMethod(request,
Integer.parseInt(currentPage), Integer.parseInt(totalCount));
params.put("startCount",
String.valueOf(this.rolePagination.getStartCount()));
params.put("endCount",
String.valueOf(this.rolePagination.getEndCount()));
List<FreeboardVO> freeboardList = this.freeboardService
.freeboardList(params);
modelView.addObject("freeboardList", freeboardList);
modelView.addObject("publicKeyMap", publicKeyMap);
modelView.addObject("Pagination", this.rolePagination.getPagingHtmls());
modelView.setViewName("user/freeboard/freeboardList");
return modelView;
}
@RequestMapping("freeboardForm")
public void freeboardForm() {
}
// 파일처리도 하자 RequestParam은 반드시 파일이 입력되어야하는데 그러면 없으면 에러난다... ;
@RequestMapping("insertFreeboard")
public String insertFreeboardInfo(FreeboardVO freeboardInfo,
@RequestParam("files") MultipartFile[] items) throws Exception {
this.freeboardService.insertFreeboard(freeboardInfo, items);
String message = URLEncoder.encode("글작성완료.", "UTF-8");
return "redirect:/user/freeboard/freeboardList.do?message=" + message;
}
@RequestMapping("freeboardView")
@ModelAttribute("freeboardInfo")
public FreeboardVO freeboardView(String bo_no, String r,
Map<String, String> params,
FreeboardVO freeboardInfo) throws Exception {
params.put("bo_no", bo_no);
freeboardInfo = this.freeboardService.freeboardInfo(params);
this.freeboardService.hitUp(params);
// modelView.addObject("freeboardInfo", freeboardInfo);
// modelView.addObject("r", r);
// modelView.setViewName("user/freeboard/freeboardView");
return freeboardInfo;
}
@RequestMapping("updateFreeboard")
public String updateFreeboard(FreeboardVO freeboardInfo) throws Exception {
int cnt = 0;
cnt = this.freeboardService.updateFreeboard(freeboardInfo);
String message = null;
if (cnt > 0) {
message = URLEncoder.encode("글수정완료", "UTF-8");
} else {
message = URLEncoder.encode("글수정실패", "UTF-8");
}
return "redirect:/user/freeboard/freeboardList.do?message=" + message;
}
@RequestMapping("deleteFreeboard/{board_no}")
public String deleteFreeboard(@PathVariable("board_no") String bo_no,
Map<String, String> params) throws Exception {
params.put("bo_no", bo_no);
int cnt = 0;
cnt = this.freeboardService.deleteFreeboard(params);
String message = null;
if (cnt > 0) {
message = URLEncoder.encode("삭제완료", "UTF-8");
} else {
message = URLEncoder.encode("삭제실패", "UTF-8");
}
return "redirect:/user/freeboard/freeboardList.do?message=" + message;
}
@RequestMapping("freeboardReplyForm")
public ModelAndView freeboardReplyForm(FreeboardVO rfFreeboardInfo,
ModelAndView modelAndView) throws Exception {
modelAndView.addObject("rfFreeboardInfo", rfFreeboardInfo);
modelAndView.setViewName("user/freeboard/freeboardReplyForm");
return modelAndView;
}
@RequestMapping("insertFreeboardReply")
public String insertFreeboardReply(FreeboardVO repalyFreeboardInfo)
throws Exception {
String cnt = null;
cnt = this.freeboardService.insertFreeboardReply(repalyFreeboardInfo);
this.freeboardService.insertFreeboardReply(repalyFreeboardInfo);
String message = null;
// if(Integer.parseInt(cnt)>0){
// message = URLEncoder.encode("답글완료","UTF-8");
// }else{
// message = URLEncoder.encode("답글실패","UTF-8");
// }
//
// return "redirect:/user/freeboard/freeboardList.do?message="+message;
return "redirect:/user/freeboard/freeboardList.do";
}
@RequestMapping("fileDownload")
public ModelAndView fileDownload(String file_seq,
Map<String, String> params, ModelAndView modelAndView)
throws Exception {
params.put("file_seq", file_seq);
FileItemVO fileItemInfo = this.fileItemService.fileitemInfo(params);
modelAndView.addObject("fileitemInfo", fileItemInfo);
modelAndView.setViewName("fileDownloadView");
return modelAndView;
}
}
|
package com.ntg.androidadministration.logicaltest_halafathymohamed;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class PalindromeNumberCheckActivity extends AppCompatActivity implements View.OnClickListener {
private Button btn_check;
private EditText et_number;
private TextView tv_result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_palindrome_number_check);
setToolbarView();
btn_check = (Button) findViewById(R.id.btn_check);
et_number = (EditText) findViewById(R.id.et_number);
tv_result = (TextView) findViewById(R.id.tv_result);
btn_check.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_check:
isPalindrome(et_number.getText().toString());
break;
}
}
private boolean isPalindrome(String numberString) {
boolean isNumberPalindrome = false;
tv_result.setText(getString(R.string.result));
try {
int number = Integer.parseInt(numberString);
int numberTemp = number;
int reverse = 0;
while (numberTemp != 0) {
int remainder = numberTemp % 10;
reverse = reverse * 10 + remainder;
numberTemp = numberTemp / 10;
}
if (number == reverse) {
tv_result.setText(getString(R.string.palindrome));
isNumberPalindrome = true;
} else {
tv_result.setText(getString(R.string.not_palindrome));
}
} catch (NumberFormatException ex) {
ex.printStackTrace();
tv_result.setText(getString(R.string.error));
}
return isNumberPalindrome;
}
private void setToolbarView() {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
// NavUtils.navigateUpFromSameTask(this);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
package cpup.poke4j;
import cpup.poke4j.events.EventRegister;
import java.util.List;
public class Cursor {
protected final Poke poke;
protected final Buffer buffer;
protected BufferPos pos;
protected Selection selection;
public Cursor(Poke _poke, Buffer _buffer, BufferPos _pos, Selection _selection) {
poke = _poke;
buffer = _buffer;
pos = _pos;
selection = _selection;
}
public Cursor(Poke _poke, Buffer _buffer, BufferPos _pos) {
this(_poke, _buffer, _pos, null);
}
public void move(int dist) {
setPos(pos.move(buffer, dist));
}
public void moveWord(int dist) {
setPos(pos.moveWord(buffer, dist));
}
public void moveUD(int dist) {
setPos(pos.moveUD(buffer, dist));
}
public void clearSelection() {
setSelection(null);
}
public void removeSelection() {
if(selection != null) {
final List<String> lines = selection.getLines();
int selLength = lines.size() - 1;
for(String line : lines) {
selLength += line.length();
}
selection.remove(new BufferPos(0, 0), selLength);
clearSelection();
}
}
public final EventRegister<MoveEvent> moveEv = new EventRegister<MoveEvent>();
public static class MoveEvent {
protected final Cursor cursor;
protected final BufferPos oldPos;
protected final BufferPos newPos;
public MoveEvent(Cursor _cursor, BufferPos _oldPos, BufferPos _newPos) {
cursor = _cursor;
oldPos = _oldPos;
newPos = _newPos;
}
// Getters and Setters
public Poke getPoke() {
return cursor.getPoke();
}
public Buffer getBuffer() {
return cursor.getBuffer();
}
public Cursor getCursor() {
return cursor;
}
public BufferPos getOldPos() {
return oldPos;
}
public BufferPos getNewPos() {
return newPos;
}
}
public final EventRegister<SelectEvent> selectEv = new EventRegister<SelectEvent>();
public static class SelectEvent {
protected final Cursor cursor;
protected final Selection oldSel;
protected final Selection newSel;
public SelectEvent(Cursor _cursor, Selection _oldSel, Selection _newSel) {
cursor = _cursor;
oldSel = _oldSel;
newSel = _newSel;
}
// Getters and Setters
public Poke getPoke() {
return cursor.getPoke();
}
public Buffer getBuffer() {
return cursor.getBuffer();
}
public Cursor getCursor() {
return cursor;
}
public Selection getOldSel() {
return oldSel;
}
public Selection getNewSel() {
return newSel;
}
}
// Getters and Setters
public Poke getPoke() {
return poke;
}
public Buffer getBuffer() {
return buffer;
}
public BufferPos getPos() {
return pos;
}
public void setPos(BufferPos pos) {
final BufferPos oldPos = this.pos;
this.pos = pos;
final MoveEvent ev = new MoveEvent(this, oldPos, pos);
moveEv.emit(ev);
buffer.moveCursorEv.emit(ev);
if(selection == null)
setSelection(new Selection(poke, buffer, oldPos, oldPos));
if(selection.begin.equals(oldPos)) {
setSelection(new Selection(poke, buffer, pos, selection.end));
} else if(selection.end.equals(oldPos)) {
setSelection(new Selection(poke, buffer, selection.begin, pos));
}
}
public void setLine(int line) {
setPos(new BufferPos(pos.getColumn(), line));
}
public void setColumn(int column) {
setPos(new BufferPos(column, pos.getLine()));
}
public Selection getSelection() {
return selection;
}
public Selection getSelectionWithDefault() {
if(selection == null) {
return new Selection(poke, buffer, pos, pos);
} else {
return selection;
}
}
public void setSelection(Selection _selection) {
final Selection oldSelection = selection;
this.selection = _selection;
final SelectEvent ev = new SelectEvent(this, oldSelection, _selection);
selectEv.emit(ev);
buffer.selectCursorEv.emit(ev);
}
} |
package es.ubu.lsi.service.asociacion;
import java.util.Date;
import java.util.List;
import es.ubu.lsi.model.asociacion.Asociacion;
import es.ubu.lsi.model.asociacion.TipoIncidenciaRanking;
import es.ubu.lsi.service.PersistenceException;
/**
* Transaction service.
*
* @author <a href="mailto:jmaudes@ubu.es">Jesús Maudes</a>
* @author <a href="mailto:rmartico@ubu.es">Raúl Marticorena</a>
* @author <a href="mailto:mmabad@ubu.es">Mario Martínez</a>
* @since 1.0
*
*/
public interface Service {
/** Máximo de puntos con el que se inicia el carné por puntos. */
public static final int MAXIMO_PUNTOS = 12;
/**
* Alta de una nueva incidencia sobre un conductor.
*
* @param fecha fecha
* @param nif nif
* @param tipo tipo de incidencia
* @throws PersistenceException si se produce un error
* @see es.ubu.lsi.service.asociacion.IncidentError
*/
public void insertarIncidencia(Date fecha, String nif, long tipo) throws PersistenceException;
/**
* Elimina todas las incidencias de un conductor poniendo sus puntos de nuevo a
* máximo.
*
* @param nif nif
* @throws PersistenceException si se produce un error
* @see es.ubu.lsi.service.asociacion.IncidentError
*/
public void indultar(String nif) throws PersistenceException;
/**
* Consulta las asociaciones. En este caso en particular es importante recuperar
* toda la información vinculada a los conductores, incidencias y tipo de
* incidencia para su visualización posterior.
*
* @return asociaciones
* @throws PersistenceException si se produce un error
*/
public List<Asociacion> consultarAsociaciones() throws PersistenceException;
/**
* Consulta el ranking de tipos de incidencias devolviendo descripcion y número
* de apariciones de cada tipo de incidencia (utilizando una clase de envoltura
* TipoIncidenciaRanking.
*
* @return ranking con la descrición y frecuencia de cada tipo de incidencia
* ordenado de mayor a menor frecuencia
* @throws PersistenceException si se produce un error
*/
public List<TipoIncidenciaRanking> consultarRanking() throws PersistenceException;
/**
* Inserta un nuevo tipo de incidencia.
*
* @param descripcion descripción
* @param valor valor de puntos a restar
* @throws PersistenceException si se produce un error
*/
public void insertarTipoIncidencia(String descripcion, int valor) throws PersistenceException;
/**
* Consulta el número de conductores pertenecientes a una asociación que tienen
* alguna incidencia.
*
* @param idasoc identificador de asociación
* @return número de conductores de la asociación con incidencias
* @throws PersistenceException si se produce un error
*/
public int consultarNumeroConductoresConIncidenciasEnAsoc(String idasoc) throws PersistenceException;
}
|
package com.prestashop.pages.order;
import org.openqa.selenium.By;
public class OrderPage {
private OrderActController act;
private OrderVerifyController verify;
private OrderPage() {
// hidden
}
private OrderPage(OrderActController act, OrderVerifyController verify) {
this.act = act;
this.verify = verify;
}
//static factory method
public static OrderPage getOrderPage() {
return new OrderPage(new OrderActController(), new OrderVerifyController());
}
public OrderActController act() { return act; }
public OrderVerifyController verify() { return verify; }
public static By addressTextField() { return By.name("address1"); }
public static By postalCodeTextField() { return By.name("postcode"); }
public static By cityTextField() { return By.name("city"); }
public static By addressesContinueButton() { return By.name("confirm-addresses"); }
public static By shippingContinueButton() { return By.name("confirmDeliveryOption"); }
public static By payByBankWireRadioButton() { return By.id("payment-option-2"); }
public static By agreeToTermsCheckBox() { return By.id("conditions_to_approve[terms-and-conditions]"); }
public static By paymentConfirmationButton() { return By.cssSelector("#payment-confirmation > div.ps-shown-by-js > button"); }
public static By orderConfirmationMessage() { return By.xpath("//h3[@class='h1 card-title']"); }
}
|
package product2;
//Concrete Product
public class ProductB1 implements ProductB {
}
|
package com.company;
class LinkedList { //singly linked list class
Node head; //head of the list
class Node { //node class
int data;
Node next;
Node(int d) { //constructors for new nodes
data = d;
next = null;
}
}
public void front(int new_data) { //inserting a new node in front of the list
Node new_node = new Node(new_data); //inserting a new node and assigning its data
new_node.next = head; //assigning new node's next as head
head = new_node; //making the new node as head of the list
}
public void afterGiven(Node prev_node, int new_data) { // inserting a new node after the given previous node
Node new_node = new Node(new_data); //inserting a new node and assigning its data
new_node.next = prev_node.next; //assigning new node's next as previous node's next
prev_node.next = new_node; //assigning previous node's next as new node
}
public void latest(int new_data) { //inserting a new node to end of the list
Node new_node = new Node(new_data); //inserting a new node and assigning its data
new_node.next = null; //assigning new node's next as null
if (head == null) { //checking if the list is empty or not
head = new Node(new_data); //if it is add the new node as head
return;
}
//at this point we don't have any way to find the latest node except checking one by one
//as we know(for singly linked lists) latest node's next is "NULL"
//so we should look for a node which its next is "NULL"
//and we should start from the head to make sure
Node last = head; //starting the process from the head
while (last.next != null) //making the process running until finding a node's next as "NULL"
last = last.next; //if the node's next if not "NULL" move to the next node
last.next = new_node; //assigning current latest node's next as new node
}
public void printList() { //printing the list from the given node
Node tnode = head; //starting the printing process from the head
while (tnode != null) { //making the process running until reaching end of the list
System.out.print(tnode.data + " "); //printing current node
tnode = tnode.next; //moving to the next node
}
}
public static class Main {
public static void main(String[] args) {
LinkedList liste = new LinkedList(); //creating a empty list
liste.latest(6); //adding a node END of the list
//{6}->NULL
liste.front(7); //adding a node HEAD of the list
//{7,6}->NULL
liste.front(1); //adding a node HEAD of the list
//{1,7,6}->NULL
liste.latest(4); //adding a node END of the list
//{1,7,6,4}->NULL
liste.afterGiven(liste.head.next, 8); //adding a node AFTER the given number
//{1,7,8,6,4}->NULL
System.out.println("Created Linked List is:");
liste.printList(); //printing process
}
}
}
|
package com.channing.snailhouse.util;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 系统工具类
*
* @author fengle
*
*/
public class SysUtils {
private static final Logger log = LoggerFactory.getLogger(SysUtils.class);
/**
* 校验空配置
*/
public static void checkNullConfig(String configKey,String configValue) {
if (StringUtils.isEmpty(configValue)) {
log.error("未在配置表配置信息项:{}", configKey);
throw new CheckedException("未在配置表配置信息项:" + configKey);
}
}
/**
* 版本号比较
*
* @param version1
* @param version2
* @return
* @throws Exception
*/
public static int compareVersion(String version1, String version2) {
if (version1 == null || version2 == null) {
throw new CheckedException("版本比较异常");
}
String[] versionArray1 = version1.split("\\.");
String[] versionArray2 = version2.split("\\.");
int idx = 0;
int minLength = Math.min(versionArray1.length, versionArray2.length);
int diff = 0;
while (idx < minLength && (diff = versionArray1[idx].length() - versionArray2[idx].length()) == 0
&& (diff = versionArray1[idx].toUpperCase().compareTo(versionArray2[idx].toUpperCase())) == 0) {
++idx;
}
diff = (diff != 0) ? diff : versionArray1.length - versionArray2.length;
return diff;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.innovaciones.reporte.service;
import com.innovaciones.reporte.dao.CabeceraInventarioDAO;
import com.innovaciones.reporte.model.CabeceraInventario;
import java.io.Serializable;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
*
* @author fyaulema
*/
@Service
@ManagedBean(name = "cabeceraInventarioService")
@ViewScoped
public class CabeceraInventarioServiceImpl implements CabeceraInventarioService, Serializable {
private CabeceraInventarioDAO cabeceraInventarioDAO;
public void setCabeceraInventarioDAO(CabeceraInventarioDAO cabeceraInventarioDAO) {
this.cabeceraInventarioDAO = cabeceraInventarioDAO;
}
@Override
@Transactional
public CabeceraInventario addCabeceraInventario(CabeceraInventario cabeceraInventario) {
return cabeceraInventarioDAO.addCabeceraInventario(cabeceraInventario);
}
@Override
@Transactional
public List<CabeceraInventario> getCabeceraInventarios(Integer idBodega) {
return cabeceraInventarioDAO.getCabeceraInventarios(idBodega);
}
@Override
@Transactional
public CabeceraInventario getCabeceraInventarioById(Integer id) {
return cabeceraInventarioDAO.getCabeceraInventarioById(id);
}
@Override
@Transactional
public CabeceraInventario getCabeceraInventarioByCodigo(String codigo) {
return cabeceraInventarioDAO.getCabeceraInventarioByCodigo(codigo);
}
@Override
@Transactional
public List<CabeceraInventario> getCabeceraInventariosByEstado(Integer idBodega, Integer estado) {
return cabeceraInventarioDAO.getCabeceraInventariosByEstado(idBodega, estado);
}
@Override
@Transactional
public String getCountInventarios() {
Integer count = cabeceraInventarioDAO.getCountInventarios();
count++;
String result = "INV-";
if (count < 10) {
result += "000";
} else {
if (count < 100) {
result += "00";
} else {
if (count < 1000) {
result += "0";
}
}
}
result += count;
return result;
}
}
|
package org.ohdsi.webapi.estimation.converter;
import org.ohdsi.webapi.estimation.Estimation;
import org.ohdsi.webapi.estimation.dto.EstimationDTO;
import org.springframework.stereotype.Component;
@Component
public class EstimationToEstimationDTOConverter extends EstimationToEstimationShortDTOConverter<EstimationDTO> {
@Override
protected EstimationDTO createResultObject() {
return new EstimationDTO();
}
@Override
public EstimationDTO convert(Estimation source) {
EstimationDTO result = super.convert(source);
result.setSpecification(source.getSpecification());
return result;
}
}
|
package com.waylau.spring.boot.security.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.waylau.spring.boot.security.domain.User;
import com.waylau.spring.boot.security.service.UserService;
/**
* 用户控制器.
*
* @author <a href="https://waylau.com">Way Lau</a>
* @date 2017年2月26日
*/
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
/**
* 查询所用用户
* @return
*/
@GetMapping
public ModelAndView list(Model model) {
List<User> list = new ArrayList<>(); // 当前所在页面数据列表
list = userService.listUsers();
model.addAttribute("title", "用户管理");
model.addAttribute("userList", list);
return new ModelAndView("users/list", "userModel", model);
}
@PreAuthorize("hasAuthority('ROLE_ADMIN')") // 指定角色权限才能操作方法
@GetMapping(value = "delete/{id}")
public ModelAndView delete(@PathVariable("id") Long id, Model model) {
userService.removeUser(id);
model.addAttribute("userList", userService.listUsers());
model.addAttribute("title", "删除用户");
return new ModelAndView("users/list", "userModel", model);
}
}
|
package net.ddns.hnmirror.mom;
import java.sql.SQLException;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import org.apache.activemq.ActiveMQConnectionFactory;
import net.ddns.hnmirror.domain.Token;
public class Receiver implements Runnable, ExceptionListener {
private ConnectionFactory factory = null;
private Connection connection = null;
private Session session = null;
private Destination destination = null;
private MessageConsumer consumer = null;
private final String queueName;
private String brokerUrl;
private Handler handler = new Handler();
public Receiver(String brokerUrl, String queueName) {
this.queueName = queueName;
this.brokerUrl = brokerUrl;
}
public void onException(JMSException ex) {
System.out.println("JMS Exception occured. Shutting down client.");
}
public void run() {
try {
factory = new ActiveMQConnectionFactory(brokerUrl); // ActiveMQConnection.DEFAULT_BROKER_URL);
connection = factory.createConnection();
connection.setExceptionListener(this);
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
destination = session.createQueue(queueName);
consumer = session.createConsumer(destination);
// --------MessageListener-----------
consumer.setMessageListener(new MessageListener() {
public void onMessage(Message msg) {
try {
if (msg instanceof ObjectMessage) {
ObjectMessage msg0 = (ObjectMessage) msg;
Token token = (Token) msg0.getObject();
handler.handleToken(token);
}
} catch (JMSException ex) {
ex.printStackTrace();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
});
connection.start();
Thread.sleep(1000 * 60 * 60 * 24 * 365);
consumer.close();
session.close();
connection.close();
} catch (JMSException ex) {
ex.printStackTrace();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
|
package edu.erlm.epi.domain.school;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import edu.erlm.epi.domain.User;
import lombok.ToString;
@Entity
@ToString
@DiscriminatorValue(value = "Admin")
public class Admin extends User{
private static final long serialVersionUID = 1L;
}
|
/*
* 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 unt.herrera.prog2.tp2;
import java.time.LocalDate;
/**
*
* @author Gianpaolo
*/
public class Trabajo {
private String titulo;
private String areatematica;
private String duracion;
private LocalDate fechaPresentacionAprobacion;
private LocalDate fechaAprobadoCA;
private LocalDate fechaPresentacionFinal;
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public String getAreatematica() {
return areatematica;
}
public void setAreatematica(String areatematica) {
this.areatematica = areatematica;
}
public String getDuracion() {
return duracion;
}
public void setDuracion(String duracion) {
this.duracion = duracion;
}
public LocalDate getFechaPresentacionAprobacion() {
return fechaPresentacionAprobacion;
}
public void setFechaPresentacionAprobacion(LocalDate fechaPresentacionAprobacion) {
this.fechaPresentacionAprobacion = fechaPresentacionAprobacion;
}
public LocalDate getFechaAproadoCA() {
return fechaAprobadoCA;
}
public void setFechaAproadoCA(LocalDate fechaAproadoCA) {
this.fechaAprobadoCA = fechaAproadoCA;
}
public LocalDate getFechaPresentacionFinal() {
return fechaPresentacionFinal;
}
public void setFechaPresentacionFinal(LocalDate fechaPresentacionFinal) {
this.fechaPresentacionFinal = fechaPresentacionFinal;
}
public Trabajo(String titulo, String areatematica, String duracion, LocalDate fechaPresentacionAprobacion, LocalDate fechaAprobadoCA, LocalDate fechaPresentacionFinal) {
this.titulo = titulo;
this.areatematica = areatematica;
this.duracion = duracion;
this.fechaPresentacionAprobacion = fechaPresentacionAprobacion;
this.fechaAprobadoCA = fechaAprobadoCA;
this.fechaPresentacionFinal = fechaPresentacionFinal;
}
public void mostrar(){
System.out.println("El titulo es: "+titulo+" el area tematica es: "+areatematica+" la duracion es: "+duracion+"meses, la fecha de presentacion de aprobacion es: "+fechaPresentacionAprobacion+" la fecha de aprobacion de la Comision Academica es: "+fechaAprobadoCA+" la fecha de realizacion de la presentacion final es: "+fechaPresentacionFinal);}
}
|
package com.gsccs.sme.plat.auth.service;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.gsccs.sme.plat.auth.model.User;
/**
* <p>
* User: x.d zhang
* <p>
* Date: 14-1-28
* <p>
* Version: 1.0
*/
@Service
public class PasswordHelper {
private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
@Value("${password.algorithmName}")
private String algorithmName = "md5";
@Value("${password.hashIterations}")
private int hashIterations = 2;
public void setRandomNumberGenerator(
RandomNumberGenerator randomNumberGenerator) {
this.randomNumberGenerator = randomNumberGenerator;
}
public void setAlgorithmName(String algorithmName) {
this.algorithmName = algorithmName;
}
public void setHashIterations(int hashIterations) {
this.hashIterations = hashIterations;
}
public void encryptPassword(User account) {
account.setSalt(randomNumberGenerator.nextBytes().toHex());
String newPassword = new SimpleHash(algorithmName, account.getPassword(),
ByteSource.Util.bytes(account.getCredentialsSalt()),
hashIterations).toHex();
account.setPassword(newPassword);
}
/*public void encryptPassword(SellerAccount account) {
account.setSalt(randomNumberGenerator.nextBytes().toHex());
String newPassword = new SimpleHash(algorithmName, account.getPwd(),
ByteSource.Util.bytes(account.getCredentialsSalt()),
hashIterations).toHex();
account.setPwd(newPassword);
}*/
}
|
package com.assignment.week2;
public class MainRunner {
public static void main(String[] args) {
DateTimeController.start();
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.