text stringlengths 10 2.72M |
|---|
package Excecoes;
import javafx.scene.control.Alert;
import javax.swing.JOptionPane;
public class UsuarioJaExistenteException extends Exception {
public UsuarioJaExistenteException() {
super("Usuario Ja Existente");
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Erro");
alert.setHeaderText(null);
alert.setContentText("Nome de usuário ja existente");
alert.showAndWait();
}
}
|
package com.citibank.ods.modules.client.mrdocprvt.form;
/**
* @author m.nakamura
*
* Form com os dados da tela de detalhe de Memo de Risco
*/
public class MrDocPrvtMovDetailForm extends BaseMrDocPrvtDetailForm implements
MrDocPrvtMovDetailable
{
// Codigo Documento MR
private String m_mrDocCode = "";
// Código da ação que originou o registro
private String m_opernCode = "";
// Tamanho da lista de contatos
private int m_contactSize = 0;
// Vetor com os opern_code do call back
private String[] m_opernCodeArray;
/**
* Recupera Codigo Documento MR
*
* @return Retorna Codigo Documento MR
*/
public String getMrDocCode()
{
return m_mrDocCode;
}
/**
* Seta Codigo Documento MR
*
* @param mrDocCode_ - Codigo Documento MR
*/
public void setMrDocCode( String mrDocCode_ )
{
m_mrDocCode = mrDocCode_;
}
/**
* Recupera o Código da ação que originou o registro
*
* @return Retorna o Código da ação que originou o registro
*/
public String getOpernCode()
{
return m_opernCode;
}
/**
* Seta o Código da ação que originou o registro
*
* @param opernCode_ - O Código da ação que originou o registro
*/
public void setOpernCode( String opernCode_ )
{
m_opernCode = opernCode_;
}
/**
* Método da interface MrDocPrvtMovDetailable.
*/
public String getSelectedMrDocCode()
{
return null;
}
/**
* Método da interface MrDocPrvtMovDetailable.
*/
public String getSelectedProdAcctCode()
{
return null;
}
/**
* Método da interface MrDocPrvtMovDetailable.
*/
public String getSelectedProdUnderAcctCode()
{
return null;
}
/**
* Método da interface MrDocPrvtMovDetailable.
*/
public void setSelectedMrDocCode( String mrDocCode_ )
{
setMrDocCode( mrDocCode_ );
}
/**
* Método da interface MrDocPrvtMovDetailable.
*/
public void setSelectedProdAcctCode( String prodAcctCode_ )
{
setProdAcctCode( prodAcctCode_ );
}
/**
* Método da interface MrDocPrvtMovDetailable.
*/
public void setSelectedProdUnderAcctCode( String prodUnderAcctCode_ )
{
setProdUnderAcctCode( prodUnderAcctCode_ );
}
/**
* @return Retorna o tamanho da lista de contatos ativos.
*/
public int getContactSize()
{
return m_contactSize;
}
/**
* @param contactSize_.Seta o tamanho da lista de contatos ativos.
*/
public void setContactSize( int contactSize_ )
{
m_contactSize = contactSize_;
}
/**
* @return Returns opernCodeArray.
*/
public String[] getOpernCodeArray()
{
return m_opernCodeArray;
}
/**
* @param opernCodeArray_ Field opernCodeArray to be setted.
*/
public void setOpernCodeArray( String[] opernCodeArray_ )
{
m_opernCodeArray = opernCodeArray_;
}
} |
package com.evature.evasdk.appinterface;
/**
* Created by iftah on 6/3/15.
*/
public enum EvaAppScope {
Flight,
Hotel,
Car,
Cruise,
Vacation,
Ski,
Explore;
@Override
public String toString() {
switch(this) {
case Flight: return "f";
case Hotel: return "h";
case Car: return "c";
case Cruise: return "r";
case Vacation: return "v";
case Ski: return "s";
case Explore: return "e";
default: throw new IllegalArgumentException();
}
}
}
|
package com.expo.platform;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import okhttp3.OkHttpClient;
import org.apache.commons.codec.binary.Hex;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;
//import org.json.JSONObject;
import com.expo.coins.Coin;
import com.expo.coins.CoinPair;
import com.expo.coins.ExpoOrderType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.gson.internal.LinkedTreeMap;
public class QuadrigaCX implements ICryptoPlatform {
private final String API_URL = "https://api.quadrigacx.com/v2/";
private final String API_KEY = "";//
private final String API_SECRET = "";//
private final String API_CLIENT = "";//
QuadrigaAPI APIClient = null;
private static ICryptoPlatform instance = null;
ObjectMapper objectMapper = new ObjectMapper();
private QuadrigaCX() {
OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
// builder.readTimeout(10, TimeUnit.SECONDS);
// builder.connectTimeout(5, TimeUnit.SECONDS);
//
// builder.addInterceptor(new Interceptor() {
// @Override
// public Response intercept(Chain chain) throws IOException {
// Request request = chain.request().newBuilder().addHeader("key",
// "value").build();
// return chain.proceed(request);
// }
// });
//
// builder.addInterceptor(new UnauthorisedInterceptor(context));
OkHttpClient client = builder.build();
Retrofit retrofit = new Retrofit.Builder().baseUrl(API_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client).build();
APIClient = retrofit.create(QuadrigaAPI.class);
}
public static ICryptoPlatform getInstance() {
if (instance == null) {
instance = new QuadrigaCX();
}
return instance;
}
public void getTransactionFee() {
// TODO Auto-generated method stub
}
public ObjectNode getCurrentBidAndAsk(String coinPair) throws IOException {
ObjectNode root = objectMapper.createObjectNode();
if (coinPair.isEmpty()) {
coinPair = this.getCoinPair(Coin.BTC, Coin.CAD);
}
LinkedTreeMap<String, Object> trades = APIClient
.getCurrentTrades(coinPair).execute().body();
ObjectNode coinPairNode = root.putObject(coinPair);
// start time
String serverTime = trades.get("timestamp").toString();
coinPairNode.put("startTime", serverTime);
// current price
String lastPrice = trades.get("last").toString();
coinPairNode.put("lastPrice", lastPrice);
LinkedTreeMap<String, Object> currentStatus = APIClient
.getCurrentBidAndAsk(coinPair).execute().body();
// asks
ArrayList<ArrayList<String>> asksBookEntry = (ArrayList<ArrayList<String>>) currentStatus
.get("asks");
ArrayNode asksNode = objectMapper.createArrayNode();
ObjectNode askNode;
for (ArrayList<String> askBookEntry : asksBookEntry) {
askNode = objectMapper.createObjectNode();
askNode.put(askBookEntry.get(0), askBookEntry.get(1));
asksNode.add(askNode);
}
coinPairNode.put("ask", asksNode);
// bids
ArrayList<ArrayList<String>> bidsBookEntry = (ArrayList<ArrayList<String>>) currentStatus
.get("bids");
ArrayNode bidsNode = objectMapper.createArrayNode();
ObjectNode bidNode;
for (ArrayList<String> bidBookEntry : bidsBookEntry) {
bidNode = objectMapper.createObjectNode();
bidNode.put(bidBookEntry.get(0), bidBookEntry.get(1));
bidsNode.add(bidNode);
}
coinPairNode.put("bid", bidsNode);
// endtime
serverTime = currentStatus.get("timestamp").toString();
coinPairNode.put("startTime", serverTime);
return root;
}
public ObjectNode getCurrentBidAndAsk(CoinPair coinPair) throws IOException {
return getCurrentBidAndAsk(this.getCoinPair(coinPair.getTargetCoin(),
coinPair.getBaseCoin()));
}
public ObjectNode getCurrentBidAndAsk(Coin targetCoin, Coin baseCoin)
throws IOException {
return getCurrentBidAndAsk(this.getCoinPair(targetCoin, baseCoin));
}
public ObjectNode placeOrder(String coinPair, ExpoOrderType orderType,
String quantity, String price) throws Exception {
if (coinPair.isEmpty()) {
coinPair = this.getCoinPair(Coin.BTC, Coin.CAD);
}
long nonce = System.currentTimeMillis() / 1000L;
StringBuilder sb = new StringBuilder();
sb.append(nonce).append(API_CLIENT).append(API_KEY);
String signature = this.encode(API_SECRET, sb.toString());
LinkedTreeMap<String, Object> order = null;
ObjectNode root = objectMapper.createObjectNode();
switch (orderType) {
case MARKETBUY:
order = APIClient.placeMarketBuyOrder(API_KEY, signature, nonce, quantity,
coinPair).execute().body();
break;
case MARKETSELL:
order = APIClient.placeMarketSellOrder(API_KEY, signature, nonce, quantity,
coinPair).execute().body();
// root.put("orders_matched",
// order.get("orders_matched").toString());
break;
case LIMITBUY:
order = APIClient.placeLimitBuyOrder(API_KEY, signature, nonce, quantity,
price, coinPair).execute().body();
root.put("orderID", order.get("id").toString());
root.put("price", order.get("price").toString());
root.put("datetime", order.get("datetime").toString());
break;
case LIMITSELL:
order = APIClient.placeLimitSellOrder(API_KEY, signature, nonce, quantity,
price, coinPair).execute().body();
root.put("orderID", order.get("id").toString());
root.put("price", order.get("price").toString());
root.put("datetime", order.get("datetime").toString());
break;
default:
break;
}
root.put("coinPair", coinPair);
return root;
}
public ObjectNode placeOrder(CoinPair coinPair, ExpoOrderType orderType,
String quantity, String price) throws Exception {
ObjectNode result = placeOrder(
this.getCoinPair(coinPair.getTargetCoin(),
coinPair.getBaseCoin()),
orderType, quantity, price);
result.put("targetCoin", coinPair.getTargetCoin().getSymbol());
result.put("baseCoin", coinPair.getBaseCoin().getSymbol());
return result;
}
public ObjectNode placeOrder(Coin targetCoin, Coin baseCoin,
ExpoOrderType orderType, String quantity, String price)
throws Exception {
ObjectNode result = placeOrder(this.getCoinPair(targetCoin, baseCoin),
orderType, quantity, price);
result.put("targetCoin", targetCoin.getSymbol());
result.put("baseCoin", baseCoin.getSymbol());
return result;
}
public void cancelOrder(String coinPair, String orderID) throws Exception {
long nonce = System.currentTimeMillis() / 1000L;
StringBuilder sb = new StringBuilder();
sb.append(nonce).append(API_CLIENT).append(API_KEY);
String signature = this.encode(API_SECRET, sb.toString());
boolean result = APIClient.cancelOrder(API_KEY, signature, nonce,
orderID).execute().body();
result = true;
}
public void cancelOrder(CoinPair coinPair, String orderID) throws Exception {
cancelOrder(
getCoinPair(coinPair.getTargetCoin(), coinPair.getBaseCoin()),
orderID);
}
public void cancelOrder(Coin targetCoin, Coin baseCoin, String orderID)
throws Exception {
cancelOrder(getCoinPair(targetCoin, baseCoin), orderID);
}
public ObjectNode getOrderStatus(String coinPair, String orderID)
throws Exception {
long nonce = System.currentTimeMillis() / 1000L;
StringBuilder sb = new StringBuilder();
sb.append(nonce).append(API_CLIENT).append(API_KEY);
String signature = this.encode(API_SECRET, sb.toString());
ObjectNode root = objectMapper.createObjectNode();
LinkedTreeMap<String, Object> result = APIClient
.getOrderStatus(API_KEY, signature, nonce, orderID).execute()
.body();
return root;
}
public ObjectNode getOrderStatus(CoinPair coinPair, String orderID) {
// TODO Auto-generated method stub
return null;
}
public ObjectNode getOrderStatus(Coin targetCoin, Coin baseCoin,
String orderID) {
// TODO Auto-generated method stub
return null;
}
public void testConnectivity() {
// TODO Auto-generated method stub
}
@Deprecated
public long getServerTime() {
// TODO Auto-generated method stub
return 0;
}
public List<Coin> getSupportedBaseCoin() {
List<Coin> coins = new ArrayList<Coin>();
coins.add(Coin.CAD);
coins.add(Coin.USD);
return coins;
}
public List<Coin> getSupportedTargetCoin() {
List<Coin> coins = new ArrayList<Coin>();
coins.add(Coin.BTC);
coins.add(Coin.ETH);
return coins;
}
public interface QuadrigaAPI {
@GET("ticker")
Call<LinkedTreeMap<String, Object>> getCurrentTrades(
@Query("book") String coinPair);
@GET("order_book")
Call<LinkedTreeMap<String, Object>> getCurrentBidAndAsk(
@Query("book") String coinPair);
@POST("buy")
Call<LinkedTreeMap<String, Object>> placeLimitBuyOrder(
@Query("key") String key, @Query("signature") String signature,
@Query("nonce") long nonce, @Query("amount") String amount,
@Query("price") String price, @Query("book") String coinPair);
@POST("buy")
Call<LinkedTreeMap<String, Object>> placeMarketBuyOrder(
@Query("key") String key, @Query("signature") String signature,
@Query("nonce") long nonce, @Query("amount") String amount,
@Query("book") String coinPair);
@POST("sell")
Call<LinkedTreeMap<String, Object>> placeLimitSellOrder(
@Query("key") String key, @Query("signature") String signature,
@Query("nonce") long nonce, @Query("amount") String amount,
@Query("price") String price, @Query("book") String coinPair);
@POST("sell")
Call<LinkedTreeMap<String, Object>> placeMarketSellOrder(
@Query("key") String key, @Query("signature") String signature,
@Query("nonce") long nonce, @Query("amount") String amount,
@Query("book") String coinPair);
@POST("cancel_order")
Call<Boolean> cancelOrder(@Query("key") String key,
@Query("signature") String signature,
@Query("nonce") long nonce, @Query("id") String orderId);
@POST("lookup_order")
Call<LinkedTreeMap<String, Object>> getOrderStatus(
@Query("key") String key,
@Query("signature") String signature,
@Query("nonce") long nonce, @Query("id") String orderId);
}
private String getCoinPair(Coin targetCoin, Coin baseCoin) {
return targetCoin.getSymbol() + "_" + baseCoin.getSymbol();
}
private String encode(String key, String data) throws Exception {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"),
"HmacSHA256");
sha256_HMAC.init(secret_key);
return Hex.encodeHexString(sha256_HMAC.doFinal(data.getBytes("UTF-8")));
}
}
|
package com.proyecto1.william.proyecto1.Settings;
import android.app.FragmentTransaction;
import android.preference.PreferenceActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import com.proyecto1.william.proyecto1.R;
import java.util.List;
public class SettingsActivity extends PreferenceActivity {
/*@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(android.R.id.content, new SettingsFragment());
ft.commit();
}*/
@Override
protected boolean isValidFragment(String fragmentName) {
// Comprobar que el fragmento esté relacionado con la actividad
return SettingsFragment.class.getName().equals(fragmentName);
}
@Override
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.pref_headers, target);
}
@Override
public boolean onIsMultiPane() {
// Determinar que siempre sera multipanel
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
return ((float)metrics.densityDpi / (float)metrics.widthPixels) < 0.30;
}
}
|
/******************************************************************************
* __ *
* <-----/@@\-----> *
* <-< < \\// > >-> *
* <-<-\ __ /->-> *
* Data / \ Crow *
* ^ ^ *
* info@datacrow.net *
* *
* This file is part of Data Crow. *
* Data Crow is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public *
* License as published by the Free Software Foundation; either *
* version 3 of the License, or any later version. *
* *
* Data Crow is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public *
* License along with this program. If not, see http://www.gnu.org/licenses *
* *
******************************************************************************/
package net.datacrow.console.components;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JToolTip;
import javax.swing.KeyStroke;
import net.datacrow.console.ComponentFactory;
import net.datacrow.console.Layout;
import net.datacrow.core.modules.DcModules;
import net.datacrow.core.objects.DcField;
import net.datacrow.core.objects.DcObject;
import net.datacrow.core.resources.DcResources;
public class DcFieldSelectorField extends JComponent implements IComponent, ActionListener {
private Map<DcField, JCheckBox> componentMap = new LinkedHashMap<DcField, JCheckBox>();
private final int module;
public DcFieldSelectorField(int module, boolean allFields, boolean showMenu) {
this.module = module;
buildComponent(allFields, showMenu);
}
@Override
public Object getValue() {
return getSelectedFields();
}
@Override
public void setValue(Object o) {
if (o instanceof int[]) {
setSelectedFields((int[]) o);
}
}
@Override
public void setEditable(boolean b) {
for (JCheckBox cb : componentMap.values())
cb.setEnabled(b);
}
@Override
public void clear() {
componentMap.clear();
componentMap = null;
}
public void invertSelection() {
JCheckBox checkBox;
for (DcField field : componentMap.keySet()) {
checkBox = componentMap.get(field);
checkBox.setSelected(!checkBox.isSelected());
}
}
public void selectAll() {
for (DcField field : componentMap.keySet())
componentMap.get(field).setSelected(true);
}
public void unselectAll() {
for (DcField field : componentMap.keySet())
componentMap.get(field).setSelected(false);
}
public int[] getSelectedFieldIndices() {
Collection<DcField> fields = getSelectedFields();
int[] indices = new int[fields.size()];
int counter = 0;
for (DcField field : fields)
indices[counter++] = field.getIndex();
return indices;
}
public Collection<DcField> getSelectedFields() {
Collection<DcField> fields = new ArrayList<DcField>();
JCheckBox checkBox;
for (DcField field : componentMap.keySet()) {
checkBox = componentMap.get(field);
if (checkBox.isSelected())
fields.add(field);
}
return fields;
}
public void setSelectedFields(int[] fields) {
JCheckBox checkBox;
for (DcField field : componentMap.keySet()) {
checkBox = componentMap.get(field);
if (fields.length == 0) {
checkBox.setSelected(true);
} else {
for (int j = 0; j < fields.length; j++) {
if (field.getIndex() == fields[j])
checkBox.setSelected(true);
}
}
}
}
@Override
public JToolTip createToolTip() {
return new DcMultiLineToolTip();
}
private void buildComponent(boolean allFields, boolean showMenu) {
setLayout(Layout.getGBL());
JPanel panel = new JPanel();
panel.setLayout(Layout.getGBL());
int x = 0;
int y = 0;
JCheckBox checkBox;
for (DcField field : DcModules.get(module).getFields()) {
if (allFields || (field.getIndex() != DcObject._ID && field.getIndex() != DcObject._SYS_EXTERNAL_REFERENCES)) {
checkBox = ComponentFactory.getCheckBox(field.getLabel());
componentMap.put(field, checkBox);
panel.add(checkBox, Layout.getGBC(x, y++, 1, 1, 1.0, 1.0
,GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL,
new Insets( 0, 10, 0, 0), 0, 0));
if (y == 12) {
x++;
y = 0;
}
}
}
if (showMenu) {
JMenu editMenu = createMenu();
JMenuBar mb = ComponentFactory.getMenuBar();
mb.add(editMenu);
mb.setMinimumSize(new Dimension(100, 23));
mb.setPreferredSize(new Dimension(100, 23));
add(mb, Layout.getGBC(0, 0, 1, 1, 10.0, 10.0
,GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL,
new Insets( 0, 0, 0, 0), 0, 0));
}
add(panel, Layout.getGBC(0, 1, 1, 1, 1.0, 1.0
,GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL,
new Insets( 0, 0, 0, 0), 0, 0));
}
private JMenu createMenu() {
JMenu menu = ComponentFactory.getMenu("Edit");
JMenuItem menuSelectAll = ComponentFactory.getMenuItem(DcResources.getText("lblSelectAll"));
JMenuItem menuUnselectAll = ComponentFactory.getMenuItem(DcResources.getText("lblUnselectAll"));
JMenuItem menuInvertSelection = ComponentFactory.getMenuItem(DcResources.getText("lblInvertSelection"));
menuSelectAll.addActionListener(this);
menuSelectAll.setActionCommand("selectAll");
menuUnselectAll.addActionListener(this);
menuUnselectAll.setActionCommand("unselectAll");
menuInvertSelection.addActionListener(this);
menuInvertSelection.setActionCommand("invertSelection");
menuSelectAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK));
menuUnselectAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_U, InputEvent.CTRL_MASK));
menuInvertSelection.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, InputEvent.CTRL_MASK));
menu.add(menuSelectAll);
menu.add(menuUnselectAll);
menu.addSeparator();
menu.add(menuInvertSelection);
return menu;
}
@Override
public void refresh() {}
@Override
public void actionPerformed(ActionEvent ae) {
if (ae.getActionCommand().equals("unselectAll"))
unselectAll();
else if (ae.getActionCommand().equals("selectAll"))
selectAll();
else if (ae.getActionCommand().equals("invertSelection"))
invertSelection();
}
}
|
package com.github.hualuomoli.commons.prop;
import java.util.Map;
import org.junit.Ignore;
import org.junit.Test;
public class PropertiesLoaderTest {
@Test
@Ignore
public void testloadProperties2MapStringArray() {
Map<String, String> map = PropertiesLoader.loadProperties2Map("classpath:/props/props.properties");
for (String key : map.keySet()) {
String location = map.get(key);
System.out.println(location);
Map<String, String> p = PropertiesLoader.loadProperties2Map(location);
System.out.println(p);
}
}
}
|
package com.protectthecarrots.Missions;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.utils.TimeUtils;
import com.badlogic.gdx.utils.viewport.StretchViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
import com.protectthecarrots.Scenes.GameParameters;
import com.protectthecarrots.Scenes.Hud;
import com.protectthecarrots.Sprites.EnemyBunny;
import com.protectthecarrots.Sprites.Operator;
import com.protectthecarrots.TheCarrots;
import com.protectthecarrots.Tools.BonusBullet;
import com.protectthecarrots.Tools.BonusLife;
import com.protectthecarrots.Tools.Bullet;
import com.protectthecarrots.Tools.WorldContactListener;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Random;
/**
* Created by Pedro on 13/03/2018.
*/
public class Level8 implements Screen, InputProcessor {
public TheCarrots game;
private OrthographicCamera gamecam;
private Viewport gameport;
private Hud hud;
private Preferences preferences = Gdx.app.getPreferences("MyPreferences");
private Texture background;
private Operator player;
private float playerAngle;
private World world;
private Box2DDebugRenderer b2dr;
// Declaration of the objects used in finger control
private Vector3 touchpos;
private int lastscreenX = 12345;
private int lastscreenY = 12345;
private float convertedscreenX = 12345.0f;
private float convertedscreenY = 12345.0f;
private GameParameters parameters;
private Texture lifebarbackground;
private Texture lifebargreen;
private float lifebarWidth;
private ArrayList<Bullet> bulletManager;
private ArrayList<BonusBullet> bonusBulletManager;
private ArrayList<BonusLife> bonusLifeManager;
private ArrayList<EnemyBunny> enemyBunnyManager;
private boolean keepcallingbunnies;
private long lastEnemyBunnyAlocation;
public float statetime;
public Random randomGenerator;
public Level8(TheCarrots game){
this.game = game;
gamecam = new OrthographicCamera();
gameport = new StretchViewport(TheCarrots.V_WIDTH / TheCarrots.PPM, TheCarrots.V_HEIGHT / TheCarrots.PPM, gamecam);
gamecam.setToOrtho(false, TheCarrots.V_WIDTH / TheCarrots.PPM, TheCarrots.V_HEIGHT / TheCarrots.PPM);
gamecam.position.set(TheCarrots.V_WIDTH / (2 * TheCarrots.PPM), TheCarrots.V_HEIGHT / (2 * TheCarrots.PPM), 0);
background = new Texture("background1.png");
world = new World(new Vector2(0, 0 ), true);
b2dr = new Box2DDebugRenderer();
hud = new Hud();
hud.timer.start();
lifebarbackground = new Texture("life bar background.png");
lifebargreen = new Texture("life bar green.png");
touchpos = new Vector3(0 , 0 , 0);
Gdx.input.setInputProcessor(this);
parameters = new GameParameters();
player = new Operator(world);
enemyBunnyManager = new ArrayList<EnemyBunny>();
keepcallingbunnies = true;
lastEnemyBunnyAlocation = 0;
bulletManager = new ArrayList<Bullet>();
bonusBulletManager = new ArrayList<BonusBullet>();
bonusLifeManager = new ArrayList<BonusLife>();
world.setContactListener(new WorldContactListener(player));
statetime = 0.0f;
randomGenerator = new Random();
}
public void placeEnemies(){
if( hud.timer.secondsPassed() % 3 == 2 && lastEnemyBunnyAlocation != hud.timer.secondsPassed() && keepcallingbunnies) {
float randomX = 1.0f + randomGenerator.nextFloat() * 6.0f;
float notRandomY = 4.8f;
enemyBunnyManager.add( new EnemyBunny(world, new Vector2( randomX, notRandomY ), new Vector2(0.0f, -60.0f)) );
lastEnemyBunnyAlocation = hud.timer.secondsPassed();
}
}
public void checkForPlayerStatus(){
if(player.playerLP <= 0 && !player.playerDestroyed) {
player.setDestroyed();
player.destroyTime = TimeUtils.millis();
hud.timer.stop();
int lastcoins = Hud.score / 10 + Math.abs(player.playerLP / 2);
preferences.putInteger("LastScore", Hud.score);
preferences.putInteger("LastCoins", lastcoins);
if(preferences.getInteger("HighScore", 0) < Hud.score)
preferences.putInteger("HighScore", Hud.score);
preferences.flush();
game.setGameEndScreen();
}
}
public void checkForCompletition(){
if(player.playerLP > 0 && !player.playerDestroyed && TheCarrots.numberOfBunniesDefeated >= 50) {
hud.timer.stop();
// Add here the code to save and flush the preferences
int lastcoins = Hud.score / 10 + Math.abs(player.playerLP / 2);
preferences.putInteger("LastScore", Hud.score);
preferences.putInteger("LastCoins", lastcoins);
if(preferences.getInteger("HighScore", 0) < Hud.score)
preferences.putInteger("HighScore", Hud.score);
preferences.putInteger("MaxLevelUnlocked", 8);
preferences.flush();
game.setLevelCompleteScreen();
}
}
public void updateParameters(){
TheCarrots.str = "gamecam.position.x__" + String.format(Locale.US, "%05f", gamecam.position.x) + "\n" +
"gamecam.position.y__" + String.format(Locale.US, "%05f", gamecam.position.y) + "\n" +
"player.b2body.getPosition().x__" + String.format(Locale.US, "%05f", player.b2body.getPosition().x) + "\n" +
"player.b2body.getPosition().y__" + String.format(Locale.US, "%05f", player.b2body.getPosition().y) + "\n" +
"player.b2body.getAngle()__" + String.format(Locale.US, "%05f", player.b2body.getAngle()) + "\n" +
"player.b2body.getWorldCenter().x__" + String.format(Locale.US, "%05f", player.b2body.getWorldCenter().x) + "\n" +
"player.b2body.getWorldCenter().y__" + String.format(Locale.US, "%05f", player.b2body.getWorldCenter().y) + "\n" +
"touchpos.x__" + String.format(Locale.US, "%05f", touchpos.x) + "\n" +
"touchpos.y__" + String.format(Locale.US, "%05f", touchpos.y) + "\n" +
"playerAngle__" + String.format(Locale.US, "%05f", playerAngle) + "\n" +
"player.playerLP__" + String.format(Locale.US, "%05d", player.playerLP) + "\n" +
"Gdx.graphics.getWidth()__" + String.format(Locale.US, "%05d", Gdx.graphics.getWidth()) + "\n" +
"Gdx.graphics.getHeight()__" + String.format(Locale.US, "%05d", Gdx.graphics.getHeight()) + "\n" +
"gameport.getWorldWidth()__" + String.format(Locale.US, "%05f", gameport.getWorldWidth()) + "\n" +
"gameport.getWorldHeight()__" + String.format(Locale.US, "%05f", gameport.getWorldHeight()) + "\n" +
"gameport.getScreenWidth()__" + String.format(Locale.US, "%05d", gameport.getScreenWidth()) + "\n" +
"gameport.getScreenHeight()__" + String.format(Locale.US, "%05d", gameport.getScreenHeight()) + "\n" +
"keepcallingbunnies__" + String.format(Locale.US, "%1b", keepcallingbunnies) + "\n" +
"screenX__" + String.format(Locale.US, "%05d", lastscreenX) + "\n" +
"screenY__" + String.format(Locale.US, "%05d", lastscreenY) + "\n" +
"convertedscreenX__" + String.format(Locale.US, "%05f", convertedscreenX) + "\n" +
"convertedscreenY__" + String.format(Locale.US, "%05f", convertedscreenY) + "\n" +
"bulletManager.size()__" + String.format(Locale.US, "%05d", bulletManager.size()) + "\n" +
"bonusBulletManager.size()__" + String.format(Locale.US, "%05d", bonusBulletManager.size()) + "\n" +
"enemyBunnyManager.size()__" + String.format(Locale.US, "%05d", enemyBunnyManager.size()) + "\n" +
"MathUtils.atan2(5.0f, 0.0f)__" + String.format(Locale.US, "%05f", MathUtils.atan2(5.0f, 0.0f)) + "\n" +
"statetime__" + String.format(Locale.US, "%05f", statetime) + "\n" +
"Gdx.input.getX()__" + String.format(Locale.US, "%05d", Gdx.input.getX()) + "\n" +
"Gdx.input.getY()__" + String.format(Locale.US, "%05d", Gdx.input.getY()) + "\n" +
"Gdx.graphics.getDeltaTime()" + String.format(Locale.US, "%05f", Gdx.graphics.getDeltaTime()) + "\n" ;
}
public void objectsManagement(float delta) {
for (int u = 0; u < bulletManager.size(); u++) {
Bullet currentBullet = bulletManager.get(u);
currentBullet.update(game.batch, delta, playerAngle);
if ((currentBullet.bulletPosition.y > 4.8f + 0.2f) || (currentBullet.bulletPosition.x < -0.5f) || ( currentBullet.bulletPosition.x > ( (TheCarrots.V_WIDTH / TheCarrots.PPM) + 0.5f )) || (currentBullet.body.getUserData() == "disposed")) { // || (bodiesShotsList.get(u).getUserData() == "disposed") was giving error
world.destroyBody(currentBullet.body);
bulletManager.remove(u);
u -= 1;
}
}
for (int u = 0; u < bonusBulletManager.size(); u++) {
BonusBullet currentBullet = bonusBulletManager.get(u);
currentBullet.update(game.batch, delta);
if ((currentBullet.bonusBulletPosition.y > 4.8f + 0.2f) || (currentBullet.bonusBulletPosition.y < -0.5f) || (currentBullet.body.getUserData() == "disposed")) { // || (bodiesShotsList.get(u).getUserData() == "disposed") was giving error
world.destroyBody(currentBullet.body);
bonusBulletManager.remove(u);
u -= 1;
}
}
for (int u = 0; u < bonusLifeManager.size(); u++) {
BonusLife currentBullet = bonusLifeManager.get(u);
currentBullet.update(game.batch, delta);
if ((currentBullet.bonusLifePosition.y > 4.8f + 0.2f) || (currentBullet.bonusLifePosition.y < -0.5f) || (currentBullet.body.getUserData() == "disposed")) { // || (bodiesShotsList.get(u).getUserData() == "disposed") was giving error
world.destroyBody(currentBullet.body);
bonusLifeManager.remove(u);
u -= 1;
}
}
for (int u = 0; u < enemyBunnyManager.size(); u++) {
EnemyBunny currentBunny = enemyBunnyManager.get(u);
if(currentBunny.body.getUserData() != "disposed") {
currentBunny.update(game.batch, delta, statetime);
} else {
currentBunny.update(game.batch, delta, (statetime - currentBunny.defeatTime) );
}
if (currentBunny.body.getUserData() == "hit") {
currentBunny.enemyBunnyLP -= Bullet.bulletDamage;
currentBunny.body.setUserData("enemyBunny");
if (currentBunny.enemyBunnyLP <= 0 && currentBunny.body.getUserData() != "disposed") {
currentBunny.body.setUserData("disposed");
Hud.score += 50;
currentBunny.defeatTime = statetime;
//currentBunny.enemyBunnyLP = 100;
}
}
if ( (currentBunny.enemyBunnyPosition.y < - 0.5f) || currentBunny.body.getUserData() == "deleteNow" || ( (currentBunny.body.getUserData() == "disposed") && (statetime - currentBunny.defeatTime >= 1.5f) ) ) { // || (bodiesShotsList.get(u).getUserData() == "disposed") was giving error
if (currentBunny.enemyBunnyPosition.y < - 0.5f) {
player.playerLP -= 100;
}
world.destroyBody(currentBunny.body);
enemyBunnyManager.remove(u);
// Add here the code to generate bonuses
// HERE
// HERE
TheCarrots.numberOfBunniesDefeated += 1;
preferences.putLong("BunniesDefeated", 1 + preferences.getLong("BunniesDefeated", 0) );
preferences.flush();
u -= 1;
}
}
}
public void update(float dt) {
statetime += Gdx.graphics.getDeltaTime();
world.step(1 / 50f, 6, 2);
gamecam.update();
placeEnemies();
checkForPlayerStatus();
checkForCompletition();
updateParameters();
}
@Override
public void show() {
}
@Override
public void render(float delta) {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
if (!player.playerDestroyed) {
game.batch.setProjectionMatrix(gamecam.combined);
game.batch.begin();
game.batch.draw(background, 0.0f, 0.0f, TheCarrots.V_WIDTH / TheCarrots.PPM, TheCarrots.V_HEIGHT / TheCarrots.PPM);
update(delta);
player.update(game.batch, playerAngle);
objectsManagement(delta);
lifebarWidth = (player.playerLP / TheCarrots.maxPlayerHealth) * 150.0f;
game.batch.draw(lifebarbackground, 40.0f / TheCarrots.PPM, (TheCarrots.V_HEIGHT - 55.0f) / TheCarrots.PPM, 150.0f + 40.0f, 35.0f);
game.batch.draw(lifebargreen, 60.0f / TheCarrots.PPM, (TheCarrots.V_HEIGHT - 50.0f) / TheCarrots.PPM, lifebarWidth, 25.0f);
game.batch.end();
b2dr.render(world, gamecam.combined);
game.batch.setProjectionMatrix(hud.hudCam.combined);
hud.draw(game.batch, TheCarrots.str);
game.batch.setProjectionMatrix(parameters.parametersCam.combined);
parameters.draw(game.batch, TheCarrots.str);
}
}
@Override
public void resize(int width, int height) {
gameport.update(width, height);
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void hide() {
}
@Override
public void dispose() {
world.dispose();
b2dr.dispose();
}
@Override
public boolean keyDown(int keycode) {
return false;
}
@Override
public boolean keyUp(int keycode) {
return false;
}
@Override
public boolean keyTyped(char character) {
return false;
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
if(!player.playerDestroyed) {
touchpos.x = ( (screenX * TheCarrots.V_WIDTH) / Gdx.graphics.getWidth() ) / TheCarrots.PPM;
touchpos.y = ( (Gdx.graphics.getHeight() - screenY) * TheCarrots.V_HEIGHT / Gdx.graphics.getHeight() ) / TheCarrots.PPM ;
if(touchpos.x >= player.playerX + player.playerWidth / 2.0f)
playerAngle = (float)( (-1.0f) * ( MathUtils.atan2(touchpos.x - (player.playerX + player.playerWidth / 2.0f) , touchpos.y - (player.playerY + player.playerHeight / 2.0f + player.centerOffsetY) )) );
if(touchpos.x < player.playerX + player.playerWidth / 2.0f)
playerAngle = (float)( MathUtils.atan2((player.playerX + player.playerWidth / 2.0f) - touchpos.x , touchpos.y - (player.playerY + player.playerHeight / 2.0f + player.centerOffsetY)) );
playerAngle = playerAngle * MathUtils.radiansToDegrees;
lastscreenX = screenX;
lastscreenY = screenY;
convertedscreenX = (screenX * TheCarrots.V_WIDTH) / Gdx.graphics.getWidth();
convertedscreenY = (Gdx.graphics.getHeight() - screenY) * TheCarrots.V_HEIGHT / Gdx.graphics.getHeight();
return false;
}
return false;
}
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
if ( !player.playerDestroyed ) {
touchpos.x = ( (screenX * TheCarrots.V_WIDTH) / Gdx.graphics.getWidth() ) / TheCarrots.PPM;
touchpos.y = ( (Gdx.graphics.getHeight() - screenY) * TheCarrots.V_HEIGHT / Gdx.graphics.getHeight() ) / TheCarrots.PPM ;
if(touchpos.x >= player.playerX + player.playerWidth / 2.0f)
playerAngle = (float)( (-1.0f) * ( MathUtils.atan2(touchpos.x - (player.playerX + player.playerWidth / 2.0f) , touchpos.y - (player.playerY + player.playerHeight / 2.0f + player.centerOffsetY) )) );
if(touchpos.x < player.playerX + player.playerWidth / 2.0f)
playerAngle = (float)( MathUtils.atan2((player.playerX + player.playerWidth / 2.0f) - touchpos.x , touchpos.y - (player.playerY + player.playerHeight / 2.0f + player.centerOffsetY)) );
playerAngle = playerAngle * MathUtils.radiansToDegrees;
if ( bulletManager.size() <= TheCarrots.bulletNumber - 1 ) {
if (TheCarrots.bulletMutiplicity == 1) {
Bullet myBullet = new Bullet(world, new Vector2(player.playerX + player.playerWidth / 2.0f, player.playerY + player.playerHeight / 2.0f + player.centerOffsetY + 1.5f), playerAngle, 1, 1.5f);
bulletManager.add(myBullet);
} else if (TheCarrots.bulletMutiplicity == 2) {
Bullet myBullet = new Bullet(world, new Vector2(player.playerX + player.playerWidth / 2.0f, player.playerY + player.playerHeight / 2.0f + player.centerOffsetY + 1.5f), playerAngle, 1, 1.5f);
bulletManager.add(myBullet);
myBullet = new Bullet(world, new Vector2(player.playerX + player.playerWidth / 2.0f, player.playerY + player.playerHeight / 2.0f + player.centerOffsetY + 2.0f), playerAngle, 1, 2.0f);
bulletManager.add(myBullet);
}
}
}
return false;
}
@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
if(!player.playerDestroyed) {
touchpos.x = ( (screenX * TheCarrots.V_WIDTH) / Gdx.graphics.getWidth() ) / TheCarrots.PPM;
touchpos.y = ( (Gdx.graphics.getHeight() - screenY) * TheCarrots.V_HEIGHT / Gdx.graphics.getHeight() ) / TheCarrots.PPM ;
if(touchpos.x >= player.playerX + player.playerWidth / 2.0f)
playerAngle = (float)( (-1.0f) * ( MathUtils.atan2(touchpos.x - (player.playerX + player.playerWidth / 2.0f) , touchpos.y - (player.playerY + player.playerHeight / 2.0f + player.centerOffsetY) )) );
if(touchpos.x < player.playerX + player.playerWidth / 2.0f)
playerAngle = (float)( MathUtils.atan2((player.playerX + player.playerWidth / 2.0f) - touchpos.x , touchpos.y - (player.playerY + player.playerHeight / 2.0f + player.centerOffsetY)) );
playerAngle = playerAngle * MathUtils.radiansToDegrees;
lastscreenX = screenX;
lastscreenY = screenY;
convertedscreenX = (screenX * TheCarrots.V_WIDTH) / Gdx.graphics.getWidth();
convertedscreenY = (Gdx.graphics.getHeight() - screenY) * TheCarrots.V_HEIGHT / Gdx.graphics.getHeight();
return false;
}
return false;
}
@Override
public boolean mouseMoved(int screenX, int screenY) {
return false;
}
@Override
public boolean scrolled(int amount) {
return false;
}
} |
package controlador;
import java.util.Vector;
import modelo.*;
public class Restaurante {
static private Restaurante restaurante = null;
private boolean mesasAsignadas;
private boolean open;
// La fecha y el dia se cargan como String al inciciar el Sistema.
// Se leen desde la hora y fecha configurada en el sistema operativo.
private String fecha; // Formato dd/mm/aaaa
private String dia; // lunes - martes - miércoles - jueves - viernes - sábado - domingo
private Carta cartaActiva;
private Vector <ItemDeCarta> itemsCarta;
private Vector <Carta> cartas;
private Vector <Mozo> mozos;
private Vector <Mesa> mesas;
private Vector <Comanda> comandas;
private Vector <Proveedor> proveedores;
private Vector <OrdenDeCompra> ordenesCompra;
private Vector <Producto> productos;
// Constructor de instancia Restaurante
// -------------------------------------------------------------
private Restaurante (){
itemsCarta = new Vector <ItemDeCarta>();
cartas = new Vector <Carta>();
mozos = new Vector <Mozo> ();
mesas = new Vector <Mesa> ();
comandas = new Vector <Comanda> ();
proveedores = new Vector <Proveedor>();
ordenesCompra = new Vector <OrdenDeCompra>();
productos = new Vector <Producto>();
open = false;
/** -------------------------------------------------------------
** Metodos que cargan datos - USAR EN LAS PRUEBAS Y BORRAR !!!!
** -------------------------------------------------------------
**/
// Mesas 12 (10 habilitadas, 2 deshabilitadas)
for (int i=0; i<5; i++)
altaDeMesa(true);
for (int i=0; i<2; i++)
altaDeMesa(false);
for (int i=0; i<5; i++)
altaDeMesa(true);
// Mozos
altaDeMozo("Cacho Garay", 15, true);
altaDeMozo("Jorge Buenaventua", 20, true);
altaDeMozo("Chichilo Viale", 9, false);
altaDeMozo("Flaco Pailos", 12, true);
// Proveedores
altaDeProveedor("99999999995", "La Vaca Loca", "Lavalle 111");
altaDeProveedor("21636582139", "La Botilleria de Jose", "Alsina 888");
altaDeProveedor("20123456783", "Verduleria El Choclo Feliz", "Marcelo T 231");
Proveedor prov = buscarProveedor("99999999995");
Proveedor prov2 = buscarProveedor("21636582139");
Proveedor prov3 = buscarProveedor("20123456783");
// Productos
altaDeProducto("lomo", 1000, 100, 5000, prov);
altaDeProducto("pollo", 1500, 80, 2000, prov);
altaDeProducto("papa", 800, 100, 1200, prov3);
altaDeProducto("ravioles", 1000, 550, 1000, prov2);
altaDeProducto("tomate", 1000, 550, 1000, prov3);
altaDeProducto("vino tinto", 20, 18, 8, prov2);
altaDeProducto("gaseosa naranja", 20, 4, 8, prov2);
altaDeProducto("gaseosa cola", 20, 4, 8, prov2);
altaDeProducto("agua sin gas 500cc", 200, 40, 80, prov3);
// Items de Carta
altaDePlato("Pollo con Papas", 18);
ItemDeCarta polloPapas = buscarItemDeCarta ("Pollo con Papas");
polloPapas.agregarIngrediente(buscarProducto("pollo"), 120);
polloPapas.agregarIngrediente(buscarProducto("papa"), 85);
altaDePlato("Ravioles con Tuco", 12);
ItemDeCarta raviolesTuco = buscarItemDeCarta ("Ravioles con Tuco");
raviolesTuco.agregarIngrediente(buscarProducto("ravioles"), 230);
raviolesTuco.agregarIngrediente(buscarProducto("tomate"), 35);
altaDePlato("Lomo con Fritas", 24);
ItemDeCarta lomoF = buscarItemDeCarta ("Lomo con Fritas");
lomoF.agregarIngrediente(buscarProducto("lomo"), 100);
lomoF.agregarIngrediente(buscarProducto("papa"), 150);
altaDeBebida("Fanta Naranja", 8);
ItemDeCarta gaseosa = buscarItemDeCarta ("Fanta Naranja");
gaseosa.agregarIngrediente(buscarProducto("gaseosa naranja"), 1);
altaDeBebida("Trapiche Malbec", 16);
ItemDeCarta vinoT = buscarItemDeCarta ("Trapiche Malbec");
vinoT.agregarIngrediente(buscarProducto("vino tinto"), 1);
altaDeBebida("Agua sin Gas 500cc", 5);
ItemDeCarta agua = buscarItemDeCarta ("Agua sin Gas 500cc");
agua.agregarIngrediente(buscarProducto("agua sin gas 500cc"), 1);
// Cartas
altaDeCarta("miércoles");
Carta carta2 = buscarCarta("miércoles");
carta2.agregarItemCarta(vinoT);
carta2.agregarItemCarta(raviolesTuco);
altaDeCarta("jueves");
Carta carta = buscarCarta("jueves");
carta.agregarItemCarta(gaseosa);
carta.agregarItemCarta(vinoT);
carta.agregarItemCarta(polloPapas);
altaDeCarta("viernes");
Carta carta3 = buscarCarta("viernes");
carta3.agregarItemCarta(gaseosa);
carta3.agregarItemCarta(vinoT);
carta3.agregarItemCarta(polloPapas);
carta3.agregarItemCarta(agua);
carta3.agregarItemCarta(lomoF);
altaDeCarta("sábado");
Carta carta1 = buscarCarta("sábado");
carta1.agregarItemCarta(gaseosa);
carta1.agregarItemCarta(polloPapas);
carta1.agregarItemCarta(vinoT);
carta1.agregarItemCarta(agua);
carta1.agregarItemCarta(lomoF);
}
/** BORRAR LOS DATOS INGRESADOS ARRIBA
** ------------------------------------------------------------ **/
// SINGLETON Restaurante getRestaurante()
// -------------------------------------------------------------
static public Restaurante getRestaurante(){
if (restaurante == null){
restaurante = new Restaurante();
}
return restaurante;
}
// Metodos sets y gets para los atributos de Restaurante
// -------------------------------------------------------------
public void setFecha(String fecha) {
this.fecha = fecha;
}
public String getFecha() {
return fecha;
}
public String getDia() {
return dia;
}
public void setDia(String dia) {
this.dia = dia;
}
public boolean isMesasAsignadas() {
return mesasAsignadas;
}
private void setMesasAsignadas(boolean mesasAsignadas) {
this.mesasAsignadas = mesasAsignadas;
}
public boolean isOpen() {
return open;
}
private void setOpen(boolean open) {
this.open = open;
}
private void setCartaActiva(Carta cartaActiva) {
this.cartaActiva = cartaActiva;
}
// Metodos de jornada (apertura y cierre)
// -------------------------------------------------------------
public boolean abrirJornada(){
// Revisa que exista una carta creada para asignar al presente dia
if (buscarCarta(dia)==null){
return false;
}
// Revisa que halla mozos y mesas disponibles para iniciar la jornada
if ((mozos == null) || (mesas == null)){
return false;
}else{
// Hay carta del dia, hay mozos y hay mesas; ergo, abre la jornada.
asignarMesas();
setOpen(true);
// Asignar la carta activa del dia
setCartaActiva(buscarCarta(dia));
return true;
}
}
public boolean cerrarJornada(){
for (int i = 0; i<mesas.size(); i++){
if (mesas.elementAt(i).isOcupada()){
return false;
}
}
pagarMozos();
generarOrdenesDeCompra();
setOpen(false);
return true;
}
/**
* -----------------------------------------------------------------------------
* ------------------ ABM - BUSCAR de las clases del NEGOCIO -----------------
* -----------------------------------------------------------------------------
*
**/
// ABM - BUSCAR Items De Carta (platos o bebidas)
// -----------------------------------------------------
private ItemDeCarta buscarItemDeCarta (String nombre){
for (int i=0; i<itemsCarta.size(); i++){
ItemDeCarta idecarta = itemsCarta.elementAt(i);
if (idecarta.getNombre().equals(nombre)){
return idecarta;
}
}
return null;
}
public void altaDePlato (String nombre, float precio){
ItemDeCarta itemc = buscarItemDeCarta(nombre);
if (itemc == null){
Plato redondo = new Plato (nombre, precio);
itemsCarta.add(redondo);
}
}
public void altaDeBebida (String nombre, float precio){
ItemDeCarta itemc = buscarItemDeCarta(nombre);
if (itemc == null){
Bebida vaso = new Bebida (nombre, precio);
itemsCarta.add(vaso);
}
}
public void bajaDeItemDeCarta (String nombre){
ItemDeCarta itemc = buscarItemDeCarta(nombre);
if (itemc != null){
itemsCarta.remove(itemc);
}
}
public void modificarItemDeCarta (String nombreViejo, String nombreNuevo, float precio){
ItemDeCarta itcar = buscarItemDeCarta(nombreViejo);
if (itcar != null){
itcar.setNombre(nombreNuevo);
itcar.setPrecio(precio);
}
}
// Carga un producto en un plato/bebida
public boolean cargarIngrediente (String nombreItem, String nombreProducto, float cantidad){
// Revisa que existan el plato/bebida y el producto
ItemDeCarta itemc = buscarItemDeCarta(nombreItem);
Producto prod = buscarProducto (nombreProducto);
if (prod != null && itemc != null){
return (itemc.agregarIngrediente(prod, cantidad));
}
return false;
}
// Elimina un producto existente de un plato/bebida
public boolean descargarIngrediente (String nombreItem, String nombreProducto){
// Revisa que existan el plato/bebida y el producto
ItemDeCarta itemc = buscarItemDeCarta(nombreItem);
Producto prod = buscarProducto (nombreProducto);
if (prod != null && itemc != null){
return (itemc.eliminarIngrediente(prod));
}
return false;
}
// ABM - BUSCAR Cartas
// -----------------------------------------------------
private Carta buscarCarta (String dia){
for (int i=0; i<cartas.size(); i++){
Carta car = cartas.elementAt(i);
if (car.getDia().equals(dia)){
return car;
}
}
return null;
}
// Comprueba que el dia de semana sea valido
public boolean diaValido (String dia){
if (dia.equalsIgnoreCase("lunes"))
return true;
else
if (dia.equalsIgnoreCase("martes"))
return true;
else
if (dia.equalsIgnoreCase("miércoles"))
return true;
else
if (dia.equalsIgnoreCase("jueves"))
return true;
else
if (dia.equalsIgnoreCase("viernes"))
return true;
else
if (dia.equalsIgnoreCase("sábado"))
return true;
else
if (dia.equalsIgnoreCase("domingo"))
return true;
else
return false;
}
public boolean altaDeCarta (String dia){
boolean valido = diaValido(dia);
// Revisa que el dia sea valido
if (valido){
Carta letter = buscarCarta(dia);
// Revisa que la carta no halla sido creada
if (letter == null){
letter = new Carta (dia);
cartas.add(letter);
return true;
}
}
return false;
}
public boolean bajaDeCarta (String dia){
boolean valido = diaValido(dia);
// Revisa que el dia sea valido
if (valido){
Carta letter = buscarCarta(dia);
// Revisa que la carta exista
if (letter != null){
cartas.remove(letter);
return true;
}
}
return false;
}
// La modificacion consiste en cambiar una carta de un dia a otro.
public boolean modificarCarta (String diaViejo, String diaNuevo){
boolean validoViejo = diaValido(diaViejo);
boolean validoNuevo = diaValido(diaNuevo);
// Revisa que ambos dias sean validos
if (validoViejo && validoNuevo){
// Revisa que no exista una carta con el mismo nombre a asignar
// para que no pueda haber dos cartas del mismo dia.
Carta letterVieja = buscarCarta(diaViejo);
Carta letterNueva = buscarCarta(diaNuevo);
if (letterVieja != null || letterNueva == null ){
letterVieja.setDia(diaNuevo);
return true;
}
}
return false;
}
// Carga un plato o bebida en la carta
public boolean cargarCarta (String nombreCarta, String nombreItem){
// Revisa que existan la carta y el plato/bebida
Carta letter = buscarCarta(nombreCarta);
ItemDeCarta itemc = buscarItemDeCarta(nombreItem);
if (letter != null && itemc != null){
return (letter.agregarItemCarta(itemc));
}
return false;
}
// Elimina un plato o bebida existentes de una carta
public boolean descargarCarta (String nombreCarta, String nombreItem){
// Revisa que existan la carta y el plato/bebida
Carta letter = buscarCarta(nombreCarta);
ItemDeCarta itemc = buscarItemDeCarta(nombreItem);
if (letter != null && itemc != null){
return (letter.eliminarItemCarta(itemc));
}
return false;
}
// ABM - BUSCAR Productos
// -----------------------------------------------------
private Producto buscarProducto (String nombre){
for (int i=0; i<productos.size(); i++){
Producto prod = productos.elementAt(i);
if (prod.getNombre().equals(nombre)){
return prod;
}
}
return null;
}
private void altaDeProducto (String nombre, int cantidad, int pedido, int reab, Proveedor prov){
Producto prod = buscarProducto(nombre);
if (prod == null){
prod = new Producto(nombre, cantidad, pedido, reab, prov);
productos.add(prod);
}
}
public void altaDeProductoFromView (String nombre, int cantidad, int pedido, int reab, String cuit){
Proveedor proveedor = buscarProveedor(cuit);
Producto prod = buscarProducto(nombre);
if ((prod == null) && (proveedor != null)){
prod = new Producto(nombre, cantidad, pedido, reab, proveedor);
productos.add(prod);
}
}
public void bajaDeProducto (String nombre){
Producto prod = buscarProducto(nombre);
if (prod != null){
productos.remove(prod);
}
}
public void modificarProducto (String name, float canti, float puntop, float puntor, String prove){
Proveedor prov = buscarProveedor(prove);
Producto prod = buscarProducto(name);
if (prod != null || prov != null){
prod.setNombre(name);
prod.setCantidad(canti);
prod.setPuntoped(puntop);
prod.setPuntoreab(puntor);
prod.setProveedor(prov);
}
}
// Actualizar stock cuando ingresa mercaderia nueva
public void ingresarMercaderia (String produc, float cantidad){
Producto prod = buscarProducto(produc);
if (prod != null){
prod.setCantidad(prod.getCantidad()+cantidad);
}
}
// ABM - BUSCAR Proveedores
// -----------------------------------------------------
private Proveedor buscarProveedor (String cuit){
for (int i=0; i<proveedores.size(); i++){
Proveedor prov = proveedores.elementAt(i);
if (prov.getCuit().equals(cuit)){
return prov;
}
}
return null;
}
public void altaDeProveedor (String cuit, String razonsocial, String domicilio){
Proveedor prov = buscarProveedor(cuit);
if (prov == null){
prov = new Proveedor(cuit, razonsocial, domicilio);
proveedores.add(prov);
}
}
public void bajaDeProveedor (String cuit){
Proveedor prov = buscarProveedor(cuit);
if (prov != null){
proveedores.remove(prov);
}
}
public boolean modificarProveedor(String cuit, String razonsocial, String domicilio){
Proveedor prov = buscarProveedor(cuit);
if (prov != null){
prov.setCuit(cuit);
prov.setDomicilio(domicilio);
prov.setRazonsocial(razonsocial);
return true;
}
return false;
}
// ABM - BUSCAR Ordenes de Compra
// -----------------------------------------------------
private OrdenDeCompra buscarOrdenDeCompra (Proveedor prove, String date){
for (int i=0; i<ordenesCompra.size(); i++){
OrdenDeCompra ord = ordenesCompra.elementAt(i);
// Busca la orden de compra segun el Proveedor
if (ord.getProveedor().equals(prove)){
// Compara fechas
if(ord.getFecha().equals(date)){
return ord;
}
}
}
return null;
}
/* Genera un vector con productos bajo punto de pedido, correspondientes
a un mismo proveedor. El vector se utiliza en altaDeOrdenDeCompra. */
private Vector<Producto> productosBajoPuntoPedido(Proveedor bajoProve){
Vector<Producto> produc = new Vector <Producto>();
for (int i= 0; i<productos.size(); i++){
Producto prod = productos.elementAt(i);
if (prod.getProveedor().equals(bajoProve)){
if (prod.estaBajoPuntoPedido()){
produc.add(prod);
}
}
}
return produc; // Vector con los productos (de un proveedor) bajos en stock.
}
/* Genera las ordenes automaticamente para los productos bajos en stock.
Es UNA orden por proveedor, por dia. El proveedor fue validado previamente. */
private int altaDeOrdenDeCompra (Proveedor prov){
OrdenDeCompra ord = buscarOrdenDeCompra(prov, fecha);
if (ord == null){
// Vector generado por productosBajoPuntoPedido
Vector<Producto> itemsApedir = productosBajoPuntoPedido(prov);
// Revisa que el vector de productos a pedir no esté vacío.
if (!itemsApedir.isEmpty()){
ord = new OrdenDeCompra(prov, fecha);
// Carga los items de pedido
for (int i= 0; i<itemsApedir.size(); i++){
Producto prod = itemsApedir.elementAt(i);
ord.agregarItemDePedido(prod, prod.getPuntoreab());
}
// Agrega la orden de compra al vector de ordenes de compra
ordenesCompra.add(ord);
// Devuelve uno para contabilizar las ordenes de compra creadas.
return 1;
}
}
// Devuelve cero si no se creo la orden de compra.
return 0;
}
// Genera todas las ordenes de compra para los productos bajos en stock
public int generarOrdenesDeCompra(){
int ord = 0;
for (int i=0; i<proveedores.size(); i++){
Proveedor prov = proveedores.elementAt(i);
int ord1 = altaDeOrdenDeCompra (prov);
ord = ord + ord1;
}
return ord;
}
// ABM - BUSCAR Mozos
// -----------------------------------------------------
private Mozo buscarMozo (int id){
for (int i=0; i<mozos.size(); i++){
Mozo m = mozos.elementAt(i);
if (m.getId()==id){
return m;
}
}
return null;
}
public void altaDeMozo (String nombre, int comision, boolean habilitado){
Mozo mozo = new Mozo (nombre, comision, habilitado);
mozos.add(mozo);
}
public void bajaDeMozo (int idMozo){
Mozo garzon = buscarMozo(idMozo);
if (garzon != null){
mozos.remove(garzon);
}
}
public void modificarMozo(int id, String nombre, int comision, boolean habilitado){
Mozo m = buscarMozo(id);
if (m != null){
m.setNombre(nombre);
m.setComision(comision);
m.setHabilitado(habilitado);
}
}
//----------------------------------------------------------
// METODOS CON MESAS
//----------------------------------------------------------
public int getCantMesasHabilitadas (){
int mesasOk = 0;
for (int i=0; i<mesas.size(); i++){
if (mesas.elementAt(i).isHabilitada()){
mesasOk++;
}
}
return mesasOk;
}
// Asigna las mesas a cada mozo.
// Determina cuantas mesas quedan habilitadas y que mozo atiende cada mesa.
public void asignarMesas(){
int indice=0;
int i=0, j=0;
int mozosHab = getCantMozosHabilitados();
int mesasHab = getCantMesasHabilitadas();
if (!mozos.isEmpty() && !mesas.isEmpty()){
if (mozosHab >= mesasHab){
while (i<mesas.size() && j<mozos.size()){
Mesa mesa = mesas.elementAt(i);
Mozo mozo = mozos.elementAt (j);
if (mozo.isHabilitado() && mesa.isHabilitada()){
mesas.elementAt(i).setMozo(mozos.elementAt(j));
mesas.elementAt(i).setAsignada(true);
i++;
j++;
}else{
// La mesa esta habilitada pero el mozo no
if (mesa.isHabilitada())
j++;
else // La mozo esta habilitado pero la mesa no
i++;
}
}
}else{
int mesasXmozo = mesasHab / mozosHab;
for (i=0; i<mozos.size(); i++){
j=0;
Mozo mozo = mozos.elementAt (i);
if (mozo.isHabilitado()){
while (j<mesasXmozo){
if (mesas.elementAt(indice).isHabilitada()){
mesas.elementAt(indice).setMozo(mozos.elementAt(i));
mesas.elementAt(indice).setAsignada(true);
indice++;
j++;
}else
indice++;
}
}else{
continue;
}
}
}
setMesasAsignadas(true);
}
}
public void cerrarMesa (int nroMesa){
Mesa mesa = buscarMesa(nroMesa);
mesa.cerrarMesa();
}
public float getTotalComanda(int nroMesa){
float totalMesa = 0;
Mesa m = buscarMesa(nroMesa);
if ((m != null) && (m.isOcupada()))
totalMesa = m.getTotal();
return totalMesa;
}
//----------------------------------------------------------
// METODOS CON MOZOS
//----------------------------------------------------------
public int getCantMozosHabilitados (){
int mozosOk = 0;
for (int i=0; i<mozos.size(); i++){
if (mozos.elementAt(i).isHabilitado()){
mozosOk++;
}
}
return mozosOk;
}
public void habilitarMozo (int idMozo){
Mozo mozoHab = buscarMozo(idMozo);
if (mozoHab != null){
mozoHab.setHabilitado(true);
}
}
public void deshabilitarMozo (int idMozo){
Mozo mozoHab = buscarMozo(idMozo);
if (mozoHab != null){
mozoHab.setHabilitado(false);
}
}
private Vector<Comanda> buscarComandasMozo(Mozo mozo){
Vector<Comanda> comandasMozo = new Vector<Comanda>();
for (int i = 0; i<comandas.size(); i++){
if (comandas.elementAt(i).getMozo().equals(mozo)){
comandasMozo.add(comandas.elementAt(i));
}
}
return comandasMozo;
}
public void pagarMozos(){
float totalMozo;
int cantMozos = mozos.size();
//Vector <Mozo> moz = getMozos();
for (int j=0; j<cantMozos; j++){
totalMozo = 0;
//Mozo mozo = restaurante.buscarMozo(j);
Mozo mozo = mozos.elementAt(j);
if (mozo != null){
Vector<Comanda> comandasMozo = buscarComandasMozo(mozo);
if (comandasMozo != null){
for (int i=0; i<comandasMozo.size(); i++){
totalMozo = totalMozo + comandasMozo.elementAt(i).getTotal();
}
totalMozo = (totalMozo * mozo.getComision()) / 100;
mozo.setLiquidacion(totalMozo);
}
}
}
}
// ABM - BUSCAR Mesas
// -----------------------------------------------------
private Mesa buscarMesa(int id){
int i = 0;
while (i < mesas.size()){
Mesa m = mesas.elementAt(i);
if (m.getNroMesa() == id)
return m;
else
i++;
}
return null;
}
public void altaDeMesa (boolean habilitada){
Mesa mesaNew = new Mesa (habilitada);
mesas.add(mesaNew);
}
public void bajaDeMesa(int id){
Mesa table = buscarMesa(id);
if (table != null){
mesas.remove(table);
}
}
public void modificarMesa(int id, boolean estado){
Mesa table = buscarMesa(id);
if (table != null){
table.setHabilitada(estado);
}
}
public int cantidadMesas (){
return (mesas.size());
}
public void abrirMesa (Mesa m){
Comanda c = m.abrirMesa();
comandas.add(c);
}
public void agregarItemComanda(int nroMesa, String nombreItemCarta, int cant){
Mesa m = buscarMesa(nroMesa);
if (m != null){
if (! m.isOcupada())
abrirMesa(m);
ItemDeCarta itemCarta = cartaActiva.buscarItemDeCarta(nombreItemCarta);
if ((itemCarta != null) && itemCarta.esPreparable(cant)){
m.agregarItemComanda(cant, itemCarta);
}
}
}
// Metodos que operan con Vectores View
// -----------------------------------------------------
// CARTAS
public CartaView getCartaView(String dia){
Carta car = buscarCarta(dia);
if (car!=null)
return car.getCartaView();
return null;
}
public Vector<CartaView> getCartasView(){
Vector<CartaView> cv = new Vector<CartaView>();
for (int i=0; i<cartas.size(); i++){
cv.add(cartas.elementAt(i).getCartaView());
}
return cv;
}
// ITEMS DE CARTA ACTIVA
public Vector<ItemDeCartaView> getItemsDeCartaActivaView(){
Vector<ItemDeCartaView> icv = new Vector<ItemDeCartaView>();
for (int i=0; i<cartaActiva.getItemsCarta().size(); i++){
icv.add(cartaActiva.getItemsCarta().elementAt(i).getItemDeCartaView());
}
return icv;
}
// PLATOS / BEBIDAS
public Vector<ItemDeCartaView> getItemsDeCartaView(){
Vector<ItemDeCartaView> icv = new Vector<ItemDeCartaView>();
for (int i=0; i<itemsCarta.size(); i++){
icv.add(itemsCarta.elementAt(i).getItemDeCartaView());
}
return icv;
}
// PRODUCTOS
public Vector<ProductoView> getProductosView(){
Vector<ProductoView> mv = new Vector<ProductoView>();
for (int i= 0; i < productos.size(); i++){
mv.add(productos.elementAt(i).getProductoView());
}
return mv;
}
// PROVEEDORES
public Vector<ProveedorView> getProveedoresView(){
Vector<ProveedorView> mv = new Vector<ProveedorView>();
for (int i= 0; i < proveedores.size(); i++){
mv.add(proveedores.elementAt(i).getProveedorView());
}
return mv;
}
// MOZOS
public Vector<MozoView> getMozosView(){
Vector<MozoView> mv = new Vector<MozoView>();
for (int i= 0; i < mozos.size(); i++)
{
mv.add(mozos.elementAt(i).getMozoView());
}
return mv;
}
// MESAS
public Vector<MesaView> getMesasView(){
Vector<MesaView> mv = new Vector<MesaView>();
for (int i= 0; i < mesas.size(); i++){
mv.add(mesas.elementAt(i).getMesaView());
}
return mv;
}
}
|
package com.arthur.leetcode;
import java.util.List;
/**
* @title: No206
* @Author ArthurJi
* @Date: 2021/3/13 9:44
* @Version 1.0
*/
public class No206 {
public class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public static void main(String[] args) {
}
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode temp = null;
ListNode cur = head;
while (cur != null) {
temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
public ListNode reverseList_2(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode cur = reverseList_2(head.next);
head.next.next = head;
head.next = null;
return cur;
}
}
/*206. 反转链表
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL*/
/*
利用外部空间
这种方式很简单,先申请一个动态扩容的数组或者容器,比如 ArrayList 这样的。
然后不断遍历链表,将链表中的元素添加到这个容器中。
再利用容器自身的 API,反转整个容器,这样就达到反转的效果了。
最后同时遍历容器和链表,将链表中的值改为容器中的值。
因为此时容器的值是:
5 4 3 2 1
链表按这个顺序重新被设置一边,就达到要求啦。
当然你可以可以再新创建 N 个节点,然后再返回,这样也可以达到目的。
这种方式很简单,但你在面试中这么做的话,面试官 100% 会追问是否有更优的方式,比如不用外部空间。所以我就不做代码和动画演示了,下面来看看如何用 O(1)O(1) 空间复杂度来实现这道题。
双指针迭代
我们可以申请两个指针,第一个指针叫 pre,最初是指向 null 的。
第二个指针 cur 指向 head,然后不断遍历 cur。
每次迭代到 cur,都将 cur 的 next 指向 pre,然后 pre 和 cur 前进一位。
都迭代完了(cur 变成 null 了),pre 就是最后一个节点了。
动画演示如下:
动画演示中其实省略了一个tmp变量,这个tmp变量会将cur的下一个节点保存起来,考虑到一张动画放太多变量会很混乱,所以我就没加了,具体详细执行过程,请点击下面的幻灯片查看。
1 / 19
代码实现:
JavaPython
class Solution {
public ListNode reverseList(ListNode head) {
//申请节点,pre和 cur,pre指向null
ListNode pre = null;
ListNode cur = head;
ListNode tmp = null;
while(cur!=null) {
//记录当前节点的下一个节点
tmp = cur.next;
//然后将当前节点指向pre
cur.next = pre;
//pre和cur节点都前进一位
pre = cur;
cur = tmp;
}
return pre;
}
}
递归解法
这题有个很骚气的递归解法,递归解法很不好理解,这里最好配合代码和动画一起理解。
递归的两个条件:
终止条件是当前节点或者下一个节点==null
在函数内部,改变节点的指向,也就是 head 的下一个节点指向 head 递归函数那句
head.next.next = head
很不好理解,其实就是 head 的下一个节点指向head。
递归函数中每次返回的 cur 其实只最后一个节点,在递归函数内部,改变的是当前节点的指向。
动画演示如下:
幻灯片演示
感谢@zhuuuu-2的建议,递归的解法光看动画比较容易理解,但真到了代码层面理解起来可能会有些困难,我补充了下递归调用的详细执行过程。
以1->2->3->4->5这个链表为例,整个递归调用的执行过程,对应到代码层面(用java做示范)是怎么执行的,以及递归的调用栈都列出来了,请点击下面的幻灯片查看吧。
1 / 24
代码实现:
JavaPython
class Solution {
public ListNode reverseList(ListNode head) {
//递归终止条件是当前为空,或者下一个节点为空
if(head==null || head.next==null) {
return head;
}
//这里的cur就是最后一个节点
ListNode cur = reverseList(head.next);
//这里请配合动画演示理解
//如果链表是 1->2->3->4->5,那么此时的cur就是5
//而head是4,head的下一个是5,下下一个是空
//所以head.next.next 就是5->4
head.next.next = head;
//防止链表循环,需要将head.next设置为空
head.next = null;
//每层递归函数都返回cur,也就是最后一个节点
return cur;
}
}
作者:wang_ni_ma
链接:https://leetcode-cn.com/problems/reverse-linked-list/solution/dong-hua-yan-shi-206-fan-zhuan-lian-biao-by-user74/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。*/
|
/**
* Created by Ari on 8/15/2016.
*/
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.exec.*;
import org.junit.Test;
import sun.plugin2.main.server.ResultHandler;
public class phantomPDF {
private final File testDir = new File("src/test/scripts");
private final File acroRd32Script = TestUtil.resolveScriptForOS(testDir + "/acrord32");
public void testTutorialExample() throws Exception {
final long printJobTimeout = 15000;
final boolean printInBackground = false;
final File pdfFile = new File("D:/lapor.pdf");
ResultHandler resultHandler;
try {
System.out.print("[main] Preparing print job ...");
resultHandler = print(pdfFile, printJobTimeout, printInBackground);
System.out.println("[main] Successfully sent the print job ...");
}catch (final Exception e){
e.printStackTrace();
fail("[main] Printing of the following document failed : "+pdfFile.getAbsolutePath());
throw e;
}
System.out.println("[main] Test is existing but waiting for the print job to finish...");
resultHandler.waitFor();
System.out.println("[main] The print job has finished...");
}
public ResultHandler print(final File file, final long printJobTimeout, final boolean printInBackground)
throws IOException{
int exitValue;
ExecuteWatchdog watchdog = null;
ResultHandler resultHandler;
final Map<String, File> map = new HashMap<String, File>();
map.put("file",file);
final CommandLine commandLine = new CommandLine(acroRd32Script);
commandLine.addArgument("/p");
commandLine.addArgument("/h");
commandLine.addArgument("${file}");
commandLine.setSubstitutionMap(map);
final Executor executor = new DefaultExecutor();
executor.setExitValue(1);
if(printJobTimeout > 0){
watchdog = new ExecuteWatchdog(printJobTimeout);
executor.setWatchdog(watchdog);
}
if(printInBackground){
System.out.println("[print] Executing non-blocking print jobb ...");
resultHandler = new ResultHandler(watchdog);
}else{
System.out.println("[print] Executing blocking print job ...");
exitValue = executor.execute(commandLine);
resultHandler = new ResultHandler(exitValue);
}
return resultHandler;
}
private class ResultHandler extends DefaultExecuteResultHandler{
private ExecuteWatchdog watchdog;
public ResultHandler(final ExecuteWatchdog watchdog){
this.watchdog = watchdog;
}
public ResultHandler(final int exitValue){
super.onProcessComplete(exitValue);
}
@Override
public void onProcessComplete(int exitValue) {
super.onProcessComplete(exitValue);
System.out.println("[resultHandler] The document was successfully printed ...");
}
@Override
public void onProcessFailed(ExecuteException e) {
super.onProcessFailed(e);
if(watchdog != null && watchdog.killedProcess()){
System.err.println("[resultHandler] The print process timed out");
}else{
System.err.println("[resultHandler] The print process failed to do "+e.getMessage());
}
}
}
}
|
package classes;
import interfaces.Part;
import interfaces.PartVisitor;
/**
* @author dylan
*
*/
public class Watch implements Part {
Part[] watchparts;
/**
*
*/
public Watch() {
super();
watchparts = new Part[] { new Spring(), new Sprocket(), new Actuator() };
}
/*
* (non-Javadoc)
*
* @see interfaces.Part#assemble()
*/
@Override
public void assemble() {
System.out.println("assembling a watch");
}
/*
* (non-Javadoc)
*
* @see interfaces.Part#acceptVisitor(interfaces.PartVisitor)
*/
@Override
public void acceptVisitor(PartVisitor visitor) {
for (int i = 0; i < watchparts.length; i++) {
watchparts[i].acceptVisitor(visitor);
}
visitor.visit(this);
}
}
|
package hey.rich.snapsaver;
import wei.mark.standout.StandOutWindow;
import wei.mark.standout.constants.StandOutFlags;
import wei.mark.standout.ui.Window;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.Toast;
public class FloatingWindow extends StandOutWindow {
// The buttons
private static Button buttonPictures = null;
private static Button buttonVideos = null;
private static Button buttonBoth = null;
// My file manager
private static FileManager mFileManager;
@Override
public String getAppName() {
return "FloatingSnapSaverWindow";
}
@Override
public int getAppIcon() {
return android.R.drawable.ic_menu_close_clear_cancel;
}
@Override
public void createAndAttachView(int id, FrameLayout frame) {
// Create a new layout from body.xml
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.floating_window_layout, frame,
true);
// Set up a button or two
buttonPictures = (Button) view
.findViewById(R.id.button_floating_pictures);
buttonVideos = (Button) view.findViewById(R.id.button_floating_videos);
buttonBoth = (Button) view.findViewById(R.id.button_floating_both);
// make my file manager
mFileManager = new FileManager();
setTheOnClickListeners();
}
/** Sets the onClickListeners for the buttons */
private void setTheOnClickListeners() {
if (buttonPictures != null && buttonVideos != null
&& buttonBoth != null) {
buttonPictures.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Copy them pictures
mFileManager.copySnapChatPictures(getApplicationContext());
// Let the world know we are finished
Toast.makeText(getBaseContext(),
getString(R.string.toast_completed_pictures),
Toast.LENGTH_SHORT).show();
}
});
buttonVideos.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Copy them videos
mFileManager.copySnapChatVideos(getApplicationContext());
// Rename them videos
//mFileManager.renameSnapChatVideos();
Toast.makeText(getBaseContext(),
getString(R.string.toast_completed_videos),
Toast.LENGTH_SHORT).show();
}
});
buttonBoth.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Copy both of them!
mFileManager.copySnapChatPictures(getApplicationContext());
mFileManager.copySnapChatVideos(getApplicationContext());
// Rename all of those things
Toast.makeText(getBaseContext(),
getString(R.string.toast_completed_both),
Toast.LENGTH_SHORT).show();
}
});
} else {
// Something is really wrong
}
}
// the window will be centered
@Override
public StandOutLayoutParams getParams(int id, Window window) {
return new StandOutLayoutParams(id, 250, 300,
StandOutLayoutParams.CENTER, StandOutLayoutParams.CENTER);
}
// move the window by dragging the view
@Override
public int getFlags(int id) {
return super.getFlags(id) | StandOutFlags.FLAG_BODY_MOVE_ENABLE
| StandOutFlags.FLAG_WINDOW_FOCUSABLE_DISABLE;
}
@Override
public String getPersistentNotificationMessage(int id) {
return getString(R.string.floating_notification_cancel_text);
}
@Override
public Intent getPersistentNotificationIntent(int id) {
return StandOutWindow.getCloseIntent(this, FloatingWindow.class, id);
}
}
|
package com.zju.courier.service.impl;
import com.zju.courier.dao.StaffDao;
import com.zju.courier.entity.Staff;
import com.zju.courier.pojo.StaffPosition;
import com.zju.courier.service.StaffService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class StaffServiceImpl implements StaffService {
@Autowired
private StaffDao staffDao;
@Override
public List<Staff> list() {
return staffDao.list();
}
@Override
public Staff query(int id) {
return staffDao.query(id);
}
@Override
public void update(Staff staff) {
staffDao.update(staff);
}
@Override
public void insert(Staff staff) {
staffDao.insert(staff);
}
@Override
public void delete(int id) {
staffDao.delete(id);
}
@Override
public List<StaffPosition> load() {
return staffDao.load();
}
}
|
// QUESTION
// Given two arrays, write a function to compute their intersection.
import java.util.Arrays;
class IntersectionOfArraysII {
public static void main(String[] args) {
System.out.println(Arrays.toString(intersect(new int[]{61,24,20,58,95,53,17,32,45,85,70,20,83,62,35,89,5,95,12,86,58,77,30,64,46,13,5,92,67,40,20,38,31,18,89,85,7,30,67,34,62,35,47,98,3,41,53,26,66,40,54,44,57,46,70,60,4,63,82,42,65,59,17,98,29,72,1,96,82,66,98,6,92,31,43,81,88,60,10,55,66,82,0,79,11,81}, new int[]{5,25,4,39,57,49,93,79,7,8,49,89,2,7,73,88,45,15,34,92,84,38,85,34,16,6,99,0,2,36,68,52,73,50,77,44,61,48})));
System.out.println(Arrays.toString(new int[]{5,4,57,79,7,89,88,45,34,92,38,85,6,0,77,44,61}));
}
public static int[] intersect(int[] nums1, int[] nums2) {
int[] big = new int[1];
int[] small = new int[1];
if (nums1.length > nums2.length) {
big = nums1;
small = nums2;
} else {
big = nums2;
small = nums1;
}
int[] intersection = new int[small.length];
int pos = 0;
for (int i = 0; i < big.length; i++) {
for (int j = 0; j < small.length; j++) {
if (big[i] == small[j]) {
intersection[pos] = small[j];
pos++;
small = removeItem(small, j);
break;
}
}
}
int[] result = new int[pos];
for (int i = 0; i < result.length; i++)
result[i] = intersection[i];
return result;
}
public static int[] removeItem(int[] array, int pos) {
int[] newArray = new int[array.length - 1];
int count = 0;
for (int i = 0; i < array.length; i++) {
if (i != pos) {
newArray[count] = array[i];
count++;
}
}
return newArray;
}
}
|
package easii.com.br.iscoolapp.fragmentos;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.List;
import easii.com.br.iscoolapp.R;
import easii.com.br.iscoolapp.adapters.DisciplinaAdapter;
import easii.com.br.iscoolapp.interfaces.RecyclerViewOnClickListener;
import easii.com.br.iscoolapp.main.TelaDeAlunosDoProfessor;
import easii.com.br.iscoolapp.objetos.Disciplina;
import easii.com.br.iscoolapp.objetos.DisciplinaProfessor;
import easii.com.br.iscoolapp.objetos.Professor;
import easii.com.br.iscoolapp.objetos.Professor2;
import easii.com.br.iscoolapp.util.DividerItemDecoration;
/**
* Created by gustavo on 16/08/2016.
*/
public class TwoFragment extends Fragment implements RecyclerViewOnClickListener {
private List<Disciplina> list = new ArrayList<>();
private RecyclerView recyclerView;
private DisciplinaAdapter mAdapter;
private View view;
public TwoFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_two, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
mAdapter = new DisciplinaAdapter(list);
mAdapter.setRecyclerViewOnClickListener(this);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(view.getContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new DividerItemDecoration(view.getContext(), LinearLayoutManager.VERTICAL));
recyclerView.setAdapter(mAdapter);
completaLista();
return view;
}
private void completaLista() {
SharedPreferences sharedPref = view.getContext().getSharedPreferences("CONSTANTES", Context.MODE_PRIVATE);
String profJson = sharedPref.getString("PROFESSOR", "NULL");
Gson gson = new Gson();
Professor2 professor = gson.fromJson(profJson, Professor2.class);
Disciplina d;
for (DisciplinaProfessor dp : professor.getDisciplinas()) {
d = new Disciplina(dp.getEscola().toString(), dp.getNome().toString());
list.add(d);
Log.i("LOG>", dp.getNome());
}
mAdapter.notifyDataSetChanged();
}
@Override
public void onClickListener(View view, int position) {
SharedPreferences sharedPref = view.getContext().getSharedPreferences("CONSTANTES", Context.MODE_PRIVATE);
String profJson = sharedPref.getString("PROFESSOR", "NULL");
Gson gson = new Gson();
Professor2 professor = gson.fromJson(profJson, Professor2.class);
List<DisciplinaProfessor> lista = professor.getDisciplinas();
Intent intent = new Intent(view.getContext(), TelaDeAlunosDoProfessor.class);
Bundle extras = new Bundle();
extras.putLong("EXTRA_ID_DISCIPLINA", lista.get(position).getId());
intent.putExtras(extras);
startActivity(intent);
}
}
|
/**
*/
package com.fun.gantt.gantt.tests;
import com.fun.gantt.gantt.GanttFactory;
import com.fun.gantt.gantt.Summary;
import junit.framework.TestCase;
import junit.textui.TestRunner;
/**
* <!-- begin-user-doc -->
* A test case for the model object '<em><b>Summary</b></em>'.
* <!-- end-user-doc -->
* @generated
*/
public class SummaryTest extends TestCase {
/**
* The fixture for this Summary test case.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected Summary fixture = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static void main(String[] args) {
TestRunner.run(SummaryTest.class);
}
/**
* Constructs a new Summary test case with the given name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SummaryTest(String name) {
super(name);
}
/**
* Sets the fixture for this Summary test case.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void setFixture(Summary fixture) {
this.fixture = fixture;
}
/**
* Returns the fixture for this Summary test case.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected Summary getFixture() {
return fixture;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see junit.framework.TestCase#setUp()
* @generated
*/
@Override
protected void setUp() throws Exception {
setFixture(GanttFactory.eINSTANCE.createSummary());
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see junit.framework.TestCase#tearDown()
* @generated
*/
@Override
protected void tearDown() throws Exception {
setFixture(null);
}
} //SummaryTest
|
class Z_ITEM extends ITEM
{
Z_ITEM()
{
}
} |
package sign.com.biz.group.service;
import com.github.pagehelper.PageInfo;
import sign.com.biz.base.service.BaseService;
import sign.com.biz.group.dto.UserGroupDto;
import sign.com.biz.user.dto.SignUserDto;
import sign.com.common.PageDto;
import java.util.List;
/**
* create by luolong on 2018/5/16
*/
public interface UserGroupService extends BaseService<UserGroupDto>{
/**
* 保存用户组
* @param userGroupDto
* @return
*/
boolean saveMember(UserGroupDto userGroupDto);
/**
* 修改用户组
* @param userGroupDto
* @return
*/
boolean updateMember(UserGroupDto userGroupDto);
/**
* 删除用户组
* @param userGroupDto
* @return
*/
boolean deleteMember(UserGroupDto userGroupDto);
/**
* 通过用户名或者邮箱查询用户列表
* @param name
* @return
*/
List<SignUserDto> selectUserByName(String name);
/**
* 返回分组列表分页
* @param userId
* @return
*/
PageDto selectGroupList(Integer userId, Integer pageSize, Integer pageIndex);
List<UserGroupDto> selectGroupName(Integer userId);
}
|
package pageobjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import tests.Config;
public class Login extends BasePage {
private By usernameLocator = By.id("username");
private By passwordLocator = By.id("password");
private By submitBtnLocator = By.cssSelector("button[type=submit]");
private By successMessageLocator = By.cssSelector(".flash.success");
private By formLocator = By.id("login");
private By failedMessageLocator = By.cssSelector(".flash.error");
public Login(WebDriver driver) throws Exception {
super(driver);
get(Config.baseUrl + "login");
if (!isDisplayed(formLocator, 10)) {
throw new Exception("Page is not ready");
}
}
public void with(String username, String password) {
type(usernameLocator, username); // TODO: can't not find element
type(passwordLocator, password);
click(submitBtnLocator); //
}
public boolean successMessagePresent() {
return isDisplayed(successMessageLocator, 10);
}
public boolean failureMessagePresent() {
return isDisplayed(failedMessageLocator, 10);
}
}
|
package b4dpxl.timestamp;
import b4dpxl.Utilities;
import burp.IBurpExtenderCallbacks;
import burp.IContextMenuFactory;
import burp.IContextMenuInvocation;
import com.github.lgooddatepicker.components.DatePickerSettings;
import com.github.lgooddatepicker.components.DateTimePicker;
import com.github.lgooddatepicker.components.TimePickerSettings;
import com.github.lgooddatepicker.optionalusertools.PickerUtilities;
import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.DayOfWeek;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
public class TimestampEditor implements IContextMenuFactory, ActionListener {
private IContextMenuInvocation invocation;
public TimestampEditor(IBurpExtenderCallbacks callbacks) {
new Utilities(callbacks, false);
Utilities.callbacks.setExtensionName("Timestamp editor");
Utilities.callbacks.registerContextMenuFactory(this);
}
@Override
public List<JMenuItem> createMenuItems(IContextMenuInvocation invocation) {
ArrayList<JMenuItem> menu = new ArrayList<>();
if (invocation.getInvocationContext() == IContextMenuInvocation.CONTEXT_MESSAGE_EDITOR_REQUEST) {
JMenuItem item = new JMenuItem("Edit timestamp");
item.addActionListener(this);
TimestampDate date = extractTimestamp(invocation);
if (date != null) {
this.invocation = invocation;
item.setToolTipText(date.toString());
item.setEnabled(true);
} else {
item.setEnabled(false);
}
menu.add(item);
} else {
TimestampDate date = extractTimestamp(invocation);
if (date != null) {
JMenuItem item = new JMenuItem("View Timestamp");
item.setToolTipText(date.toString());
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
JTextArea jta = new JTextArea(date.toString());
jta.setColumns(30);
jta.setEditable(false);
int result = JOptionPane.showOptionDialog(
null,
jta,
"Timestamp",
JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE,
null,
new Object[] {"Copy", "Close"},
null
);
if (result == JOptionPane.YES_OPTION) {
//copy to clipboard
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(date.toString()), null);
}
}
});
menu.add(item);
}
}
return menu;
}
private TimestampDate extractTimestamp(IContextMenuInvocation invocation) {
int[] bounds = invocation.getSelectionBounds();
if (invocation.getSelectedMessages() != null) {
byte[] messageBytes;
switch(invocation.getInvocationContext()) {
case IContextMenuInvocation.CONTEXT_MESSAGE_EDITOR_REQUEST:
case IContextMenuInvocation.CONTEXT_MESSAGE_VIEWER_REQUEST:
messageBytes = invocation.getSelectedMessages()[0].getRequest();
break;
case IContextMenuInvocation.CONTEXT_MESSAGE_EDITOR_RESPONSE:
case IContextMenuInvocation.CONTEXT_MESSAGE_VIEWER_RESPONSE:
messageBytes = invocation.getSelectedMessages()[0].getResponse();
break;
default:
Utilities.debug("Cannot extract selection");
return null;
}
String message = Utilities.helpers.bytesToString(messageBytes);
try {
long timestamp = Long.parseLong(message.substring(bounds[0], bounds[1]));
if (timestamp > 9999999999999L) {
// microseconds
return new MicrosecondsTimestampDate(timestamp);
} else if (timestamp <= 9999999999L) {
// seconds
return new SecondsTimestampDate(timestamp);
}
return new TimestampDate(timestamp);
} catch (NumberFormatException e) {
Utilities.debug("Not a timestamp");
}
}
return null;
}
@Override
public void actionPerformed(ActionEvent evt) {
if (invocation == null) {
return;
}
TimestampDate date = extractTimestamp(invocation);
Utilities.debug("Date: " + date.toString());
DatePickerSettings dateSettings = new DatePickerSettings();
dateSettings.setFirstDayOfWeek(DayOfWeek.MONDAY);
dateSettings.setVisibleClearButton(false);
dateSettings.setColor(DatePickerSettings.DateArea.TextMonthAndYearMenuLabels, Color.BLACK);
dateSettings.setColor(DatePickerSettings.DateArea.TextTodayLabel, Color.BLACK);
TimePickerSettings timeSettings = new TimePickerSettings();
timeSettings.setFormatForDisplayTime(
PickerUtilities.createFormatterFromPatternString("HH:mm:ss", timeSettings.getLocale())
);
DateTimePicker picker = new DateTimePicker(dateSettings, timeSettings);
picker.setDateTimeStrict(date.getLocalDateTime());
Box box = Box.createHorizontalBox();
box.setAlignmentX(Box.LEFT_ALIGNMENT);
box.add(picker);
JButton button = new JButton("Copy");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
// Thu Feb 25 13:13:59 GMT 2021
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(
new StringSelection(picker.getDateTimeStrict().atZone(ZoneId.of("UTC")).format(DateTimeFormatter.RFC_1123_DATE_TIME)),
null
);
}
});
box.add(button);
int results = JOptionPane.showConfirmDialog(
null,
new JScrollPane(box),
"Choose Date/Time",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE
);
if (results == JOptionPane.OK_OPTION) {
date.setTime(picker.getDateTimeStrict());
Utilities.debug(date.getTimestamp());
int[] bounds = invocation.getSelectionBounds();
byte[] request = invocation.getSelectedMessages()[0].getRequest();
String message = Utilities.helpers.bytesToString(request);
StringBuilder builder = new StringBuilder(message.substring(0, bounds[0]))
.append(date.getTimestamp())
.append(message.substring(bounds[1]));
invocation.getSelectedMessages()[0].setRequest(Utilities.helpers.stringToBytes(builder.toString()));
}
invocation = null;
}
class SecondsTimestampDate extends TimestampDate {
public SecondsTimestampDate(long date) {
super(date * 1000L);
}
public long getTimestamp() {
return super.getTime() / 1000L;
}
}
class MicrosecondsTimestampDate extends TimestampDate {
public MicrosecondsTimestampDate(long date) {
super(date / 1000L);
}
public long getTimestamp() {
return super.getTime() * 1000L;
}
}
class TimestampDate {
private LocalDateTime ldt;
public TimestampDate(long date) {
ldt = LocalDateTime.ofInstant(Instant.ofEpochMilli(date), ZoneId.of("UTC"));
}
public long getTimestamp() {
return getTime();
}
public long getTime() {
return ldt.atZone(ZoneId.of("UTC")).toInstant().toEpochMilli();
}
public LocalDateTime getLocalDateTime() {
return ldt;
}
public void setTime(LocalDateTime ldt) {
this.ldt = ldt;
}
public String toString() {
if (ldt == null) {
return "";
}
// Thu, 27 May 2021, 09:58:51 UTC
// return DateTimeFormatter.RFC_1123_DATE_TIME.format(ldt.atZone(ZoneId.of("UTC")));
return DateTimeFormatter.ofPattern("EE, dd LLL yyyy HH:mm:ss z").format(ldt.atZone(ZoneId.of("UTC")));
}
}
} |
package javazaawansowana.pokaz.kolekcje.listy;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> integerList = new ArrayList<>();
List<Integer> integerList1 = new LinkedList<>();
integerList.add(1);
integerList1.add(1);
integerList.remove(1);
integerList1.remove(1);
System.out.println(integerList.indexOf(1));
System.out.println(integerList.lastIndexOf(1));
}
}
|
/*
* Copyright (c) 2015 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.engine;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import pl.edu.icm.unity.engine.authz.AuthorizationManagerImpl;
import pl.edu.icm.unity.exceptions.IllegalIdentityValueException;
import pl.edu.icm.unity.exceptions.MergeConflictException;
import pl.edu.icm.unity.stdext.attr.StringAttribute;
import pl.edu.icm.unity.stdext.attr.StringAttributeSyntax;
import pl.edu.icm.unity.stdext.identity.IdentifierIdentity;
import pl.edu.icm.unity.stdext.identity.PersistentIdentity;
import pl.edu.icm.unity.stdext.identity.TargetedPersistentIdentity;
import pl.edu.icm.unity.types.authn.CredentialPublicInformation;
import pl.edu.icm.unity.types.authn.CredentialRequirements;
import pl.edu.icm.unity.types.authn.LocalCredentialState;
import pl.edu.icm.unity.types.basic.AttributeExt;
import pl.edu.icm.unity.types.basic.AttributeType;
import pl.edu.icm.unity.types.basic.AttributeVisibility;
import pl.edu.icm.unity.types.basic.AttributesClass;
import pl.edu.icm.unity.types.basic.Entity;
import pl.edu.icm.unity.types.basic.EntityParam;
import pl.edu.icm.unity.types.basic.Group;
import pl.edu.icm.unity.types.basic.Identity;
import pl.edu.icm.unity.types.basic.IdentityParam;
import com.google.common.collect.Sets;
public class TestMerge extends DBIntegrationTestBase
{
@Before
public void setup() throws Exception
{
setupPasswordAuthn(1, false);
}
@Test
public void sourceEntityRemoved() throws Exception
{
Identity target = createUsernameUser("target", AuthorizationManagerImpl.USER_ROLE, "p1");
Identity merged = createUsernameUser("merged", AuthorizationManagerImpl.USER_ROLE, "p2");
idsMan.mergeEntities(new EntityParam(target), new EntityParam(merged), false);
try
{
idsMan.getEntity(new EntityParam(merged.getEntityId()));
fail("Merged entity still valid");
} catch (IllegalIdentityValueException e)
{
//OK
}
}
@Test
public void regularIdentitiesAdded() throws Exception
{
Identity target = createUsernameUser("target", AuthorizationManagerImpl.USER_ROLE, "p1");
Identity merged = createUsernameUser("merged", AuthorizationManagerImpl.USER_ROLE, "p2");
Entity mergedFull = idsMan.getEntity(new EntityParam(merged), "tt", true, "/");
Entity targetFull = idsMan.getEntity(new EntityParam(merged), null, true, "/");
idsMan.addIdentity(new IdentityParam(IdentifierIdentity.ID, "id"), new EntityParam(merged), false);
idsMan.mergeEntities(new EntityParam(target), new EntityParam(merged), false);
Entity result = idsMan.getEntityNoContext(new EntityParam(target.getEntityId()), "/");
//regular - simply added
Collection<Identity> idT = getIdentitiesByType(result.getIdentities(), IdentifierIdentity.ID);
assertEquals(1, idT.size());
assertEquals("id", idT.iterator().next().getValue());
//dynamic but added as target has no one of this type
Collection<Identity> srcT = getIdentitiesByType(mergedFull.getIdentities(),
TargetedPersistentIdentity.ID);
assertEquals(1, srcT.size());
idT = getIdentitiesByType(result.getIdentities(), TargetedPersistentIdentity.ID);
assertEquals(1, idT.size());
assertEquals(srcT.iterator().next().getValue(), idT.iterator().next().getValue());
//dynamic not added as target has one
idT = getIdentitiesByType(result.getIdentities(), PersistentIdentity.ID);
assertEquals(1, idT.size());
srcT = getIdentitiesByType(targetFull.getIdentities(), PersistentIdentity.ID);
assertEquals(1, srcT.size());
assertEquals(srcT.iterator().next().getValue(), idT.iterator().next().getValue());
}
@Test
public void groupMembershipsAdded() throws Exception
{
Identity target = createUsernameUser("target", AuthorizationManagerImpl.USER_ROLE, "p1");
Identity merged = createUsernameUser("merged", AuthorizationManagerImpl.USER_ROLE, "p2");
groupsMan.addGroup(new Group("/A"));
groupsMan.addGroup(new Group("/B"));
groupsMan.addGroup(new Group("/B/C"));
groupsMan.addMemberFromParent("/A", new EntityParam(target));
groupsMan.addMemberFromParent("/A", new EntityParam(merged));
groupsMan.addMemberFromParent("/B", new EntityParam(merged));
groupsMan.addMemberFromParent("/B/C", new EntityParam(merged));
idsMan.mergeEntities(new EntityParam(target), new EntityParam(merged), false);
Collection<String> groups = idsMan.getGroups(new EntityParam(target)).keySet();
assertTrue(groups.contains("/A"));
assertTrue(groups.contains("/B"));
assertTrue(groups.contains("/B/C"));
}
@Test
public void onlyNewAttributesAdded() throws Exception
{
Identity target = createUsernameUser("target", AuthorizationManagerImpl.USER_ROLE, "p1");
Identity merged = createUsernameUser("merged", AuthorizationManagerImpl.USER_ROLE, "p2");
groupsMan.addGroup(new Group("/A"));
groupsMan.addMemberFromParent("/A", new EntityParam(merged));
attrsMan.addAttributeType(new AttributeType("a", new StringAttributeSyntax()));
attrsMan.addAttributeType(new AttributeType("b", new StringAttributeSyntax()));
attrsMan.setAttribute(new EntityParam(target), new StringAttribute("a", "/", AttributeVisibility.full,
"v1"), false);
attrsMan.setAttribute(new EntityParam(merged), new StringAttribute("a", "/", AttributeVisibility.full,
"v2"), false);
attrsMan.setAttribute(new EntityParam(merged), new StringAttribute("b", "/", AttributeVisibility.full,
"v1"), false);
attrsMan.setAttribute(new EntityParam(merged), new StringAttribute("a", "/A", AttributeVisibility.full,
"v1"), false);
idsMan.mergeEntities(new EntityParam(target), new EntityParam(merged), false);
Collection<AttributeExt<?>> a = attrsMan.getAllAttributes(
new EntityParam(target), false, "/", "a", false);
assertEquals(1, a.size());
assertEquals(1, a.iterator().next().getValues().size());
assertEquals("v1", a.iterator().next().getValues().get(0));
a = attrsMan.getAllAttributes(new EntityParam(target), false, "/", "b", false);
assertEquals(1, a.size());
assertEquals(1, a.iterator().next().getValues().size());
assertEquals("v1", a.iterator().next().getValues().get(0));
a = attrsMan.getAllAttributes(new EntityParam(target), false, "/A", "a", false);
assertEquals(1, a.size());
assertEquals(1, a.iterator().next().getValues().size());
assertEquals("v1", a.iterator().next().getValues().get(0));
}
@Test
public void attributeClassesUnchanged() throws Exception
{
Identity target = createUsernameUser("target", AuthorizationManagerImpl.USER_ROLE, "p1");
Identity merged = createUsernameUser("merged", AuthorizationManagerImpl.USER_ROLE, "p2");
attrsMan.addAttributeClass(new AttributesClass("acT", "", new HashSet<String>(),
new HashSet<String>(), true, new HashSet<String>()));
attrsMan.addAttributeClass(new AttributesClass("acM", "", new HashSet<String>(),
new HashSet<String>(), true, new HashSet<String>()));
attrsMan.setEntityAttributeClasses(new EntityParam(target), "/", Sets.newHashSet("acT"));
attrsMan.setEntityAttributeClasses(new EntityParam(merged), "/", Sets.newHashSet("acM"));
idsMan.mergeEntities(new EntityParam(target), new EntityParam(merged), false);
Collection<AttributesClass> ac = attrsMan.getEntityAttributeClasses(new EntityParam(target), "/");
assertEquals(1, ac.size());
assertEquals("acT", ac.iterator().next().getName());
}
@Test
public void credentialRequirementUnchanged() throws Exception
{
Identity target = createUsernameUser("target", AuthorizationManagerImpl.USER_ROLE, "p1");
Identity merged = createUsernameUser("merged", AuthorizationManagerImpl.USER_ROLE, "p2");
authnMan.addCredentialRequirement(new CredentialRequirements("crT", "", new HashSet<String>()));
authnMan.addCredentialRequirement(new CredentialRequirements("crM", "", new HashSet<String>()));
idsMan.setEntityCredentialRequirements(new EntityParam(target), "crT");
idsMan.setEntityCredentialRequirements(new EntityParam(merged), "crM");
idsMan.mergeEntities(new EntityParam(target), new EntityParam(merged), false);
Entity entity = idsMan.getEntity(new EntityParam(target));
assertEquals("crT", entity.getCredentialInfo().getCredentialRequirementId());
}
@Test
public void newCredentialAdded() throws Exception
{
Identity target = createUsernameUser("target", AuthorizationManagerImpl.USER_ROLE, "p1");
Identity merged = createUsernameUser("merged", AuthorizationManagerImpl.USER_ROLE, "p2");
setupPasswordAndCertAuthn();
authnMan.addCredentialRequirement(new CredentialRequirements("pandc", "", Sets.newHashSet(
"credential2", "credential1")));
idsMan.setEntityCredentialRequirements(new EntityParam(target), "pandc");
idsMan.setEntityCredentialRequirements(new EntityParam(merged), "pandc");
idsMan.setEntityCredentialStatus(new EntityParam(target), "credential1", LocalCredentialState.notSet);
idsMan.setEntityCredential(new EntityParam(merged), "credential2", "");
Entity result = idsMan.getEntity(new EntityParam(target.getEntityId()));
Map<String, CredentialPublicInformation> credentialsState =
result.getCredentialInfo().getCredentialsState();
assertEquals(LocalCredentialState.notSet, credentialsState.get("credential1").getState());
assertEquals(LocalCredentialState.correct, credentialsState.get("credential2").getState());
idsMan.mergeEntities(new EntityParam(target), new EntityParam(merged), false);
result = idsMan.getEntity(new EntityParam(target.getEntityId()));
credentialsState = result.getCredentialInfo().getCredentialsState();
assertEquals(LocalCredentialState.correct, credentialsState.get("credential1").getState());
assertEquals(LocalCredentialState.correct, credentialsState.get("credential2").getState());
}
@Test
public void credentialConflictsDetectedInSafeMode() throws Exception
{
Identity target = createUsernameUser("target", null, "p1");
Identity merged = createUsernameUser("merged", null, "p2");
try
{
idsMan.mergeEntities(new EntityParam(target), new EntityParam(merged), true);
fail("No error");
} catch (MergeConflictException e)
{
//ok
}
idsMan.setEntityCredentialStatus(new EntityParam(target), "credential1", LocalCredentialState.notSet);
idsMan.mergeEntities(new EntityParam(target), new EntityParam(merged), true);
}
@Test
public void attributeConflictsDetectedInSafeMode() throws Exception
{
Identity target = createUsernameUser("target", null, "p1");
Identity merged = createUsernameUser("merged", null, "p2");
idsMan.setEntityCredentialStatus(new EntityParam(target), "credential1", LocalCredentialState.notSet);
attrsMan.addAttributeType(new AttributeType("a", new StringAttributeSyntax()));
attrsMan.setAttribute(new EntityParam(target), new StringAttribute("a", "/", AttributeVisibility.full,
"v1"), false);
attrsMan.setAttribute(new EntityParam(merged), new StringAttribute("a", "/", AttributeVisibility.full,
"v2"), false);
try
{
idsMan.mergeEntities(new EntityParam(target), new EntityParam(merged), true);
fail("No error");
} catch (MergeConflictException e)
{
//ok
}
attrsMan.removeAttribute(new EntityParam(merged), "/", "a");
idsMan.mergeEntities(new EntityParam(target), new EntityParam(merged), true);
}
}
|
package common.db.dao.impl;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcDaoSupport;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import common.db.dao.GenericDao;
import common.db.util.ClassTree;
import common.db.util.ORMClass;
import common.util.reflection.ReflectionUtil;
public class GenericDaoImpl extends NamedParameterJdbcDaoSupport implements GenericDao {
private static Map<Class, ORMClass> orm = new HashMap<Class, ORMClass>();
public static synchronized ORMClass getOrmClass(Class cls) {
ORMClass ormClass = orm.get(cls);
if(ormClass == null) {
ormClass = new ORMClass(cls);
orm.put(cls, ormClass);
}
return ormClass;
}
public static ORMClass getOrmClass(Object obj) {
return getOrmClass(obj.getClass());
}
@Autowired
public void init(DataSource dataSource) {
super.setDataSource(dataSource);
}
@Override
public void insert(Object obj) {
insert(obj, false);
}
@Override
public void insert(Object obj, boolean ignore) {
ORMClass oc = getOrmClass(obj);
oc.insert(getNamedParameterJdbcTemplate(), obj, ignore);
}
@Override
public <T> T getEntity(Class<T> cls, String id, String... columns) {
if(columns == null || columns.length == 0)
columns = new String[]{"*"};
ORMClass oc = getOrmClass(cls);
return (T) oc.getById(getNamedParameterJdbcTemplate(), id, columns);
}
@Override
public <T> T getUniqueResult(Class<T> cls, Map<String, ? extends Object> where) {
return getUniqueResult(cls, where, "*");
}
@Override
public <T> T getUniqueResult(Class<T> cls, Map<String, ? extends Object> where, String... columns) {
List<T> list = query(cls, where, columns);
if(list.size() == 0)
return null;
if(list.size() > 1)
throw new RuntimeException("duplicated records found for " + where);
return list.get(0);
}
@Override
public <T> List<T> query(Class<T> cls, Map<String, ? extends Object> where) {
return query(cls, where, "*");
}
@Override
public <T> List<T> query(Class<T> cls, Map<String, ? extends Object> where, String... columns) {
ORMClass oc = getOrmClass(cls);
return oc.query(getNamedParameterJdbcTemplate(), where, columns);
}
@Override
public <T> List<T> queryBySql(Class<T> cls, Map<String, ? extends Object> params, String sql) {
ORMClass oc = getOrmClass(cls);
return oc.queryBySql(getNamedParameterJdbcTemplate(), sql, params);
}
@Override
public <T> List<T> queryBySql(Class<T> cls, String sql, Object... objs) {
ORMClass oc = getOrmClass(cls);
return oc.queryBySql(getJdbcTemplate(), sql, objs);
}
@Override
public <T> T queryUniqueBySql(Class<T> cls, Map<String, ? extends Object> params, String sql) {
ORMClass oc = getOrmClass(cls);
return (T) oc.queryUniqueBySql(getNamedParameterJdbcTemplate(), sql, params);
}
@Override
public <T> T queryUniqueBySql(Class<T> cls, Object[] params, String sql) {
ORMClass oc = getOrmClass(cls);
return (T) oc.queryUniqueBySql(getJdbcTemplate(), sql, params);
}
@Override
public <T> List<T> queryColumn(Class<?> cls, Map<String, ? extends Object> where, String column) {
ORMClass oc = getOrmClass(cls);
return oc.queryColumn(getNamedParameterJdbcTemplate(), column, where);
}
@Override
public void updateEntity(Object obj, String... columns) {
ORMClass oc = getOrmClass(obj);
oc.updateEntity(getNamedParameterJdbcTemplate(), obj, columns);
}
@Override
public void delete(Class class1, Map values) {
ORMClass oc = getOrmClass(class1);
oc.delete(getNamedParameterJdbcTemplate(), values);
}
@Override
public void update(Class<?> class1, Map<String, ? extends Object> values, Map<String, ? extends Object> where) {
ORMClass oc = getOrmClass(class1);
oc.update(getNamedParameterJdbcTemplate(), values, where);
}
@Override
public void replace(Object obj) {
ORMClass oc = getOrmClass(obj);
oc.replace(getNamedParameterJdbcTemplate(), obj);
}
@Override
public Object getDetailsAndParents(ClassTree classTree, String id) {
String sql = "select * from " + classTree.getThisClass().getSimpleName() + " where id=:id";
List detailsAndParents = getDetailsAndParents(classTree, sql, Collections.singletonMap("id", id));
if(detailsAndParents.size() == 0)
return null;
return detailsAndParents.get(0);
}
@Override
public List getDetailsAndParents(ClassTree classTree, String sql, Map<String, ? extends Object> params) {
List detailsList = new ArrayList();
List list = queryBySql(classTree.getThisClass(), params, sql);
Class detailClass = classTree.getDetailsClass();
for(Object obj : list) {
detailsList.add(ReflectionUtil.copy(detailClass, obj));
}
if(classTree.getParent() == null)
return detailsList;
List foreignValues = new ArrayList();
for(Object obj : list) {
try {
Object value = ReflectionUtil.getFieldValue(obj, classTree.getParent().getIdFieldName());
if(!foreignValues.contains(value)) {
foreignValues.add(value);
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
String parentSql = "select * from " + classTree.getParent().getThisClass().getSimpleName() + " where id in (:ids)";
List parents = getDetailsAndParents(classTree.getParent(), parentSql, Collections.singletonMap("ids", foreignValues));
Map<Object, Object> parentMap = new HashMap<Object, Object>();
for(Object parent : parents) {
try {
parentMap.put(ReflectionUtil.getFieldValue(parent, "id"), parent);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
for(Object obj : detailsList) {
try {
Object key = ReflectionUtil.getFieldValue(obj, classTree.getParent().getIdFieldName());
Object value = parentMap.get(key);
if(value != null) {
ReflectionUtil.setField(obj, classTree.getParent().getDetailsFieldName(), value);
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
return detailsList;
}
@Override
public Object getDetailsAndChildren(ClassTree classTree, String id) {
String sql = "select * from " + classTree.getThisClass().getSimpleName() + " where id=:id";
List detailsAndChildren = getDetailsAndChildren(classTree, sql, Collections.singletonMap("id", id));
if(detailsAndChildren.size() == 0)
return null;
return detailsAndChildren.get(0);
}
@Override
public List getDetailsAndChildren(ClassTree classTree, String sql, Map<String, ? extends Object> params) {
List detailsList = new ArrayList();
List list = queryBySql(classTree.getThisClass(), params, sql);
Class detailClass = classTree.getDetailsClass();
for(Object obj : list) {
detailsList.add(ReflectionUtil.copy(detailClass, obj));
}
if(classTree.getChild() == null)
return detailsList;
Map<Object, Object> map = new HashMap<Object, Object>();
List foreignValues = new ArrayList();
for(Object obj : list) {
try {
Object value = ReflectionUtil.getFieldValue(obj, "id");
foreignValues.add(value);
map.put(value, obj);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
String idFieldName = classTree.getIdFieldName();
String parentSql = "select * from " + classTree.getChild().getThisClass().getSimpleName() + " where " + idFieldName + " in (:ids)";
List children = getDetailsAndChildren(classTree.getParent(), parentSql, Collections.singletonMap("ids", foreignValues));
for(Object child : children) {
try {
Object parentId = ReflectionUtil.getFieldValue(child, idFieldName);
Object parent = map.get(parentId);
Object childDetailsList = ReflectionUtil.getFieldValue(parent, classTree.getChild().getDetailsListFieldName());
List childList = (List) ReflectionUtil.getFieldValue(childDetailsList, "items");
childList.add(child);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
return detailsList;
}
@Override
public int update(String sql) {
return getJdbcTemplate().update(sql);
}
@Override
public int update(String sql, Object... args) {
return getJdbcTemplate().update(sql, args);
}
@Override
public int update(String sql, String[] names, Object[] values) {
return getJdbcTemplate().update(sql, names, values);
}
@Override
public NamedParameterJdbcTemplate getNamedJdbcTemplate() {
return getNamedParameterJdbcTemplate();
}
}
|
package com.arjun.beginspring.service;
import com.arjun.beginspring.dao.AccountDao;
import com.arjun.beginspring.model.Account;
import com.example.beginspring.exceptions.InsufficientFundsException;
import com.example.beginspring.exceptions.UserNotFoundException;
public class AccountServiceImpl implements AccountService {
private AccountDao accountDao;
public void setAccountDao(AccountDao accountDao)
{
this.accountDao = accountDao;
}
public void transferMoney(long src, long dest, double amount) throws UserNotFoundException, InsufficientFundsException
{
withdrawMoney(src, amount);
depositMoney(dest, amount);
}
public void depositMoney(long accountId, double amount) throws UserNotFoundException {
Account acc = accountDao.find(accountId);
if (acc == null) {
throw new UserNotFoundException("Invalid Account");
}
acc.UpdateBalance(amount);
}
public void withdrawMoney(long accountId, double amount) throws UserNotFoundException, InsufficientFundsException {
Account acc = accountDao.find(accountId);
if (acc == null) {
throw new UserNotFoundException("Invalid Account");
}
if (acc.getBalance() < amount) {
throw new InsufficientFundsException("Insufficient funds avaiable");
}
acc.UpdateBalance(-amount);
}
public Account findAccount(long accountId) throws UserNotFoundException {
Account acc = accountDao.find(accountId);
if (acc == null) {
throw new UserNotFoundException("Invalid Account");
}
return acc;
}
}
|
package org.softRoad.models.query;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.util.ArrayList;
import java.util.List;
public class SearchCriteria {
@Valid
private SearchCondition condition;
@Min(1)
@Max(100)
private Integer pageSize = 100;
private Integer offset = 0;
@Valid
private List<SearchOrder> searchOrders = new ArrayList<>();
public SearchCondition getCondition() {
return condition;
}
public void setCondition(SearchCondition condition) {
this.condition = condition;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getOffset() {
return offset;
}
public void setOffset(Integer offset) {
this.offset = offset;
}
public List<SearchOrder> getSearchOrders() {
return searchOrders;
}
public void setSearchOrders(List<SearchOrder> searchOrders) {
this.searchOrders = searchOrders;
}
}
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
final String LINE_SPR = System.getProperty("line.separator");
final int BIG_MOD = 1000000007;
Stack<Integer> a = new Stack<Integer>();
Stack<Integer> b = new Stack<Integer>();
Stack<Integer> c = new Stack<Integer>();
Set<Problem> visited = new HashSet<Problem>();
class Problem {
Stack<Integer> a, b, c;
int count;
public Problem(Stack<Integer> a, Stack<Integer> b, Stack<Integer> c, int count) {
this.a = (Stack)a.clone();
this.b = (Stack)b.clone();
this.c = (Stack)c.clone();
this.count = count;
}
public int hashCode() {
return a.hashCode() + 31 * b.hashCode() + 31 * 31 * c.hashCode() + 31 * 31 * 31 * count;
}
public boolean equals(Object obj) {
if(obj instanceof Problem) {
Problem p = (Problem)obj;
return a.equals(p.a) && b.equals(p.b) && c.equals(p.c) && count == p.count;
} else {
return false;
}
}
}
void run() throws Exception {
while(true) {
a.clear();
b.clear();
c.clear();
String[] nums = ns().split(" ");
int n = Integer.parseInt(nums[0]);
int m = Integer.parseInt(nums[1]);
if(n == 0 && m == 0)
break;
for(int i = 0; i < 3; i++) {
String[] datas = ns().split(" ");
int k = Integer.parseInt(datas[0]);
for(int j = 0; j < k; j++) {
stackAt(i).push(Integer.parseInt(datas[j+1]));
}
}
Deque<Problem> queue = new ArrayDeque<Problem>();
queue.offer(new Problem(a, b, c, 0));
while(!queue.isEmpty()) {
Problem p = queue.poll();
}
}
}
Stack<Integer> stackAt(int n) {
switch(n) {
case 0:
return a;
case 1:
return b;
case 2:
return c;
}
return null;
}
/*
* Templates
*/
void dumpObjArr(Object[] arr, int n) {
for(int i = 0; i < n; i++) {
System.out.print(arr[i]);
if(i < n - 1)
System.out.print(" ");
}
System.out.println("");
}
void dumpObjArr2(Object[][] arr, int m, int n) {
for(int j = 0; j < m; j++)
dumpObjArr(arr[j], n);
}
int ni() throws Exception {
return Integer.parseInt(br.readLine().trim());
}
long nl() throws Exception {
return Long.parseLong(br.readLine().trim());
}
String ns() throws Exception {
return br.readLine();
}
boolean isPrime(int n) {
for(int i=2;i<n;i++) {
if(n%i==0)
return false;
}
return true;
}
int getPrime(int n) {
List<Integer> primes = new ArrayList<Integer>();
primes.add(2);
int count = 1;
int x = 1;
while(primes.size() < n) {
x+=2;
int m = (int)Math.sqrt(x);
for(int p : primes) {
if(p > m) {
primes.add(x);
break;
}
if(x % p == 0)
break;
}
}
return primes.get(primes.size() - 1);
}
long lcm(long a, long b) {
return a * b / gcd(a, b);
}
long gcd(long a, long b) {
if(a < b) {
long tmp = a;
a = b;
b = tmp;
}
// a >= b
long mod = a % b;
if(mod == 0)
return b;
else
return gcd(b, mod);
}
void gcjPrint(String str, int t) {
System.out.println("Case #" + t + ": " + str);
}
public static void main(String[] args) throws Exception {
new Main().run();
}
}
|
package com.openfarmanager.android.view;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.futuremind.recyclerviewfastscroll.viewprovider.DefaultBubbleBehavior;
import com.futuremind.recyclerviewfastscroll.viewprovider.ScrollerViewProvider;
import com.futuremind.recyclerviewfastscroll.Utils;
import com.futuremind.recyclerviewfastscroll.viewprovider.ViewBehavior;
import com.futuremind.recyclerviewfastscroll.viewprovider.VisibilityAnimationManager;
import com.openfarmanager.android.App;
import com.openfarmanager.android.R;
/**
* @author Vlad Namashko
*/
public class CustomScrollerViewProvider extends ScrollerViewProvider {
private TextView mBubble;
private View mHandle;
@Override
public View provideHandleView(ViewGroup container) {
mHandle = new View(getContext());
int dimen = getContext().getResources().getDimensionPixelSize(R.dimen.fast_navigation_handle_size);
mHandle.setLayoutParams(new ViewGroup.LayoutParams(dimen, dimen));
Utils.setBackground(mHandle, drawCircle(dimen, dimen, App.sInstance.getSettings().getSecondaryColor()));
mHandle.setVisibility(View.INVISIBLE);
return mHandle;
}
@Override
public View provideBubbleView(ViewGroup container) {
mBubble = new TextView(getContext());
int dimen = getContext().getResources().getDimensionPixelSize(R.dimen.fast_navigation_bubble_size);
mBubble.setLayoutParams(new ViewGroup.LayoutParams(dimen, dimen));
Utils.setBackground(mBubble, drawCircle(dimen, dimen, App.sInstance.getSettings().getSecondaryColor()));
mBubble.setVisibility(View.INVISIBLE);
mBubble.setGravity(Gravity.CENTER);
mBubble.setTextColor(ContextCompat.getColor(getContext(), android.R.color.white));
return mBubble;
}
@Override
public TextView provideBubbleTextView() {
return mBubble;
}
@Override
public int getBubbleOffset() {
return (int) (getScroller().isVertical() ? (float) mHandle.getHeight() / 2f - (float) mBubble.getHeight() / 2f : (float) mHandle.getWidth() / 2f - (float) mBubble.getWidth() / 2);
}
@Override
protected ViewBehavior provideHandleBehavior() {
return new CustomHandleBehavior(
new VisibilityAnimationManager.Builder(mHandle)
.withHideDelay(2000)
.build(),
new CustomHandleBehavior.HandleAnimationManager.Builder(mHandle)
.withGrabAnimator(R.animator.custom_grab)
.withReleaseAnimator(R.animator.custom_release)
.build()
);
}
@Override
protected ViewBehavior provideBubbleBehavior() {
return new DefaultBubbleBehavior(new VisibilityAnimationManager.Builder(mBubble).withHideDelay(0).build());
}
private static ShapeDrawable drawCircle(int width, int height, int color) {
ShapeDrawable oval = new ShapeDrawable(new OvalShape());
oval.setIntrinsicHeight(height);
oval.setIntrinsicWidth(width);
oval.getPaint().setColor(color);
return oval;
}
}
|
package com.gjm.file_cloud.exceptions.http;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.NOT_FOUND)
public class FileDoesntExistException extends RuntimeException {
}
|
package com.revature.repository;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.revature.models.EmployeeAccount;
import com.revature.util.ConnectionFactory;
public class EmployeeDaoImpl implements EmployeeDao {
/**
* Inserts a new employee account into the bank database.
* @param account: the account to be added to the database
* @return true if the insertion is successful, false if an error is encountered
*/
@Override
public boolean insertEmployeeAccount(EmployeeAccount account) {
String sql = "INSERT INTO employee_accounts (user_name, pass_word) VALUES (?, ?);";
try (Connection conn = ConnectionFactory.getConnection();) {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, account.getUsername());
ps.setString(2, account.getPassword());
ps.execute();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* Finds the employee account associated with a given (unique) username.
* @param the username used to find the account
* @return the employee account associated with the given username
*/
@Override
public EmployeeAccount selectEmployeeAccountByUsername(String username) {
String sql = "SELECT * FROM employee_accounts WHERE user_name = ?;";
EmployeeAccount account = null;
try (Connection conn = ConnectionFactory.getConnection();) {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, username);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
account = new EmployeeAccount(rs.getInt("employee_id"),
rs.getString("user_name"),
rs.getString("pass_word"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return account;
}
}
|
package it.almaviva.siap.wsclient.titoli;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import java.util.Date;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.xml.transform.StringResult;
import it.sian.wsdl.ObjectFactory;
import it.sian.wsdl.InputMovimentazioneTitoli;
import it.sian.wsdl.CUAA;
import it.sian.wsdl.Intestatario;
import it.sian.wsdl.Cedente;
import it.sian.wsdl.ArrayOfTitoliMovimentati;
import it.sian.wsdl.TitoliMovimentati;
import it.sian.wsdl.ISWSResponse;
import it.almaviva.siap.config.AcquisizioneDUConfiguration;
public class CSVReader {
private final Logger log = LoggerFactory.getLogger(CSVReader.class);
private final String wsdlUrl = "http://cooperazione.sian.it/wspdd/services/RiformaTitoli?wsdl";
private ObjectFactory objectFactory = new ObjectFactory();
private final SimpleDateFormat sdf_in = new SimpleDateFormat("dd.MM.yyyy");
private final SimpleDateFormat sdf_out = new SimpleDateFormat("yyyyMMyy");
private int cntTit = 0;
/*
* Legge i file CSV restituisce l'oggetto domanda da passare in input al WS
*/
public void inviaMovimentiTitoli (String prov) throws Exception
{
int cnt = 0, numErrori = 0;
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AcquisizioneDUConfiguration.class);
TitoliClient client = context.getBean(TitoliClient.class);
client.setDefaultUri(wsdlUrl);
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setContextPath("it.sian.wsdl");
List<InputMovimentazioneTitoli> listaMov = this.readMovimenti(prov, "trasf-titoli-bz-02082016.csv");
for (InputMovimentazioneTitoli mov : listaMov) {
//debugging
try {
ISWSResponse response = client.inviaMovimentiTitoli(mov);
if (response != null && !response.getCodRet().equals("012")) {
StringResult result = new StringResult();
marshaller.marshal(mov, result);
log.debug("mov: " + result.toString());
log.info("Documento = " + mov.getIdDocumento());
log.info("Cod.ret. = " + response.getCodRet() + " - " + response.getSegnalazione());
numErrori++;
}
}
catch (Exception ex) {
ex.printStackTrace();
numErrori++;
}
cnt++;
}
log.info("Movimenti inviati: " + cnt
+ " (num. titoli: " + cntTit
+ ") di cui con esito negativo: " + numErrori);
}
/*
* Legge il file CSV relativo all'anagrafica e restituisce l'oggetto
* da passare in input al WS
*/
private List<InputMovimentazioneTitoli> readMovimenti (String prov, String fileName)
{
String csvFile = prov + "/" + fileName;
String line = "";
String cvsSplitBy = ";";
DecimalFormat df = new DecimalFormat("000000000000");
int cnt = 0;
List<InputMovimentazioneTitoli> lista = new ArrayList<InputMovimentazioneTitoli>();
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream(csvFile);
try (BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")))
{
String keySup = null;
InputMovimentazioneTitoli mov = null;
ArrayOfTitoliMovimentati titoliMov = null;
while ((line = br.readLine()) != null) {
// use comma as separator
String[] fields = line.split(cvsSplitBy);
StringBuilder sbk = new StringBuilder();
//...
if (!fields[0].equalsIgnoreCase("INTESTATARIO")
&& !fields[0].equalsIgnoreCase("CUAA acquirente")
) {
for (int i = 0; i < fields.length; i++) {
log.debug("field[" + i + "] = " + fields[i]);
if (i < 7) {
sbk.append(fields[i]);
}
}
if (keySup != null && !keySup.equals(sbk.toString())) {
mov.setTitoliMovimentatiInput(titoliMov);
lista.add(mov);
mov = objectFactory.createInputMovimentazioneTitoli();
titoliMov = objectFactory.createArrayOfTitoliMovimentati();
}
else {
if (keySup == null) {
mov = objectFactory.createInputMovimentazioneTitoli();
titoliMov = objectFactory.createArrayOfTitoliMovimentati();
}
}
keySup = sbk.toString();
CUAA cuaaIntestatario = objectFactory.createCUAA();
Intestatario intestatario = objectFactory.createIntestatario();
if (fields[0].trim().length() == 16) {
cuaaIntestatario.setCodiceFiscalePersonaFisica(fields[0].trim());
}
else {
cuaaIntestatario.setCodiceFiscalePersonaGiuridica(fields[0].trim());
}
intestatario.setCUAA(cuaaIntestatario);
mov.setIntestatario(intestatario);
mov.setIdDocumento(fields[1]);
mov.setCampagna(fields[2]);
mov.setFattispecie(fields[3]);
if (!fields[4].isEmpty()) {
CUAA cuaaCedente = objectFactory.createCUAA();
Cedente cedente = objectFactory.createCedente();
if (fields[4].trim().length() == 16) {
cuaaCedente.setCodiceFiscalePersonaFisica(fields[4].trim());
}
else {
cuaaCedente.setCodiceFiscalePersonaGiuridica(fields[4].trim());
}
cedente.setCUAA(cuaaCedente);
mov.setCedente(cedente);
}
if (!fields[5].isEmpty()) {
mov.setConsensoCedente(fields[5]);
}
if (!fields[6].isEmpty()) {
// BZ
Date dt = sdf_in.parse(fields[6]);
mov.setDataConsenso(sdf_out.format(dt));
// TN
//mov.setDataConsenso(fields[6]);
}
/*
* aggiunta titolo movimentato
*/
TitoliMovimentati titMov = objectFactory.createTitoliMovimentati();
titMov.setPrimoIdentificativo(df.format(Long.parseLong(fields[7])));
if (fields.length > 8 && !fields[8].isEmpty()) {
// BZ
Date dt = sdf_in.parse(fields[8]);
titMov.setDataScadenzaAffitto(sdf_out.format(dt));
// TN
//titMov.setDataScadenzaAffitto(fields[8]);
}
if (fields.length > 9 && !fields[9].isEmpty()) {
java.math.BigDecimal bd = new java.math.BigDecimal(new Double(fields[9]).doubleValue())
.setScale(6, java.math.BigDecimal.ROUND_HALF_UP);
titMov.setSuperficieUBA(bd);
}
titoliMov.getTitoliMovimentati().add(titMov);
cntTit++;
}
}
mov.setTitoliMovimentatiInput(titoliMov);
lista.add(mov);
cnt++;
}
catch (Exception e) {
e.printStackTrace();
}
log.debug("Movimenti#: " + lista.size());
return lista;
}
} |
package cl.sportapp.evaluation.dto;
import cl.sportapp.evaluation.entitie.Evaluacion;
import cl.sportapp.evaluation.entitie.TipoMedicion;
import lombok.Data;
import java.util.List;
@Data
public class SubtipoMedicionDto {
private Long id;
private String nombre;
private boolean estado;
private TipoMedicion tipoMedicion;
private List<Evaluacion> evaluacions;
}
|
package thread.kfc;
/**食物类
* Created by fanwei_last on 2017/11/10.
*/
public class Food {
String name;
public Food(String name){
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
package by.client.android.railwayapp.ui.page.scoreboard;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.TextView;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import java.util.Arrays;
import java.util.List;
import javax.inject.Inject;
import by.client.android.railwayapp.ApplicationComponent;
import by.client.android.railwayapp.GlobalExceptionHandler;
import by.client.android.railwayapp.R;
import by.client.android.railwayapp.api.ScoreboardStation;
import by.client.android.railwayapp.api.rw.RailwayApi;
import by.client.android.railwayapp.model.Train;
import by.client.android.railwayapp.ui.ModifiableRecyclerAdapter;
import by.client.android.railwayapp.ui.base.BaseDaggerFragment;
import by.client.android.railwayapp.ui.page.settings.SettingsService;
import by.client.android.railwayapp.ui.utils.Dialogs;
import by.client.android.railwayapp.ui.utils.UiUtils;
/**
* Страница "Виртуальное онлайн-табло" отправки и прибытия поездов
* <p>
* <p>По умолчанию отображается станция "Минск-Пассажирский"</p>
*
* @author ROMAN PANTELEEV
*/
@EFragment(R.layout.activity_scoreboard)
public class ScoreboardActivityFragment extends BaseDaggerFragment
implements SwipeRefreshLayout.OnRefreshListener, ScoreboardContract.View {
private static final int SCOREBOARD_ACTIVITY_CODE = 1;
@Inject
RailwayApi railwayApi;
@Inject
SettingsService settingsService;
@Inject
GlobalExceptionHandler globalExceptionHandler;
@ViewById(R.id.emptyView)
TextView emptyView;
@ViewById(R.id.swiperefresh)
SwipeRefreshLayout swipeRefreshLayout;
@ViewById(R.id.toolBar)
Toolbar toolbar;
@ViewById(R.id.trainsListView)
RecyclerView trainsRecyclerView;
@ViewById(R.id.stationsSpinner)
Spinner stationsSpinner;
@ViewById(R.id.collapsingToolbarLayout)
CollapsingToolbarLayout collapsingToolbarLayout;
@ViewById(R.id.appBar)
AppBarLayout appBarLayout;
private TrainAdapter trainsAdapter;
private ScoreboardContract.Presenter presenter;
public static ScoreboardActivityFragment newInstance() {
return new ScoreboardActivityFragment_();
}
@AfterViews
void initFragment() {
new ScoreboardPresenter(railwayApi, this);
List<ScoreboardStation> scoreboardStations = Arrays.asList(ScoreboardStation.values());
swipeRefreshLayout.setOnRefreshListener(this);
trainsRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
trainsRecyclerView.setItemAnimator(new DefaultItemAnimator());
trainsRecyclerView.setHasFixedSize(true);
StationAdapter stationAdapter = new StationAdapter(getActivity());
stationAdapter.setData(scoreboardStations);
stationsSpinner.setAdapter(stationAdapter);
stationsSpinner.setOnItemSelectedListener(new StationClickListener());
stationsSpinner.setSelection(scoreboardStations.indexOf(settingsService.getScoreboardStation()));
trainsAdapter = new TrainAdapter(getContext());
trainsAdapter.setItemClickListener(new TrainClickListener());
trainsRecyclerView.setAdapter(trainsAdapter);
loadData();
}
@Override
public void injectFragment(ApplicationComponent component) {
component.inject(this);
}
@Override
public void onDestroyView() {
super.onDestroyView();
if (presenter != null) {
presenter.onViewDetached();
}
}
@Override
public void onRefresh() {
loadData();
}
@Override
public void setProgressIndicator(boolean active) {
swipeRefreshLayout.setRefreshing(active);
UiUtils.setVisibility(trainsAdapter.getItemCount() > 0, emptyView);
}
@Override
public void loadScoreboard(List<Train> articles) {
trainsAdapter.setData(articles);
}
@Override
public void loadingError(Exception exception) {
// TODO fix exception
Dialogs.showToast(getContext(), exception.getMessage());
}
@Override
public void setPresenter(ScoreboardContract.Presenter presenter) {
this.presenter = presenter;
}
private void loadData() {
presenter.load(getStation());
settingsService.saveScoreboardStation(getStation());
}
private ScoreboardStation getStation() {
return UiUtils.getSpinnerSelected(stationsSpinner);
}
private class TrainClickListener implements ModifiableRecyclerAdapter.RecyclerItemsClickListener {
@Override
public void itemClick(View view, int position) {
ScoreboardDetailActivity.start(getActivity(), trainsAdapter.getItem(position), SCOREBOARD_ACTIVITY_CODE);
}
}
private class StationClickListener implements AdapterView.OnItemSelectedListener {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
loadData();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
}
|
package unab.com;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Leer
{
public static String leer(String mensaje)
{
String lectura ="";
//leyendo de teclado
InputStreamReader flujo = new InputStreamReader(System.in);
BufferedReader texto = new BufferedReader(flujo);
try
{ if (!mensaje.equals(""))
System.out.println(mensaje);
lectura = texto.readLine();
} catch (IOException e)
{System.out.println("Error de lectura");
}
return lectura;
}
} |
package org.apache.hadoop.hdfs.server.blockmanagement;
/**
*
* @author Hooman <hooman@sics.se>
*/
public class GenerationStamp {
public static enum Finder implements org.apache.hadoop.hdfs.server.namenode.FinderType<GenerationStamp> {
// Value of the generation stamp.
Counter;
@Override
public Class getType() {
return GenerationStamp.class;
}
}
private long counter;
public GenerationStamp(long counter) {
this.counter = counter;
}
public long getCounter() {
return counter;
}
public void setCounter(long counter)
{
this.counter = counter;
}
}
|
package 算法.回溯算法;
import java.util.ArrayList;
import java.util.List;
/**
* @Title: 子集 : 给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
* @Date: 2018/8/20 9:57
*/
public class 子集 {
public static List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> list = new ArrayList<>();
List<Integer> single = new ArrayList<>();
//标记数组
boolean[] a = new boolean[nums.length];
digui(list,single,nums,a,0);
return list;
}
public static void digui(List<List<Integer>> list,List<Integer> single,int[] nums,boolean[] a,int n) {
if (n == nums.length) {
//吧标记了取的元素放进single队列里
for (int i = 0; i < a.length; i++) {
if (a[i]) {
single.add(nums[i]);
}
}
//注意一定要new一个,不然只是复制一个引用
list.add(new ArrayList<Integer>(single));
//清空队列
single.removeAll(single);
return;
}
else {
//取n的情况,准备看下一个
a[n] = false;//通过这个来选择到底是去几个数作为其中的一个子集,如果全为false,则取零个,那么子集为空集,如果全为true,那么子集为{1,2,3}
digui(list, single, nums, a, n+1);
//不取n的情况,看下一个
a[n] =true;
digui(list, single, nums, a, n+1);
}//
}
public static void main(String[] args) {
System.out.println(subsets(new int[]{1,2,3}));
}
} |
package vista;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
import javax.swing.border.TitledBorder;
import javax.swing.SwingUtilities;
import controlador.Restaurante;
import vista.Comandas.FormVender;
import vista.Mozos.FormRendicionMozo;
import vista.Productos.FormIngresarMercaderia;
/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class FormMAIN extends javax.swing.JFrame {
private JButton btnIniciarDia;
private JButton btnCerrarDia;
private JButton btnComandas;
private JPanel jPanel5;
private JPanel jPanel4;
private JPanel jPanel3;
private JPanel jPanel2;
private JPanel jPanel1;
private JButton btnABM;
private JButton btnIngMerca;
private JButton btnGenerar;
private JButton btnSalir;
private AbstractAction getAbrirDia;
private AbstractAction getCerrarDia;
private AbstractAction getComandas;
private AbstractAction getABM;
private AbstractAction getIngresarMercaderia;
private AbstractAction getGenerarOrdenesDeCompra;
private AbstractAction getSalirAccion;
public FormMAIN() {
super();
initGUI();
}
private void initGUI() {
try {
getContentPane().setLayout(null);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
this.setTitle("Restaurante");
this.setPreferredSize(new java.awt.Dimension(520, 370));
{
btnSalir = new JButton();
getContentPane().add(btnSalir);
btnSalir.setText("CERRAR");
btnSalir.setAction(getSalirAccion());
btnSalir.setBounds(161, 280, 190, 27);
getJPanel1();
}
pack();
this.setSize(512, 370);
} catch (Exception e) {
e.printStackTrace();
}
}
private JPanel getJPanel1() {
if(jPanel1 == null) {
jPanel1 = new JPanel();
{
btnIniciarDia = new JButton();
jPanel1.add(btnIniciarDia);
getContentPane().add(getJPanel1());
getContentPane().add(getJPanel3());
jPanel1.setBounds(12, 12, 488, 79);
jPanel1.setBorder(BorderFactory.createTitledBorder(null, "JORNADA", TitledBorder.LEADING, TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma",1,11), new java.awt.Color(0,0,255)));
jPanel1.setLayout(null);
jPanel1.setForeground(new java.awt.Color(0,0,255));
btnIniciarDia.setText("INICIAR DIA");
btnIniciarDia.setAction(getAbrirDia());
btnIniciarDia.setBounds(25, 31, 190, 27);
}
{
btnCerrarDia = new JButton();
jPanel1.add(btnCerrarDia);
btnCerrarDia.setText("CERRAR DIA");
btnCerrarDia.setAction(getCerrarDia());
btnCerrarDia.setBounds(274, 31, 190, 27);
}
}
return jPanel1;
}
private JPanel getJPanel2() {
if(jPanel2 == null) {
jPanel2 = new JPanel();
jPanel2.setBounds(261, 103, 237, 73);
jPanel2.setBorder(BorderFactory.createTitledBorder(null, "ABMs GENERALES", TitledBorder.LEADING, TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma",1,11), new java.awt.Color(0,0,255)));
jPanel2.setLayout(null);
jPanel2.setForeground(new java.awt.Color(0,0,255));
{
btnABM = new JButton();
jPanel2.add(btnABM);
btnABM.setText("ABM");
btnABM.setAction(getABM());
btnABM.setBounds(26, 26, 190, 27);
}
}
return jPanel2;
}
private JPanel getJPanel3() {
if(jPanel3 == null) {
jPanel3 = new JPanel();
jPanel3.setBounds(12, 103, 237, 73);
jPanel3.setBorder(BorderFactory.createTitledBorder(null, "VENTAS", TitledBorder.LEADING, TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma",1,11), new java.awt.Color(0,0,255)));
jPanel3.setLayout(null);
jPanel3.setForeground(new java.awt.Color(0,0,255));
{
btnComandas = new JButton();
jPanel3.add(btnComandas);
getContentPane().add(getJPanel2());
getContentPane().add(getJPanel5());
btnComandas.setText("COMANDAS");
btnComandas.setAction(getComandas());
btnComandas.setBounds(25, 24, 190, 27);
}
}
return jPanel3;
}
private JPanel getJPanel4() {
if(jPanel4 == null) {
jPanel4 = new JPanel();
jPanel4.setBounds(12, 188, 237, 73);
jPanel4.setBorder(BorderFactory.createTitledBorder(null, "COMPRAS", TitledBorder.LEADING, TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma",1,11), new java.awt.Color(0,0,255)));
jPanel4.setLayout(null);
jPanel4.setForeground(new java.awt.Color(0,0,255));
{
btnGenerar = new JButton();
jPanel4.add(btnGenerar);
btnGenerar.setText("GENERAR ORDENES DE COMPRA");
btnGenerar.setAction(getGenerarOrdenesDeCompra());
btnGenerar.setBounds(26, 24, 190, 27);
}
}
return jPanel4;
}
private JPanel getJPanel5() {
if(jPanel5 == null) {
jPanel5 = new JPanel();
jPanel5.setBounds(261, 188, 237, 73);
jPanel5.setBorder(BorderFactory.createTitledBorder(null, "STOCK", TitledBorder.LEADING, TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma",1,11), new java.awt.Color(0,0,255)));
jPanel5.setLayout(null);
jPanel5.setForeground(new java.awt.Color(0,0,255));
{
btnIngMerca = new JButton();
jPanel5.add(btnIngMerca);
getContentPane().add(getJPanel4());
btnIngMerca.setText("INGRESAR MERCADERIA");
btnIngMerca.setAction(getIngresarMercaderia());
btnIngMerca.setBounds(26, 25, 190, 27);
}
}
return jPanel5;
}
private AbstractAction getAbrirDia() {
if(getAbrirDia == null) {
getAbrirDia = new AbstractAction("INICIAR DIA", null) {
public void actionPerformed(ActionEvent evt){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Revisa que la jornada no este abierta
if (Restaurante.getRestaurante().isOpen()){
// Jornada ya abierta y en curso
JOptionPane.showMessageDialog(null, "La jornada ya se encuentra abierta", "ATENCION", JOptionPane.WARNING_MESSAGE);
}else{
// Revisa que se pueda abrir la jornada
if (Restaurante.getRestaurante().abrirJornada())
JOptionPane.showMessageDialog(null, "Jornada abierta con exito", "MENSAJE", JOptionPane.WARNING_MESSAGE);
else{
// Notifica que faltan mesas, mozos o que no hay carta activa
JOptionPane.showMessageDialog(null, "No puede abrise la jornada ¿Carta? / ¿Mesas? / ¿Mozos?", "ATENCION", JOptionPane.WARNING_MESSAGE);
}
}
}
});
}
};
}
return getAbrirDia;
}
private AbstractAction getCerrarDia() {
if(getCerrarDia == null) {
getCerrarDia = new AbstractAction("CERRAR DIA", null) {
public void actionPerformed(ActionEvent evt){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Revisa que la jornada halla sido abierta
if (Restaurante.getRestaurante().isOpen()){
if (Restaurante.getRestaurante().cerrarJornada()){
FormRendicionMozo inst = new FormRendicionMozo();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
JOptionPane.showMessageDialog(null, "Jornada cerrada con exito", "MENSAJE", JOptionPane.WARNING_MESSAGE);
}else{
JOptionPane.showMessageDialog(null, "No se pudo cerrar. Mesa/s con comanda/s en curso.", "ATENCION", JOptionPane.WARNING_MESSAGE);
}
}else{
// Jornada cerrada
JOptionPane.showMessageDialog(null, "La jornada no ha sido abierta.", "ATENCION", JOptionPane.WARNING_MESSAGE);
}
}
});
}
};
}
return getCerrarDia;
}
private AbstractAction getABM() {
if(getABM == null) {
getABM = new AbstractAction("ABMs", null) {
public void actionPerformed(ActionEvent evt){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Revisa que la jornada no este abierta
if (!Restaurante.getRestaurante().isOpen()){
FormABMs inst = new FormABMs();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}else{
// Con jornada abierta no permite modificar los objetos
JOptionPane.showMessageDialog(null, "Jornada en curso. No se puede modificar.", "Prohibido", JOptionPane.WARNING_MESSAGE);
}
}
});
}
};
}
return getABM;
}
private AbstractAction getIngresarMercaderia() {
if(getIngresarMercaderia== null) {
getIngresarMercaderia= new AbstractAction("INGRESAR MERCADERIA", null) {
public void actionPerformed(ActionEvent evt){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
FormIngresarMercaderia inst = new FormIngresarMercaderia();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}
};
}
return getIngresarMercaderia;
}
private AbstractAction getGenerarOrdenesDeCompra() {
getGenerarOrdenesDeCompra = new AbstractAction("GENERAR ORDENES", null) {
public void actionPerformed(ActionEvent evt){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Revisa que el dia no halla sido abierto
if (!Restaurante.getRestaurante().isOpen()){
int ord = Restaurante.getRestaurante().generarOrdenesDeCompra();
JOptionPane.showMessageDialog(null, "Ordenes de compra generadas: " +ord+"", "Atencion", JOptionPane.WARNING_MESSAGE);
}else{
// Si el dia esta abierto, no permite generar las ordenes de compra
JOptionPane.showMessageDialog(null, "Jornada en curso. No se pueden generar ordenes de compra.", "Prohibido", JOptionPane.WARNING_MESSAGE);
}
}
});
}
};
return getGenerarOrdenesDeCompra;
}
private AbstractAction getComandas() {
getComandas = new AbstractAction("COMANDAS", null) {
public void actionPerformed(ActionEvent evt){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Revisa que la jornada halla sido abierta para poder vender.
if (Restaurante.getRestaurante().isOpen()){
FormVender inst = new FormVender();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}else{
// Con la jornada cerrada no permite vernder
JOptionPane.showMessageDialog(null, "Jornada cerrada. No se puede vender.", "Prohibido", JOptionPane.WARNING_MESSAGE);
}
}
});
}
};
return getComandas;
}
private AbstractAction getSalirAccion() {
if(getSalirAccion == null) {
getSalirAccion = new AbstractAction("CERRAR", null) {
public void actionPerformed(ActionEvent evt) {
if(!Restaurante.getRestaurante().isOpen()){
JOptionPane.showMessageDialog(null, "Se cerrará el sistema. Que tenga un buen dia.", "ADIOS", JOptionPane.WARNING_MESSAGE);
System.exit(0);
}else{
JOptionPane.showMessageDialog(null, "Jornada en curso. No se puede salir.", "PROHIBIDO", JOptionPane.WARNING_MESSAGE);
}
}
};
}
return getSalirAccion;
}
}
|
public class Vista{
public static void main(String[] args){
System.out.println("Vista");
}
} |
package pe.edu.pucp.musicsoft.model;
public class EmpresaDiscografica {
private int idEmpresa;
private String nombreEmpresa;
public EmpresaDiscografica(){
}
public int getIdEmpresa() {
return idEmpresa;
}
public void setIdEmpresa(int idEmpresa) {
this.idEmpresa = idEmpresa;
}
public String getNombreEmpresa() {
return nombreEmpresa;
}
public void setNombreEmpresa(String nombreEmpresa) {
this.nombreEmpresa = nombreEmpresa;
}
}
|
package com.exam.jsp_tags;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.log4j.Log4j;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import static com.exam.logic.Constants.USER_ZONE_ID;
@Log4j
@Setter
@Getter
public class ZonedTimeFormatter extends TagSupport {
private static final long serialVersionUID = 3081514849669679223L;
private ZonedDateTime time;
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm dd-MM-yyyy");
@Override
public int doStartTag() throws JspException {
JspWriter out = pageContext.getOut();
ZoneId zoneId = (ZoneId) pageContext.getSession().getAttribute(USER_ZONE_ID);
if (zoneId == null) zoneId = ZoneId.of("UTC");
ZonedDateTime zonedDateTime = time.toInstant().atZone(zoneId);
try {
out.write(formatter.format(zonedDateTime));
} catch (IOException e) {
throw new RuntimeException(e);
}
return SKIP_BODY;
}
} |
package com.example.dbdemo;
import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;
import com.example.bean.Person;
import com.example.db.DatabaseUtil;
import com.example.db.MyHelper;
public class Add_Date extends Activity {
/*界面组件*/
private Button add_enter;
private Button add_cancel;
private EditText name_edt;
private RadioButton radio_male;
private RadioButton radio_female;
private RadioGroup radioGroup;
private DatabaseUtil mDBUtil;
private int sex = 1; //判断性别
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.add_data);
//初始化
initview();
Log.e("init", "init");
this.setListener();
}
//性别监听
public void setListener(){
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
Log.e("radio", "radio");
if(checkedId == R.id.radio_male){
sex = 1;
}else if(checkedId == R.id.radio_female){
sex = 0;
}
}
});
}
/*初始化界面*/
private void initview() {
add_enter = (Button)findViewById(R.id.add_enter_btn);
add_cancel = (Button)findViewById(R.id.add_cancel_btn);
name_edt = (EditText)findViewById(R.id.name_edt);
radioGroup = (RadioGroup)findViewById(R.id.radioGroup_selectSex);
radio_male = (RadioButton)findViewById(R.id.radio_male);
radio_female = (RadioButton)findViewById(R.id.radio_female);
//获取数据库
mDBUtil = new DatabaseUtil(Add_Date.this);
//监听添加
add_enter.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.e("add_enter", "add_enter");
Person person = new Person();
if(null == name_edt.getText().toString().trim() || name_edt.getText().toString().length() == 0){
Toast.makeText(getApplicationContext(), "请输入姓名", Toast.LENGTH_SHORT).show();
return;
}
person.setName(name_edt.getText().toString());
if(sex == 1){
person.setSex(radio_male.getText().toString());
}else{
person.setSex(radio_female.getText().toString());
}
if(mDBUtil.Insert(person)){
Toast.makeText(getApplicationContext(), "添加数据成功", Toast.LENGTH_SHORT).show();
clear();
}else{
Toast.makeText(getApplicationContext(), "添加数据失败", Toast.LENGTH_SHORT).show();
}
}
});
add_cancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
private void clear(){
name_edt.setText("");
}
}
|
package com.zl.action.front;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.zl.pojo.business.ApplyCardPlan;
import com.zl.service.front.ApplyCardService;
@Controller
@RequestMapping("/creditCard")
public class CardMangerController {
@Autowired
private ApplyCardService acs;
@RequestMapping("/queryPlan")
@ResponseBody
public Map<String,Object> findPlan(String IDcard){
Map<String,Object> result=new HashMap<String,Object>();
List<ApplyCardPlan> plan =acs.queryCardPlanByIDCard(IDcard);
result.put("plan", plan);
return result;
}
}
|
package com.form.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
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.form.dao.BookDAO;
import com.form.model.Book;
@WebServlet(urlPatterns = {"/edit"})
public class editBookController extends HttpServlet {
private BookDAO edit;
@Override
public void init() throws ServletException {
edit= new BookDAO();
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
editBook(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
public void editBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int id =Integer.parseInt(request.getParameter("id"));
String title = request.getParameter("title");
String author = request.getParameter("author");
float price = Float.valueOf(request.getParameter("price"));
int qty = Integer.valueOf(request.getParameter("qty"));
Book book = new Book();
book.setId(id);
book.setTitle(title);
book.setAuthor(author);
book.setPrice(price);
book.setQty(qty);
edit.edit(book);
response.sendRedirect("/MVC/danhsach");
}
}
|
/*
* Created on 10/12/2008
*
*/
package com.citibank.ods.persistence.pl.dao;
import com.citibank.ods.common.dataset.DataSet;
/**
* @author lfabiano
* @since 10/12/2008
*/
public interface TplReasonEndRelationDAO {
public DataSet loadDomain();
}
|
package us.gibb.dev.gwt.server.command.handler;
import java.util.Map;
import us.gibb.dev.gwt.command.Command;
import us.gibb.dev.gwt.command.CommandException;
import us.gibb.dev.gwt.command.Result;
public interface CommandHandler<C extends Command<R>, R extends Result> {
public R execute(C command, Context context) throws CommandException;
public Map<Class<? extends Command<?>>, CommandHandler<?, ?>> getCommandMapping();
}
|
package com.gxtc.huchuan.adapter;
import android.content.Context;
import android.widget.ImageView;
import android.widget.TextView;
import com.gxtc.commlibrary.base.BaseRecyclerAdapter;
import com.gxtc.commlibrary.helper.ImageHelper;
import com.gxtc.huchuan.R;
import com.gxtc.huchuan.data.ArticleSpecialBean;
import java.util.List;
/**
* 来自 苏修伟 on 2018/5/12.
*/
public class ArticleSpecialAdapter extends BaseRecyclerAdapter<ArticleSpecialBean> {
private String isPay;
public ArticleSpecialAdapter(Context context, List<ArticleSpecialBean> list, int itemLayoutId, String isPay) {
super(context, list, itemLayoutId);
this.isPay = isPay;
}
@Override
public void bindData(ViewHolder holder, int position, ArticleSpecialBean articleSpecialBean) {
ImageView mCover = (ImageView) holder.getView(R.id.iv_specia_cover);
TextView mTitle = (TextView) holder.getView(R.id.tv_specia_title);
TextView mType = (TextView) holder.getView(R.id.tv_type_type);
if ("1".equals(isPay)) {
mType.setText("立即阅读");
mType.setTextColor(getContext().getResources().getColor(R.color.pay_finish));
}else {
//0=非专题文章或视频,1=免费,2=收费,3=试看
switch (articleSpecialBean.isFreeSee()) {
case 1:
mType.setText("免费阅读");
mType.setTextColor(getContext().getResources().getColor(R.color.pay_finish));
break;
case 2:
mType.setText("订阅阅读");
mType.setTextColor(getContext().getResources().getColor(R.color.color_ff7531));
break;
case 3:
mType.setText("试读");
mType.setTextColor(getContext().getResources().getColor(R.color.color_2b8cff));
break;
}
}
mTitle.setText(articleSpecialBean.getTitle());
ImageHelper.loadImage(getContext(), mCover, articleSpecialBean.getCover());
}
}
|
package com.brainacademy.threads;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ScheduledThreadPoolTest {
private static final ScheduledExecutorService SCHEDULED_EXECUTOR_SERVICE = Executors.newScheduledThreadPool(10);
public static void main(String[] args) {
SCHEDULED_EXECUTOR_SERVICE.schedule(new Runnable() {
@Override
public void run() {
System.out.println("Start with delay 5 sec.");
}
}, 5, TimeUnit.SECONDS);
SCHEDULED_EXECUTOR_SERVICE.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("FixedRate at: " + new Date());
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},0, 1, TimeUnit.SECONDS);
SCHEDULED_EXECUTOR_SERVICE.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
System.out.println("FixedDelay at: " + new Date());
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},0, 1, TimeUnit.SECONDS);
try {
TimeUnit.SECONDS.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
SCHEDULED_EXECUTOR_SERVICE.shutdown();
}
}
|
package com.carlos.theculinaryapp;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.StrictMode;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
class CustomAdapterProfile extends ArrayAdapter<ProfileItem>{
public CustomAdapterProfile(Context context, ProfileItem[] resource) {
super(context, R.layout.profile_row, resource);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inf = LayoutInflater.from(getContext());
View customView = inf.inflate(R.layout.profile_row, parent, false);
String itemName = getItem(position).getName();
String itemImageFile = getItem(position).getImageFile();
TextView name = (TextView) customView.findViewById(R.id.name_text);
ImageView imagev = (ImageView) customView.findViewById(R.id.image_row);
imagev.setScaleType(ImageView.ScaleType.CENTER_CROP);
name.setText(itemName);
Context context = this.getContext();
Bitmap b = getPicture(getItem(position).getImageFile());
if(b==null)
imagev.setImageResource(context.getResources().getIdentifier(itemImageFile, "drawable", context.getPackageName()));
else imagev.setImageBitmap(b);
return customView;
}
private Bitmap getPicture(String picUrl){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Bitmap bmp = null;
URL url;
try {
url = new URL(picUrl);
try {
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
Log.e("Error", e.getMessage());
}
} catch (MalformedURLException e) {
Log.e("Error", e.getMessage());
}
return bmp;
}
}
|
package com.goodreads;
import com.goodreads.dataproviders.OpenCartDataProvider;
import com.goodreads.utils.listeners.OpenCartTestListener;
import com.google.inject.Inject;
import com.jayway.restassured.response.Response;
import com.opencart.allure.AllureEnvironmentController;
import com.opencart.api.OpenCartBO;
import com.opencart.api.strategies.ProductAddingStrategy;
import com.opencart.modules.OpenCartBOModule;
import com.opencart.verification.VerificationDirector;
import com.opencart.verification.commands.ContentVerificationCommand;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.hamcrest.Matchers;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Guice;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
@Guice(modules = {OpenCartBOModule.class})
@Listeners(OpenCartTestListener.class)
@Feature("Opencart endpoints")
@Story("Opencart endpoints should work correctly")
public class OpenCartTest {
@Inject
private OpenCartBO openCartBO;
@Test(description = "Verify adding product to cart (product id: %s; quantity: %s)",
dataProvider = "provideItemData",
dataProviderClass = OpenCartDataProvider.class)
public void verifyProductToCartAdding(String productId, String quantity, ProductAddingStrategy productAddingStrategy) {
ContentVerificationCommand contentVerificationCommand = new ContentVerificationCommand();
contentVerificationCommand.addContentVerification("products.product_id[0]", Matchers.equalTo(productId));
contentVerificationCommand.addContentVerification("products.quantity[0]", Matchers.equalTo(quantity));
Response response = openCartBO.addItem(productAddingStrategy, productId, quantity);
new VerificationDirector().createVerification(contentVerificationCommand, response).verifyAll();
}
@Test(description = "Verify cart deletion")
public void verifyCartDeletion() {
ContentVerificationCommand contentVerificationCommand = new ContentVerificationCommand();
contentVerificationCommand.addContentVerification("products", Matchers.empty());
Response response = openCartBO.removeCart();
new VerificationDirector().createVerification(contentVerificationCommand, response).verifyAll();
}
@AfterClass
public void createPropertyFile() {
new AllureEnvironmentController().createPropertyFile();
}
}
|
package com.ants.theantsgo.payByThirdParty.aliPay;
/**
* ===============Txunda===============
* 作者:DUKE_HwangZj
* 日期:2017/6/30 0030
* 时间:下午 4:43
* 描述:支付宝回调接口
* ===============Txunda===============
*/
public interface AliPayCallBack {
/**
* 当支付成功时的回调函数
*/
void onComplete();
/**
* 当支付失败时的回调函数(包括用户主动取消支付,或者系统返回的错误
*/
void onFailure();
/**
* 当等待支付结果确认时的回调函�?<br/>
* 在终交易是否成功以服务端异步通知为准(小概率状况)
*/
void onProcessing();
}
|
package com.ron.messageBoard.entity.data;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.time.LocalDateTime;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "topic")
public class Topic {
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "NAME")
private String name;
@Column(name = "CREATE_DATE")
private LocalDateTime createDate;
@Column(name = "MODIFY_DATE")
private LocalDateTime modifyDate;
}
|
package com.igs.qhrzlc.presenter;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.hl.util.ExitApplication;
import com.hl.util.NetUtils;
import com.hl.util.ToastUtils;
import com.igs.qhrzlc.utils.view.NoticeDialog;
import com.igs.qhrzlc.utils.view.LoadingDialog;
import qhrzzx.igs.com.igs_mvp.R;
/**
* 类描述:
* 创建人:heliang
* 创建时间:2015/10/30 17:17
* 修改人:8153
* 修改时间:2015/10/30 17:17
* 修改备注:
*/
public class BasePresenter implements Presenter {
public LoadingDialog loadingDialog;
public NoticeDialog noticeDialog;
/**
* 初始化加载dialog,数据弹框dialog
* @param context
*/
public void initDialog(Context context){
loadingDialog = new LoadingDialog(context);
noticeDialog = new NoticeDialog(context);
}
/**
* 显示加载dialog
*/
public void showLoadingDialog(Context context, LoadingDialog loadingDialog) {
if (!loadingDialog.isShowing()) {
loadingDialog.show();
}
}
/**
* 删除加载dialog
*/
public void cancleLoadingDialog(Context context, LoadingDialog loadingDialog) {
if (loadingDialog.isShowing()) {
loadingDialog.cancel();
}
}
/**
* 设置titleBar
*
* @param context
*/
public void initTitleBar(Activity context, TextView tv, int stringId) {
ExitApplication.getInstance().addActivity(context);
tv.setText(context.getResources().getString(stringId));
}
/**
* 检查网络连接
*
* @param context
*/
public boolean checkNetCon(Context context) {
if(!NetUtils.isConnected(context)){
// ((Activity)context).showNoticeDialog(context, "请检查您的网络是否可用!");
ToastUtils.showShort(context, "请检查您的网络是否可用!");
return false;
}
return true;
}
/**
* @Description: 显示提示对话框
* @param: @param noticeDialog
* @param: @param msg
* @param: @param onClickListener
* @return: void
* @throws
* @author heliang
* @Date 2015-6-5 上午9:31:36
*/
public void showNoticeDialog(final Context context, final NoticeDialog noticeDialog, String noticeMsg, final boolean needFinish)
{
if (!noticeDialog.isShowing())
{
noticeDialog.show();
TextView tv_noticeContent = (TextView) noticeDialog.findViewById(R.id.tv_notice_content);
Button btn_dialog_sure = (Button) noticeDialog.findViewById(R.id.btn_dialog_sure);
tv_noticeContent.setText(noticeMsg);
btn_dialog_sure.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
noticeDialog.cancel();
if (needFinish)
{
Activity activity = (Activity) context;
activity.finish();
activity.overridePendingTransition(R.anim.default_translate_in_from_left, R.anim.defaut_translate_out_to_right);
}
}
});
}
}
public void showNoticeDialog(final Context context, final NoticeDialog noticeDialog, String noticeMsg)
{
if (!noticeDialog.isShowing())
{
noticeDialog.show();
TextView tv_noticeContent = (TextView) noticeDialog.findViewById(R.id.tv_notice_content);
Button btn_dialog_sure = (Button) noticeDialog.findViewById(R.id.btn_dialog_sure);
tv_noticeContent.setText(noticeMsg);
btn_dialog_sure.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
noticeDialog.cancel();
}
});
}
}
public void showNoticeDialog(final Context context, final NoticeDialog noticeDialog, String noticeMsg, final Intent intent)
{
if (!noticeDialog.isShowing())
{
noticeDialog.show();
TextView tv_noticeContent = (TextView) noticeDialog.findViewById(R.id.tv_notice_content);
Button btn_dialog_sure = (Button) noticeDialog.findViewById(R.id.btn_dialog_sure);
tv_noticeContent.setText(noticeMsg);
btn_dialog_sure.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
noticeDialog.cancel();
Activity activity = (Activity)context;
activity.finish();
activity.startActivity(intent);
activity.overridePendingTransition(R.anim.default_translate_in_from_right, R.anim.defaut_translate_out_to_left);
}
});
}
}
}
|
package com.pacck.safety.model;
import java.time.LocalDate;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
@Entity
@Table(name="funcionario_tbl")
public class Funcionario {
@Id
private int idFuncionario;
private String nome;
private String sobrenome;
private String email;
private String tipo;
private String cidade;
private String estado;
private String zona;
private int telefone;
@Column(name="data_nasc")
private LocalDate dataNascimento;
@JsonIgnore
@ManyToMany(mappedBy="funcionario", fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
private List<Servico> servico;
public int getIdFuncionario() {
return idFuncionario;
}
public void setIdFuncionario(int idFuncionario) {
this.idFuncionario = idFuncionario;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getSobrenome() {
return sobrenome;
}
public void setSobrenome(String sobrenome) {
this.sobrenome = sobrenome;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
public String getCidade() {
return cidade;
}
public void setCidade(String cidade) {
this.cidade = cidade;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
public String getZona() {
return zona;
}
public void setZona(String zona) {
this.zona = zona;
}
public int getTelefone() {
return telefone;
}
public void setTelefone(int telefone) {
this.telefone = telefone;
}
public LocalDate getDataNascimento() {
return dataNascimento;
}
public void setDataNascimento(LocalDate dataNascimento) {
this.dataNascimento = dataNascimento;
}
public List<Servico> getServico() {
return servico;
}
public void setServico(List<Servico> servico) {
this.servico = servico;
}
}
|
package controlador;
import dao.CharUsuarioImpl;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import org.primefaces.model.charts.ChartData;
import org.primefaces.model.charts.pie.PieChartDataSet;
import org.primefaces.model.charts.pie.PieChartModel;
@Named(value = "barcharC")
@SessionScoped
public class BarcharC implements Serializable {
private List<Number> lstpersona;
private CharUsuarioImpl dao = new CharUsuarioImpl();
private PieChartModel pieModel = new PieChartModel();
public BarcharC() {
}
@PostConstruct
public void init() {
try {
lstpersona = dao.graficoPer();
createPieModel();
} catch (Exception e) {
System.out.println(e);
}
}
private void createPieModel() throws Exception{
ChartData data = new ChartData();
PieChartDataSet dataSet = new PieChartDataSet();
List<Number> values = lstpersona;
dataSet.setData(values);
List<String> bgColors = new ArrayList<>();
bgColors.add("rgb(255, 99, 132)");
bgColors.add("rgb(54, 162, 235)");
dataSet.setBackgroundColor(bgColors);
data.addChartDataSet(dataSet);
List<String> labels = new ArrayList<>();
labels.add("Hombres");
labels.add("Mujeres");
data.setLabels(labels);
pieModel.setData(data);
}
public PieChartModel getPieModel() {
return pieModel;
}
public void setPieModel(PieChartModel pieModel) {
this.pieModel = pieModel;
}
public List<Number> getLstpersona() {
return lstpersona;
}
public void setLstpersona(List<Number> lstpersona) {
this.lstpersona = lstpersona;
}
public CharUsuarioImpl getDao() {
return dao;
}
public void setDao(CharUsuarioImpl dao) {
this.dao = dao;
}
}
|
package gameVoiceHandler.intents.handlers;
import com.amazon.speech.slu.Intent;
import com.amazon.speech.speechlet.SpeechletResponse;
import gameData.GameDataInstance;
import gameData.StateManager;
import gameVoiceHandler.intents.handlers.Utils.BadIntentUtil;
import gameVoiceHandler.intents.HandlerInterface;
import gameVoiceHandler.intents.handlers.Utils.GameStarterUtil;
import gameVoiceHandler.intents.handlers.Utils.InstructionsUtil;
import gameVoiceHandler.intents.speeches.Speeches;
import gameVoiceHandler.intents.speeches.SpeechesGenerator;
/**
* Created by corentinl on 2/22/16.
*/
public class HandleStartQuickGame implements HandlerInterface {
@Override
public SpeechletResponse handleIntent(Intent intent, GameDataInstance gameDataInstance) {
if (!isIntentExpected(gameDataInstance)) {
return BadIntentUtil.initializationUnexpected();
}
StateManager stateManager = gameDataInstance.getStateManager();
InstructionsUtil.defaultInstructionsRequiredToNoIfQuestionNotAnswered(stateManager);
GameStarterUtil.startQuickGame(gameDataInstance);
String speechOutput = Speeches.QUICK_GAME_LAUNCH + GameStarterUtil.startGameSpeech(stateManager);
String repromptText = Speeches.YOUR_TURN + InstructionsUtil.fireInstructions(stateManager);
stateManager.setLastQuestionAsked(repromptText);
return SpeechesGenerator.newAskResponse(speechOutput, false, repromptText, false);
}
private boolean isIntentExpected(GameDataInstance gameDataInstance) {
return gameDataInstance.getStateManager().isGamesBeingInitialized();
}
}
|
import java.io.*;
import java.util.HashMap;
public class VMWriter {
private FileWriter out = null;
private static HashMap<Command, String> commands;
private static HashMap<Segment, String> segments;
public VMWriter(File output) throws IOException {
out = new FileWriter(output);
commands = new HashMap<Command, String>();
segments = new HashMap<Segment, String>();
initializeCommands();
initializeSegments();
}
public void writePush(Segment type, int index) throws IOException {
out.write("push " + segments.get(type) + " " + index + "\n");
}
public void writePop(Segment type, int index) throws IOException {
out.write("pop " + segments.get(type) + " " + index + "\n");
}
public void writeArithmetic(Command operation) throws IOException {
out.write(commands.get(operation) +"\n");
}
public void writeLabel(String label) throws IOException {
out.write("label " + label + "\n");
}
public void writeGoto(String label) throws IOException {
out.write("goto " + label+ "\n");
}
public void writeIf(String label) throws IOException {
out.write("if-goto " + label+ "\n");
}
public void writeCall(String name, int nArgs) throws IOException {
out.write("call " + name + " " + nArgs + "\n");
}
public void writeFunction(String name, int nLocals) throws IOException {
out.write("function " + name + nLocals + "\n");
}
public void writeReturn() throws IOException {
out.write("return\n");
}
public void writeRaw(String input) throws IOException {
out.write(input + "\n");
}
private void initializeCommands() {
commands.put(Command.ADD, "add");
commands.put(Command.SUB, "sub");
commands.put(Command.EQ, "eq");
commands.put(Command.GT, "gt");
commands.put(Command.AND, "and");
commands.put(Command.OR, "or");
commands.put(Command.LT, "lt");
commands.put(Command.NOT, "not");
commands.put(Command.NEG, "neg");
}
private void initializeSegments() {
segments.put(Segment.ARG, "argument");
segments.put(Segment.LOCAL, "local");
segments.put(Segment.CONST, "constant");
segments.put(Segment.POINTER, "pointer");
segments.put(Segment.THIS, "this");
segments.put(Segment.THAT, "that");
segments.put(Segment.STATIC, "static");
segments.put(Segment.TEMP, "temp");
}
public void close() throws IOException {
out.close();
}
}
enum Segment {
CONST, ARG, LOCAL, STATIC, POINTER, TEMP, THIS, THAT, INVALID, NONE
}
enum Command {
ADD, SUB, EQ, GT, LT, AND, OR, NOT, NEG
}
|
package com.ut.base.dialog;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.view.View;
import com.ut.base.AppManager;
import com.ut.base.R;
import java.util.Objects;
/**
* author : chenjiajun
* time : 2019/1/26
* desc :
*/
public class DialogHelper {
private AlertDialog.Builder sBuilder = null;
private AlertDialog alertDialog;
private boolean isShowing;
private DialogHelper() {
}
private static DialogHelper instance;
public static DialogHelper getInstance() {
if (instance == null) {
synchronized (DialogHelper.class) {
instance = new DialogHelper();
}
}
if (!instance.isShowing()) {
instance.sBuilder = new AlertDialog.Builder(AppManager.getAppManager().currentActivity());
}
return instance;
}
public DialogHelper newDialog() {
instance.isShowing = false;
if(instance.alertDialog != null) {
instance.alertDialog.dismiss();
}
instance.sBuilder = new AlertDialog.Builder(AppManager.getAppManager().currentActivity());
return instance;
}
public DialogHelper setTitle(String title) {
if (!isShowing()) {
sBuilder.setTitle(title);
}
return instance;
}
public DialogHelper setMessage(String message) {
if (!isShowing()) {
sBuilder.setMessage(message);
}
return instance;
}
public DialogHelper setContentView(View contentView) {
if (!isShowing()) {
sBuilder.setView(contentView);
}
return instance;
}
public DialogHelper setPositiveButton(String positiveBtnText, DialogInterface.OnClickListener clickListener) {
if (!isShowing()) {
sBuilder.setPositiveButton(positiveBtnText, clickListener);
}
return instance;
}
public DialogHelper setNegativeButton(String positiveBtnText, DialogInterface.OnClickListener clickListener) {
if (!isShowing()) {
sBuilder.setNegativeButton(positiveBtnText, clickListener);
}
return instance;
}
private boolean isShowing() {
return instance.isShowing;
}
public DialogHelper setCanCancelOutSide(boolean can) {
if (!isShowing()) {
sBuilder.setCancelable(can);
}
return instance;
}
public void show() {
if (instance.isShowing()) {
return;
}
instance.alertDialog = instance.sBuilder.create();
instance.alertDialog.setOnDismissListener(dialog -> {
instance.sBuilder = null;
instance.alertDialog = null;
instance.isShowing = false;
});
instance.alertDialog.show();
instance.isShowing = true;
Objects.requireNonNull(instance.alertDialog.getWindow()).setBackgroundDrawable(instance.alertDialog.getContext().getResources().getDrawable(R.drawable.shape_bg_corner));
}
}
|
package factory.factorymethod.developers;
public class JavaDeveloper implements Developer{
@Override
public void write() {
System.out.println("writes java code");
}
}
|
package com.company.bookmark.entities;
import com.company.bookmark.constants.KidsFriendlyStatus;
public abstract class Bookmark {
private long id;
private String title;
private String profileUrl;
private User kidsFriendlyMarkedUser;
public User getSharedBy() {
return sharedBy;
}
public void setSharedBy(User sharedBy) {
this.sharedBy = sharedBy;
}
private User sharedBy;
public KidsFriendlyStatus getKidFriendlyStatus() {
return kidFriendlyStatus;
}
public void setKidFriendlyStatus(KidsFriendlyStatus kidFriendlyStatus) {
this.kidFriendlyStatus = kidFriendlyStatus;
}
private KidsFriendlyStatus kidFriendlyStatus= KidsFriendlyStatus.UNKNOWN;
@Override
public String toString() {
return "Bookmark{" +
"id=" + id +
", title='" + title + '\'' +
", profileUrl='" + profileUrl + '\'' +
'}';
}
public abstract boolean isKidFriendly();
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getProfileUrl() {
return profileUrl;
}
public void setProfileUrl(String profileUrl) {
this.profileUrl = profileUrl;
}
public User getKidsFriendlyMarkedUser() {
return kidsFriendlyMarkedUser;
}
public void setKidsFriendlyMarkedUser(User kidsFriendlyMarkedUser) {
this.kidsFriendlyMarkedUser = kidsFriendlyMarkedUser;
}
}
|
package com.icanit.app.bmap;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.mapapi.search.MKSearch;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.icanit.app.R;
import com.icanit.app.common.IConstants;
import com.icanit.app.entity.AppCommunity;
import com.icanit.app.util.AppUtil;
/**public class BMapActivity extends MapActivity implements LocationListener {
private BMapManager mapManager;
private MapView map;
private MKSearch search;
private MapController mapController;
private EditText editText;
private ImageButton textDisposer,backButton;
private Button searchConfirmButton;
public GeoPoint centerPoint;
private MKLocationManager locationManager;
private MyLocationOverlay myLocationOverlay;
private TextView textView;
private AppCommunity community;
private CommunityBoundOverlay cbo=new CommunityBoundOverlay();
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.activity_bmap);
init();
initMapNsearch();
bindListeners();
}
private void init() {
mapManager = AppUtil.getMapUtilInstance().getMapManager();
initMapActivity(mapManager);
// locationManager = mapManager.getLocationManager();
map = (MapView) findViewById(R.id.mapView1);
mapController = map.getController();
search = new MKSearch();
editText = (EditText) findViewById(R.id.editText1);
// myLocationOverlay = new MyLocationOverlay(this,map);
// map.getOverlays().add(myLocationOverlay);
map.setBuiltInZoomControls(true);
textDisposer=(ImageButton)findViewById(R.id.imageButton1);
backButton=(ImageButton)findViewById(R.id.imageButton2);
searchConfirmButton=(Button)findViewById(R.id.button1);
textView=(TextView)findViewById(R.id.textView1);
community=(AppCommunity)getIntent().getSerializableExtra(IConstants.COMMUNITY_INFO);
textView.setText(community.commName);
}
private void bindListeners() {
AppUtil.bindBackListener(backButton);
AppUtil.bindSearchTextNtextDisposerNsearchConfirm(editText, textDisposer,searchConfirmButton);
search.init(mapManager, new MyMKSearchListener(map,this,search,cbo));
search.geocode(community.commName,community.cityName );
searchConfirmButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
String text = editText.getText().toString();
if(!AppUtil.isNumber(text)){
Toast.makeText(BMapActivity.this, "无效数值输入", Toast.LENGTH_SHORT).show();return;
}
int distance= Integer.parseInt(text);
cbo.setDistance(distance);
search.poiSearchNearBy("kfc", centerPoint, distance);
}
});
}
private void initMapNsearch() {
}
protected boolean isRouteDisplayed() {
return false;
}
protected void onResume() {
super.onResume();
AppUtil.getMapUtilInstance().startMap(myLocationOverlay, locationManager, this, mapManager);
}
protected void onStop() {
super.onStop();
AppUtil.getMapUtilInstance().stopMap(myLocationOverlay, locationManager, this, mapManager);
}
public void onLocationChanged(Location location) {
if (location != null) {
mapController.setCenter(new GeoPoint(
(int) (location.getLatitude() * 1E6), (int) (location
.getLongitude() * 1E6)));
}
}
@Override
protected void onDestroy() {
super.onDestroy();
try {
AppUtil.getMapUtilInstance().finalize();
} catch (Throwable e) {
e.printStackTrace();
}
}
}*/
|
package BridgePattern08.exercise;
import BridgePattern08.exercise.action.File;
import BridgePattern08.exercise.service.FileImp;
public class Client {
public static void main(String[] args) {
File file = (File) XMLUtil.getBean("file");
FileImp fileImp= (FileImp) XMLUtil.getBean("database");
file.setFileImp(fileImp);
file.transform();
}
}
|
package com.sample.gitprojet.GitSample;
public class TestDemo {
}
|
/**
* The classes in this package represent RDBMS queries, updates, and stored
* procedures as threadsafe, reusable objects. This approach is modeled by JDO,
* although objects returned by queries are of course "disconnected" from the
* database.
*
* <p>This higher-level JDBC abstraction depends on the lower-level
* abstraction in the {@code org.springframework.jdbc.core} package.
* Exceptions thrown are as in the {@code org.springframework.dao} package,
* meaning that code using this package does not need to implement JDBC or
* RDBMS-specific error handling.
*
* <p>This package and related packages are discussed in Chapter 9 of
* <a href="https://www.amazon.com/exec/obidos/tg/detail/-/0764543857/">Expert One-On-One J2EE Design and Development</a>
* by Rod Johnson (Wrox, 2002).
*/
@NonNullApi
@NonNullFields
package org.springframework.jdbc.object;
import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package StaticMethods;
/**
*
* @author rm
*/
public class Mainclass1 {
public static void main(String[]args){
program1 p1=new program1("shady", "cairo");
System.out.println(p1);
System.out.println(program1.value());
}
}
|
// Decompiled by Jad v1.5.7d. Copyright 2000 Pavel Kouznetsov.
// Jad home page: http:// www.geocities.com/SiliconValley/Bridge/8617/jad.html
// Decompiler options: packimports(3)
// Source File Name: HttpMessage.java
package com.ziaan.scorm.multi;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Properties;
// Referenced classes of package com.ziaan.scorm.multi:
// Base64Encoder
public class HttpMessage
{
public HttpMessage(URL url)
{
servlet = null;
headers = null;
servlet = url;
}
public InputStream sendGetMessage()
throws IOException
{
return sendGetMessage(null );
}
public InputStream sendGetMessage(Properties properties)
throws IOException
{
String s = "";
if ( properties != null )
s = "?" + toEncodedString(properties);
URL url = new URL(servlet.toExternalForm() + s);
URLConnection urlconnection = url.openConnection();
urlconnection.setUseCaches(false);
sendHeaders(urlconnection);
return urlconnection.getInputStream();
}
public InputStream sendPostMessage()
throws IOException
{
return sendPostMessage(null );
}
public InputStream sendPostMessage(Properties properties)
throws IOException
{
String s = "";
if ( properties != null )
s = toEncodedString(properties);
URLConnection urlconnection = servlet.openConnection();
urlconnection.setDoInput(true);
urlconnection.setDoOutput(true);
urlconnection.setUseCaches(false);
urlconnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
sendHeaders(urlconnection);
DataOutputStream dataoutputstream = new DataOutputStream(urlconnection.getOutputStream() );
dataoutputstream.writeBytes(s);
dataoutputstream.flush();
dataoutputstream.close();
return urlconnection.getInputStream();
}
public InputStream sendPostMessage(Serializable serializable)
throws IOException
{
URLConnection urlconnection = servlet.openConnection();
urlconnection.setDoInput(true);
urlconnection.setDoOutput(true);
urlconnection.setUseCaches(false);
urlconnection.setRequestProperty("Content-Type", "application/x-java-serialized-object");
sendHeaders(urlconnection);
ObjectOutputStream objectoutputstream = new ObjectOutputStream(urlconnection.getOutputStream() );
objectoutputstream.writeObject(serializable);
objectoutputstream.flush();
objectoutputstream.close();
return urlconnection.getInputStream();
}
public void setHeader(String s, String s1)
{
if ( headers == null )
headers = new Hashtable();
headers.put(s, s1);
}
private void sendHeaders(URLConnection urlconnection)
{
if ( headers != null )
{
String s;
String s1;
for ( Enumeration enumeration = headers.keys(); enumeration.hasMoreElements(); urlconnection.setRequestProperty(s, s1))
{
s = (String)enumeration.nextElement();
s1 = (String)headers.get(s);
}
}
}
public void setCookie(String s, String s1)
{
if ( headers == null )
headers = new Hashtable();
String s2 = (String)headers.get("Cookie");
if ( s2 == null )
setHeader("Cookie", s + "=" + s1);
else
setHeader("Cookie", s2 + "; " + s + "=" + s1);
}
public void setAuthorization(String s, String s1)
{
String s2 = Base64Encoder.encode(s + ":" + s1);
setHeader("Authorization", "Basic " + s2);
}
private String toEncodedString(Properties properties)
{
StringBuffer stringbuffer = new StringBuffer();
for ( Enumeration enumeration = properties.propertyNames(); enumeration.hasMoreElements();)
{
String s = (String)enumeration.nextElement();
String s1 = properties.getProperty(s);
stringbuffer.append(URLEncoder.encode(s) + "=" + URLEncoder.encode(s1));
if ( enumeration.hasMoreElements() )
stringbuffer.append("&");
}
return stringbuffer.toString();
}
URL servlet;
Hashtable headers;
}
|
package com.stone.framework.bean;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import java.lang.reflect.Method;
public class Handler {
private Class<?> controllerClass;
private Method actionMethod;
public Handler (Class<?> controllerClass, Method actionMethod) {
this.controllerClass = controllerClass;
this.actionMethod = actionMethod;
}
public Class<?> getControllerClass() {
return controllerClass;
}
public void setControllerClass(Class<?> controllerClass) {
this.controllerClass = controllerClass;
}
public Method getActionMethod() {
return actionMethod;
}
public void setActionMethod(Method actionMethod) {
this.actionMethod = actionMethod;
}
@Override
public boolean equals(Object o) {
return EqualsBuilder.reflectionEquals(this, o);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
}
|
package gromcode.main.lesson10.homework10_1;
import java.util.Date;
public class Demo {
public static void main(String[] args) {
testElectronicsOrder();
testFurnitureOrder();
/*Customer customer1 = new Customer("Альона", "Одесса", "Женский");
Customer customer2 = new Customer("Михаил", "Буча", "Мужской");
Customer customer3 = new Customer("Test", "Полтава", "Мужской");
Customer customer4 = new Customer("Анна", "Киев", "Женский");
ElectronicsOrder eOrder1 = new ElectronicsOrder("Пылесос", new Date(), "Киев", "Одесса", 4500, customer1, 12);
eOrder1.validateOrder();
eOrder1.calculatePrice();
eOrder1.confirmShipping();
ElectronicsOrder eOrder2 = new ElectronicsOrder("Флешка", new Date(), "Одесса", "Буча", 300, customer2, 3);
eOrder2.validateOrder();
eOrder2.calculatePrice();
eOrder2.confirmShipping();
FurnitureOrder fOrder1 = new FurnitureOrder("Шторы", new Date(), "Полтава", "Киев", 1000, customer3, "Str99734");
fOrder1.validateOrder();
fOrder1.calculatePrice();
fOrder1.confirmShipping();
FurnitureOrder fOrder2 = new FurnitureOrder("Ковер", new Date(), "Харьков", "Одесса", 2100, customer4, "453rfdtg");
fOrder2.validateOrder();
fOrder2.calculatePrice();
fOrder2.confirmShipping();*/
/*Customer customer7 = new Customer("Альона", "Одесса", "Женский");
FurnitureOrder eOrder7 = new FurnitureOrder("Пылесос", new Date(), "xcvfxc", "Бровары", 1001, customer7, "fdgd");
eOrder7.validateOrder();
eOrder7.calculatePrice();
System.out.println(eOrder7.getDateConfirmed());
System.out.println(eOrder7.getTotalPrice());*/
}
static void testElectronicsOrder(){
{
//validateOrder city not in list
System.out.print("testElectronicsOrder - validateOrder - city not in list: ");
Customer customer = new Customer("Альона", "Одесса", "Женский");
Order eOrder = new ElectronicsOrder("Пылесос", new Date(), "Житомир", "Одесса", 4500, customer, 12);
eOrder.validateOrder();
System.out.println(eOrder.getDateConfirmed() == null ? "\tOk" : "\tFAIL!");
}
{
//validateOrder cities are null
System.out.print("testElectronicsOrder - validateOrder - cities are null: ");
Customer customer = new Customer("Альона", "Одесса", "Женский");
Order eOrder = new ElectronicsOrder("Пылесос", new Date(), null, null, 4500, customer, 12);
eOrder.validateOrder();
System.out.println(eOrder.getDateConfirmed() == null ? "\tOk" : "\tFAIL!");
}
{
//validateOrder customer is null
System.out.print("testElectronicsOrder - validateOrder - customer is null: ");
Order eOrder = new ElectronicsOrder("Пылесос", new Date(), "Одесса", "Киев", 4500, null, 12);
eOrder.validateOrder();
System.out.println(eOrder.getDateConfirmed() == null ? "\tOk" : "\tFAIL!");
}
{
//validateOrder price < 100
System.out.print("testElectronicsOrder - validateOrder - price < 100: ");
Customer customer = new Customer("Альона", "Одесса", "Женский");
Order eOrder = new ElectronicsOrder("Пылесос", new Date(), "Одесса", "Киев", 50, customer, 12);
eOrder.validateOrder();
System.out.println(eOrder.getDateConfirmed() == null ? "\tOk" : "\tFAIL!");
}
{
//validateOrder gender = m
System.out.print("testElectronicsOrder - validateOrder - gender = m: ");
Customer customer = new Customer("Саня", "Киев", "Мужской");
Order eOrder = new ElectronicsOrder("Пылесос", new Date(), "Одесса", "Киев", 50, customer, 12);
eOrder.validateOrder();
System.out.println(eOrder.getDateConfirmed() == null ? "\tOk" : "\tFAIL!");
}
{
//calculatePrice toCity is Kiev or Odessa
System.out.print("testElectronicsOrder - calculatePrice - price < 0: ");
Customer customer = new Customer("Альона", "Одесса", "Женский");
String[] cities = {"Киев","Одесса"};
boolean check = false;
for(String c : cities){
Order eOrder = new ElectronicsOrder("Пылесос", new Date(), "Ужгород", c, 150, customer, 12);
eOrder.calculatePrice();
if(eOrder.getTotalPrice() == 165)
check = true;
}
System.out.println(check ? "\tOk" : "\tFAIL!");
}
{
//calculatePrice toCity is not Kiev or Odessa
System.out.print("testElectronicsOrder - calculatePrice - price < 0: ");
Customer customer = new Customer("Альона", "Одесса", "Женский");
Order eOrder = new ElectronicsOrder("Пылесос", new Date(), "Ужгород", "Ужгород", 150, customer, 12);
eOrder.calculatePrice();
System.out.println(eOrder.getTotalPrice() == 172.5 ? "\tOk" : "\tFAIL!");
}
{
//calculatePrice price < 0
System.out.print("testElectronicsOrder - calculatePrice - price < 0: ");
Customer customer = new Customer("Альона", "Одесса", "Женский");
Order eOrder = new ElectronicsOrder("Пылесос", new Date(), "Ужгород", "Ужгород", -500, customer, 12);
eOrder.calculatePrice();
System.out.println(eOrder.getTotalPrice() == 0 ? "\tOk" : "\tFAIL!");
}
{
//calculatePrice shipment for price > 1000
System.out.print("testElectronicsOrder - calculatePrice - shipment for price > 1000: ");
Customer customer = new Customer("Альона", "Одесса", "Женский");
Order eOrder = new ElectronicsOrder("Пылесос", new Date(), "Ужгород", "Ужгород", 2000, customer, 12);
eOrder.calculatePrice();
System.out.println(eOrder.getTotalPrice() == 2185.0 ? "\tOk" : "\tFAIL!");
}
}
static void testFurnitureOrder(){
{
//validateOrder city not in list
System.out.print("testFurnitureOrder - validateOrder - city not in list: ");
Customer customer = new Customer("Альона", "Одесса", "Женский");
Order eOrder = new FurnitureOrder("Ковер", new Date(), "Харьков", "Одесса", 2100, customer, "453rfdtg");
eOrder.validateOrder();
System.out.println(eOrder.getDateConfirmed() == null ? "\tOk" : "\tFAIL!");
}
{
//validateOrder cities are null
System.out.print("testFurnitureOrder - validateOrder - cities are null: ");
Customer customer = new Customer("Альона", "Одесса", "Женский");
Order eOrder = new FurnitureOrder("Ковер", new Date(), "Киев", null, 2100, customer, "453rfdtg");
eOrder.validateOrder();
System.out.println(eOrder.getDateConfirmed() == null ? "\tOk" : "\tFAIL!");
}
{
//validateOrder customer id null
System.out.print("testFurnitureOrder - validateOrder - customer id null: ");
Order eOrder = new FurnitureOrder("Ковер", new Date(), "Харьков", "Одесса", 2100, null, "453rfdtg");
eOrder.validateOrder();
System.out.println(eOrder.getDateConfirmed() == null ? "\tOk" : "\tFAIL!");
}
{
//validateOrder price < 500
System.out.print("testFurnitureOrder - validateOrder - price < 500: ");
Customer customer = new Customer("Альона", "Одесса", "Женский");
Order eOrder = new FurnitureOrder("Ковер", new Date(), "Киев", "Харьков", 100, customer, "453rfdtg");
eOrder.validateOrder();
System.out.println(eOrder.getDateConfirmed() == null ? "\tOk" : "\tFAIL!");
}
{
//validateOrder name = "Тест"
System.out.print("testFurnitureOrder - validateOrder - name = \"Тест\": ");
Customer customer = new Customer("Тест", "Одесса", "Женский");
Order eOrder = new FurnitureOrder("Ковер", new Date(), "Киев", "Харьков", 8000, customer, "453rfdtg");
eOrder.validateOrder();
System.out.println(eOrder.getDateConfirmed() == null ? "\tOk" : "\tFAIL!");
}
{
//calculatePrice shipment for price >= 5000
System.out.print("testFurnitureOrder - calculatePrice - shipment for price > 5000: ");
Customer customer = new Customer("Альона", "Одесса", "Женский");
Order eOrder = new FurnitureOrder("Ковер", new Date(), "Киев", "Харьков", 8000, customer, "453rfdtg");
eOrder.calculatePrice();
System.out.println(eOrder.getTotalPrice() == 8160.0 ? "\tOk" : "\tFAIL!");
}
{
//calculatePrice shipment for price < 5000
System.out.print("testFurnitureOrder - calculatePrice - shipment for price > 5000: ");
Customer customer = new Customer("Альона", "Одесса", "Женский");
Order eOrder = new FurnitureOrder("Ковер", new Date(), "Киев", "Харьков", 3000, customer, "453rfdtg");
eOrder.calculatePrice();
System.out.println(eOrder.getTotalPrice() == 3150.0 ? "\tOk" : "\tFAIL!");
}
}
}
|
package com.playbox.niranjani.sandboxapp;
class ActivityTestRule<T> {
}
|
package io.projekat.predmet;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Transient;
@Entity
public class Predmet {
@Id
private String id;
private String ime;
@OneToMany
private List<Smer> smerovi;
@OneToMany
//@Column
//@ElementCollection(targetClass=Profesor.class)
//private List<Integer> countries;
private List<Profesor> profesori;
public Predmet(String ID,String predmet,List<Smer> smerovi2,List<Profesor> profesori){
this.ime = predmet;
this.id = ID;
this.smerovi = smerovi2;
this.profesori = profesori;
}
public Predmet()
{
}
public Predmet(String id)
{
this.id = id;
}
public String getIme() {
return ime;
}
public void setIme(String predmet) {
this.ime = predmet;
}
public List<Profesor> getProfesori() {
return profesori;
}
public void setProfesori(List<Profesor> profesori) {
this.profesori = profesori;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public List<Smer> getSmerovi() {
return smerovi;
}
public void setSmerovi(List<Smer> smerovi) {
this.smerovi = smerovi;
}
}
|
package com.test;
/**
* https://leetcode.com/problems/longest-increasing-subsequence/
*
* Given an unsorted array of integers, find the length of longest increasing
* subsequence.
*
* Example:
*
* Input: [10,9,2,5,3,7,101,18] Output: 4 Explanation: The longest increasing
* subsequence is [2,3,7,101], therefore the length is 4.
*
* @author yline
*
*/
public class SolutionA {
public int lengthOfLIS(int[] nums) {
if (null == nums || nums.length == 0) {
return 0;
}
int[] resultArray = new int[nums.length];
resultArray[0] = 1;
for (int k = 1; k < nums.length; k++) {
int temp = 1;
for (int i = k - 1; i >= 0; i--) {
if (nums[k] > nums[i]) {
temp = Math.max(temp, resultArray[i] + 1);
}
}
resultArray[k] = temp;
}
int max = 1;
for (int i = 0; i < resultArray.length; i++) {
max = Math.max(resultArray[i], max);
}
return max;
}
}
|
/**
* Created with IntelliJ IDEA.
* User: dexctor
* Date: 12-11-15
* Time: 上午9:38
* To change this template use File | Settings | File Templates.
*/
public class Algs4Test3 {
public static void main(String[] args)
{
double sum = 0.0;
int cnt = 0;
while (!StdIn.isEmpty())
{
sum += StdIn.readDouble();
cnt++;
}
double avg = sum / cnt;
StdOut.printf("Average is %.5f\n", avg);
}
}
|
package com.liuzhihang.doc.view.config;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.project.Project;
import com.intellij.util.xmlb.XmlSerializerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* DocView 的标签设置
*
* @author liuzhihang
* @date 2020/11/22 13:51
*/
@State(name = "TagsSettingsComment", storages = {@Storage("DocViewTagsSettings.xml")})
public class TagsSettings implements PersistentStateComponent<TagsSettings> {
private String name = "docName";
private String required = "required";
public static TagsSettings getInstance(@NotNull Project project) {
return ServiceManager.getService(project, TagsSettings.class);
}
@Nullable
@Override
public TagsSettings getState() {
return this;
}
@Override
public void loadState(@NotNull TagsSettings state) {
XmlSerializerUtil.copyBean(state, this);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRequired() {
return required;
}
public void setRequired(String required) {
this.required = required;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.davivienda.multifuncional.cuadremulticifras.formato;
/**
* TituloLogGeneral - 15/09/2008
* @author AA.Garcia
* Davivienda 2008
*/
public class TituloInformeAyerMulti {
public static String[] tituloHoja ;
static{
tituloHoja = new String[2] ;
tituloHoja[0] = "Informe Ayer Multifuncionales" ;
tituloHoja[1] = com.davivienda.utilidades.conversion.Fecha.aCadena(com.davivienda.utilidades.conversion.Fecha.getCalendarHoy(), com.davivienda.utilidades.conversion.FormatoFecha.FECHA_HORA);
}
/**
* Titulos de las columnas
*/
public static String[] tituloColumnas = {"ATM","OFICINA", "PROV.CAJA", "DISMI.PROV", "EF.RECIBIDO", "EF.PAGADO","EF.CAJA","EF.REC.HOR.ANT","EF.REC.HOR.SIG"};
}
|
package fr.epsi.service;
import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.UserTransaction;
import fr.epsi.entite.Article;
import fr.epsi.entite.Facture;
@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class FactureServiceImpl implements FactureService {
@PersistenceContext
private EntityManager em;
public void createFacture(Facture p) {
em.persist(p.getPrix());
em.persist(p.getDate());
em.persist(p.getNom());
}
}
|
package de.varylab.discreteconformal.heds.adapter;
import java.util.HashMap;
import java.util.Map;
import de.jreality.math.Pn;
import de.jtem.halfedgetools.adapter.AbstractTypedAdapter;
import de.jtem.halfedgetools.adapter.AdapterSet;
import de.varylab.discreteconformal.heds.CoEdge;
import de.varylab.discreteconformal.heds.CoFace;
import de.varylab.discreteconformal.heds.CoVertex;
public class MetricErrorAdapter extends AbstractTypedAdapter<CoVertex, CoEdge, CoFace, Double> {
private Map<CoEdge, Double>
lengthMap = new HashMap<CoEdge, Double>();
private int
signature = Pn.EUCLIDEAN;
public MetricErrorAdapter() {
super(null, CoEdge.class, null, Double.class, true, false);
}
public void setLengthMap(Map<CoEdge, Double> lengthMap) {
this.lengthMap = lengthMap;
}
public void setSignature(int signature) {
this.signature = signature;
}
@Override
public Double getEdgeValue(CoEdge e, AdapterSet a) {
double d = lengthMap.get(e) == null ? 0.0 : lengthMap.get(e);
double[] s = e.getStartVertex().T;
double[] t = e.getTargetVertex().T;
double rd = Pn.distanceBetween(s, t, signature);
return Math.abs(d - rd);
}
}
|
package com.ecej.nove.rabbit.common;
public enum TypeModel {
PRODUCER, CONSUMER;
}
|
package com.jrz.bettingsite.event;
import com.jrz.bettingsite.team.Team;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
public interface EventService {
Iterable<Event> findAll();
Optional<Event> findById(Long id);
void saveEvent(Event event);
void updateEvent(Event event, Long id);
void deleteEvent(Event event);
}
|
package com.nisum.webflux.controller;
import com.nisum.webflux.config.KafkaServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SampleController {
@Autowired
KafkaServer kafkaServer;
@GetMapping("/send")
public String producer(@RequestParam String msg) {
System.out.println("into Controller");
return kafkaServer.send(msg);
}
}
|
package javaDay5;
interface InterfaceOne{
default void printMessage(String s){
System.out.println("First Interface " +s);
}
}
interface InterfaceTwo{
default void displayMessage(String s){
System.out.println("Second Interface " +s);
}
}
public class Program8 implements InterfaceOne, InterfaceTwo {
public static void main(String[] args) {
Program8 obj = new Program8();
obj.printMessage("Hello");
obj.displayMessage("Hello");
}
}
|
package com.robin.springbootlearn.app.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.text.SimpleDateFormat;
/**
* @author silkNets
* @program springboot-learn
* @description Jackson 配置
* @createDate 2020-02-27 09:25
*/
@Configuration
public class JacksonConf {
// 自定义序列化的形式,代替默认的
@Bean
public ObjectMapper getObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
return objectMapper;
}
} |
package commands;
import java.util.ArrayList;
import observer.Observable;
import observer.Observer;
public class TrainingGuy implements Observable {
private String position;
private ArrayList<Observer> observers;
public TrainingGuy()
{
this.observers = new ArrayList<Observer>();
this.position = "standing";
}
public String getPosition()
{
return this.position;
}
public void setStateToStanding() {
System.out.println("Training guy is standing.");
this.position = "standing";
this.notifyObservers();
}
public void setStateToLying() {
System.out.println("Training guy is lying down.");
this.position = "lying";
this.notifyObservers();
}
@Override
public void attach(Observer observer) {
this.observers.add(observer);
}
@Override
public void detach(Observer observer) {
this.observers.remove(observer);
}
@Override
public void notifyObservers() {
for (Observer observer : this.observers)
{
observer.update();
}
}
}
|
package com.example.myapplication;
import android.content.Intent;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.tb1);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.dl1);
NavigationView navigationView = findViewById(R.id.nv1);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
}
@Override
public boolean onNavigationItemSelected(MenuItem menuItem)
{
int id = menuItem.getItemId();
if (id == R.id.a) {
Intent intent=new Intent(this,Main2Activity.class);
startActivity(intent);
}
DrawerLayout drawer = findViewById(R.id.dl1);
drawer.closeDrawer(GravityCompat.START);
return true;
}
} |
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.target;
import org.junit.jupiter.api.Test;
import org.springframework.aop.TargetSource;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.testfixture.beans.SerializablePerson;
import org.springframework.beans.testfixture.beans.TestBean;
import org.springframework.core.testfixture.io.SerializationTestUtils;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Unit tests relating to the abstract {@link AbstractPrototypeBasedTargetSource}
* and not subclasses.
*
* @author Rod Johnson
* @author Chris Beams
*/
public class PrototypeBasedTargetSourceTests {
@Test
public void testSerializability() throws Exception {
MutablePropertyValues tsPvs = new MutablePropertyValues();
tsPvs.add("targetBeanName", "person");
RootBeanDefinition tsBd = new RootBeanDefinition(TestTargetSource.class);
tsBd.setPropertyValues(tsPvs);
MutablePropertyValues pvs = new MutablePropertyValues();
RootBeanDefinition bd = new RootBeanDefinition(SerializablePerson.class);
bd.setPropertyValues(pvs);
bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
bf.registerBeanDefinition("ts", tsBd);
bf.registerBeanDefinition("person", bd);
TestTargetSource cpts = (TestTargetSource) bf.getBean("ts");
TargetSource serialized = SerializationTestUtils.serializeAndDeserialize(cpts);
boolean condition = serialized instanceof SingletonTargetSource;
assertThat(condition).as("Changed to SingletonTargetSource on deserialization").isTrue();
SingletonTargetSource sts = (SingletonTargetSource) serialized;
assertThat(sts.getTarget()).isNotNull();
}
private static class TestTargetSource extends AbstractPrototypeBasedTargetSource {
private static final long serialVersionUID = 1L;
/**
* Nonserializable test field to check that subclass
* state can't prevent serialization from working
*/
@SuppressWarnings({"unused", "serial"})
private TestBean thisFieldIsNotSerializable = new TestBean();
@Override
public Object getTarget() throws Exception {
return newPrototypeInstance();
}
@Override
public void releaseTarget(Object target) throws Exception {
// Do nothing
}
}
}
|
package com.ai.platform.agent.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class ConfigInit {
public static Logger logger = LogManager.getLogger(ConfigInit.class);
public static Map<String, String> serverConstant = new HashMap<String, String>();
static {
Properties p = new Properties();
try {
BufferedReader bf = new BufferedReader(new InputStreamReader(
ConfigInit.class.getClassLoader().getResourceAsStream(AgentConstant.AGENT_CONFIG_FILE_NAME),
"UTF-8"));
p.load(bf);
String keyStr = null;
for (Entry<Object, Object> tmpEntry : p.entrySet()) {
if(((String)tmpEntry.getKey()).startsWith("netty")){
keyStr = ((String)tmpEntry.getKey()).substring("netty.".length());
serverConstant.put(keyStr, (String) tmpEntry.getValue());
logger.info("init key[{}] value {{}}", (String) keyStr, (String) tmpEntry.getValue());
}else if(((String)tmpEntry.getKey()).startsWith("client")){
keyStr = ((String)tmpEntry.getKey()).substring("client.".length());
serverConstant.put(keyStr, (String) tmpEntry.getValue());
logger.info("init key[{}] value {{}}", (String) keyStr, (String) tmpEntry.getValue());
}else if(((String)tmpEntry.getKey()).startsWith("jetty")){
keyStr = ((String)tmpEntry.getKey()).substring("jetty.".length());
serverConstant.put(keyStr, (String) tmpEntry.getValue());
logger.info("init key[{}] value {{}}", (String) keyStr, (String) tmpEntry.getValue());
}else if(((String)tmpEntry.getKey()).startsWith("web")){
keyStr = ((String)tmpEntry.getKey()).substring("web.".length());
serverConstant.put(keyStr, (String) tmpEntry.getValue());
logger.info("init key[{}] value {{}}", (String) keyStr, (String) tmpEntry.getValue());
}
}
} catch (IOException e) {
logger.error("{} config properties read exception !!!");
e.printStackTrace();
}
}
public static void main(String[] args) {
System.out.println(ConfigInit.serverConstant);
}
}
|
package com.show.comm.utils;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
/**
* ID工具
*
* @author heyuhua
* @date 2017年6月22日
*/
public class IdUtils {
private IdUtils() {
}
/** 时间匹配表达式 - yyyyMM */
public static final String REG_MONTH_S = "20[0-9][0-9](([0][1-9])|([1][0-2]))";
/** 时间匹配表达式 - yyyyMMdd */
public static final String REG_DATE_S = "20[0-9][0-9](([0][1-9])|([1][0-2]))(([0][1-9])|([1-2][0-9])|(3[0,1]))";
/** 时间匹配表达式 - yyyyMMddHHmmss */
public static final String REG_TIME_S = "20[0-9][0-9](([0][1-9])|([1][0-2]))(([0][1-9])|([1-2][0-9])|(3[0,1]))(([0-1][0-9])|([2][0-3]))[0-5][0-9][0-5][0-9]";
/**
* 获取UUID
*
* @return 36位UUID字符串
*/
public static String uuid() {
return UUID.randomUUID().toString();
}
/**
* 根据当前时间生成20位ID
*
* @return yyyyMMddHHmmssSSS+ranNum(3)
*/
public static String id20() {
return msid(20, new Date());
}
/**
* 根据时间生成20位ID
*
* @param date
* 指定时间
* @return yyyyMMddHHmmssSSS+ranNum(3)
*/
public static String id20(Date date) {
return msid(20, date);
}
/**
* 根据当前时间生成32位ID
*
* @return yyyyMMddHHmmssSSS+ranNum(15)
*/
public static String id32() {
return msid(32, new Date());
}
/**
* 根据时间生成32位ID
*
* @param date
* 指定时间
* @return yyyyMMddHHmmssSSS+ranNum(15)
*/
public static String id32(Date date) {
return msid(32, date);
}
/**
* 根据8位前缀生成32位ID
*
* @param p8
* 8位长度前缀(长度大于8时将抛出runtime异常)
* @return p8+yyyyMMddHHmmssSSS+ranNum(7)
*/
public static String p8(String p8) {
String p = StringUtils.padZeroToLeft(p8, 8);
if (p.length() != 8) {
throw new RuntimeException("length of p8 out of 8.");
}
StringBuilder sb = new StringBuilder();
sb.append(p);
sb.append(msid(24, null));
return sb.toString();
}
/**
* 是否根据8位前缀生成32位ID
*
* @param id
* ID
* @return true:符合P8规则
*/
public static boolean isP8(String id) {
return null != id && id.length() == 32 && id.matches("[0-9]{8}20[0-9]{22}");
}
/**
* 根据4位前缀生成32位ID
*
* @param p4
* 4位长度前缀(长度大于8时将抛出runtime异常)
* @return p4+yyyyMMddHHmmssSSS+ranNum(11)
*/
public static String p4(String p4) {
String p = StringUtils.padZeroToLeft(p4, 4);
if (p.length() != 4) {
throw new RuntimeException("length of p4 out of 4.");
}
StringBuilder sb = new StringBuilder();
sb.append(p);
sb.append(msid(28, null));
return sb.toString();
}
/**
* 是否根据4位前缀生成32位ID
*
* @param id
* ID
* @return true:符合P4规则
*/
public static boolean isP4(String id) {
return null != id && id.length() == 32 && id.matches("[0-9]{4}20[0-9]{26}");
}
/**
* ID 生成 - 按时间生成,yyyyMMddHHmmssSSS(17位)+(len-17)位随机数字
*
* @param len
* 长度,超过17的填充随机数字
* @param date
* 指定时间
* @return 指定长度的数字字符串
*/
private static String msid(int len, Date date) {
StringBuilder id = new StringBuilder();
id.append(DateUtils.DF_TIME_SF.format(null != date ? date : new Date()));
int l = len - 17;
if (l > 0) {
id.append(StringUtils.ranNum(l));
return id.toString();
} else {
return id.substring(0, len);
}
}
/**
* 字符串是否符合id规则
*
* <pre>
* id32、id20、idP4、idP8
* </pre>
*
* @see IdUtils#id32()
* @see IdUtils#id20()
* @param id
* ID
* @return 1: id32() <br/>
* 2: id20()<br/>
* 3: 32位数字(p4、p8)
*/
public static int isId(String id) {
if (null != id) {
int l = id.length();
if (l == 20) {
if (id.matches("20[0-9]{18}")) {
return 2;
}
} else if (l == 32) {
if (id.matches("20[0-9]{30}")) {
return 1;
}
if (id.matches("[0-9]{32}")) {
return 3;
}
}
}
return 0;
}
/**
* 字符串是否符合id20规则
*
* <pre>
* match 20[0-9]{18}
* </pre>
*
* @see #id20()
* @param id
* ID
* @return true:符合id20规则
*/
public static boolean isId20(String id) {
return null != id && id.matches("20[0-9]{18}");
}
/**
* 字符串是否符合id32规则
*
* <pre>
* match 20[0-9]{30}
* </pre>
*
* @see #id32()
* @param id
* ID
* @return true:符合id32规则
*/
public static boolean isId32(String id) {
return null != id && id.matches("20[0-9]{30}");
}
/**
* 基于id32()/id20()生成的id获取时间
*
* @param id
* id
* @return 时间(yyyy-MM-dd HH:mm:ss)/null
*/
public static String idToTime(String id) {
if (null != id && id.length() > 14) {
String s = id.substring(0, 14);
if (s.matches(REG_TIME_S)) {
StringBuilder sb = new StringBuilder(s);
sb.insert(12, ":");
sb.insert(10, ":");
sb.insert(8, " ");
sb.insert(6, "-");
sb.insert(4, "-");
return sb.toString();
}
}
return null;
}
/**
* 基于idP4生成的id获取时间
*
* @param id
* id
* @return 时间(yyyy-MM-dd HH:mm:ss)/null
*/
public static String idToTimeP4(String id) {
if (null != id && id.length() >= 18) {
String s = id.substring(4, 18);
if (s.matches(REG_TIME_S)) {
StringBuilder sb = new StringBuilder(s);
sb.insert(12, ":");
sb.insert(10, ":");
sb.insert(8, " ");
sb.insert(6, "-");
sb.insert(4, "-");
return sb.toString();
}
}
return null;
}
/**
* 基于idP8生成的id获取时间
*
* @param id
* id
* @return 时间(yyyy-MM-dd HH:mm:ss)/null
*/
public static String idToTimeP8(String id) {
if (null != id && id.length() >= 22) {
String s = id.substring(8, 22);
if (s.matches(REG_TIME_S)) {
StringBuilder sb = new StringBuilder(s);
sb.insert(12, ":");
sb.insert(10, ":");
sb.insert(8, " ");
sb.insert(6, "-");
sb.insert(4, "-");
return sb.toString();
}
}
return null;
}
/**
* 根据P4及时间,生成用于对比的ID字符串
*
* @param p4
* P4
* @param time
* 能解析为yyyyMMddHHmmss、yyyyMMddd或者yyyyMM的时间/日期字符串
* @param max
* 是否最大ID
* @return time格式错误:null<br/>
* max true:32位p4及时间最大可能ID值<br/>
* max false:32位p4及时间最小可能ID值
*/
public static String timeToIdP4(String p4, String time, boolean max) {
String s = timeFullS(time, max);
if (null == s) {
return null;
}
StringBuilder sb = new StringBuilder();
sb.append(p4);// 4
sb.append(s);// 14
if (max) {
sb.append("99999999999999");// 14
} else {
sb.append("00000000000000");// 14
}
return sb.toString();
}
/**
* 根据P8及时间,生成用于对比的ID字符串
*
* @param p8
* P8
* @param time
* 能解析为yyyyMMddHHmmss、yyyyMMddd或者yyyyMM的时间/日期字符串
* @param max
* 是否最大ID
* @return time格式错误:null<br/>
* max true:32位p8及时间最大可能ID值<br/>
* max false:32位p8及时间最小可能ID值
*/
public static String timeToIdP8(String p8, String time, boolean max) {
String s = timeFullS(time, max);
if (null == s) {
return null;
}
StringBuilder sb = new StringBuilder();
sb.append(p8);// 8
sb.append(s);// 14
if (max) {
sb.append("9999999999");// 10
} else {
sb.append("0000000000");// 10
}
return sb.toString();
}
/**
* 根据时间生成用于对比的ID字符串
*
* @param time
* 能解析为yyyyMMddHHmmss、yyyyMMddd或者yyyyMM的时间/日期字符串
* @param max
* 是否最大ID
* @return time格式错误:null<br/>
* max true:20位时间最大可能ID值<br/>
* max false:20位时间最小可能ID值
*/
public static String timeToId20(String time, boolean max) {
String s = timeFullS(time, max);
if (null == s) {
return null;
}
StringBuilder sb = new StringBuilder();
sb.append(s);// 14
if (max) {
sb.append("999999");// 6
} else {
sb.append("000000");// 6
}
return sb.toString();
}
/**
* 根据时间生成用于对比的ID字符串
*
* @param time
* 能解析为yyyyMMddHHmmss、yyyyMMddd或者yyyyMM的时间/日期字符串
* @param max
* 是否最大ID
* @return time格式错误:null<br/>
* max true:32位时间最大可能ID值<br/>
* max false:32位时间最小可能ID值
*/
public static String timeToId32(String time, boolean max) {
String s = timeFullS(time, max);
if (null == s) {
return null;
}
StringBuilder sb = new StringBuilder();
sb.append(s);// 14
if (max) {
sb.append("999999999999999999");// 18
} else {
sb.append("000000000000000000");// 18
}
return sb.toString();
}
/** 时间/日期/月份字符串处理为yyyyMMddHHmmss字符串 */
private static String timeFullS(String time, boolean max) {
String s = null;
if (null != time) {
int l = time.length();
if (l == 19) {
s = time.replaceAll("[^0-9]", "");
s = s.matches(REG_TIME_S) ? s : null;
} else if (l == 14) {
s = time.matches(REG_TIME_S) ? time : null;
} else {
if (l == 10) {
s = time.replaceAll("[^0-9]", "");
s = s.matches(REG_DATE_S) ? (s + (max ? "235959" : "000000")) : null;
} else if (l == 8) {
s = time.matches(REG_DATE_S) ? (time + (max ? "235959" : "000000")) : null;
} else if (l == 7) {
s = time.replaceAll("[^0-9]", "");
s = s.matches(REG_MONTH_S) ? (s + (max ? "31235959" : "01000000")) : null;
} else if (l == 6) {
s = time.matches(REG_MONTH_S) ? (time + (max ? "31235959" : "01000000")) : null;
}
}
}
return s;
}
/**
* 字符串组合转为id32集合(id32,id32,...)
*
* @param str
* 字符串组合
* @param p
* P4/P8前缀值||null
* @param distinct
* 是否过滤重复数据
* @return List/null
*/
public static List<String> strTo32s(String str, String p, boolean distinct) {
return strTo32s(str, p, distinct, ",");
}
/**
* 字符串组合转为id32集合
*
* @param str
* 字符串组合
* @param p
* P4/P8前缀值||null
* @param distinct
* 是否过滤重复数据
* @param split
* 分割字符(允许,;)
* @return List/null
*/
public static List<String> strTo32s(String str, String p, boolean distinct, String split) {
if (null != str) {
str = str.replaceAll("[^0-9" + split + "]", "");
String[] rr = str.split(split);
String regex;
int i = null != p ? p.length() : 0;
if (i == 4) {
regex = p + "20[0-9]{26}";
} else if (i == 8) {
regex = p + "20[0-9]{22}";
} else {
regex = "20[0-9]{30}";
}
List<String> ids = new ArrayList<String>();
if (distinct) {
Set<String> set = new LinkedHashSet<>();
for (String s : rr) {
if (s.length() == 32 && s.matches(regex)) {
set.add(s);
}
}
ids.addAll(set);
set.clear();
set = null;
} else {
for (String s : rr) {
if (s.length() == 32 && s.matches(regex)) {
ids.add(s);
}
}
}
if (!ids.isEmpty()) {
return ids;
}
}
return null;
}
}
|
package com.burningfire.designpattern.lessonone;
import java.util.Scanner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* GCD Computation using Euclidian Algorithm
* @author Kristian Josef L. Delos Reyes
*/
public class Gcd
{
private static Scanner scanner;
private static final Logger LOGGER = LoggerFactory.getLogger(Gcd.class);
public static void main( String[] args )
{
// Get input from user
scanner = new Scanner(System.in);
int var1 = scanner.nextInt();
int var2 = scanner.nextInt();
// Solve for GCD
int result = solveGCD(var1, var2);
LOGGER.info("The GCD is: {}", result);
}
/**
*
* @param var1
* @param var2
* @return
*/
private static int solveGCD(int var1, int var2){
// Recursive GCD Computation,
// 1. gets 2 variables
// 2. var2 is place on temp container
// 3. var2 new = var1 % of var2
// 4. var1 = vartemp
// 5. solve until var2 = 0
if (var2 == 0){
return var1;
}
else{
int vartemp = var2;
var2 = var1 % var2;
var1= vartemp;
}
return solveGCD(var1, var2);
}
}
|
package fluxed314.FluXedMod.init.blocks.machines.purifyingfurnace;
import java.util.Map;
import java.util.Map.Entry;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Maps;
import com.google.common.collect.Table;
import fluxed314.FluXedMod.init.BlockInit;
import fluxed314.FluXedMod.init.ItemInit;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
public class PurifyingFurnaceRecipes
{
private static final PurifyingFurnaceRecipes INSTANCE = new PurifyingFurnaceRecipes();
private final Table<ItemStack, ItemStack, ItemStack> smeltingList = HashBasedTable.<ItemStack, ItemStack, ItemStack>create();
private final Map<ItemStack, Float> experienceList = Maps.<ItemStack, Float>newHashMap();
public static PurifyingFurnaceRecipes getInstance()
{
return INSTANCE;
}
private PurifyingFurnaceRecipes()
{
//addPurifyingRecipe(new ItemStack(BlockInit.copper_block), new ItemStack(BlockInit.copper_ore), new ItemStack(Blocks.ACACIA_FENCE), 5.0F);
addPurifyingRecipe(new ItemStack(Blocks.IRON_ORE), new ItemStack(Blocks.IRON_ORE), new ItemStack(Blocks.IRON_ORE), new ItemStack(ItemInit.iron_ingot_pure), 5.0F);
}
public void addPurifyingRecipe(ItemStack input1, ItemStack input2, ItemStack input3, ItemStack result, float experience)
{
if(getPurifyingResult(input1, input2, input3) != ItemStack.EMPTY) return;
this.smeltingList.put(input1, input2, result);
this.experienceList.put(result, Float.valueOf(experience));
}
public ItemStack getPurifyingResult(ItemStack input1, ItemStack input2, ItemStack input3)
{
for(Entry<ItemStack, Map<ItemStack, ItemStack>> entry : this.smeltingList.columnMap().entrySet())
{
if(this.compareItemStacks(input1, (ItemStack)entry.getKey()))
{
for(Entry<ItemStack, ItemStack> ent : entry.getValue().entrySet())
{
if(this.compareItemStacks(input2, (ItemStack)ent.getKey()))
{
//for(Entry<ItemStack, ItemStack> ent2 : entry.getValue().entrySet())
//{
//if(this.compareItemStacks(input3, (ItemStack)ent.getKey()))
//{
return (ItemStack)ent.getValue();
//}
//}
}
}
}
}
return ItemStack.EMPTY;
}
private boolean compareItemStacks(ItemStack stack1, ItemStack stack2)
{
return stack2.getItem() == stack1.getItem() && (stack2.getMetadata() == 32767 || stack2.getMetadata() == stack1.getMetadata());
}
public Table<ItemStack, ItemStack, ItemStack> getDualSmeltingList()
{
return this.smeltingList;
}
public float getPurifyingExperience(ItemStack stack)
{
for (Entry<ItemStack, Float> entry : this.experienceList.entrySet())
{
if(this.compareItemStacks(stack, (ItemStack)entry.getKey()))
{
return ((Float)entry.getValue()).floatValue();
}
}
return 0.0F;
}
}
/*
import java.util.Map;
import java.util.Map.Entry;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Maps;
import com.google.common.collect.Table;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.Mod.Instance;
public class SmeltingFurnaceRecipes
{
private static final SmeltingFurnaceRecipes INSTANCE = new SmeltingFurnaceRecipes();
private final Table<ItemStack, ItemStack, ItemStack> smeltingList = HashBasedTable.<ItemStack, ItemStack, ItemStack>create();
private final Map<ItemStack, Float> experienceList = Maps.<ItemStack, Float>newHashMap();
public static SmeltingFurnaceRecipes getInstance()
{
return INSTANCE;
}
private SmeltingFurnaceRecipes()
{
}
public void addSmeltingRecipes(ItemStack input1, ItemStack input2, ItemStack input3, ItemStack result, float experience)
{
if(getSmeltingResult(input1, input2, input3) != ItemStack.EMPTY)return;
this.smeltingList.put(input1, input2, input3, result);
this.experienceList.put(result, Float.valueOf(experience));
}
public ItemStack getSmeltingResult(ItemStack input1, ItemStack input2, ItemStack input3)
{
for(Entry<ItemStack, Map<ItemStack, ItemStack>> entry : this.smeltingList.columnMap().entrySet())
{
if(this.compareItemStacks(input1, (ItemStack)entry.getKey()))
{
for(Entry<ItemStack, ItemStack> ent : entry.getValue().entrySet())
{
if(this.compareItemStacks(input2, (ItemStack)ent.getKey()))
{
return(ItemStack)ent.getValue();
}
}
}
}
return ItemStack.EMPTY;
}
private boolean compareItemStacks(ItemStack stack1, ItemStack stack2, ItemStack stack3)
{
return stack2.getItem() == stack1.getItem() && (stack2.getMetadata() == 32767 || stack2.getMetadata() == stack1.getMetadata());
}
public Table<ItemStack, ItemStack, ItemStack> getDualSmeltingList()
{
return this.smeltingList;
}
}
*/
|
package com.robin.springboot.demo.java_date;
import org.apache.commons.lang3.StringUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTest {
public static void main(String[] args) {
// String startDateStr = "2018-12-01";
// String endDateStr = "2019-01-01";
// String dealDateStr = "2018-12-14";
// System.out.println(getStartDateStrForRound(startDateStr, endDateStr, dealDateStr));
StringBuilder sb = new StringBuilder();
System.out.println("s");
System.out.println(sb);
System.out.println(sb.toString());
System.out.println(StringUtils.isNotEmpty(sb.toString()));
System.out.println("b");
// System.out.println(getLatestBookTimeForAhead(1, 60));
}
private static void isRang(Date date, Date star) {
}
// 判断日期是否在允许范围内:如果在,返回最早日期;如果不在,返回 null
private static String getStartDateStrForRound(String startDateStr, String endDateStr, String dealDateStr) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Date starDate = sdf.parse(startDateStr);
Date endDate = sdf.parse(endDateStr);
Date dealDate = sdf.parse(dealDateStr);
if (starDate.getTime() <= dealDate.getTime() && dealDate.getTime() < endDate.getTime()) {
return dealDateStr;
} else if (starDate.getTime() > dealDate.getTime()) {
return startDateStr;
} else {
return null;
}
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
private static BookDateDesc getStarDateForAheadTime(Integer aheadTimeType, Integer aheadMinutes) {
BookDateDesc dateDesc = new BookDateDesc();
if (2 == aheadTimeType) {
dateDesc.setType(2);
Date startDate = new Date(new Date().getTime() + aheadMinutes * 60 * 1000);
if (MyDateUtils.getEndOfDay(startDate).getTime() > startDate.getTime()) {
dateDesc.setDateStr(MyDateUtils.formatDate(startDate));
} else {
dateDesc.setDateStr(MyDateUtils.formatDate(MyDateUtils.addDays(startDate, 1)));
}
} else if (3 == aheadTimeType) {
Date currentTime = new Date();
if (currentTime.getTime() + aheadMinutes * 60 * 1000 > MyDateUtils.getEndOfDay(currentTime).getTime()) {
dateDesc.setType(2);
dateDesc.setDateStr(MyDateUtils.formatDate(MyDateUtils.addDays(currentTime, 1)));
} else {
dateDesc.setType(1);
long dateInterval = MyDateUtils.getEndOfDay(currentTime).getTime() - aheadMinutes * 60 * 1000;
String pattern = "HH:mm";
dateDesc.setDateStr(MyDateUtils.formatDate(new Date(dateInterval), pattern));
}
} else {
dateDesc.setType(0);
}
return dateDesc;
}
private static Date getLatestBookTimeForAhead(Integer aheadTimeType, Integer aheadMinutes) {
Date currentTime = new Date();
long gap = aheadMinutes * 60 * 1000;
long oneDay = 24 * 60 * 60 * 1000;
long oneSecond = 1000;
switch (aheadTimeType) {
case 1:
return MyDateUtils.getEndOfDay(currentTime);
case 2:
gap = gap + oneDay;
case 3:
Date tempDate = new Date(currentTime.getTime() + gap);
if (MyDateUtils.getEndOfDay(currentTime).getTime() > tempDate.getTime()) {
return new Date(MyDateUtils.getEndOfDay(currentTime).getTime() + oneSecond - gap);
} else {
return MyDateUtils.getStartOfDay(tempDate);
}
}
return MyDateUtils.getEndOfDay(currentTime);
}
}
|
package com.jxtb.test.entity;
/**
* Created with IntelliJ IDEA.
* User: Administrator
* Date: 17-8-4
* Time: 下午1:59
* 债券上传持仓信息
* 表 : KM_UPLOAD_BOND_POS
*/
public class UploadBondPos {
private String l_id; //guid
private String upload_group; //上传群组ID(保险公司:葡保 MIG 鼎睿 复保 永安【SELECT * FROM SYSROLE WHERE ROLETYPE = '402881ea0b8bf8e3010b8bfd2885000b' AND ISDELETE = 0】)
private String bond_code; //债券代码
private String bond_name; //债券名称
private String code_type; //代码类型:ISIN,TICKER,BLBGID,CUISP,CINS,FIGI,SEDO
private String code_orig; //未转换代码
private String d_line; //截止日期
private String sum_count; //持股总数
private String total_value; //总市值
private String accured_interst; //应计利息
private String cur_type; //币种
private String ent_time;//记录进表时间
private String upd_time;//记录修改时间
private String upload_log_id; //外键关联KM_UPLOAD_POS_LOG的L_ID ,对应UploadPosLog实体类
public String getL_id() {
return l_id;
}
public void setL_id(String l_id) {
this.l_id = l_id;
}
public String getUpload_group() {
return upload_group;
}
public void setUpload_group(String upload_group) {
this.upload_group = upload_group;
}
public String getBond_code() {
return bond_code;
}
public void setBond_code(String bond_code) {
this.bond_code = bond_code;
}
public String getBond_name() {
return bond_name;
}
public void setBond_name(String bond_name) {
this.bond_name = bond_name;
}
public String getCode_type() {
return code_type;
}
public void setCode_type(String code_type) {
this.code_type = code_type;
}
public String getCode_orig() {
return code_orig;
}
public void setCode_orig(String code_orig) {
this.code_orig = code_orig;
}
public String getD_line() {
return d_line;
}
public void setD_line(String d_line) {
this.d_line = d_line;
}
public String getSum_count() {
return sum_count;
}
public void setSum_count(String sum_count) {
this.sum_count = sum_count;
}
public String getTotal_value() {
return total_value;
}
public void setTotal_value(String total_value) {
this.total_value = total_value;
}
public String getAccured_interst() {
return accured_interst;
}
public void setAccured_interst(String accured_interst) {
this.accured_interst = accured_interst;
}
public String getCur_type() {
return cur_type;
}
public void setCur_type(String cur_type) {
this.cur_type = cur_type;
}
public String getEnt_time() {
return ent_time;
}
public void setEnt_time(String ent_time) {
this.ent_time = ent_time;
}
public String getUpd_time() {
return upd_time;
}
public void setUpd_time(String upd_time) {
this.upd_time = upd_time;
}
public String getUpload_log_id() {
return upload_log_id;
}
public void setUpload_log_id(String upload_log_id) {
this.upload_log_id = upload_log_id;
}
} |
/*
* Copyright 2020 WeBank
*
* 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.webank.wedatasphere.schedulis.system.entity;
import com.webank.wedatasphere.schedulis.common.executor.DepartmentGroup;
public class WebankDepartment {
public Long dpId ; //NOT NULL 部门ID
public String dpName; //NOT NULL 英文部门名称
public String dpChName; //NOT NULL 中文部门名称
public Long orgId ; //NOT NULL 室ID
public String orgName ; //NOT NULL 室名称
public String division; //NOT NULL 部门所属事业条线
public Long pid;
private Integer groupId;
private Integer uploadFlag;
private DepartmentGroup departmentGroup;
public WebankDepartment() {
}
public WebankDepartment(Long dpId, String dpName, String dpChName, Long orgId, String orgName, String division, Long pid, Integer uploadFlag) {
this.dpId = dpId;
this.dpName = dpName;
this.dpChName = dpChName;
this.orgId = orgId;
this.orgName = orgName;
this.division = division;
this.pid = pid;
this.uploadFlag = uploadFlag;
}
public WebankDepartment(Long dpId, String dpName, String dpChName, Long orgId, String orgName, String division, Long pid, Integer groupId, Integer uploadFlag) {
this.dpId = dpId;
this.dpName = dpName;
this.dpChName = dpChName;
this.orgId = orgId;
this.orgName = orgName;
this.division = division;
this.pid = pid;
this.groupId = groupId;
this.uploadFlag = uploadFlag;
}
public Integer getGroupId() {
return groupId;
}
public void setGroupId(Integer groupId) {
this.groupId = groupId;
}
public Long getDpId() {
return dpId;
}
public void setDpId(Long dpId) {
this.dpId = dpId;
}
public String getDpName() {
return dpName;
}
public void setDpName(String dpName) {
this.dpName = dpName;
}
public String getDpChName() {
return dpChName;
}
public void setDpChName(String dpChName) {
this.dpChName = dpChName;
}
public Long getOrgId() {
return orgId;
}
public void setOrgId(Long orgId) {
this.orgId = orgId;
}
public String getOrgName() {
return orgName;
}
public void setOrgName(String orgName) {
this.orgName = orgName;
}
public String getDivision() {
return division;
}
public void setDivision(String division) {
this.division = division;
}
public Long getPid() {
return pid;
}
public void setPid(Long pid) {
this.pid = pid;
}
public DepartmentGroup getDepartmentGroup() {
return departmentGroup;
}
public void setDepartmentGroup(DepartmentGroup departmentGroup) {
this.departmentGroup = departmentGroup;
}
public Integer getUploadFlag() {
return uploadFlag;
}
public void setUploadFlag(Integer uploadFlag) {
this.uploadFlag = uploadFlag;
}
@Override
public String toString() {
return "WebankDepartment{" +
"dpId=" + dpId +
", dpName='" + dpName + '\'' +
", dpChName='" + dpChName + '\'' +
", orgId=" + orgId +
", orgName='" + orgName + '\'' +
", division='" + division + '\'' +
", uploadFlag='" + uploadFlag + '\'' +
'}';
}
}
|
/**
* @Title:ResourceServiceImpl.java
* @Package:com.git.cloud.resource.service.impl
* @Description:TODO
* @author LINZI
* @date 2015-1-7 下午04:11:40
* @version V1.0
*/
package com.git.cloud.resource.service.impl;
import java.util.List;
import java.util.Map;
import com.git.cloud.common.exception.RollbackableBizException;
import com.git.cloud.common.support.Pagination;
import com.git.cloud.common.support.PaginationParam;
import com.git.cloud.resource.dao.IResouceDao;
import com.git.cloud.resource.model.po.MachineInfoPo;
import com.git.cloud.resource.model.po.VmInfoPo;
import com.git.cloud.resource.service.IResourceService;
/**
* @ClassName:ResourceServiceImpl
* @Description:TODO
* @author LINZI
* @date 2015-1-7 下午04:11:40
*
*
*/
public class ResourceServiceImpl implements IResourceService {
private IResouceDao resouceDao;
public IResouceDao getResouceDao() {
return resouceDao;
}
public void setResouceDao(IResouceDao resouceDao) {
this.resouceDao = resouceDao;
}
/* (non-Javadoc)
* <p>Title:queryMachineInfoPagination</p>
* <p>Description:</p>
* @param paginationParam
* @return
* @see com.git.cloud.resource.service.ResourceService#queryMachineInfoPagination(com.git.cloud.common.support.PaginationParam)
*/
@Override
public Pagination<MachineInfoPo> queryMachineInfoPagination(PaginationParam paginationParam) {
return resouceDao.queryMachineInfoPagination(paginationParam);
}
/* (non-Javadoc)
* <p>Title:queryVmInfoPagination</p>
* <p>Description:</p>
* @param paginationParam
* @return
* @see com.git.cloud.resource.service.ResourceService#queryVmInfoPagination(com.git.cloud.common.support.PaginationParam)
*/
@Override
public Pagination<VmInfoPo> queryVmInfoPagination(PaginationParam paginationParam) {
return resouceDao.queryVmInfoPagination(paginationParam);
}
/* (non-Javadoc)
* <p>Title:queryCluster</p>
* <p>Description:</p>
* @param id
* @return
* @throws RollbackableBizException
* @see com.git.cloud.resource.service.IResourceService#queryCluster(java.lang.String)
*/
@Override
public List<Map<String, Object>> queryCluster(String id) throws RollbackableBizException {
return resouceDao.queryCluster(id);
}
/* (non-Javadoc)
* <p>Title:queryPool</p>
* <p>Description:</p>
* @param id
* @return
* @throws RollbackableBizException
* @see com.git.cloud.resource.service.IResourceService#queryPool(java.lang.String)
*/
@Override
public List<Map<String, Object>> queryPool(String id) throws RollbackableBizException {
return resouceDao.queryPool(id);
}
/* (non-Javadoc)
* <p>Title:queryDeployUnit</p>
* <p>Description:</p>
* @param id
* @return
* @throws RollbackableBizException
* @see com.git.cloud.resource.service.IResourceService#queryDeployUnit(java.lang.String)
*/
@Override
public List<Map<String, Object>> queryDeployUnit(String id) throws RollbackableBizException {
return resouceDao.queryDeployUnit(id);
}
/* (non-Javadoc)
* <p>Title:queryMachineInfo</p>
* <p>Description:</p>
* @param hostId
* @return
* @throws RollbackableBizException
* @see com.git.cloud.resource.service.IResourceService#queryMachineInfo(java.lang.String)
*/
@Override
public MachineInfoPo queryMachineInfo(String hostId) throws RollbackableBizException {
return resouceDao.queryMachineInfo(hostId);
}
/* (non-Javadoc)
* <p>Title:queryVmInfo</p>
* <p>Description:</p>
* @param vmId
* @return
* @throws RollbackableBizException
* @see com.git.cloud.resource.service.IResourceService#queryVmInfo(java.lang.String)
*/
@Override
public VmInfoPo queryVmInfo(String vmId) throws RollbackableBizException {
return resouceDao.queryVmInfo(vmId);
}
}
|
package com.kavai.zopa.loanmatcher.engine;
import com.google.inject.Inject;
import com.kavai.zopa.loanmatcher.engine.configuration.MaximumLoanAmount;
import com.kavai.zopa.loanmatcher.engine.configuration.MinimumAmountIncrement;
import com.kavai.zopa.loanmatcher.engine.configuration.MinimumLoanAmount;
import com.kavai.zopa.loanmatcher.engine.exception.InputValidationException;
import com.kavai.zopa.loanmatcher.engine.model.LoanInput;
import java.io.File;
public class InputValidator {
private final int minimumLoanAmount;
private final int maximumLoanAmount;
private final int minimumAmountIncrement;
@Inject
public InputValidator(@MinimumLoanAmount int minimumLoanAmount,
@MaximumLoanAmount int maximumLoanAmount,
@MinimumAmountIncrement int minimumAmountIncrement) {
this.minimumLoanAmount = minimumLoanAmount;
this.maximumLoanAmount = maximumLoanAmount;
this.minimumAmountIncrement = minimumAmountIncrement;
}
public void validateInput(LoanInput loanInput) throws InputValidationException {
if (!new File(loanInput.getMarketFilePath()).exists()) {
throw new InputValidationException("The market file does not exists:" + loanInput.getMarketFilePath());
}
if (loanInput.getRequestedAmount() < minimumLoanAmount) {
throw new InputValidationException("The requested amount is too small. The minimum amount is £" + minimumLoanAmount);
}
if (loanInput.getRequestedAmount() > maximumLoanAmount) {
throw new InputValidationException("The requested amount is too large. The maximum amount is £" + maximumLoanAmount);
}
if (loanInput.getRequestedAmount() % minimumAmountIncrement != 0) {
throw new InputValidationException("The requested amount should be a multiplier of £" + minimumAmountIncrement);
}
}
}
|
package com.example.gerenciamentodesalas.model;
import java.math.BigDecimal;
import java.util.Date;
public class Sala {
private final int id;
private final Organizacao idOrganizacao;
private final String nome;
private final int quantidadePessoasSentadas;
private final boolean possuiMultimidia;
private final boolean possuiAC;
private final BigDecimal areaDaSala;
private final String localizacao;
private final Double latitude;
private final Double longitude;
private final boolean ativo;
private final Date dataCriacao;
private final Date dataAlteracao;
private final String urlImagem;
public Sala (int id, Organizacao idOrganizacao, String nome, int quantidadePessoasSentadas, boolean possuiMultimidia, boolean possuiAC, BigDecimal areaDaSala, String localizacao, Double latitude, Double longitude, boolean ativo, Date dataCriacao, Date dataAlteracao, String urlImagem) {
this.id = id;
this.idOrganizacao = idOrganizacao;
this.nome = nome;
this.quantidadePessoasSentadas = quantidadePessoasSentadas;
this.possuiMultimidia = possuiMultimidia;
this.possuiAC = possuiAC;
this.areaDaSala = areaDaSala;
this.localizacao = localizacao;
this.latitude = latitude;
this.longitude = longitude;
this.ativo = ativo;
this.dataCriacao = dataCriacao;
this.dataAlteracao = dataAlteracao;
this.urlImagem = urlImagem;
}
public int getId() {
return id;
}
public Organizacao getIdOrganizacao() {
return idOrganizacao;
}
public String getNome() {
return nome;
}
public int getQuantidadePessoasSentadas() {
return quantidadePessoasSentadas;
}
public boolean isPossuiMultimidia() {
return possuiMultimidia;
}
public boolean isPossuiAC() {
return possuiAC;
}
public BigDecimal getAreaDaSala() {
return areaDaSala;
}
public String getLocalizacao() {
return localizacao;
}
public Double getLatitude() {
return latitude;
}
public Double getLongitude() {
return longitude;
}
public boolean isAtivo() {
return ativo;
}
public Date getDataCriacao() {
return dataCriacao;
}
public Date getDataAlteracao() {
return dataAlteracao;
}
public String getUrlImagem() {
return urlImagem;
}
} |
package View.Alimentazione;
import javax.swing.*;
import java.awt.event.ActionListener;
/**
* La classe IndexProgAlimView contiene attributi e metodi associati al file XML IndexProgAlimView.form
*/
public class IndexProgAlimView {
private JPanel mainPanel;
private JButton combinatoButton;
private JButton manualeButton;
public IndexProgAlimView() {
}
public JPanel getMainPanel() {
return mainPanel;
}
/** Listener associati ad elementi di cui è composto il file XML IndexProgAlimForm.form */
public void addNewProgManButtonListener(ActionListener listener){
manualeButton.addActionListener(listener);
}
public void addNewProgCombButtonListener(ActionListener listener){
combinatoButton.addActionListener(listener);
}
}
|
/**
* Sencha GXT 1.0.0-SNAPSHOT - Sencha for GWT
* Copyright (c) 2006-2018, Sencha Inc.
*
* licensing@sencha.com
* http://www.sencha.com/products/gxt/license/
*
* ================================================================================
* Commercial License
* ================================================================================
* This version of Sencha GXT is licensed commercially and is the appropriate
* option for the vast majority of use cases.
*
* Please see the Sencha GXT Licensing page at:
* http://www.sencha.com/products/gxt/license/
*
* For clarification or additional options, please contact:
* licensing@sencha.com
* ================================================================================
*
*
*
*
*
*
*
*
* ================================================================================
* Disclaimer
* ================================================================================
* THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND
* REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE
* IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY,
* FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE AND
* THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING.
* ================================================================================
*/
package com.sencha.gxt.explorer.client.layout;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.DateCell;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;
import com.sencha.gxt.data.shared.ListStore;
import com.sencha.gxt.examples.resources.client.ExampleStyles;
import com.sencha.gxt.examples.resources.client.TestData;
import com.sencha.gxt.examples.resources.client.model.Stock;
import com.sencha.gxt.examples.resources.client.model.StockProperties;
import com.sencha.gxt.explorer.client.app.ui.ExampleContainer;
import com.sencha.gxt.explorer.client.model.Example.Detail;
import com.sencha.gxt.widget.core.client.Portlet;
import com.sencha.gxt.widget.core.client.button.ToolButton;
import com.sencha.gxt.widget.core.client.container.PortalLayoutContainer;
import com.sencha.gxt.widget.core.client.event.SelectEvent;
import com.sencha.gxt.widget.core.client.event.SelectEvent.SelectHandler;
import com.sencha.gxt.widget.core.client.grid.ColumnConfig;
import com.sencha.gxt.widget.core.client.grid.ColumnModel;
import com.sencha.gxt.widget.core.client.grid.Grid;
import com.sencha.gxt.widget.core.client.tips.QuickTip;
@Detail(
name = "Portal Layout",
category = "Layouts",
icon = "portallayout",
classes = {
Stock.class,
StockProperties.class,
TestData.class
},
minHeight = PortalLayoutContainerExample.MIN_HEIGHT,
minWidth = PortalLayoutContainerExample.MIN_WIDTH,
preferredHeight = PortalLayoutContainerExample.PREFERRED_HEIGHT,
preferredWidth = PortalLayoutContainerExample.PREFERRED_WIDTH
)
public class PortalLayoutContainerExample implements IsWidget, EntryPoint {
protected static final int MIN_HEIGHT = 1;
protected static final int MIN_WIDTH = 1280;
protected static final int PREFERRED_HEIGHT = 1;
protected static final int PREFERRED_WIDTH = 1;
private static final StockProperties properties = GWT.create(StockProperties.class);
private PortalLayoutContainer portal;
@Override
public Widget asWidget() {
if (portal == null) {
Portlet portlet1 = new Portlet();
portlet1.setHeading("Portal Layout — Panel 1 with Grid");
portlet1.add(createGrid());
portlet1.setHeight(250);
configPanel(portlet1);
Portlet portlet2 = new Portlet();
portlet2.setHeading("Portal Layout — Panel 2");
portlet2.add(getBogusText());
configPanel(portlet2);
Portlet portlet3 = new Portlet();
portlet3.setHeading("Portal Layout — Panel 3");
portlet3.add(getBogusText());
configPanel(portlet3);
Portlet portlet4 = new Portlet();
portlet4.setHeading("Portal Layout — Panel 4");
portlet4.add(getBogusText());
configPanel(portlet4);
portal = new PortalLayoutContainer(3);
portal.setSpacing(20);
portal.setColumnWidth(0, .40);
portal.setColumnWidth(1, .30);
portal.setColumnWidth(2, .30);
portal.add(portlet1, 0);
portal.add(portlet2, 0);
portal.add(portlet3, 1);
portal.add(portlet4, 1);
}
return portal;
}
public Widget createGrid() {
final NumberFormat number = NumberFormat.getFormat("0.00");
ColumnConfig<Stock, String> nameCol = new ColumnConfig<Stock, String>(properties.name(), 200, "Company");
ColumnConfig<Stock, String> symbolCol = new ColumnConfig<Stock, String>(properties.symbol(), 75, "Symbol");
ColumnConfig<Stock, Double> lastCol = new ColumnConfig<Stock, Double>(properties.last(), 75, "Last");
ColumnConfig<Stock, Double> changeCol = new ColumnConfig<Stock, Double>(properties.change(), 75, "Change");
ColumnConfig<Stock, Date> lastTransCol = new ColumnConfig<Stock, Date>(properties.lastTrans(), 100, "Last Updated");
changeCol.setCell(new AbstractCell<Double>() {
@Override
public void render(Context context, Double value, SafeHtmlBuilder sb) {
String style = "style='color: " + (value < 0 ? "red" : "green") + "'";
String v = number.format(value);
// The quicktip has to initialized to use the quick tips in this element.
sb.appendHtmlConstant("<span " + style + " qtitle='Change' qtip='" + v + "'>" + v + "</span>");
}
});
lastTransCol.setCell(new DateCell(DateTimeFormat.getFormat("MM/dd/yyyy")));
List<ColumnConfig<Stock, ?>> columns = new ArrayList<ColumnConfig<Stock, ?>>();
columns.add(nameCol);
columns.add(symbolCol);
columns.add(lastCol);
columns.add(changeCol);
columns.add(lastTransCol);
ColumnModel<Stock> cm = new ColumnModel<Stock>(columns);
ListStore<Stock> store = new ListStore<Stock>(properties.key());
store.addAll(TestData.getStocks());
final Grid<Stock> grid = new Grid<Stock>(store, cm);
grid.getView().setAutoExpandColumn(nameCol);
grid.getView().setForceFit(true);
grid.getView().setStripeRows(true);
grid.getView().setColumnLines(true);
// This is needed to enable quicktips to be displayed in the grid.
// See the cell renderer HTML above with qtip attribute.
QuickTip.of(grid);
return grid;
}
@Override
public void onModuleLoad() {
new ExampleContainer(this)
.setMinHeight(MIN_HEIGHT)
.setMinWidth(MIN_WIDTH)
.setPreferredHeight(PREFERRED_HEIGHT)
.setPreferredWidth(PREFERRED_WIDTH)
.doStandalone();
}
private void configPanel(final Portlet portlet) {
portlet.setCollapsible(true);
portlet.setAnimCollapse(false);
portlet.getHeader().addTool(new ToolButton(ToolButton.GEAR));
portlet.getHeader().addTool(new ToolButton(ToolButton.CLOSE, new SelectHandler() {
@Override
public void onSelect(SelectEvent event) {
portlet.removeFromParent();
}
}));
}
private HTML getBogusText() {
HTML html = new HTML(TestData.DUMMY_TEXT_SHORT);
html.addStyleName(ExampleStyles.get().paddedText());
return html;
}
}
|
package cn.jiufungqx.common.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.util.Date;
/**
* @author: jiufung
* @create: 2019/8/7 22:19
*/
@Data
@TableName(value = "user")
public class User {
@TableId(value = "id", type = IdType.UUID)
private String id;
private String name;
private String password;
private String nickName;
private Integer age;
private String email;
private String phoneNumber;
private String idNumber;
private String qq;
private Integer loginCount;
private Date createTime;
private Date updateTime;
}
|
package com.boku.auth.http.stringsigner;
import java.security.InvalidKeyException;
/**
* Simple interface for signing text data with a particular key, where the implementation owns the key.
*/
public interface StringSigner {
/**
* Generate a signature for the given text data, using the given algorithm and a key that will be retrieved using
* the given partnerId and keyId.
*
* @param algorithm One of {@link SignatureAlgorithm}
* @param partnerId The partner ID under which the key to be used is stored
* @param keyId The key ID under which the key to be used is stored
* @param stringToSign The string to sign
* @return The signature, which is guaranteed to be printable ASCII but is otherwise of an algorithm-specific format
* @throws InvalidKeyException If the referenced key was not found, or is invalid
*/
String generateSignature(SignatureAlgorithm algorithm, String partnerId, String keyId, String stringToSign) throws InvalidKeyException;
}
|
package project.core.header;
import project.BasePage;
public class Header extends BasePage {
public Header() {
}
@Override
protected void check() {
}
}
|
package com.codigo.smartstore.sdk.core.checksum.crc;
/**
* Interfejs deklaruje kontrakt definujący metodę dostarczającą parametry do
* wyznaczenia sumy kontrolnej CRC.
*
* @author andrzej.radziszewski
* @version 1.0.0.0
* @category interface
*/
interface ICrcParametrizable {
/**
* Właściwość określa wartości atrybutów parametru sumy kontrolnej
*
* @return Wartośći atrybutów parametru CRC, referencja do obiektu
*/
ICrcParameter getParameters();
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.