text
stringlengths 10
2.72M
|
|---|
package steps;
import cucumber.api.Scenario;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.service.local.AppiumDriverLocalService;
import io.appium.java_client.service.local.AppiumServiceBuilder;
import io.appium.java_client.service.local.flags.GeneralServerFlag;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.remote.DesiredCapabilities;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Set;
import java.util.concurrent.TimeUnit;
public class StartingSteps extends BaseSteps {
private AppiumDriverLocalService appiumService;
@Before
public void startAppiumServer() throws IOException {
int port = 4723;
String nodeJS_Path = "C:/Program Files/NodeJS/node.exe";
String appiumJS_Path = "C:/Program Files/Appium/node_modules/appium/bin/appium.js";
String osName = System.getProperty("os.name");
if (osName.contains("Mac")) {
appiumService = AppiumDriverLocalService.buildService(new AppiumServiceBuilder()
.usingDriverExecutable(new File(("/usr/local/bin/node")))
.withAppiumJS(new File(("/usr/local/bin/appium")))
.withIPAddress("0.0.0.0")
.usingPort(port)
.withArgument(GeneralServerFlag.SESSION_OVERRIDE)
.withLogFile(new File("build/appium.log")));
} else if (osName.contains("Windows")) {
appiumService = AppiumDriverLocalService.buildService(new AppiumServiceBuilder()
.usingDriverExecutable(new File(nodeJS_Path))
.withAppiumJS(new File(appiumJS_Path))
.withIPAddress("0.0.0.0")
.usingPort(port)
.withArgument(GeneralServerFlag.SESSION_OVERRIDE)
.withLogFile(new File("build/appium.log")));
}
appiumService.start();
/* We have put a check based on the tag passed to determine whether to run Android or iOS
This can be handled by having gradle decide which is the target device to be tested against.
*/
DesiredCapabilities capabilities = new DesiredCapabilities();
String target = System.getProperty("targetDevice");
System.out.println("Input Target Device is: " + target);
if (target.equalsIgnoreCase("android")) {
capabilities.setCapability("platformName", "Android");
capabilities.setCapability("platformVersion", "5.1");
capabilities.setCapability("deviceName", "Nexus6");
capabilities.setCapability("noReset", false);
capabilities.setCapability("fullReset", true);
capabilities.setCapability("app", "app/quikr.apk");
} else if (target.equalsIgnoreCase("ios")) {
capabilities.setCapability("appium-version", "1.0");
capabilities.setCapability("platformName", "iOS");
capabilities.setCapability("platformVersion", "8.4");
capabilities.setCapability("deviceName", "iPhone 6");
capabilities.setCapability("app", "app/TestApp.app");
} else if (target.equalsIgnoreCase("mweb")) {
capabilities.setCapability("platformName", "Android");
capabilities.setCapability("deviceName", "Nexus");
capabilities.setCapability("browserName", "Browser");
}
appiumDriver = new AppiumDriver(new URL("http://0.0.0.0:4723/wd/hub"), capabilities);
appiumDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
@After
public void tearDown(Scenario scenario) {
try {
if (scenario.isFailed()) {
final byte[] screenshot = appiumDriver
.getScreenshotAs(OutputType.BYTES);
scenario.embed(screenshot, "image/png");
}
appiumDriver.quit();
appiumService.stop();
} catch (Exception e) {
System.out.println("Exception while running Tear down :" + e.getMessage());
}
}
public static void changeDriverContextToWeb(AppiumDriver driver) {
Set<String> allContext = driver.getContextHandles();
for (String context : allContext) {
if (context.contains("WEBVIEW"))
driver.context(context);
}
}
}
|
/*******************************************************************************
* =============LICENSE_START=========================================================
*
* =================================================================================
* Copyright (c) 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
*
*******************************************************************************/
package org.onap.ccsdk.dashboard.model.consul;
import java.util.Map;
import org.onap.ccsdk.dashboard.model.ECTransportModel;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Model for message returned by Consul about a node registered for health
* monitoring.
*
* <pre>
{
"ID":"a2788806-6e2e-423e-8ee7-6cad6f3d3de6",
"Node":"cjlvmcnsl00",
"Address":"10.170.8.13",
"TaggedAddresses":{"lan":"10.170.8.13","wan":"10.170.8.13"},
"Meta":{},
"CreateIndex":6,
"ModifyIndex":179808
}
* </pre>
*/
public final class ConsulNodeInfo extends ECTransportModel {
public final String id;
public final String node;
public final String address;
public final Map<String, Object> taggedAddresses;
public final Map<String, Object> meta;
public final int createIndex;
public final int modifyIndex;
@JsonCreator
public ConsulNodeInfo(@JsonProperty("ID") String id, @JsonProperty("Node") String node,
@JsonProperty("Address") String address,
@JsonProperty("TaggedAddresses") Map<String, Object> taggedAddresses,
@JsonProperty("Meta") Map<String, Object> meta,
@JsonProperty("CreateIndex") int createIndex,
@JsonProperty("ModifyIndex") int modifyIndex) {
this.id = id;
this.node = node;
this.address = address;
this.taggedAddresses = taggedAddresses;
this.meta = meta;
this.createIndex = createIndex;
this.modifyIndex = modifyIndex;
}
}
|
package jvm_test;
/**
* Description: ๆฅ็ClassLoader็ฑป็ๅฑๆฌก็ปๆ
*
* Reference: http://www.codeceo.com/article/java-classloader.html
*
* @author Baltan
* @date 2019-05-30 18:30
*/
public class Test3 {
public static void main(String[] args) {
ClassLoader loader = Test3.class.getClassLoader();
while (loader != null) {
System.out.println(loader);
loader = loader.getParent();
}
}
}
|
package org.example.junit;
import junit.framework.TestCase;
import org.junit.Test;
public class SimpleJUnit3Test extends TestCase {
@Test
public void testFoo() throws Exception {
assertTrue(true);
}
@Test
public void testBar() throws Exception {
assertTrue(false);
}
}
|
package com.ipartek.formacion.soap;
import java.util.ArrayList;
public class FrasesMotivacion {
ArrayList<String> frases = null;
int numeroAleatorio;
public FrasesMotivacion() {
super();
this.frases = new ArrayList<String>();
this.frases.add("Solo hay una felicidad en la vida - amar y ser amado-George Sand");
this.frases.add("Siempre es temprano para rendirse-Norman Vincent Peale");
this.frases.add("La fortuna favorece al valiente-Virgilio");
this.frases.add("Estaba asi cuando llegue - Homer Simpson");
this.frases.add("Ser un buen perdedor es aprender cรณmo ganar-Carl Sandburg");
}
public String dameFrase() {
String resul = "Upppppppppppppppppppppppps";
try {
this.numeroAleatorio = (int) (Math.random() * (this.frases.size() - 1));
resul = this.frases.get(this.numeroAleatorio);
} catch (Exception e) {
e.printStackTrace();
}
return resul;
}
public String pedirFrase(int idFrase) {
String resul = "NO se ha podido encontrar la frase con id:" + idFrase;
try {
resul = this.frases.get(idFrase);
} catch (Exception e) {
e.printStackTrace();
}
return resul;
}
}
|
package com.cnk.travelogix.sapintegrations.zif.erp.ws.opportunity.data;
public class ZifProdCatForexData
{
protected String noOfTraveller;
protected String fulfilmentLocation;
protected String purposeOfPurchase;
protected String product;
protected String currencyToBuySell;
/**
* Gets the value of the noOfTraveller property.
*
* @return possible object is {@link String }
*
*/
public String getNoOfTraveller()
{
return noOfTraveller;
}
/**
* Sets the value of the noOfTraveller property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setNoOfTraveller(final String value)
{
this.noOfTraveller = value;
}
/**
* Gets the value of the fulfilmentLocation property.
*
* @return possible object is {@link String }
*
*/
public String getFulfilmentLocation()
{
return fulfilmentLocation;
}
/**
* Sets the value of the fulfilmentLocation property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setFulfilmentLocation(final String value)
{
this.fulfilmentLocation = value;
}
/**
* Gets the value of the purposeOfPurchase property.
*
* @return possible object is {@link String }
*
*/
public String getPurposeOfPurchase()
{
return purposeOfPurchase;
}
/**
* Sets the value of the purposeOfPurchase property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setPurposeOfPurchase(final String value)
{
this.purposeOfPurchase = value;
}
/**
* Gets the value of the product property.
*
* @return possible object is {@link String }
*
*/
public String getProduct()
{
return product;
}
/**
* Sets the value of the product property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setProduct(final String value)
{
this.product = value;
}
/**
* Gets the value of the currencyToBuySell property.
*
* @return possible object is {@link String }
*
*/
public String getCurrencyToBuySell()
{
return currencyToBuySell;
}
/**
* Sets the value of the currencyToBuySell property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setCurrencyToBuySell(final String value)
{
this.currencyToBuySell = value;
}
}
|
package kr.KENNYSOFT.SEHomework.Operator;
import java.math.BigInteger;
public class Subtractor extends Operator
{
@Override
public String operate(String operand1, String operand2) throws NumberFormatException
{
BigInteger mOperand1 = new BigInteger(operand1);
BigInteger mOperand2 = new BigInteger(operand2);
BigInteger result = mOperand1.subtract(mOperand2);
return result.toString();
}
}
|
package com.utils;
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONObject;
//import com.alibaba.fastjson.JSONObject;
/**
* @author lyx
*
* 2015-8-18ไธๅ1:39:40
*
*com.yr.utils.ResultUtil
* TODO ็ปๆๅทฅๅ
ท็ฑป
*/
public class ResultUtil {
/**
* ไฟๅญjsonๅฏน่ฑก
*/
private Map<String,Object> results;
//---- keyๅผ๏ผ
private static final String MSG="msg";
private static final String SUCCESS="success";
/**
* ๅ็ฌๅฏน่ฑก
*/
private static final String OBJ ="obj";
/**
* ๅ่กจๅฏน่ฑก
*/
private static final String ROWS="rows";
private static final String TOTAL ="total";
private static final String STATUS="status";
private static final String SIZE="size";
/**
*ๆ้ ๅฝๆฐๅๅงๅ
*/
public ResultUtil() {
this.results = new HashMap<String,Object>();
//้ป่ฎคๅผ
this.results.put(SUCCESS, true);
}
public Map<String, Object> getResult() {
return results;
}
public void setResult(Map<String, Object> results) {
this.results = results;
}
public String getMsg() {
return (String) results.get(MSG);
}
public boolean getSuccess() {
return (Boolean) results.get(SUCCESS);
}
public String getObj() {
return OBJ;
}
public void setRows(Object rows) {
this.results.put(ROWS,rows);
}
public void setTotal(Integer total) {
this.results.put(TOTAL, total);
}
public void setSize(Integer szie) {
this.results.put(SIZE, szie);
}
/**
* @param key
* @param value
* ่ชๅฎไนๆทปๅ ๅฑๆงๆ ่ฏ
*/
public void setProperty(String key,Object value)
{
try {
this.results.put(key, value);
} catch (Exception e) {
// TODO: handle exception
//logger.error("ๅบ้ๆถ๏ผkey:"+key+",value๏ผ"+value+",Jsonๆถ้่ฏฏๆฏ๏ผ",e);
}
}
public void setStatus(String status)
{
setProperty(STATUS, status);
}
public void setSuccess(boolean success)
{
setProperty(SUCCESS, success);
}
public void setMsg(String Msg)
{
setProperty(MSG, Msg);
}
public void setTotal(int size)
{
setProperty(TOTAL, size);
}
public void setSize(int size)
{
setProperty(SIZE, size);
}
public void setData(String data)
{
setProperty(ROWS, data);
}
public void setObj(Object obj)
{
setProperty(OBJ, obj);
}
public String toJsonString()
{
JSONObject obj =new JSONObject();
obj.put("data", this.results);
return obj.toString();
}
public static void main(String[] args)
{
ResultUtil utils =new ResultUtil();
System.out.println(utils.toJsonString());
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package DAO;
import Conexao.ModuloConexao;
import JavaBean.Funcionario;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLDataException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
/**
*
* @author wramu
*/
public class FuncionarioDAO {
private Connection conecta;
public FuncionarioDAO(){
this.conecta = new ModuloConexao().conector();
}
//rotinas SQL
//Metodo Cadastrar funcionario
public void cadastrarFuncionario(Funcionario cadastrar) throws SQLException{
try {
String cmdsql= "insert into funcionarios(id, nome, rg, cpf, endereco, bairro, cidade, estado, email, dataCadastro, Salario, Formacao, Cargo, CTPS, NCarteTraba, cep, Celular, Telefone) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?, ?, ?)";
//16 colunas
PreparedStatement stmt = conecta.prepareStatement(cmdsql);
stmt.setInt(1, cadastrar.getIdfuncionario());
stmt.setString(2, cadastrar.getNome());
stmt.setString(3, cadastrar.getRg());
stmt.setString(4, cadastrar.getCpf());
stmt.setString(5, cadastrar.getEndereco());
stmt.setString(6, cadastrar.getBairro());
stmt.setString(7, cadastrar.getCidade());
stmt.setString(8, cadastrar.getEstado());
stmt.setString(9, cadastrar.getEmail());
stmt.setString(10, cadastrar.getDataCadastro());
stmt.setString(11, cadastrar.getSalario());
stmt.setString(12, cadastrar.getFormacao());
stmt.setString(13, cadastrar.getCargo());
stmt.setString(14, cadastrar.getCtps());
stmt.setString(15, cadastrar.getNCarteTraba());
stmt.setString(16, cadastrar.getCep());
stmt.setString(17, cadastrar.getCelular());
stmt.setString(18, cadastrar.getTelefone());
//execultar
stmt.execute();
//fechar conexao
stmt.close();
} catch (SQLDataException error) {
throw new RuntimeException(error);
}
}
//metodo de busca
public List<Funcionario> readForDesc(String desc) throws SQLException{
PreparedStatement stmt = null;
ResultSet rs = null;
List<Funcionario> funcionarios = new ArrayList<>();
try {
stmt = conecta.prepareStatement("SELECT * FROM funcionarios WHERE nome LIKE ?");
stmt.setString(1, "%"+desc+"%");
rs = stmt.executeQuery();
while (rs.next()) {
Funcionario funcionario = new Funcionario();
funcionario.setIdfuncionario(rs.getInt("id"));
funcionario.setNome(rs.getString("nome"));
funcionario.setCpf(rs.getString("cpf"));
funcionario.setCelular(rs.getString("Celular"));
funcionario.setEmail(rs.getString("email"));
funcionarios.add(funcionario);
}
} catch (SQLException ex) {
Logger.getLogger(ProdutosDAO.class.getName()).log(Level.SEVERE, null, ex);
}finally{
stmt.close();
rs.close();
}
return funcionarios;
}
public void update(Funcionario alterar) throws SQLException {
try {
String cmdsql = "UPDATE funcionarios SET nome = ?, rg=?, cpf= ?, endereco = ?, bairro=?, cidade=?, estado=?, email=?, Salario=?, Formacao=?, Cargo=?, CTPS=?, NCarteTraba=?, CEP=?, Celular=?, Telefone=? WHERE id = ?";
//organizar
PreparedStatement stmt = conecta.prepareStatement(cmdsql);
stmt.setString(1, alterar.getNome());
stmt.setString(2, alterar.getRg());
stmt.setString(3, alterar.getCpf());
stmt.setString(4, alterar.getEndereco());
stmt.setString(5, alterar.getBairro());
stmt.setString(6, alterar.getCidade());
stmt.setString(7, alterar.getEstado());
stmt.setString(8, alterar.getEmail());
stmt.setString(9, alterar.getSalario());
stmt.setString(10, alterar.getFormacao());
stmt.setString(11, alterar.getCargo());
stmt.setString(12, alterar.getCtps());
stmt.setString(13, alterar.getNCarteTraba());
stmt.setString(14, alterar.getCep());
stmt.setString(15, alterar.getCelular());
stmt.setString(16, alterar.getTelefone());
stmt.setInt(17, alterar.getIdfuncionario());
//execultar
stmt.execute();
// fechar conexao
stmt.close();
JOptionPane.showMessageDialog(null, "Editado com sucesso!");
} catch (SQLDataException error) {
JOptionPane.showMessageDialog(null,error);
}
}
//deletar produtos da tabela
public void delete(Funcionario deletar) throws SQLException{
try {
String cmdsql = "DELETE FROM funcionarios WHERE id = ?";
//organizar
PreparedStatement stmt = conecta.prepareStatement(cmdsql);
stmt.setInt(1,deletar.getIdfuncionario());
//execultar
stmt.execute();
// fechar conexao
stmt.close();
JOptionPane.showMessageDialog(null, "Excluido com sucesso!");
} catch (SQLDataException error) {
throw new RuntimeException(error);
}
}
}
|
package com.fillikenesucn.petcare.activities;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import com.fillikenesucn.petcare.R;
import com.fillikenesucn.petcare.models.Pet;
import com.fillikenesucn.petcare.utils.IOHelper;
import com.fillikenesucn.petcare.adapters.PetListAdapter;
import java.util.ArrayList;
/**
* Esta clase representa a la actividad que se encargarรก de desplegar el listado de mascotas registradas en el sistema
* @author: Marcelo Lazo Chavez
* @version: 30/03/2020
*/
public class PetListFragmentActivity extends FragmentActivity {
private Button btnAgregarMascota;
private ArrayList<Pet> petList = new ArrayList<>();
/**
* CONSTRUCTOR DE LA ACTIVIDAD
* @param savedInstanceState
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pet_list_fragment);
btnAgregarMascota = (Button) findViewById(R.id.btnAgregarMascota);
btnAgregarMascota.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(PetListFragmentActivity.this, RegisterPetFragmentActivity.class);
startActivity(intent);
}
}
);
InitPetData();
}
/**
* Mรฉtodo que se encarga de obtener las mascotas que se encuentran registradas en el sistema
*/
private void InitPetData(){
petList = IOHelper.PetList(PetListFragmentActivity.this);
InitPetList();
}
/**
* Mรฉtodo que se encarga de actualiar el listado/recyclerview de la actividad
* permitiendo asociar un adapter para brindarle funcionalidad a cada uno de los item pertenecientes
* a la mascotas del sistema
*/
private void InitPetList(){
RecyclerView recyclerView = findViewById(R.id.recycler_view);
PetListAdapter adapter = new PetListAdapter(this, petList);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
/**
* Mรฉtodo que se encarga en redireccionar a la actividad de pet info con el epc de la mascota que fue seleccionada del listado
* @param txtEPC es el epc asociado a la mascota
*/
public void OpenInfoPet(String txtEPC){
Intent intent = new Intent(this, PetInfoFragmentActivity.class);
intent.putExtra("EPC",txtEPC);
startActivity(intent);
}
/**
* Mรฉtodo que se encarga de refrescar la informaciรณn de la actividad, una vez que esta vuelva a ser la actividad
* principal de la aplicaciรณn
*/
@Override
protected void onRestart() {
super.onRestart();
InitPetData();
}
}
|
package eg.ipvii.fotp.init;
import com.teamwizardry.librarianlib.features.base.item.ItemMod;
import com.teamwizardry.librarianlib.features.base.item.ItemModFood;
import eg.ipvii.fotp.FotPMod;
import eg.ipvii.fotp.items.*;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
public class ModItems {
public static Item ful = new ItemMod("ful").setCreativeTab(FotPMod.FotPCreativeTab);
public static Item pitabreadk = new ItemMod("pitabread").setCreativeTab(FotPMod.FotPCreativeTab);
public static Item fulsandwich = new ItemModFood("fulsandwich", 8, 1F, true).setCreativeTab(FotPMod.FotPCreativeTab);
public static Item beans = new ItemSeedFoodMod("beans", ModBlocks.beanscrop, Blocks.FARMLAND, 6, 0.7F).setCreativeTab(FotPMod.FotPCreativeTab);
public static Item rawpastrami = new ItemRawPastrami("rawpastrami");
public static Item pastrami = new ItemModFood("pastrami", 6, 0.6F, true).setCreativeTab(FotPMod.FotPCreativeTab);
public static Item cumin = new ItemSeedMod("cumin", ModBlocks.cumincrop, Blocks.FARMLAND).setCreativeTab(FotPMod.FotPCreativeTab);
public static Item garlic = new ItemSeedMod("garlic", ModBlocks.garliccrop, Blocks.FARMLAND).setCreativeTab(FotPMod.FotPCreativeTab);
public static Item mudball = new ItemMod("mudball");
public static Item earthenware = new ItemMod("earthenware");
public static ItemMortarandPestle mortarandpestle = new ItemMortarandPestle("mortarandpestle");
public static Item earthenwarebowl = new ItemMod("earthenwarebowl");
public static Item earthenwarestick = new ItemMod("earthenwarestick");
public static Item redpepper = new ItemModFood("redpepper", 1, 0.5F, false);
public static Item redpepperseeds = new ItemSeedMod("redpepperseeds", ModBlocks.redpeppercrop, Blocks.FARMLAND).setCreativeTab(FotPMod.FotPCreativeTab);
public static ItemOkra okra = new ItemOkra("okra");
public static Item okraseeds = new ItemSeedMod("okraseeds", ModBlocks.okracrop, Blocks.FARMLAND).setCreativeTab(FotPMod.FotPCreativeTab);
public static Item rice = new ItemMod("rice").setCreativeTab(FotPMod.FotPCreativeTab);
public static Item riceseeds = new ItemSeedMod("riceseeds", ModBlocks.ricecrop, Blocks.FARMLAND).setCreativeTab(FotPMod.FotPCreativeTab);
public static Item paprikapowder = new ItemMod("paprikapowder").setCreativeTab(FotPMod.FotPCreativeTab);
public static Item tomato = new ItemModFood("tomato", 1, 0.5F, false);
public static Item tomatoseeds = new ItemSeedMod("tomatoseeds", ModBlocks.tomatocrop, Blocks.FARMLAND).setCreativeTab(FotPMod.FotPCreativeTab);
public static Item tomatosauce = new ItemMod("tomatosauce").setCreativeTab(FotPMod.FotPCreativeTab);
public static Item presser = new ItemPresser("presser");
public static Item sunfloweroil = new ItemMod("sunfloweroil").setCreativeTab(FotPMod.FotPCreativeTab);
public static Item parsley = new ItemModFood("parsley", 2, 0.3F, false).setCreativeTab(FotPMod.FotPCreativeTab);
public static Item parsleyseeds = new ItemSeedMod("parsleyseeds", ModBlocks.parsleycrop, Blocks.FARMLAND).setCreativeTab(FotPMod.FotPCreativeTab);
public static Item falafeldough = new ItemMod("falafeldough").setCreativeTab(FotPMod.FotPCreativeTab);
public static Item falafel = new ItemModFood("falafel", 4, 0.5F, false).setCreativeTab(FotPMod.FotPCreativeTab);
public static Item falafelsandwich = new ItemModFood("falafelsandwich", 8, 1F, true).setCreativeTab(FotPMod.FotPCreativeTab);
public static Item ladle = new ItemMod("ladle").setCreativeTab(FotPMod.FotPCreativeTab);
}
|
package net.minecraft.command;
import net.minecraft.command.server.CommandBanIp;
import net.minecraft.command.server.CommandBanPlayer;
import net.minecraft.command.server.CommandBroadcast;
import net.minecraft.command.server.CommandDeOp;
import net.minecraft.command.server.CommandEmote;
import net.minecraft.command.server.CommandListBans;
import net.minecraft.command.server.CommandListPlayers;
import net.minecraft.command.server.CommandMessage;
import net.minecraft.command.server.CommandMessageRaw;
import net.minecraft.command.server.CommandOp;
import net.minecraft.command.server.CommandPardonIp;
import net.minecraft.command.server.CommandPardonPlayer;
import net.minecraft.command.server.CommandPublishLocalServer;
import net.minecraft.command.server.CommandSaveAll;
import net.minecraft.command.server.CommandSaveOff;
import net.minecraft.command.server.CommandSaveOn;
import net.minecraft.command.server.CommandScoreboard;
import net.minecraft.command.server.CommandSetBlock;
import net.minecraft.command.server.CommandSetDefaultSpawnpoint;
import net.minecraft.command.server.CommandStop;
import net.minecraft.command.server.CommandSummon;
import net.minecraft.command.server.CommandTeleport;
import net.minecraft.command.server.CommandTestFor;
import net.minecraft.command.server.CommandTestForBlock;
import net.minecraft.command.server.CommandWhitelist;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.server.MinecraftServer;
import net.minecraft.tileentity.CommandBlockBaseLogic;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.util.text.TextFormatting;
public class ServerCommandManager extends CommandHandler implements ICommandListener {
private final MinecraftServer server;
public ServerCommandManager(MinecraftServer serverIn) {
this.server = serverIn;
registerCommand(new CommandTime());
registerCommand(new CommandGameMode());
registerCommand(new CommandDifficulty());
registerCommand(new CommandDefaultGameMode());
registerCommand(new CommandKill());
registerCommand(new CommandToggleDownfall());
registerCommand(new CommandWeather());
registerCommand(new CommandXP());
registerCommand(new CommandTP());
registerCommand((ICommand)new CommandTeleport());
registerCommand(new CommandGive());
registerCommand(new CommandReplaceItem());
registerCommand(new CommandStats());
registerCommand(new CommandEffect());
registerCommand(new CommandEnchant());
registerCommand(new CommandParticle());
registerCommand((ICommand)new CommandEmote());
registerCommand(new CommandShowSeed());
registerCommand(new CommandHelp());
registerCommand(new CommandDebug());
registerCommand((ICommand)new CommandMessage());
registerCommand((ICommand)new CommandBroadcast());
registerCommand(new CommandSetSpawnpoint());
registerCommand((ICommand)new CommandSetDefaultSpawnpoint());
registerCommand(new CommandGameRule());
registerCommand(new CommandClearInventory());
registerCommand((ICommand)new CommandTestFor());
registerCommand(new CommandSpreadPlayers());
registerCommand(new CommandPlaySound());
registerCommand((ICommand)new CommandScoreboard());
registerCommand(new CommandExecuteAt());
registerCommand(new CommandTrigger());
registerCommand(new AdvancementCommand());
registerCommand(new RecipeCommand());
registerCommand((ICommand)new CommandSummon());
registerCommand((ICommand)new CommandSetBlock());
registerCommand(new CommandFill());
registerCommand(new CommandClone());
registerCommand(new CommandCompare());
registerCommand(new CommandBlockData());
registerCommand((ICommand)new CommandTestForBlock());
registerCommand((ICommand)new CommandMessageRaw());
registerCommand(new CommandWorldBorder());
registerCommand(new CommandTitle());
registerCommand(new CommandEntityData());
registerCommand(new CommandStopSound());
registerCommand(new CommandLocate());
registerCommand(new CommandReload());
registerCommand(new CommandFunction());
if (serverIn.isDedicatedServer()) {
registerCommand((ICommand)new CommandOp());
registerCommand((ICommand)new CommandDeOp());
registerCommand((ICommand)new CommandStop());
registerCommand((ICommand)new CommandSaveAll());
registerCommand((ICommand)new CommandSaveOff());
registerCommand((ICommand)new CommandSaveOn());
registerCommand((ICommand)new CommandBanIp());
registerCommand((ICommand)new CommandPardonIp());
registerCommand((ICommand)new CommandBanPlayer());
registerCommand((ICommand)new CommandListBans());
registerCommand((ICommand)new CommandPardonPlayer());
registerCommand(new CommandServerKick());
registerCommand((ICommand)new CommandListPlayers());
registerCommand((ICommand)new CommandWhitelist());
registerCommand(new CommandSetPlayerTimeout());
} else {
registerCommand((ICommand)new CommandPublishLocalServer());
}
CommandBase.setCommandListener(this);
}
public void notifyListener(ICommandSender sender, ICommand command, int flags, String translationKey, Object... translationArgs) {
boolean flag = true;
MinecraftServer minecraftserver = this.server;
if (!sender.sendCommandFeedback())
flag = false;
TextComponentTranslation textComponentTranslation = new TextComponentTranslation("chat.type.admin", new Object[] { sender.getName(), new TextComponentTranslation(translationKey, translationArgs) });
textComponentTranslation.getStyle().setColor(TextFormatting.GRAY);
textComponentTranslation.getStyle().setItalic(Boolean.valueOf(true));
if (flag)
for (EntityPlayer entityplayer : minecraftserver.getPlayerList().getPlayerList()) {
if (entityplayer != sender && minecraftserver.getPlayerList().canSendCommands(entityplayer.getGameProfile()) && command.checkPermission(this.server, sender)) {
boolean flag1 = (sender instanceof MinecraftServer && this.server.shouldBroadcastConsoleToOps());
boolean flag2 = (sender instanceof net.minecraft.network.rcon.RConConsoleSource && this.server.shouldBroadcastRconToOps());
if (flag1 || flag2 || (!(sender instanceof net.minecraft.network.rcon.RConConsoleSource) && !(sender instanceof MinecraftServer)))
entityplayer.addChatMessage((ITextComponent)textComponentTranslation);
}
}
if (sender != minecraftserver && minecraftserver.worldServers[0].getGameRules().getBoolean("logAdminCommands"))
minecraftserver.addChatMessage((ITextComponent)textComponentTranslation);
boolean flag3 = minecraftserver.worldServers[0].getGameRules().getBoolean("sendCommandFeedback");
if (sender instanceof CommandBlockBaseLogic)
flag3 = ((CommandBlockBaseLogic)sender).shouldTrackOutput();
if (((flags & 0x1) != 1 && flag3) || sender instanceof MinecraftServer)
sender.addChatMessage((ITextComponent)new TextComponentTranslation(translationKey, translationArgs));
}
protected MinecraftServer getServer() {
return this.server;
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\command\ServerCommandManager.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
package com.Epsilon.deliveryservice.app.model;
import org.json.JSONObject;
public class DeliveryItem {
public DeliveryItem(int id, String address, JSONObject delivery, int visibleId)
{
this.id = id;
this.address = address;
this.delivery = delivery;
this.visibleId = visibleId;
}
private int id;
private final String address;
private final JSONObject delivery;
private int visibleId;
public JSONObject getDelivery() {
return delivery;
}
public int getId() {
return id;
}
public String getAddress() {
return address;
}
public int getVisibleId() {
return visibleId;
}
public void setVisibleId(int visibleId) {
this.visibleId = visibleId;
}
}
|
package net.javaguides.springboot.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import net.javaguides.springboot.service.Blog;
import net.javaguides.springboot.web.dto.UserRegistrationDto;
@Controller
public class MainController{
@GetMapping("/login")
public String login() {
return "login";
}
}
|
package spi.movieorganizer.data.person;
import spi.movieorganizer.data.MovieOrganizerType;
import exane.osgi.jexlib.data.object.AbstractDataObject;
import exane.osgi.jexlib.data.object.ExaneDataType;
public class PersonDO extends AbstractDataObject<Integer> {
private final boolean adult;
private final String biography;
private final String birthday;
private final String deathday;
private final String homepage;
private final String name;
private final String placeOfBirth;
private final String profilePath;
public PersonDO(final Integer key, final boolean adult, final String biography, final String birthday, final String deathday, final String homepage, final String name,
final String placeOfBirth, final String profilePath) {
super(key);
this.adult = adult;
this.biography = biography;
this.birthday = birthday;
this.deathday = deathday;
this.homepage = homepage;
this.name = name;
this.placeOfBirth = placeOfBirth;
this.profilePath = profilePath;
}
public boolean isAdult() {
return this.adult;
}
public String getBiography() {
return this.biography;
}
public String getBirthday() {
return this.birthday;
}
public String getDeathday() {
return this.deathday;
}
public String getHomepage() {
return this.homepage;
}
public String getName() {
return this.name;
}
public String getPlaceOfBirth() {
return this.placeOfBirth;
}
public String getProfilePath() {
return this.profilePath;
}
@Override
public ExaneDataType getDataType() {
return MovieOrganizerType.PEOPLE;
}
}
|
package com.module.controllers.veterandialog.tabs;
import com.module.controllers.veterandialog.tables.AddWorkPlaceController;
import com.module.helpers.CustomAlertCreator;
import com.module.model.entity.WorkPlaceEntity;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import lombok.Data;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Optional;
@Data
@Component
public class WorkPlacesTabController {
@FXML
private Tab workPlacesTab;
@FXML
private TableView<WorkPlaceEntity> workPlaceTable;
@FXML
private TableColumn<WorkPlaceEntity, String> localityOfWorkColumn;
@FXML
private TableColumn<WorkPlaceEntity, String> workOrganizationColumn;
@FXML
private TableColumn<WorkPlaceEntity, String> workPositionColumn;
@FXML
private TableColumn<WorkPlaceEntity, String> numberOfDepartmentColumn;
@FXML
private Button addWorkPlaceButton;
@FXML
private Button editWorkPlaceButton;
@FXML
private Button deleteWorkPlaceButton;
private Stage dialogStage;
private ObservableList<WorkPlaceEntity> workPlacesData = FXCollections.observableArrayList();
@FXML
public void initialize() {
localityOfWorkColumn.setCellValueFactory(new PropertyValueFactory<>("locality"));
workOrganizationColumn.setCellValueFactory(new PropertyValueFactory<>("organization"));
workPositionColumn.setCellValueFactory(new PropertyValueFactory<>("position"));
numberOfDepartmentColumn.setCellValueFactory(new PropertyValueFactory<>("hrNumber"));
workPlacesData.clear();
}
@FXML
private void handleAddWorkPlace() {
WorkPlaceEntity workPlaceEntity = new WorkPlaceEntity();
boolean addButtonClicked = showAddWorkPlaceDialog(workPlaceEntity);
if (addButtonClicked) {
workPlacesData.add(workPlaceEntity);
workPlaceTable.refresh();
}
}
@FXML
private void handleDeleteWorkPlace() {
int selectedIndex = workPlaceTable.getSelectionModel().getSelectedIndex();
if (selectedIndex >= 0) {
CustomAlertCreator customAlertCreator = new CustomAlertCreator();
Optional<ButtonType> result = customAlertCreator.createDeleteConfirmationAlert().showAndWait();
if (result.get() == customAlertCreator.getButtonTypeOk()) {
workPlacesData.remove(selectedIndex);
workPlaceTable.refresh();
}
}
}
@FXML
private void handleEditWorkPlace() {
WorkPlaceEntity workPlaceEntity = workPlaceTable.getSelectionModel().getSelectedItem();
int selectedIndex = workPlaceTable.getSelectionModel().getSelectedIndex();
if (workPlaceEntity != null) {
boolean addButtonClicked = showAddWorkPlaceDialog(workPlaceEntity);
if (addButtonClicked) {
workPlacesData.set(selectedIndex, workPlaceEntity);
workPlaceTable.refresh();
}
}
}
private boolean showAddWorkPlaceDialog(WorkPlaceEntity workPlaceEntity) {
try {
FXMLLoader loader = new FXMLLoader(getClass().getClassLoader().getResource("view/veterandialog/veterantabledialogs/AddWorkPlaceDialog.fxml"));
AnchorPane page = loader.load();
Stage stage = new Stage();
stage.initModality(Modality.WINDOW_MODAL);
stage.initOwner(dialogStage);
stage.setResizable(false);
stage.initStyle(StageStyle.UTILITY);
Scene scene = new Scene(page);
stage.setScene(scene);
AddWorkPlaceController controller = loader.getController();
controller.setDialogStage(stage);
controller.setWorkPlaceEntity(workPlaceEntity);
stage.showAndWait();
return controller.isSaveClicked();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
|
package interpreter.input.value;
import java.io.Serializable;
public interface IInputValue<T> extends Serializable{
int getIdentifier();
T getInputValue();
}
|
package com.scf.skyware.mobile.controller;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import com.scf.skyware.common.domain.SessionVO;
import com.scf.skyware.common.util.AdminLoginCheck;
import com.scf.skyware.common.util.Base64;
import com.scf.skyware.common.util.SessionManager;
import com.scf.skyware.main.domain.User;
import com.scf.skyware.main.service.MainService;
import com.scf.skyware.manage.service.ManageService;
import net.sf.json.JSONObject;
@Controller()
public class MobileMainController
{
private MainService mainService;
private ManageService manageService;
@Autowired
public void setMainService(MainService mainService)
{
this.mainService = mainService;
}
@Autowired
public void setManageService(ManageService manageService)
{
this.manageService = manageService;
}
@RequestMapping(value = { "/mobile", "/mobile/index", "/mobile/home" })
public String index(Model model, HttpServletRequest request, HttpSession session) throws Exception
{
return null;
}
// @RequestMapping(value={"/mobile/LoginAction"}, method =
// RequestMethod.POST)
@RequestMapping("/mobile/LoginAction")
public String loginAction(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response) throws Exception
{
String userId = request.getParameter("userId") == null ? "" : request.getParameter("userId").toString();
String userPw = request.getParameter("userPw") == null ? "" : request.getParameter("userPw").toString();
User u = new User();
u.setUserId(userId);
User user = mainService.getUser(u);
int result = 0;
if (user == null)
{
System.err.println(1);
result = AdminLoginCheck.ID_NOT_FOUND;
}
else if (!Base64.base64Encode(userPw).equals(user.getUserPw()))
{
System.err.println(2);
result = AdminLoginCheck.PASSWORD_MISMATCH;
}
else if ("N".equals(user.getUseYn()))
{
System.err.println(3);
result = AdminLoginCheck.ACCESS_DENIED;
}
else
{
UserSession(user, request);
// session.setAttribute("userNm", user.getUserId());
// session.setAttribute("userId", user.getUserNm());
// session.setAttribute("isLogin", false);
result = AdminLoginCheck.LOGIN_SUCCESS;
}
response.setContentType("text/html;charset=UTF-8");
System.err.println(user);
JSONObject json = new JSONObject();
json.put("result", result);
if (result == AdminLoginCheck.LOGIN_SUCCESS)
{
json.put("userInfo", (SessionVO) SessionManager.getSession().getAttribute("sessionVO"));
}
else
{
json.put("userInfo", null);
}
response.getWriter().write(JSONObject.fromObject(json).toString());
return null;
}
//*
private void UserSession(User user, HttpServletRequest request)
{
SessionVO sessionVO = new SessionVO();
sessionVO.setUserId(user.getUserId());
sessionVO.setUserPw(user.getUserPw());
sessionVO.setUserNm(user.getUserNm());
sessionVO.setUserEmail(user.getUserEmail());
sessionVO.setUserPhone(user.getUserPhone());
sessionVO.setUserGender(user.getUserGender());
sessionVO.setUserAddrFull(user.getUserAddrFull());
sessionVO.setUserAddrFullRoad(user.getUserAddrFullRoad());
sessionVO.setUserAddrSido(user.getUserAddrSido());
sessionVO.setUserAddrSigungu(user.getUserAddrSigungu());
sessionVO.setUserAddrEMD(user.getUserAddrEMD());
sessionVO.setUserAddrJibun(user.getUserAddrJibun());
sessionVO.setUserAddrRoad(user.getUserAddrRoad());
sessionVO.setUserAddrBuldNo(user.getUserAddrBuldNo());
sessionVO.setUserAddrDetail(user.getUserAddrDetail());
sessionVO.setUserZipcode(user.getUserZipcode());
sessionVO.setUserBirth(user.getUserBirth());
sessionVO.setUserSL(user.getUserSL());
sessionVO.setUserRegDate(user.getUserRegDate());
sessionVO.setUserModDate(user.getUserModDate());
sessionVO.setUserJoinDate(user.getUserJoinDate());
sessionVO.setUseYn(user.getUseYn());
HttpSession session = request.getSession();
session.setAttribute("sessionVO", sessionVO);
SessionManager.setSession(session);
}//*/
@RequestMapping("/mobile/LogoutAction")
public String logout(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response) throws Exception
{
// session.setAttribute("userNm", "nonmem");
// session.setAttribute("userId", "nonmem");
// session.setAttribute("isLogin", false);
session.setAttribute("sessionVO", null);
JSONObject json = new JSONObject();
// json.put("result", result);
// json.put("userSession", null);
response.getWriter().write(JSONObject.fromObject(json).toString());
return null;
}
@RequestMapping("/mobile/getAddress")
public String getAddress(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception
{
String keyword = URLDecoder.decode(request.getParameter("keyword") == null ? "" : request.getParameter("keyword"), "UTF-8"); // ๊ฒ์
String curPage = request.getParameter("curPage") == null ? "0" : request.getParameter("curPage");
String pageSize = request.getParameter("pageSize") == null ? "100" : request.getParameter("pageSize");
int totalCount = 0; // ์ด ์ฃผ์ ๊ฑด์
List<HashMap<String, String>> addrList = new ArrayList<HashMap<String, String>>();
// ๊ฒ์์ด๊ฐ ์์ ๊ฒฝ์ฐ
if (!keyword.equals(""))
{
String confmKey = "U01TX0FVVEgyMDE3MDcxNDE3MTc1NTIyOTE2"; // ์ธ์ฆํค
// ํ์ฌ ํ์ด์ง ์ง์ ํ์ง ์์ ๊ฒฝ์ฐ 1ํ์ด์ง๋ก ์ค์
if (curPage.equals("") || curPage.equals("0"))
curPage = "1";
// ํ์ด์ง๋ณ ๊ฐ์๋ฅผ ์ง์ ํ์ง ์์ ๊ฒฝ์ฐ 100๊ฐ๋ก ์ค์
if (pageSize.equals("") || pageSize.equals("0"))
pageSize = "100";
String apiUrl = "http://www.juso.go.kr/addrlink/addrLinkApi.do?currentPage=" + curPage + "&countPerPage=" + pageSize + "&keyword="
+ URLEncoder.encode(keyword, "UTF-8") + "&confmKey=" + confmKey;
URL url = new URL(apiUrl);
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
String tempStr = null;
InputSource is = null;
while (true)
{
tempStr = br.readLine();
if (tempStr == null)
{
break;
}
is = new InputSource(new StringReader(tempStr));
}
// XML Document ๊ฐ์ฒด ์์ฑ
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
// xpath ์์ฑ
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList userAddrFullNode = (NodeList) xpath.evaluate("//results//juso//jibunAddr", document, XPathConstants.NODESET);
NodeList userAddrFullRoadNode = (NodeList) xpath.evaluate("//results//juso//roadAddr", document, XPathConstants.NODESET);
NodeList userAddrSidoNode = (NodeList) xpath.evaluate("//results//juso//siNm", document, XPathConstants.NODESET);
NodeList userAddrSigunguNode = (NodeList) xpath.evaluate("//results//juso//sggNm", document, XPathConstants.NODESET);
NodeList userAddrEMDNode = (NodeList) xpath.evaluate("//results//juso//emdNm", document, XPathConstants.NODESET);
NodeList userAddrJibun1Node = (NodeList) xpath.evaluate("//results//juso//lnbrMnnm", document, XPathConstants.NODESET);
NodeList userAddrJibun2Node = (NodeList) xpath.evaluate("//results//juso//lnbrSlno", document, XPathConstants.NODESET);
NodeList userAddrRoadNode = (NodeList) xpath.evaluate("//results//juso//rn", document, XPathConstants.NODESET);
NodeList userAddrBuld1Node = (NodeList) xpath.evaluate("//results//juso//buldMnnm", document, XPathConstants.NODESET);
NodeList userAddrBuld2Node = (NodeList) xpath.evaluate("//results//juso//buldSlno", document, XPathConstants.NODESET);
NodeList userZipcodeNode = (NodeList) xpath.evaluate("//results//juso//zipNo", document, XPathConstants.NODESET);
NodeList totalCountNode = (NodeList) xpath.evaluate("//common//totalCount", document, XPathConstants.NODESET);
// ์ด ์ฃผ์ ๊ฑด์
totalCount = Integer.parseInt(totalCountNode.item(0).getTextContent());
for (int idx = 0; idx < userAddrFullNode.getLength(); idx++)
{
HashMap<String, String> map = new HashMap<String, String>();
String userAddrFull = userAddrFullNode.item(idx).getTextContent();
String userAddrFullRoad = userAddrFullRoadNode.item(idx).getTextContent();
String userAddrSido = userAddrSidoNode.item(idx).getTextContent();
String userAddrSigungu = userAddrSigunguNode.item(idx).getTextContent();
String userAddrEMD = userAddrEMDNode.item(idx).getTextContent();
String userAddrJibun = userAddrJibun1Node.item(idx).getTextContent() + "-" + userAddrJibun2Node.item(idx).getTextContent();
String userAddrRoad = userAddrRoadNode.item(idx).getTextContent();
String userAddrBuld = userAddrBuld1Node.item(idx).getTextContent() + "-" + userAddrBuld2Node.item(idx).getTextContent();
String userZipcode = userZipcodeNode.item(idx).getTextContent();
map.put("userAddrFull", userAddrFull);
map.put("userAddrFullRoad", userAddrFullRoad);
map.put("userAddrSido", userAddrSido);
map.put("userAddrSigungu", userAddrSigungu);
map.put("userAddrEMD", userAddrEMD);
map.put("userAddrJibun", userAddrJibun);
map.put("userAddrRoad", userAddrRoad);
map.put("userAddrBuld", userAddrBuld);
map.put("userZipcode", userZipcode);
addrList.add(map);
}
br.close();
}
else
{
}
// ํ๊ธ๊นจ์ง ๋ฐฉ์ง
response.setContentType("text/html;charset=UTF-8");
// ๋ฆฌํด JSONObject ๊ฐ์ฒด ์ ์ธ
JSONObject json = new JSONObject();
json.put("totalCount", totalCount);
json.put("addrList", addrList);
response.getWriter().write(JSONObject.fromObject(json).toString());
return null;
}
// @RequestMapping("/mobile/popup/regUserView")
// public String joinUserView(Model model, HttpServletRequest request)
// {
// return null;
// }
@RequestMapping("/mobile/regUserAction")
public String joinUserAction(Model model, HttpServletRequest request, HttpServletResponse response, @ModelAttribute("user") User u) throws Exception
{
// String userId = request.getParameter("userId");
// String userPw = request.getParameter("userPw");
// String userNm = request.getParameter("userNm");
// String userEmail = request.getParameter("userEmail");
// String userPhone = request.getParameter("userPhone");
// String userGender = request.getParameter("userGender");
// String userSL = request.getParameter("userSL");
// String userBirth = request.getParameter("userBirth");
// String userAddrFull = request.getParameter("userAddrFull");
// String userAddrDetail = request.getParameter("userAddrDetail");
// String userAddrFullRoad = request.getParameter("userAddrFullRoad");
// String userAddrSido = request.getParameter("userAddrSido");
// String userAddrSigungu = request.getParameter("userAddrSigungu");
// String userAddrEMD = request.getParameter("userAddrEMD");
// String userAddrJibun = request.getParameter("userAddrJibun");
// String userAddrRoad = request.getParameter("userAddrRoad");
// String userAddrBuldNo = request.getParameter("userAddrBuldNo");
// String userZipcode = request.getParameter("userZipCode");
//
// User u = new User();
//
// u.setUserId(userId);
// u.setUserPw(Base64.base64Encode(userPw));
// u.setUserNm(userNm);
// u.setUserEmail(userEmail);
// u.setUserPhone(userPhone);
// u.setUserGender(userGender);
// u.setUserSL(userSL);
// u.setUserBirth(userBirth);
// u.setUserAddrFull(userAddrFull);
// u.setUserAddrFullRoad(userAddrFullRoad);
// u.setUserAddrDetail(userAddrDetail);
// u.setUserAddrSido(userAddrSido);
// u.setUserAddrSigungu(userAddrSigungu);
// u.setUserAddrEMD(userAddrEMD);
// u.setUserAddrJibun(userAddrJibun);
// u.setUserAddrRoad(userAddrRoad);
// u.setUserAddrBuldNo(userAddrBuldNo);
// u.setUserZipcode(userZipcode);
int result = mainService.regUser(u);
JSONObject json = new JSONObject();
if (result > 0)
{
json.put("result", "S00000");
}
else
{
json.put("result", "F00001");
}
response.getWriter().write(JSONObject.fromObject(json).toString());
return null;
}
@RequestMapping("/mobile/overlapIdCheck")
public String overlapIdCheck(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception
{
User u = new User();
String userId = request.getParameter("userId");
u.setUserId(userId);
User user = mainService.getUser(u);
boolean result = false;
if (user != null)
{
if (userId.equals(user.getUserId()))
{
result = true;
}
}
//model.addAttribute("result", result);
JSONObject json = new JSONObject();
json.put("result", result);
response.getWriter().write(JSONObject.fromObject(json).toString());
return null;
}
}
|
package com.hqhcn.android.service;
import com.hqh.android.entity.VehInspRecord;
import com.hqh.android.entity.VehInspRecordExample;
import java.util.List;
public interface VehInspRecordService {
void create(VehInspRecord entity);
/**
* ๆทปๅ ๆฃๆต่ฎฐๅฝ
* ๅๆญฅๆดๆฐ่ฝฆ่พ็็ถๆ
* @param entity
*/
void createSelective(VehInspRecord entity);
List<VehInspRecord> retrieve(VehInspRecordExample example);
VehInspRecord retrieve(long id);
void update(VehInspRecord entity, VehInspRecordExample example);
void updateSelective(VehInspRecord entity, VehInspRecordExample example);
void delete(long id);
List<VehInspRecord> selectByExampleToPage(VehInspRecordExample example);
}
|
package com.rudecrab.rbac.model.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
/**
* ๅบ็กๅฎไฝ็ฑป๏ผๆๆๅฎไฝๅฏน่ฑก้ๆๆญค็ฑป
*
* @author RudeCrab
*/
@Data
public abstract class BaseEntity {
/**
* ไธป้ฎ
*/
@TableId(type = IdType.AUTO)
private Long id;
}
|
package com.teachonmars.modules.widget.overlapLayout.appDemo;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import java.util.ArrayList;
class GravitySelectorAdapter extends RecyclerView.Adapter<GravityHolder> {
private final LayoutInflater layoutInflater;
private ArrayList<Integer> gravityList = new ArrayList<>();
private GravityHolder.SelectionListener gravitySelectedListener = new GravityHolder.SelectionListener() {
@Override
public void selected(int viewPos, Integer gravity) {
gravityList.set(viewPos, gravity);
updateChild();
}
};
private void updateChild() {
boolean found = false;
ArrayList<Integer> gravList = (ArrayList<Integer>) gravityList.clone();
for (int i = 0; i < gravList.size(); i++) {
Integer gravity = gravList.get(i);
if (gravity == Gravity.NO_GRAVITY) {
if (!found) {
found = true;
} else {
gravityList.remove(i);
}
}
}
if (!found) {
gravityList.add(Gravity.NO_GRAVITY);
}
notifyDataSetChanged();
}
public GravitySelectorAdapter(Context context) {
gravityList.add(Gravity.NO_GRAVITY);
layoutInflater = LayoutInflater.from(context);
}
@Override
public GravityHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new GravityHolder(parent, layoutInflater, gravitySelectedListener);
}
@Override
public void onBindViewHolder(GravityHolder holder, int position) {
holder.setGravity(position, gravityList.get(position));
}
@Override
public int getItemCount() {
return gravityList.size();
}
public int getGravity() {
int result = 0;
for (Integer integer : gravityList) {
result |= integer;
}
return result;
}
}
|
/**
* Paintroid: An image manipulation application for Android.
* Copyright (C) 2010-2013 The Catrobat Team
* (<http://developer.catrobat.org/credits>)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.catrobat.paintroid.test.integration;
import org.catrobat.paintroid.PaintroidApplication;
import org.catrobat.paintroid.R;
import org.catrobat.paintroid.dialog.IndeterminateProgressDialog;
import org.catrobat.paintroid.test.utils.PrivateAccess;
import org.catrobat.paintroid.tools.ToolType;
import org.catrobat.paintroid.ui.DrawingSurface;
import org.catrobat.paintroid.ui.Perspective;
import org.junit.Before;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.PointF;
import android.graphics.drawable.BitmapDrawable;
import android.widget.ImageButton;
public class UndoRedoIntegrationTest extends BaseIntegrationTestClass {
private static final String PRIVATE_ACCESS_TRANSLATION_X = "mSurfaceTranslationX";
public UndoRedoIntegrationTest() throws Exception {
super();
}
@Override
@Before
protected void setUp() {
super.setUp();
}
public void testDisableEnableUndo() {
ImageButton undoButton1 = (ImageButton) mSolo.getView(R.id.btn_top_undo);
Bitmap bitmap1 = ((BitmapDrawable) undoButton1.getDrawable()).getBitmap();
mSolo.clickOnView(mButtonTopUndo);
mSolo.waitForDialogToClose();
// assertTrue("Undo has not finished", hasProgressDialogFinished(LONG_WAIT_TRIES));
Bitmap bitmap2 = ((BitmapDrawable) undoButton1.getDrawable()).getBitmap();
assertEquals(bitmap1, bitmap2);
PointF point = new PointF(mCurrentDrawingSurfaceBitmap.getWidth() / 2,
mCurrentDrawingSurfaceBitmap.getHeight() / 2);
mSolo.clickOnScreen(point.x, point.y);
Bitmap bitmap3 = ((BitmapDrawable) undoButton1.getDrawable()).getBitmap();
assertNotSame(bitmap1, bitmap3);
mSolo.clickOnView(mButtonTopUndo);
Bitmap bitmap4 = ((BitmapDrawable) undoButton1.getDrawable()).getBitmap();
assertEquals(bitmap1, bitmap4);
}
public void testDisableEnableRedo() {
ImageButton redoButton1 = (ImageButton) mSolo.getView(R.id.btn_top_redo);
Bitmap bitmap1 = ((BitmapDrawable) redoButton1.getDrawable()).getBitmap();
mSolo.clickOnView(mButtonTopRedo);
Bitmap bitmap2 = ((BitmapDrawable) redoButton1.getDrawable()).getBitmap();
assertEquals(bitmap1, bitmap2);
PointF point = new PointF(mCurrentDrawingSurfaceBitmap.getWidth() / 2,
mCurrentDrawingSurfaceBitmap.getHeight() / 2);
mSolo.clickOnScreen(point.x, point.y);
Bitmap bitmap3 = ((BitmapDrawable) redoButton1.getDrawable()).getBitmap();
assertEquals(bitmap1, bitmap3);
mSolo.clickOnView(mButtonTopUndo);
mSolo.waitForDialogToClose();
Bitmap bitmap4 = ((BitmapDrawable) redoButton1.getDrawable()).getBitmap();
assertNotSame(bitmap1, bitmap4);
}
public void testPreserveZoomAndMoveAfterUndo() throws SecurityException, NoSuchFieldException,
IllegalAccessException {
// DrawingSurface drawingSurface = (DrawingSurface) getActivity().findViewById(R.id.drawingSurfaceView);
int xCoord = 100;
int yCoord = 200;
PointF pointOnBitmap = new PointF(xCoord, yCoord);
int colorOriginal = PaintroidApplication.drawingSurface.getPixel(pointOnBitmap);
// fill bitmap
selectTool(ToolType.FILL);
PointF pointOnScreen = new PointF(pointOnBitmap.x, pointOnBitmap.y);
PaintroidApplication.perspective.convertFromScreenToCanvas(pointOnScreen);
mSolo.clickOnScreen(pointOnScreen.x, pointOnScreen.y);
// mSolo.sleep(4000);
// move & zoom
float scale = 0.5f;
PaintroidApplication.perspective.setScale(scale); // done this way since robotium does not support > 1
// touch event
mSolo.clickOnView(mButtonTopTool); // switch to move-tool
mSolo.drag(pointOnScreen.x, pointOnScreen.x + 20, pointOnScreen.y, pointOnScreen.y + 20, 1);
float translationXBeforeUndo = (Float) PrivateAccess.getMemberValue(Perspective.class,
PaintroidApplication.perspective, PRIVATE_ACCESS_TRANSLATION_X);
float translationYBeforeUndo = (Float) PrivateAccess.getMemberValue(Perspective.class,
PaintroidApplication.perspective, PRIVATE_ACCESS_TRANSLATION_X);
// press undo
mSolo.clickOnView(mButtonTopUndo);
mSolo.waitForDialogToClose();
// check perspective and undo
int colorAfterFill = PaintroidApplication.drawingSurface.getPixel(pointOnBitmap);
assertEquals("Pixel color should be the same", colorOriginal, colorAfterFill);
float translationXAfterUndo = (Float) PrivateAccess.getMemberValue(Perspective.class,
PaintroidApplication.perspective, PRIVATE_ACCESS_TRANSLATION_X);
assertEquals("X-Translation should stay the same after undo", translationXBeforeUndo, translationXAfterUndo);
float translationYAfterUndo = (Float) PrivateAccess.getMemberValue(Perspective.class,
PaintroidApplication.perspective, PRIVATE_ACCESS_TRANSLATION_X);
assertEquals("Y-Translation should stay the same after undo", translationYBeforeUndo, translationYAfterUndo);
assertEquals("Scale should stay the same after undo", PaintroidApplication.perspective.getScale(), scale);
}
public void testPreserveZoomAndMoveAfterRedo() throws SecurityException, NoSuchFieldException,
IllegalAccessException {
assertTrue("Waiting for DrawingSurface", mSolo.waitForView(DrawingSurface.class, 1, TIMEOUT));
PaintroidApplication.perspective.setScale(1.0f);
int xCoord = mScreenHeight / 2;
int yCoord = mScreenWidth / 2;
PointF pointOnBitmap = new PointF(xCoord, yCoord);
int colorOriginal = PaintroidApplication.drawingSurface.getPixel(pointOnBitmap);
// fill bitmap
selectTool(ToolType.FILL);
int colorToFill = PaintroidApplication.currentTool.getDrawPaint().getColor();
PointF pointOnScreen = new PointF(pointOnBitmap.x, pointOnBitmap.y);
PaintroidApplication.perspective.convertFromScreenToCanvas(pointOnScreen);
mSolo.clickOnScreen(pointOnScreen.x, pointOnScreen.y);
mSolo.waitForDialogToClose(TIMEOUT);
int colorAfterFill = PaintroidApplication.drawingSurface.getPixel(pointOnBitmap);
assertEquals("Pixel color should be the same", colorToFill, colorAfterFill);
// press undo
mSolo.clickOnView(mButtonTopUndo);
mSolo.waitForDialogToClose();
int colorAfterUndo = PaintroidApplication.drawingSurface.getPixel(pointOnBitmap);
assertEquals("Pixel color should be the same", colorOriginal, colorAfterUndo);
// move & zoom
float scale = 0.5f;
PaintroidApplication.perspective.setScale(scale); // done this way since robotium does not support > 1
// touch event
mSolo.clickOnView(mButtonTopTool); // switch to move-tool
mSolo.drag(pointOnScreen.x, pointOnScreen.x + 20, pointOnScreen.y, pointOnScreen.y + 20, 1);
float translationXBeforeUndo = (Float) PrivateAccess.getMemberValue(Perspective.class,
PaintroidApplication.perspective, PRIVATE_ACCESS_TRANSLATION_X);
float translationYBeforeUndo = (Float) PrivateAccess.getMemberValue(Perspective.class,
PaintroidApplication.perspective, PRIVATE_ACCESS_TRANSLATION_X);
// press redo
mSolo.clickOnView(mButtonTopRedo);
mSolo.waitForDialogToClose();
// check perspective and redo
int colorAfterRedo = PaintroidApplication.drawingSurface.getPixel(pointOnBitmap);
assertEquals("Pixel color should be the same", colorToFill, colorAfterRedo);
float translationXAfterUndo = (Float) PrivateAccess.getMemberValue(Perspective.class,
PaintroidApplication.perspective, PRIVATE_ACCESS_TRANSLATION_X);
assertEquals("X-Translation should stay the same after undo", translationXBeforeUndo, translationXAfterUndo);
float translationYAfterUndo = (Float) PrivateAccess.getMemberValue(Perspective.class,
PaintroidApplication.perspective, PRIVATE_ACCESS_TRANSLATION_X);
assertEquals("Y-Translation should stay the same after undo", translationYBeforeUndo, translationYAfterUndo);
assertEquals("Scale should stay the same after undo", PaintroidApplication.perspective.getScale(), scale);
}
// @FlakyTest(tolerance = 3)
public void testUndoProgressDialogIsShowing() {
ImageButton undoButton = (ImageButton) mSolo.getView(R.id.btn_top_undo);
PointF point = new PointF(mCurrentDrawingSurfaceBitmap.getWidth() / 2,
mCurrentDrawingSurfaceBitmap.getHeight() / 2);
mSolo.clickOnScreen(point.x, point.y);
mSolo.waitForView(undoButton);
mSolo.clickOnView(undoButton);
// assertProgressDialogShowing();
mSolo.waitForDialogToClose();
assertFalse("Progress Dialog is still showing", IndeterminateProgressDialog.getInstance().isShowing());
}
@dk.au.cs.thor.robotium2espresso.UnstableTest
public void testRedoProgressDialogIsClosing() {
ImageButton undoButton = (ImageButton) mSolo.getView(R.id.btn_top_undo);
ImageButton redoButton = (ImageButton) mSolo.getView(R.id.btn_top_redo);
PointF point = new PointF(mCurrentDrawingSurfaceBitmap.getWidth() / 2,
mCurrentDrawingSurfaceBitmap.getHeight() / 2);
mSolo.clickOnScreen(point.x, point.y);
selectTool(ToolType.FILL);
PaintroidApplication.currentTool.changePaintColor(Color.BLUE);
point = new PointF(mCurrentDrawingSurfaceBitmap.getWidth() / 4, mCurrentDrawingSurfaceBitmap.getHeight() / 4);
mSolo.clickOnScreen(point.x, point.y);
mSolo.waitForView(undoButton);
mSolo.clickOnView(undoButton);
mSolo.waitForView(redoButton);
mSolo.clickOnView(redoButton);
// assertProgressDialogShowing(); // redo is too fast, assert fails
mSolo.waitForDialogToClose();
assertFalse("Progress Dialog is still showing", IndeterminateProgressDialog.getInstance().isShowing());
}
// @Override
// protected boolean hasProgressDialogFinished(int numberOfTries) {
// mSolo.sleep(500);
// Dialog progressDialog = ProgressIntermediateDialog.getInstance();
//
// int waitForDialogSteps = 0;
// final int MAX_TRIES = 200;
// for (; waitForDialogSteps < MAX_TRIES; waitForDialogSteps++) {
// if (progressDialog.isShowing())
// mSolo.sleep(100);
// else
// break;
// }
// return waitForDialogSteps < MAX_TRIES ? true : false;
// }
}
|
package config;
public class Configuration {
public static int MRS = 1;
public static long PASSIVE_PRICE_IMPROVEMENT = 50L;
public static short MAX_ORDER_DURATION_DAYS = 90;
public static short CIRCUIT_BREAKER_TOLERANCE_PERCENTAGE = 10;
}
|
package com.geekparkhub.core.kafka.producer;
import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;
import java.util.Properties;
/**
* Geek International Park | ๆๅฎขๅฝ้
ๅ
ฌๅญ
* GeekParkHub | ๆๅฎขๅฎ้ชๅฎค
* Website | https://www.geekparkhub.com/
* Description | Openๅผๆพ ยท Creationๅๆณ | OpenSourceๅผๆพๆๅฐฑๆขฆๆณ GeekParkHubๅ
ฑๅปบๅๆๆช่ง
* HackerParkHub | ้ปๅฎขๅ
ฌๅญๆข็บฝ
* Website | https://www.hackerparkhub.com/
* Description | ไปฅๆ ๆ็ๆง็ๆข็ดข็ฒพ็ฅ ๅผๅๆช็ฅๆๆฏไธๅฏนๆๆฏ็ๅดๆ
* GeekDeveloper : JEEP-711
*
* @author system
* <p>
* OldProduce
* <p>
*/
public class OldProduce {
@SuppressWarnings("deprecation")
public static void main(String[] args) {
/**
* Configuration information
* ้
็ฝฎไฟกๆฏ
*/
Properties props = new Properties();
/**
* Kafka configuration information
* Kafka้
็ฝฎไฟกๆฏ
*/
props.put("metadata.broker.list", "systemhub511:9092");
/**
* Response level
* ๅบ็ญ็บงๅซ
*/
props.put("request.required.acks", "1");
/**
* K value serialization
* Kๅผ ๅบๅๅ
*/
props.put("serializer.class", "kafka.serializer.StringEncoder");
/**
* Instantiate producer object
* ๅฎไพๅ ็ไบง่
ๅฏน่ฑก
*/
Producer<Integer, String> producer = new Producer<Integer, String>(new ProducerConfig(props));
/**
* Send data
* ๅ้ๆฐๆฎ
*/
KeyedMessage<Integer, String> message = new KeyedMessage<Integer, String>("topic001", "Hello,World");
producer.send(message);
}
}
|
import java.io.Serializable;
public abstract class Customer implements Serializable
{
private String ID; //instance variable declaration for customer class
private String name;
private String phone;
public Customer(String ID,String name,String phone) //constructor for customer class
{
this.ID = ID;
this.name = name;
this.phone = phone;
}
public abstract double getDiscount(double tot_charge);
public String getcusID() //accessors for instance variables
{
return ID;
}
public void setcusID(String ID)
{
this.ID = ID;
}
public String getcusname()
{
return name;
}
public void setcusname(String name)
{
this.name = name;
}
public String getcusphone()
{
return phone;
}
public void setcusphone(String phone)
{
this.phone = phone;
}
public void print()
{
System.out.println("**************** Vehicle Details ****************");
System.out.print("Customer ID="+this.getcusID());
System.out.print("\tName="+this.getcusname());
System.out.print("\tPhone="+this.getcusphone());
}
}
|
package com.smxknife.java2.thread.scheduledexecutorservice.demo01;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
/**
* @author smxknife
* 2019/8/29
*/
public class MyCallableA implements Callable<String> {
@Override
public String call() throws Exception {
System.out.println("A begin: " + Thread.currentThread().getName() + " " + System.currentTimeMillis());
TimeUnit.SECONDS.sleep(3);
System.out.println("A end: " + Thread.currentThread().getName() + " " + System.currentTimeMillis());
return "returnA";
}
}
|
package com.elvis.web.action;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
import com.elvis.dao.impl.UserDaoImpl;
import com.elvis.domain.User;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class LoginAction extends ActionSupport implements SessionAware {
UserDaoImpl dao = new UserDaoImpl();
private String username;
private String password;
private Map<String,Object> session;
public String execute(){
User user = dao.isValidAdmin(username, password);//ๅฐusernameๅpasswordไผ ้ๅฐdaoๅฑไบค็ปhibernateๅคๆญ
if(user!=null){
session.put("user", user);//่ฅ็ป้ๆๅๅๅฐ่ฏฅuser่ฎฐๅฝๅจsessionไธญ
return "success";
}else{
addActionError("ไฝ ๆฒกๆ็ฎก็ๆ้");
return "error";
}
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Map<String, Object> getSession() {
return session;
}
@Override
public void setSession(Map<String, Object> session) {
this.session = session;
}
}
|
package com.heinrichreimersoftware.materialdrawer.structure;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.os.Parcel;
import android.test.AndroidTestCase;
import android.test.mock.MockResources;
import junit.framework.TestCase;
import java.io.ByteArrayInputStream;
/**
* Created by serayuzgur on 24/10/15.
*/
public class DrawerItemTest extends AndroidTestCase {
public void testWriteToParcel() throws Exception {
DrawerItem test = new DrawerItem()
.setRoundedImage(new BitmapDrawable(MockResources.getSystem(), makeBitmap()))
.setTextPrimary("TestPrimary")
.setTextSecondary("TestSecondary");
Parcel parcel = Parcel.obtain();
test.writeToParcel(parcel, 0);
// After you're done with writing, you need to reset the parcel for reading:
parcel.setDataPosition(0);
// Reconstruct object from parcel and asserts:
DrawerItem createdFromParcel = DrawerItem.CREATOR.createFromParcel(parcel);
assertEquals(test, createdFromParcel);
}
static Bitmap makeBitmap() {
return makeBitmap(10, 10);
}
static Bitmap makeBitmap(int width, int height) {
return Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
}
}
|
import java.util.Scanner;
public class Tetromino_14500 {
static String[][] blocks = {
{"1111"},
{"11", "11"},
{"10", "10", "11"},
{"111", "010"},
{"10", "11", "01"}
};
static String[] mirror(String[] input) {
String[] answer = new String[input.length];
for (int i = 0; i < input.length; i++) {
answer[i] = new StringBuilder(input[i]).reverse().toString();
}
return answer;
}
static String[] rotate(String[] input) {
String[] answer = new String[input[0].length()];
for (int i = 0; i < input[0].length(); i++) {
StringBuilder sb = new StringBuilder();
for (int j = input.length - 1; j >= 0; j--) {
sb.append(input[j].charAt(i));
}
answer[i] = sb.toString();
}
return answer;
}
public static int calculate(int[][] array, String[] temp, int starting_x, int starting_y) {
int n = array.length;
int m = array[0].length;
int sum = 0;
for (int i = 0; i < temp.length; i++) {
for (int j = 0; j < temp[0].length(); j++) {
if (temp[i].charAt(j) == '0') {
continue;
}
int nx = starting_x + i;
int ny = starting_y + j;
if (nx >= 0 && nx < n && ny >= 0 && ny < m) {
sum += array[nx][ny];
} else {
return -1;
}
}
}
return sum;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] line = sc.nextLine().split(" ");
int n = Integer.parseInt(line[0]);
int m = Integer.parseInt(line[1]);
int[][] array = new int[n][m];
for (int i = 0; i < n; i++) {
String[] row = sc.nextLine().split(" ");
for (int j = 0; j < m; j++) {
array[i][j] = Integer.parseInt(row[j]);
}
}
int answer = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
for (String[] block: blocks) {
String[] temp = new String[block.length];
System.arraycopy(block, 0, temp, 0, block.length);
for (int mirror = 0; mirror < 2; mirror++) {
for (int rotate = 0; rotate < 4; rotate++) {
int current = calculate(array, temp, i, j);
if (current != -1 && answer < current) {
answer = current;
}
temp = rotate(temp);
}
temp = mirror(temp);
}
}
}
}
System.out.println(answer);
}
}
|
package com.ssm.wechatpro.service.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;
import com.ssm.wechatpro.bean.wechat.AccessToken;
import com.ssm.wechatpro.bean.wechat.Button;
import com.ssm.wechatpro.bean.wechat.CommonButton;
import com.ssm.wechatpro.bean.wechat.ComplexButton;
import com.ssm.wechatpro.bean.wechat.Menu;
import com.ssm.wechatpro.bean.wechat.ViewButton;
import com.ssm.wechatpro.dao.WechatAppMapper;
import com.ssm.wechatpro.dao.WechatButtomMenuMapper;
import com.ssm.wechatpro.object.InputObject;
import com.ssm.wechatpro.object.OutputObject;
import com.ssm.wechatpro.service.WechatButtomMenuService;
import com.ssm.wechatpro.util.Constants;
import com.ssm.wechatpro.util.DateUtil;
import com.ssm.wechatpro.util.ToolUtil;
import com.ssm.wechatpro.util.WeixinUtil;
@Service
public class WechatButtomMenuServiceImpl implements WechatButtomMenuService {
@Resource
private WechatButtomMenuMapper wechatButtomMenuMapper;
@Resource
private WechatAppMapper wechatAppMapper;
/***
* ๆฅๆพๆๆ่ๅ้กน
* @amparam inputObject
* @par outputObject
* @throws Exception
*/
@Override
public void selectAllMenus(InputObject inputObject, OutputObject outputObject) throws Exception {
Map<String, Object> params = inputObject.getParams();
params.put("menuVersion", "%" + params.get("menuVersion") + "%");
int page = Integer.parseInt(params.get("offset").toString())
/ Integer.parseInt(params.get("limit").toString());
page++;
int limit = Integer.parseInt(params.get("limit").toString());
List<Map<String, Object>> menus = wechatButtomMenuMapper.selectAllMenuList(params,new PageBounds(page, limit));
PageList<Map<String, Object>> abilityInfoPageList = (PageList<Map<String, Object>>) menus;
int total = abilityInfoPageList.getPaginator().getTotalCount();
outputObject.setBeans(menus);
outputObject.settotal(total);
}
/***
* ๆฅ็Version็ธๅ็่ๅ้กน
* @amparam inputObject
* @par outputObject
* @throws Exception
*/
@Override
public void selectMenuByVersion(InputObject inputObject, OutputObject outputObject) throws Exception {
Map<String, Object> params = inputObject.getParams();
List<Map<String, Object>> menus = wechatButtomMenuMapper.selectMenuByVersion(params);
for(Map<String, Object> menu : menus){
List<Map<String, Object>> menuItems = wechatButtomMenuMapper.selectMenuByBelong(menu);
menu.put("menuItems", menuItems);
}
outputObject.setBeans(menus);
}
/***
*ๅๅธ่ๅ
* @amparam inputObject
* @par outputObject
* @throws Exception
*/
@Override
public void updateMenuPublish(InputObject inputObject, OutputObject outputObject) throws Exception {
Map<String, Object> params = inputObject.getParams();
List<Map<String, Object>> appBeans = wechatAppMapper.getApp();
if (appBeans.isEmpty()) {
outputObject.setreturnMessage("่ฏท็กฎ่ฎคAPPIDๆ่
APPSECRETๅญๅจ...");
} else {
AccessToken at = WeixinUtil.getAccessToken(appBeans.get(0).get("appId").toString(), appBeans.get(0).get("appSecret").toString());
if (null != at) {
// ่ฐ็จๆฅๅฃๅๅปบ่ๅ
Map<String, Object> bean = new HashMap<>();
bean.put("menuVersion", params.get("menuVersion"));
Map<String,Object> result = WeixinUtil.createMenu(selectPublish(bean),at.getToken());
// ๅคๆญ่ๅๅๅปบ็ปๆ
if (!result.isEmpty()) {
if(result.get("returnCode").toString().equals(Constants.WECHAT_BUTTOM_MENU_SUCCESS)){
wechatButtomMenuMapper.updatewetherPublish();
params.put("publishUser",inputObject.getLogParams().get("id"));
params.put("publishTime", DateUtil.getTimeAndToString());
wechatButtomMenuMapper.updatePublish(params);
}else{
outputObject.setreturnMessage("ๅๅปบ่ๅๅคฑ่ดฅใ้่ฏฏ็ผ็ errcode๏ผ" + result.get("returnCode") + "้่ฏฏไฟกๆฏerrmsg:" + result.get("returnMsg"));
}
} else {
outputObject.setreturnMessage("่ฏทๆฑๅพฎไฟกๆๅกๅจๅคฑ่ดฅ...");
}
}
}
}
public Menu selectPublish(Map<String,Object> map) throws Exception{
// ๆฅ่ฏขๆๆ็ไธ็บง่ๅ
map.put("menuLevel", "1");
List<Map<String,Object>> firstBeans = wechatButtomMenuMapper.SelectAllByLevel(map);
// ๆฅ่ฏขๆๆ็ไบ็บง่ๅ
map.put("menuLevel", "2");
List<Map<String,Object>> secondBeans = wechatButtomMenuMapper.SelectAllByLevel(map);
Menu menu = new Menu();
// ็จๆฅๅญๅจไธ็บง่ๅ
List<ComplexButton> btn_0 = new ArrayList<ComplexButton>();
List<ViewButton> btn_1 = new ArrayList<ViewButton>();
List<CommonButton> btn_2 = new ArrayList<CommonButton>();
for (Map<String,Object> bean : firstBeans) {
ComplexButton mainBtn = new ComplexButton();
if (Integer.parseInt(bean.get("hasChild").toString()) == 1) {
// ไธ็บง่ๅไธ้ขๆไบ็บง่ๅ
mainBtn.setName(bean.get("menuName").toString());
// ็จๆฅๅญๅจไบ็บง่ๅ
List<CommonButton> btn1 = new ArrayList<CommonButton>();
List<ViewButton> btn2 = new ArrayList<ViewButton>();
for (Map<String,Object> bean1 : secondBeans) {
if (bean1.get("menuBelong").equals(bean.get("id")) && bean1.get("menuType").equals("click")) {
// ๅๅคๅ
ๅฎน็่ๅ
CommonButton btnbe = new CommonButton();
btnbe.setName(bean1.get("menuName").toString());
btnbe.setType(bean1.get("menuType").toString());
btnbe.setKey(bean1.get("menuKey").toString());
btn1.add(btnbe);
} else if (bean1.get("menuBelong").equals(bean.get("id")) && bean1.get("menuType").equals("view")) {
// ่ทณ่ฝฌ็ฝ้กต็่ๅ
ViewButton btnbe = new ViewButton();
btnbe.setName(bean1.get("menuName").toString());
btnbe.setType(bean1.get("menuType").toString());
btnbe.setUrl(bean1.get("rebackContext").toString());
btn2.add(btnbe);
}
}
switch (btn1.size() + btn2.size()) {
case 1:
switch (btn1.size()) {
case 0:mainBtn.setSub_button(new Button[] { btn2.get(0) });break;
case 1:mainBtn.setSub_button(new Button[] { btn1.get(0) });break;
default:break;
}break;
case 2:
switch (btn1.size()) {
case 0:mainBtn.setSub_button(new Button[] { btn2.get(0),btn2.get(1) });break;
case 1:mainBtn.setSub_button(new Button[] { btn1.get(0),btn2.get(0) });break;
case 2:mainBtn.setSub_button(new Button[] { btn1.get(0),btn1.get(1) });break;
default:break;
}break;
case 3:
switch (btn1.size()) {
case 0:mainBtn.setSub_button(new Button[] { btn2.get(0),btn2.get(1), btn2.get(2) });break;
case 1:mainBtn.setSub_button(new Button[] { btn1.get(0),btn2.get(0), btn2.get(1) });break;
case 2:mainBtn.setSub_button(new Button[] { btn1.get(0),btn1.get(1), btn2.get(0) });break;
case 3:mainBtn.setSub_button(new Button[] { btn1.get(0),btn1.get(1), btn1.get(2) });break;
default:break;
}
break;
case 4:
switch (btn1.size()) {
case 0:mainBtn.setSub_button(new Button[] { btn2.get(0),btn2.get(1), btn2.get(2), btn2.get(3) });break;
case 1:mainBtn.setSub_button(new Button[] { btn1.get(0),btn2.get(0), btn2.get(1), btn2.get(2) });break;
case 2:mainBtn.setSub_button(new Button[] { btn1.get(0),btn1.get(1), btn2.get(0), btn2.get(1) });break;
case 3:mainBtn.setSub_button(new Button[] { btn1.get(0),btn1.get(1), btn1.get(2), btn2.get(0) });break;
case 4:mainBtn.setSub_button(new Button[] { btn1.get(0),btn1.get(1), btn1.get(2), btn1.get(3) });break;
default:break;
}break;
case 5:
switch (btn1.size()) {
case 0:mainBtn.setSub_button(new Button[] { btn2.get(0),btn2.get(1), btn2.get(2), btn2.get(3),btn2.get(4) });break;
case 1:mainBtn.setSub_button(new Button[] { btn1.get(0),btn2.get(0), btn2.get(1), btn2.get(2),btn2.get(3) });break;
case 2:mainBtn.setSub_button(new Button[] { btn1.get(0),btn1.get(1), btn2.get(0), btn2.get(1),btn2.get(2) });break;
case 3:mainBtn.setSub_button(new Button[] { btn1.get(0),btn1.get(1), btn1.get(2), btn2.get(0),btn2.get(1) });break;
case 4:mainBtn.setSub_button(new Button[] { btn1.get(0),btn1.get(1), btn1.get(2), btn1.get(3),btn2.get(0) });break;
case 5:mainBtn.setSub_button(new Button[] { btn1.get(0),btn1.get(1), btn1.get(2), btn1.get(3),btn1.get(4) });break;
default:break;
}
mainBtn.setSub_button(new Button[] { btn1.get(0),btn1.get(1), btn1.get(2), btn1.get(3), btn1.get(4) });break;
default:break;
}
btn_0.add(mainBtn);
} else {
// ไธ็บง่ๅไธ้ขๆฒกๆไบ็บง่ๅ
if (bean.get("menuType").equals("click")) {
CommonButton btnbe = new CommonButton();
btnbe.setName(bean.get("menuName").toString());
btnbe.setType(bean.get("menuType").toString());
btnbe.setKey(bean.get("menuKey").toString());
btn_2.add(btnbe);
} else if (bean.get("menuType").equals("view")) {
ViewButton btnbe = new ViewButton();
btnbe.setName(bean.get("menuName").toString());
btnbe.setType(bean.get("menuType").toString());
btnbe.setUrl(bean.get("rebackContext").toString());
btn_1.add(btnbe);
}
}
}
switch (btn_0.size() + btn_1.size() + btn_2.size()) {
case 1:
switch (btn_0.size()) {
case 0:
switch (btn_1.size()) {
case 0: menu.setButton(new Button[] { btn_2.get(0) }); break;
case 1: menu.setButton(new Button[] { btn_1.get(0) }); break;
default: break;
}break;
case 1: menu.setButton(new Button[] { btn_0.get(0) }); break;
default: break;
}break;
case 2:
switch (btn_0.size()) {
case 0:
switch (btn_1.size()) {
case 0:menu.setButton(new Button[] { btn_2.get(0), btn_2.get(1) });break;
case 1:menu.setButton(new Button[] { btn_1.get(0), btn_2.get(0) });break;
case 2:menu.setButton(new Button[] { btn_1.get(0), btn_1.get(1) });break;
default:break;
}break;
case 1:
switch (btn_1.size()) {
case 0:menu.setButton(new Button[] { btn_0.get(0), btn_2.get(0) });break;
case 1:menu.setButton(new Button[] { btn_0.get(0), btn_1.get(0) });break;
default:break;
}break;
case 2:menu.setButton(new Button[] { btn_0.get(0), btn_0.get(1) });break;
default:break;
} break;
case 3:
switch (btn_0.size()) {
case 0:
switch (btn_1.size()) {
case 0: menu.setButton(new Button[] { btn_2.get(0), btn_2.get(1), btn_2.get(2) }); break;
case 1: menu.setButton(new Button[] { btn_1.get(0), btn_2.get(0), btn_2.get(1) }); break;
case 2: menu.setButton(new Button[] { btn_1.get(0), btn_1.get(1), btn_2.get(0) }); break;
case 3: menu.setButton(new Button[] { btn_1.get(0), btn_1.get(1), btn_1.get(2) }); break;
default: break;
} break;
case 1:
switch (btn_1.size()) {
case 0: menu.setButton(new Button[] { btn_0.get(0), btn_2.get(0), btn_2.get(1) }); break;
case 1: menu.setButton(new Button[] { btn_0.get(0), btn_1.get(0), btn_2.get(0) }); break;
case 2: menu.setButton(new Button[] { btn_0.get(0), btn_1.get(0), btn_1.get(1) }); break;
default: break;
} break;
case 2:
switch (btn_1.size()) {
case 0: menu.setButton(new Button[] { btn_0.get(0), btn_2.get(0) }); break;
case 1: menu.setButton(new Button[] { btn_0.get(0), btn_1.get(0) }); break;
default: break;
} break;
case 3: menu.setButton(new Button[] { btn_0.get(0), btn_0.get(1), btn_0.get(2) }); break;
default: break;
} break;
default: break;
}
return menu;
}
/***
*ๆ นๆฎidๆฅ่ฏข่ๅ้กน
* @amparam inputObject
* @par outputObject
* @throws Exception
*/
@Override
public void selectMenuById(InputObject inputObject, OutputObject outputObject) throws Exception {
Map<String, Object> params = inputObject.getParams();
Map<String, Object> menu = wechatButtomMenuMapper.selectMenuById(params);
outputObject.setBean(menu);
}
/***
*ไฟฎๆน่ๅ้กน
* @amparam inputObject
* @par outputObject
* @throws Exception
*/
@Override
public void updatemenuById(InputObject inputObject, OutputObject outputObject) throws Exception {
Map<String,Object> params = inputObject.getParams();
if(!ToolUtil.contains(params,Constants.BUTTOMMENU_KEY,Constants.BUTTOMMENU_RETURNMESSAGE, inputObject, outputObject)){
return ;
}
if(params.get("rebackInt").equals("6"))
params.put("menuType", "view");
else
params.put("menuType", "click");
wechatButtomMenuMapper.updateMenu(params);
}
/***
*ๆทปๅ ่ๅ้กน
* @amparam inputObject
* @par outputObject
* @throws Exception
*/
@Override
public void addMenu(InputObject inputObject, OutputObject outputObject) throws Exception {
Map<String,Object> params = inputObject.getParams();
params.put("menuType","click");
params.put("menuKey", DateUtil.getToString());
if(params.get("menuLevel").toString().equals("1")){
params.put("menuBelong", 0);
}else{
Map<String,Object> map=new HashMap<String, Object>();
map.put("id", params.get("menuBelong"));
map.put("hasChild", 1);
wechatButtomMenuMapper.updateMenu(map);
}
params.put("hasChild", 0);
params.put("publishTime", "-");
params.put("createId", inputObject.getLogParams().get("id"));
params.put("createTime", DateUtil.getTimeAndToString());
params.put("wetherPublish", 0);
params.put("wetherUser", 0);
wechatButtomMenuMapper.addMenu(params);
}
/***
*็ๆ็ๆฌๅท
* @amparam inputObject
* @par outputObject
* @throws Exception
*/
@Override
public void getmenuVersion(InputObject inputObject,OutputObject outputObject) throws Exception {
Map<String,Object> map = new HashMap<String, Object>();
map.put("menuVersion", DateUtil.getToString());
outputObject.setBean(map);
}
/***
*ๅ ้ค่ๅ้กน
* @amparam inputObject
* @par outputObject
* @throws Exception
*/
@Override
public void deleteMenus(InputObject inputObject, OutputObject outputObject) throws Exception {
Map<String,Object> params = inputObject.getParams();
Map<String,Object> map = wechatButtomMenuMapper.selectMenuById(params);
if(map.get("menuLevel").toString().equals("2")){//ๅฆๆๆฏไบ็บง่ๅ
//็ดๆฅๆ นๆฎidๅ ้ค่ฏฅ้กน
wechatButtomMenuMapper.deleteButtomById(params);
//่ทๅ่ฏฅไบ็บง่ๅๆๅฑ็ไธ็บง่ๅ
map.put("id", map.get("menuBelong"));
List<Map<String,Object>> buttoms = wechatButtomMenuMapper.selectMenuByBelong(map);
////ๅคๆญ่ฏฅไบ็บง่ๅๆๅฑ็ไธ็บง่ๅๆฏ่ฟๆๅญ่็น
if(buttoms.isEmpty()){//่ฅไธบ็ฉบ็ๆญคไธ็บง่ๅ็ๆฏๅฆๆๅญๅญฉๅญ็ๅฑๆง่ฎพ็ฝฎไธบ0
Map<String,Object> updatebuttom = new HashMap<>();
updatebuttom.put("id", map.get("menuBelong"));
updatebuttom.put("hasChild",'0');
wechatButtomMenuMapper.updateMenu(updatebuttom);
}
}else{//ไธ็บง่ๅๅ ้ค่ฏฅ้กน๏ผๅ็ถ่ๅไธบ่ฏฅไธ็บง่ๅ็ๅญ่ๅ
wechatButtomMenuMapper.deleteButtomById(params);
map.put("menuBelong", map.get("id"));
wechatButtomMenuMapper.deleteButtomBymenuBelong(map);
}
}
}
|
package com.bh.noteon.viewmodel;
import android.arch.lifecycle.ViewModel;
public class MainViewModel extends ViewModel {
public MainViewModel() {
}
}
|
package generic;
/**
* Author: fangxueshun
* Description:
* Date: 2017/5/31
* Time: 10:18
*/
public interface Fruit {
String taste();
}
|
package com.baidu.dudu.framework.handler;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baidu.dudu.framework.exception.DuDuException;
import com.baidu.dudu.framework.interaction.TestInteraction;
import com.baidu.dudu.framework.mapper.DuDuMapper;
import com.baidu.dudu.framework.message.DuDuMessage;
import com.baidu.dudu.framework.message.DuDuSessionMessage;
import com.baidu.dudu.framework.message.DuDuTimeoutMessage;
/**
* @author rzhao
*/
public class IncomingMessageHandlerImpl implements IncomingMessageHandler {
private static Logger logger = LoggerFactory.getLogger(IncomingMessageHandlerImpl.class);
private DuDuMapper mapper;
private BlockingQueue<DuDuSessionMessage> receviedMessageQueue;
private TestInteraction testInteraction;
private long timeout;
public IncomingMessageHandlerImpl(BlockingQueue<DuDuSessionMessage> messageQueue, DuDuMapper mapper, long timeout) {
this.receviedMessageQueue = messageQueue;
this.mapper = mapper;
this.timeout = timeout;
}
@Override
public void incomingMessage(DuDuSessionMessage sessionMessage) {
try {
receviedMessageQueue.put(sessionMessage);
}
catch (InterruptedException e) {
logger.error("put message into messageQueue error!");
throw new DuDuException("put message into messageQueue error!");
}
}
/*
* (non-Javadoc)
* @see com.dudu.free.framework.handler.IncomingMessageHandler#receive()
*/
@Override
public DuDuSessionMessage receive() {
return receive(null);
}
public DuDuSessionMessage receive(DuDuMessage message) {
DuDuSessionMessage receivedMessage = null;
try {
if (message == null) {
receivedMessage = receviedMessageQueue.poll(timeout, TimeUnit.MILLISECONDS);
return receivedMessage;
}
if (message instanceof DuDuTimeoutMessage) {
DuDuTimeoutMessage timeoutMessage = (DuDuTimeoutMessage) message;
receivedMessage = receviedMessageQueue.poll(timeoutMessage.getTimeout(), timeoutMessage.getTimeunit());
if (receivedMessage == null) {
final String errorInfo = "No message recevied! Expect:" + timeoutMessage.getMessage().getClass();
logger.error(errorInfo);
throw new DuDuException(errorInfo);
}
testInteraction.analyticResult(timeoutMessage.getMessage(), mapper.compare(timeoutMessage.getMessage(), receivedMessage.getMessage()));
}
else {
receivedMessage = receviedMessageQueue.poll(timeout, TimeUnit.MILLISECONDS);
if (receivedMessage == null) {
final String errorInfo = "No message recevied! Expect:" + message.getClass();
logger.error(errorInfo);
throw new DuDuException(errorInfo);
}
logger.info("<------ recevied message: {} <------", message.getClass());
testInteraction.analyticResult(message, mapper.compare(message, receivedMessage.getMessage()));
}
return receivedMessage;
}
catch (InterruptedException e) {
throw new DuDuException("get message from receive queue error!", e);
}
catch (DuDuException e) {
throw new DuDuException("get message from receive queue error!", e);
}
finally {
//TODO:
}
}
public DuDuMapper getMapper() {
return mapper;
}
public void setMapper(DuDuMapper mapper) {
this.mapper = mapper;
}
public void setTestInteraction(TestInteraction testInteraction) {
this.testInteraction = testInteraction;
}
}
|
package com.ojas.rpo.security.dao.addressdetails;
import java.util.List;
import com.ojas.rpo.security.dao.Dao;
import com.ojas.rpo.security.entity.AddressDetails;
public interface AddressDetailsDao extends Dao<AddressDetails,Long> {
public List<AddressDetails> findBycpId(Long cpid);
}
|
package com.realcom.helloambulance.controller.changepassword;
import javax.servlet.http.HttpServletRequest;
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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.realcom.helloambulance.services.ChangePasswordService;
import com.realcom.helloambulance.util.ApplicationsUtil;
@Controller
@RequestMapping(value = "/user")
public class UserChangePasswordController {
@Autowired
private ChangePasswordService changePasswordService;
// ############# Change password (Narendra) #####################
@RequestMapping(value = "/changePassword", method = RequestMethod.GET)
public String changePassword(HttpServletRequest request) {
return "changePassword";
}
@RequestMapping(value = "/success", method = RequestMethod.POST)
public ModelAndView success(ModelAndView model, @RequestParam("password") String password,
HttpServletRequest request) {
String emailId = ApplicationsUtil.addUserName(request);
changePasswordService.changePasswordForUser(emailId, password);
model.setViewName("success");
return model;
}
@RequestMapping(value = "/check_oldpassword_user")
@ResponseBody
public String check_oldpassword_user(@RequestParam String old_password, HttpServletRequest request) {
String Email_Id = ApplicationsUtil.addUserName(request);
return changePasswordService.checkOldpasswordForUser(old_password, Email_Id);
}
//#################### Change password Completed #################
}
|
package com.mtihc.minecraft.treasurechest.events;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.block.Block;
import org.bukkit.block.DoubleChest;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.Event.Result;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import com.mtihc.minecraft.treasurechest.Permission;
import com.mtihc.minecraft.treasurechest.TreasureChestPlugin;
import com.mtihc.minecraft.treasurechest.persistance.TChestCollection;
import com.mtihc.minecraft.treasurechest.persistance.TreasureChest;
public class ChestOpenListener implements Listener{
private TreasureChestPlugin plugin;
private Map<String, TreasureInventory> inventories;
public ChestOpenListener(TreasureChestPlugin plugin) {
this.plugin = plugin;
this.inventories = new HashMap<String, TreasureInventory>();
}
@EventHandler(priority=EventPriority.HIGHEST)
public void onPlayerInteract(final PlayerInteractEvent event) {
// check action
if(!event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
return;
}
//
// get InventoryHolder and Block
//
// If it's a double chest...
// The InventoryHolder will be instanceof DoubleChest.
// The block will be DoubleChest.getLocation().getBlock() (which is always the left side)
//
Block block;
InventoryHolder holder;
block = event.getClickedBlock();
if(block.getState() instanceof InventoryHolder) {
// block is an InventoryHolder
holder = (InventoryHolder) block.getState();
if(holder.getInventory().getHolder() instanceof DoubleChest) {
// block is part of a DoubleChest
// adjust holder and block to be DoubleChest's
holder = holder.getInventory().getHolder();
block = ((DoubleChest)holder).getLocation().getBlock();
}
}
else {
// block is not an InventoryHolder
return;
}
TreasureChest tchest;
// get treasure chest id for that location
String id = TChestCollection.getChestId(block.getLocation());
// get the treasure chest object
try {
tchest = plugin.getChests().values().getChest(id);
} catch(NullPointerException e) {
tchest = null;
}
if(tchest == null) {
// not a treasure chest
return;
}
//
// right clicked a treasure chest !
//
// check/ignore protection
if(!tchest.ignoreProtection() && event.useInteractedBlock().equals(Result.DENY)) {
// protected, and protection is not ignored
return;
}
// deny anyway, because the player will open a "fake inventory"
event.setUseInteractedBlock(Result.DENY);
Player player = event.getPlayer();
// check permission
if(!allowAccess(player, tchest.isUnlimited())) {
player.sendMessage(ChatColor.RED + "You don't have permission to access this Treasure Chest.");
return;
}
Inventory inventory;
// get unique key for player @ inventory location
final String KEY = player.getName()+"@"+block.getLocation().toString();
// get remembered inventory for player, or null
TreasureInventory tInventory = inventories.get(KEY);
if(tInventory != null) {
// inventory still remembered, maybe there's still some old items in there
inventory = tInventory.getInventory();
}
else {
// create new Inventory
if(holder instanceof DoubleChest) {
inventory = plugin.getServer().createInventory(holder, holder.getInventory().getSize());
}
else {
inventory = plugin.getServer().createInventory(holder, holder.getInventory().getType());
}
// wrap inventory in an object that will clear itself from memory
tInventory = new TreasureInventory(plugin, 600L, inventory) {
@Override
protected void execute() {
inventories.remove(KEY);
}
};
inventories.put(KEY, tInventory);
}
// inventory will clear itself from the map
tInventory.schedule();
//
// copy the contents from the treasure chest,
// and open the fake inventory
//
//
// if treasure is unlimited,
// copy the items from the treasure chest, no matter what
//
if(tchest.isUnlimited()) {
tchest.toInventory(inventory);
// message unlimited!
String message = tchest.getMessage(TreasureChest.Message.FOUND_UNLIMITED);
if(message != null) {
player.sendMessage(ChatColor.GOLD + message);
}
}
//
// if treasure is not unlimited,
// check if/when the player has found the treasure before,
// and compare the time with the treasure's "forget-time".
//
else {
// when has player found before
long time = plugin.getMemory().whenHasPlayerFound((OfflinePlayer)player, id);
if(time != 0 && !hasForgotten(time, tchest.getForgetTime())) {
// already found and not forgotten that it was found
// message found already
String alreadyFoundMessage = tchest.getMessage(TreasureChest.Message.FOUND_ALREADY);
if(alreadyFoundMessage != null) {
player.sendMessage(ChatColor.GOLD + alreadyFoundMessage);
}
}
else {
// found for the first time (or after forget time)
// remember that this player found it at this time
plugin.getMemory().rememberPlayerFound((OfflinePlayer)player, id);
// set items to chest
// (calls setContents(ItemStack[]) )
tchest.toInventory(inventory);
// message found treasure!
String foundMessage = tchest.getMessage(TreasureChest.Message.FOUND);
if(foundMessage != null) {
player.sendMessage(ChatColor.GOLD + foundMessage);
}
}
}
// player opens "fake" inventory,
// this ensures players don't interfere with eachother's items
// (prevents ninjas, and treasure chest campers)
player.openInventory(inventory);
}
/* (non-Javadoc)
* @see org.bukkit.event.player.PlayerListener#onPlayerInteract(org.bukkit.event.player.PlayerInteractEvent)
*/
// @EventHandler
// public void onInventoryOpen(final InventoryOpenEvent event) {
//
// }
//
// public void onContainerBlockOpen(Player player, Block block, InventoryOpenEvent event) {
//
// // opening a treasure chest
//
// // prevent players looking in the same chest
// // only for non-unlimited chests
// if(!tchest.isUnlimited() && event.getViewers().size() > 1) {
// player.sendMessage(ChatColor.RED + "Somebody else is already looking in this Treasure Chest.");
// player.sendMessage(ChatColor.RED + "Please give him/her a minute.");
// return;
// }
//
//
//
// if(tchest.isUnlimited()) {
// // chest is unlimited
// // reset items
// tchest.toInventoryHolder((InventoryHolder)block.getState());
// // message
// String message = tchest.getMessage(TreasureChest.Message.FOUND_UNLIMITED);
// if(message != null) {
// player.sendMessage(ChatColor.GOLD + message);
// }
// }
// else {
// // chest is not-unlimited
// // when has player found before
// long time = plugin.getMemory().whenHasPlayerFound((OfflinePlayer)player, id);
//
// if(time != 0 && !hasForgotten(time, tchest.getForgetTime())) {
// // already found and not forgotten
//
// // message
// String alreadyFoundMessage = tchest.getMessage(TreasureChest.Message.FOUND_ALREADY);
// if(alreadyFoundMessage != null) {
// player.sendMessage(ChatColor.GOLD + alreadyFoundMessage);
// }
//
// }
// else {
// // found for the first time (or after forget time)
// // remember that this player found it
// plugin.getMemory().rememberPlayerFound((OfflinePlayer)player, id);
//
// // set items to chest
// tchest.toInventoryHolder((InventoryHolder)block.getState());
//
// // message
// String foundMessage = tchest.getMessage(TreasureChest.Message.FOUND);
// if(foundMessage != null) {
// player.sendMessage(ChatColor.GOLD + foundMessage);
// }
//
// }
// }
// return;
// }
//
// /* (non-Javadoc)
// * @see org.bukkit.event.player.PlayerListener#onPlayerInteract(org.bukkit.event.player.PlayerInteractEvent)
// */
// @EventHandler(priority = EventPriority.HIGHEST)
// public void onInventoryOpen(final InventoryOpenEvent event) {
// // get player
// Player player;
// if(event.getPlayer() instanceof Player) {
// player = (Player) event.getPlayer();
// }
// else {
// return;
// }
//
// // get inventory holder
// // could be a DoubleChest (which is not a block)
// InventoryHolder holder = event.getInventory().getHolder();
//
// if(holder instanceof DoubleChest) {
// // holder is a DoubleChest
// // get left and right side blocks
// DoubleChest chest = (DoubleChest) holder;
// Block left = getBlock(chest.getLeftSide());
// Block right = getBlock(chest.getRightSide());
//
// // handle left and right side seperately
// onContainerBlockOpen(player, right, event);
// onContainerBlockOpen(player, left, event);
// }
// else if(holder instanceof BlockState) {
// // holder not a DoubleChest
// // must be a normal container block
// Block block = getBlock(event.getInventory().getHolder());
// onContainerBlockOpen(player, block, event);
// }
// else {
// // this inventory does not belong to a block or double chest.
// return;
// }
// }
//
// private Block getBlock(InventoryHolder holder) {
// // convert an InventoryHolder to Block
// // (impossible for DoubleChest and others like HumanEntity)
// try {
// return ((BlockState)holder).getBlock();
// } catch(ClassCastException e) {
// return null;
// }
// }
//
private boolean hasForgotten(long foundTime, long forgetTime) {
if(foundTime <= 0) {
// never found, so yeah... act like forgotten
return true;
}
else if(forgetTime <= 0) {
// never forgets, so no
return false;
}
// now
Calendar now = Calendar.getInstance();
// when will the chest forget?
Calendar forgot = Calendar.getInstance();
forgot.setTimeInMillis(foundTime + forgetTime);
// is "now" later than "forgot"? Then yes, is forgotten
return now.compareTo(forgot) > 0;
}
private boolean allowAccess(HumanEntity humanEntity, boolean isUnlimitedChest) {
if(isUnlimitedChest) {
return humanEntity.hasPermission(Permission.ACCESS_UNLIMITED.getNode());
}
else {
return humanEntity.hasPermission(Permission.ACCESS_TREASURE.getNode());
}
}
}
|
package com.example.asynctaskexample;
import android.os.AsyncTask;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
private TextView txv_message;
private final static int MAX_LENGTH = 2000;
private Integer[] numbers = new Integer[MAX_LENGTH];
private Button btn_cancel;
private Button btn_short;
SimpleAsyncTask simpleAsyncTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txv_message = (TextView)findViewById(R.id.txv_message);
btn_short = (Button)findViewById(R.id.btn_Sort);
btn_cancel = (Button)findViewById(R.id.btn_cancel);
generarNumbers();
}
private void generarNumbers(){
Random rnd = new Random();
for (int i = 0; i < MAX_LENGTH; i++) {
numbers[i] = rnd.nextInt();
}
}
/**
* metodo que se ejecuta cuando se da a ordenar
* @param v
*/
public void onClickSort(View v){
if(v == btn_short) {
/**
* Opciรณn 1
*/
//bubbleShort(numbers);
//txv_message.setText("Operaciรณn Terminada");
/**
* Opciรณn 2
*/
//execWithThread();
/**
* opcion 3
*/
simpleAsyncTask = new SimpleAsyncTask();
simpleAsyncTask.execute();
}
if(v == btn_cancel){
simpleAsyncTask.cancel(true);
}
}
private void execWithThread() {
new Thread(new Runnable() {
@Override
public void run() {
bubbleShort();
runOnUiThread(new Runnable() {
@Override
public void run() {
txv_message.setText("Operaciรณn Terminada");
}
});
}
}).start();
}
/**
* Metodo que ordena un array mediante el metodo de la burbuja simple
*/
private void bubbleShort() {
int tmp;
for (int i = 0; i < numbers.length-1; i++) {
for (int j = i+1; j < numbers.length-1; j++) {
if(numbers[i]>numbers[j]){
tmp = numbers[i];
numbers[i] = numbers[j];
numbers[j]=tmp;
}
}
}
}
private class SimpleAsyncTask extends AsyncTask<Void,Integer,Void>{
@Override
protected Void doInBackground(Void... voids) {
int tmp;
for (int i = 0; i < numbers.length-1; i++) {
for (int j = i+1; j < numbers.length-1; j++) {
if(numbers[i]>numbers[j]){
tmp = numbers[i];
numbers[i] = numbers[j];
numbers[j]=tmp;
}
}
//si no se cancela la operacion se actualiza la barra de progreso;
if(!isCancelled()){
publishProgress(i , numbers.length);
}else{
return null;
}
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
float s = ((values[0]).floatValue()/ (values[1]).floatValue())*100;
txv_message.setText(String.valueOf(s)+"%");
}
@Override
protected void onPreExecute() {
btn_cancel.setVisibility(View.VISIBLE);
btn_short.setEnabled(false);
super.onPreExecute();
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
btn_cancel.setVisibility(View.INVISIBLE);
btn_short.setEnabled(true);
txv_message.setText("Operacion Terminada");
}
@Override
protected void onCancelled() {
btn_cancel.setVisibility(View.INVISIBLE);
btn_short.setEnabled(true);
txv_message.setText("Operacion Cancelada");
super.onCancelled();
}
}
}
|
package com.ybh.front.model;
public class DomainProductlistWithBLOBs extends DomainProductlist {
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column FreeHost_DomainProductlist.info
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
private String info;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column FreeHost_DomainProductlist.infomore
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
private String infomore;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column FreeHost_DomainProductlist.domstr
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
private String domstr;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column FreeHost_DomainProductlist.info
*
* @return the value of FreeHost_DomainProductlist.info
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public String getInfo() {
return info;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column FreeHost_DomainProductlist.info
*
* @param info the value for FreeHost_DomainProductlist.info
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public void setInfo(String info) {
this.info = info == null ? null : info.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column FreeHost_DomainProductlist.infomore
*
* @return the value of FreeHost_DomainProductlist.infomore
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public String getInfomore() {
return infomore;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column FreeHost_DomainProductlist.infomore
*
* @param infomore the value for FreeHost_DomainProductlist.infomore
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public void setInfomore(String infomore) {
this.infomore = infomore == null ? null : infomore.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column FreeHost_DomainProductlist.domstr
*
* @return the value of FreeHost_DomainProductlist.domstr
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public String getDomstr() {
return domstr;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column FreeHost_DomainProductlist.domstr
*
* @param domstr the value for FreeHost_DomainProductlist.domstr
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public void setDomstr(String domstr) {
this.domstr = domstr == null ? null : domstr.trim();
}
}
|
package project;
public enum Section {
ADULT, CHILD, FUN
}
|
package DataBase_Package;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
/**
* Questa Classe gestisce l'estrazione dei Fenomeni dal File DataSet.
* Contiene una serie di metodi utili per determianre le caratteristiche del file caricato.
* @author Angelo Casolaro
* @version 1.0
*/
public class Estrazione_Dati_File
{
private int Num_Caratteristiche = 0;
private int Num_Fenomeni = 0;
private RandomAccessFile LetturaFile = null;
private String Separatore = ",";
public Estrazione_Dati_File()
{
Num_Caratteristiche = 0;
Num_Fenomeni = 0;
LetturaFile = null;
}
public Estrazione_Dati_File( String Path )
{
setFile(Path);
}
public Estrazione_Dati_File( String Path, String Separatore )
{
setFile(Path);
// Andiamo a settare l'eventuale separatore che puรฒ essere diverso dalla
// classica "virgola"
if( Separatore != "" )
this.Separatore = Separatore;
}
public void setFile( String Path )
{
if( LetturaFile == null )
LetturaFile = File_DataSet.GetPointerFile(Path);
}
/**
* Questo Metodo ha il compito di restituire il numero di Caratteristiche del Fenomeni del DataSet.
* @return Numero di Caratteristiche dei Fenomeni osservati.
*/
public int get_Num_Caratt()
{
String Record;
// Se abbiamo gia' calcolato il Numero di Caratteristiche del Fenomeno
if( Num_Caratteristiche > 0 )
return Num_Caratteristiche;
try
{
// Ci posizioniamo all'inizio del File
LetturaFile.seek(0);
// Andiamo a leggere la prima riga...
Record = LetturaFile.readLine();
// Si vanno a prendere tutti i campi che sono divisi dal separatore scelto
String[] Campi = Record.split(Separatore);
int Numero_Campi = Campi.length;
// Per tutti i campi estratti...
for( int i=0; i<Numero_Campi; i++ )
{
try
{
@SuppressWarnings("unused")
double value = 0.0;
// Andiamo a verificare eventualmente se vi sono dei campi di tipo Stringa...
// quelli nel DataSet non vengono considerati
if( Campi[i] == " " || Campi[i] == "" )
Num_Caratteristiche++;
else
{
value = Double.parseDouble(Campi[i]);
Num_Caratteristiche++;
}
}
catch (NumberFormatException e)
{ }
}
LetturaFile.seek(0);
}
catch( IOException e )
{
e.printStackTrace();
}
return Num_Caratteristiche;
}
/**
* Questo Metodo ha il compito di restituire tutte le caratteristiche del Fenomeno attualmente elaborato.
* @return ArrayList di tutte le caratteristiche del Fenomeno attuale.
*/
public ArrayList<Double> get_NextFenomeno()
{
String Record = "";
ArrayList<Double> List_Caratteristiche = new ArrayList<>();
try
{
// Ci posizioniamo all'inizio del File
Record = LetturaFile.readLine();
// Se abbiamo la possibilitร di leggere...
if( Record != null )
{
// Si vanno a prendere tutti i campi che sono divisi dal separatore scelto
String[] Campi = Record.split(Separatore);
int Numero_Campi = Campi.length;
// Per tutti i campi estratti...
for( int i=0; i<Numero_Campi; i++ )
{
try
{
// Andiamo ad inserire tutte le caratteristiche che risultano essere
// di tipo double.
double value = 0.0;
// Nel caso in cui di valore Mancante
if( Campi[i] == " " || Campi[i] == "" )
value = 0.0;
else
value = Double.parseDouble(Campi[i]);
List_Caratteristiche.add(value);
}
catch (NumberFormatException e)
{ }
}
}
else
List_Caratteristiche = null;
}
catch( IOException e )
{
List_Caratteristiche = null;
e.printStackTrace();
}
return List_Caratteristiche;
}
/**
* Questo Metodo ha il compito di restituire il numero di Fenomeni del DataSet
* @return Numero Fenomeni del DataSet
*/
public int getNumFen()
{
Num_Fenomeni = 0;
try
{
while( LetturaFile.readLine() != null )
Num_Fenomeni++;
}
catch( IOException e )
{
e.printStackTrace();
}
return Num_Fenomeni;
}
}
|
package com.rofour.baseball.dao.order.bean;
import java.io.Serializable;
import java.sql.Time;
import java.util.Date;
/**
* @ClassName: PacketOrderBean
* @Description: ๅฐๆดพ่ฎขๅ่ฏฆๆ
bean
* @author lijun
* @date 2016ๅนด10ๆ13ๆฅ ไธๅ2:56:13
*/
public class PacketOrderBean implements Serializable {
private String userPhone;//ๆถไปถไบบๆๆบๅท
private String userName;//ๆถไปถไบบๅงๅ
private Long collegeId;//ๅญฆๆ กId
private String collegeName;//ๅญฆๆ กๅ็งฐ
private String deliAddress;//้่ดงๅฐๅ
private String sex;//ๆงๅซ
private String fetchAddress;//ๅไปถๅฐๅ
private String cityName;//ๅๅธ
private String expressAddress;//ๅฟซ้็ซ็น
private String orderId;//่ฎขๅๅท
private Long payMoney;//ๅฎ้
ๆฏไป้้ข
private String waybillNo;//่ฟๅๅท
private String rebateType;//ไผๆ ๆนๅผ
/**
* ่ฎขๅ็ถๆ 1:ๅๅปบ2:ๅทฒๆฅๅ,3:้
้ไธญ,4: ๅค็ไธญ ,5:ๅฎๆ,6:ๅๆถ,7:ๅผๅธธ
*/
private String state;
/**
* ๆฏไปๆนๅผ ๆ นๆฎuserAgentๅบๅๅพฎไฟก่ฟๆฏๆฏไปๅฎ...
* 1๏ผๅพฎไฟก๏ผ2๏ผๆฏไปๅฎ
*/
private String payMethod;
private Integer feeMoney;//ๆ่ต้้ข
private String payType;//ๆฏไป็ฑปๅ
private Integer rebateMoney;//ไผๆ ้้ข
private String distribionRemark;//้
้่ฆๆฑ
private String payTime;
private String signTime;
private String pickupTime;
private String grabTime;
private String updateFeeTime;
private String createTime;
private String pickupCode;//ๅ่ดง็
private String bookTime;//้ข็บฆๆถ้ด
private Integer goodsAmount;//ๅๅ้้ข
public String getUserPhone() {
return userPhone;
}
public void setUserPhone(String userPhone) {
this.userPhone = userPhone;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Long getCollegeId() {
return collegeId;
}
public void setCollegeId(Long collegeId) {
this.collegeId = collegeId;
}
public String getCollegeName() {
return collegeName;
}
public void setCollegeName(String collegeName) {
this.collegeName = collegeName;
}
public String getDeliAddress() {
return deliAddress;
}
public void setDeliAddress(String deliAddress) {
this.deliAddress = deliAddress;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getFetchAddress() {
return fetchAddress;
}
public void setFetchAddress(String fetchAddress) {
this.fetchAddress = fetchAddress;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public String getExpressAddress() {
return expressAddress;
}
public void setExpressAddress(String expressAddress) {
this.expressAddress = expressAddress;
}
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public Long getPayMoney() {
return payMoney;
}
public void setPayMoney(Long payMoney) {
this.payMoney = payMoney;
}
public String getWaybillNo() {
return waybillNo;
}
public void setWaybillNo(String waybillNo) {
this.waybillNo = waybillNo;
}
public String getRebateType() {
return rebateType;
}
public void setRebateType(String rebateType) {
this.rebateType = rebateType;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPayMethod() {
return payMethod;
}
public void setPayMethod(String payMethod) {
this.payMethod = payMethod;
}
public Integer getFeeMoney() {
return feeMoney;
}
public void setFeeMoney(Integer feeMoney) {
this.feeMoney = feeMoney;
}
public String getPayType() {
return payType;
}
public void setPayType(String payType) {
this.payType = payType;
}
public Integer getGoodsAmount() {
return goodsAmount;
}
public void setGoodsAmount(Integer goodsAmount) {
this.goodsAmount = goodsAmount;
}
public Integer getRebateMoney() {
return rebateMoney;
}
public void setRebateMoney(Integer rebateMoney) {
this.rebateMoney = rebateMoney;
}
public String getDistribionRemark() {
return distribionRemark;
}
public void setDistribionRemark(String distribionRemark) {
this.distribionRemark = distribionRemark;
}
public String getPayTime() {
return payTime;
}
public void setPayTime(String payTime) {
this.payTime = payTime;
}
public String getSignTime() {
return signTime;
}
public void setSignTime(String signTime) {
this.signTime = signTime;
}
public String getPickupTime() {
return pickupTime;
}
public void setPickupTime(String pickupTime) {
this.pickupTime = pickupTime;
}
public String getGrabTime() {
return grabTime;
}
public void setGrabTime(String grabTime) {
this.grabTime = grabTime;
}
public String getUpdateFeeTime() {
return updateFeeTime;
}
public void setUpdateFeeTime(String updateFeeTime) {
this.updateFeeTime = updateFeeTime;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String getPickupCode() {
return pickupCode;
}
public void setPickupCode(String pickupCode) {
this.pickupCode = pickupCode;
}
public String getBookTime() {
return bookTime;
}
public void setBookTime(String bookTime) {
this.bookTime = bookTime;
}
}
|
package chap08.sec06.exam01_interface_extends;
public class Example {
public static void main(String[] args) {
ImplementationC c = new ImplementationC();
InterfaceA ia = c;
ia.methodA();
InterfaceB ib = c;
ib.mathodB();
InterfaceC ic = c;
ic.methodA();
ic.mathodB();
ic.methodC();
}
}
|
/*
* Copyright (C) 2019-2023 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hedera.mirror.importer.parser.record.transactionhandler;
import static com.hedera.mirror.common.domain.token.TokenFreezeStatusEnum.NOT_APPLICABLE;
import static com.hedera.mirror.common.domain.token.TokenFreezeStatusEnum.UNFROZEN;
import static com.hedera.mirror.importer.util.Utility.RECOVERABLE_ERROR;
import com.hedera.mirror.common.domain.entity.Entity;
import com.hedera.mirror.common.domain.entity.EntityId;
import com.hedera.mirror.common.domain.token.Token;
import com.hedera.mirror.common.domain.token.TokenAccount;
import com.hedera.mirror.common.domain.token.TokenKycStatusEnum;
import com.hedera.mirror.common.domain.token.TokenPauseStatusEnum;
import com.hedera.mirror.common.domain.token.TokenSupplyTypeEnum;
import com.hedera.mirror.common.domain.token.TokenTypeEnum;
import com.hedera.mirror.common.domain.transaction.RecordItem;
import com.hedera.mirror.common.domain.transaction.Transaction;
import com.hedera.mirror.common.domain.transaction.TransactionType;
import com.hedera.mirror.common.util.DomainUtils;
import com.hedera.mirror.importer.domain.EntityIdService;
import com.hedera.mirror.importer.parser.record.entity.EntityListener;
import com.hedera.mirror.importer.parser.record.entity.EntityProperties;
import com.hederahashgraph.api.proto.java.TokenAssociation;
import jakarta.inject.Named;
import lombok.CustomLog;
@CustomLog
@Named
class TokenCreateTransactionHandler extends AbstractEntityCrudTransactionHandler {
private final EntityProperties entityProperties;
private final TokenFeeScheduleUpdateTransactionHandler tokenFeeScheduleUpdateTransactionHandler;
TokenCreateTransactionHandler(
EntityIdService entityIdService,
EntityListener entityListener,
EntityProperties entityProperties,
TokenFeeScheduleUpdateTransactionHandler tokenFeeScheduleUpdateTransactionHandler) {
super(entityIdService, entityListener, TransactionType.TOKENCREATION);
this.entityProperties = entityProperties;
this.tokenFeeScheduleUpdateTransactionHandler = tokenFeeScheduleUpdateTransactionHandler;
}
@Override
public EntityId getEntity(RecordItem recordItem) {
return EntityId.of(recordItem.getTransactionRecord().getReceipt().getTokenID());
}
@Override
protected void doUpdateEntity(Entity entity, RecordItem recordItem) {
var transactionBody = recordItem.getTransactionBody().getTokenCreation();
if (transactionBody.hasAdminKey()) {
entity.setKey(transactionBody.getAdminKey().toByteArray());
}
if (transactionBody.hasAutoRenewAccount()) {
var autoRenewAccountId = entityIdService
.lookup(transactionBody.getAutoRenewAccount())
.orElse(EntityId.EMPTY);
if (EntityId.isEmpty(autoRenewAccountId)) {
log.error(RECOVERABLE_ERROR + "Invalid autoRenewAccountId at {}", recordItem.getConsensusTimestamp());
} else {
entity.setAutoRenewAccountId(autoRenewAccountId.getId());
recordItem.addEntityId(autoRenewAccountId);
}
}
if (transactionBody.hasAutoRenewPeriod()) {
entity.setAutoRenewPeriod(transactionBody.getAutoRenewPeriod().getSeconds());
}
if (transactionBody.hasExpiry()) {
entity.setExpirationTimestamp(DomainUtils.timestampInNanosMax(transactionBody.getExpiry()));
}
entity.setMemo(transactionBody.getMemo());
entityListener.onEntity(entity);
}
@Override
protected void doUpdateTransaction(Transaction transaction, RecordItem recordItem) {
if (!entityProperties.getPersist().isTokens() || !recordItem.isSuccessful()) {
return;
}
var transactionBody = recordItem.getTransactionBody().getTokenCreation();
long consensusTimestamp = transaction.getConsensusTimestamp();
var tokenId = transaction.getEntityId();
var treasury = EntityId.of(transactionBody.getTreasury());
var token = new Token();
token.setCreatedTimestamp(consensusTimestamp);
token.setDecimals(transactionBody.getDecimals());
token.setFreezeDefault(transactionBody.getFreezeDefault());
token.setInitialSupply(transactionBody.getInitialSupply());
token.setMaxSupply(transactionBody.getMaxSupply());
token.setName(transactionBody.getName());
token.setSupplyType(TokenSupplyTypeEnum.fromId(transactionBody.getSupplyTypeValue()));
token.setSymbol(transactionBody.getSymbol());
token.setTimestampLower(consensusTimestamp);
token.setTokenId(tokenId.getId());
token.setTotalSupply(transactionBody.getInitialSupply());
token.setTreasuryAccountId(treasury);
token.setType(TokenTypeEnum.fromId(transactionBody.getTokenTypeValue()));
if (transactionBody.hasFeeScheduleKey()) {
token.setFeeScheduleKey(transactionBody.getFeeScheduleKey().toByteArray());
}
if (transactionBody.hasFreezeKey()) {
token.setFreezeKey(transactionBody.getFreezeKey().toByteArray());
}
if (transactionBody.hasKycKey()) {
token.setKycKey(transactionBody.getKycKey().toByteArray());
}
if (transactionBody.hasPauseKey()) {
token.setPauseKey(transactionBody.getPauseKey().toByteArray());
token.setPauseStatus(TokenPauseStatusEnum.UNPAUSED);
} else {
token.setPauseStatus(TokenPauseStatusEnum.NOT_APPLICABLE);
}
if (transactionBody.hasSupplyKey()) {
token.setSupplyKey(transactionBody.getSupplyKey().toByteArray());
}
if (transactionBody.hasWipeKey()) {
token.setWipeKey(transactionBody.getWipeKey().toByteArray());
}
var customFees = transactionBody.getCustomFeesList();
var autoAssociatedAccounts =
tokenFeeScheduleUpdateTransactionHandler.updateCustomFees(customFees, recordItem, transaction);
autoAssociatedAccounts.add(treasury);
// automatic_token_associations does not exist prior to services 0.18.0
if (recordItem.getTransactionRecord().getAutomaticTokenAssociationsCount() > 0) {
autoAssociatedAccounts.clear();
recordItem.getTransactionRecord().getAutomaticTokenAssociationsList().stream()
.map(TokenAssociation::getAccountId)
.map(EntityId::of)
.forEach(autoAssociatedAccounts::add);
}
var freezeStatus = token.getFreezeKey() != null ? UNFROZEN : NOT_APPLICABLE;
var kycStatus = token.getKycKey() != null ? TokenKycStatusEnum.GRANTED : TokenKycStatusEnum.NOT_APPLICABLE;
autoAssociatedAccounts.forEach(account -> {
var tokenAccount = new TokenAccount();
tokenAccount.setAccountId(account.getId());
tokenAccount.setAssociated(true);
tokenAccount.setAutomaticAssociation(false);
tokenAccount.setCreatedTimestamp(consensusTimestamp);
tokenAccount.setFreezeStatus(freezeStatus);
tokenAccount.setKycStatus(kycStatus);
tokenAccount.setTimestampLower(consensusTimestamp);
tokenAccount.setTokenId(tokenId.getId());
entityListener.onTokenAccount(tokenAccount);
recordItem.addEntityId(account);
});
entityListener.onToken(token);
}
}
|
package kuaishou;
import java.util.Map;
public class PushMessageModel {
/**
* push business type ้ป่ฎคไธบๅฟซๆไธปapp๏ผ็ฎๅ่ฟๆฏๆGAME
*/
// private InfraPushCommon.BusinessType businessType = KUAISHOU;
/**
* push app ็ฑปๅ
*/
// private RecoPushBase.PushAppType pushAppType = KUAISHOU_MAIN;
/**
* pushไธๅกๅ
*/
private String promotionPushBiz;
/**
* ๅ้ๆถๆฏ็็ฑปๅ๏ผ็ฎๅๆpushๅ็ญไฟกไธค็ง็ฑปๅ๏ผ้ป่ฎคไธบpush
*/
// private MessageType messageType;
/**
* ่ฅไธบๅ้็ญไฟก็ฑปๅ๏ผ้่ฆ่ฎพ็ฝฎ็ญไฟกๆถๆฏๆจกๅ
*/
// private SmsModel smsModel;
/**
* push็ฑปๅ
*/
// private PushType pushTypeEnum;
/**
* ๆฅๆถๆนuserId
*/
private long userId;
/**
* ๆฅๆถๆนdeviceId
*/
private String deviceId;
/**
* ่ฅpush็ๆฏ่ง้ข๏ผ่ฟ้ไธบ่ง้ขid๏ผ่ฅpush็ๆฏ็ดๆญ๏ผ่ฟ้ๆฏ็ดๆญid
*/
private long photoId;
/**
* ๅ้่
Id๏ผๅฏไปฅไธบ0
*/
private long senderId;
/**
* ๆถๆฏๆ ้ข
*/
private String title;
/**
* ๅ้pushๆถ็ๆถๆฏๆ่ฆ
*/
private String body;
/**
* ๅฆๆmessageIdไธkeywork้็ฉบ๏ผmessageIๅฟ
้กปๅ
ๅซkeywork
*/
private String messageId;
/**
* ๆถๆฏidๅ
ณ้ฎๅญ
*/
// private PushMessageIdKeyworkEnum keywork;
/**
* push่ฝๅฐ็้พๆฅ
*/
private String rawUrl;
/**
* pushๆถๆฏๅฐๅพ
*/
private String smallPicture;
/**
* pushๅคงๅพ
*/
private String largePicture;
/**
* ็ดๆญpush็ธๅ
ณไฟกๆฏ๏ผๅฆๆpushๆถๆฏไธบ็ดๆญ็ฑปๅ๏ผ้่ฆ่ฎพ็ฝฎ่ฏฅๅญๆฎต
*/
// private LiveStreamModel liveStreamModel;
/**
* ๆฏๅฆๅธฆ้ขๆง็push,้ป่ฎคไธบfalse,ๅณๆ้ขๆง
*/
private boolean noQuotaControlFlag;
/**
* pushๆชๆญขๆถ้ด๏ผๅณๅจ่ฟไธชๆถ้ดไนๅ๏ผไฟ่ฏpushไธๅๅ้๏ผไธป่ฆ็จๆฅ่ฎพ็ฝฎๆๆๆ๏ผ็จๆชๆญขๆถ้ดๅๅปๅ้pushๆถ็ๅฝๅๆถ้ดๅณไธบ่ฏฅๆกpush็ๆๆๆ
*/
private long pushEndTime;
/**
* pushๅผๅงๅ้ๆถ้ด
*/
private long pushStartTime;
/**
* ็จไบๅฎๆถ็ๆง็tag
*/
private String tag;
/**
* ๆต่ฏ็ฏๅขtopicๆฐๆฎๆฏๅฆๅฏไปฅๅคๅ๏ผ้ป่ฎคไธๅ
่ฎธ
*/
private boolean testEnvSend = false;
/**
* ๆฏๅฆๆฏๅ็ปๆฐ็จๆท๏ผ้ป่ฎคfalse
*/
private boolean newUserPush = false;
/**
* ๆฏๅฆๆฏๅ็ปๆฐ่ฎพๅค๏ผ้ป่ฎคfalse
*/
private boolean newDevicePush = false;
/**
* ๅ้ๆฏไพ๏ผ้ป่ฎค100
*/
private int pushPercent = 100;
/**
* ๆฏๅฆไฝฟ็จhive
*/
private boolean useHive = false;
/**
* ๆฉๅฑๅญๆฎต๏ผA็ซ็target_typeๅฐฑๅฏไปฅๆพๅฐ่ฟ้้ข
*/
// private Map<String, String> extraInfo = Maps.newHashMap();
/**
* ๆบๅๅ้็ฑปๅ
*/
private String mobileType;
}
|
package com.jidouauto.mvvm.rxjava;
import com.jidouauto.mvvm.rxjava.transformer.Transformers;
/**
* The interface Result validator.
*
* @author eddie
* <p>
* ResultValidatorๆฅๅฃ็จไบๆฐๆฎ็ปๆ็ๆ ก้ช ่ฏฅๆฅๅฃ้
ๅ{@link Transformers#validate()} ()} ๅฎ็ฐๆฐๆฎ็ปๆๆ ก้ช๏ผๅนถๅฐ้่ฏฏไฟกๆฏๅ้ฆๅฐ่ฐ็จ่
* @see {@link Transformers} eg. ่ฏทๆฑ่ฟๅ็้่ฏฏcode ๆฐๆฎๅผๅธธใ
*/
public interface Validator<T extends Exception> {
/**
* ๆฐๆฎๆ ก้ชๅคฑ่ดฅ็ๆ
ๅตๆๅบๅผๅธธ
*
* @throws T the base exception
*/
void validate() throws T;
}
|
/**
*
*/
package com.yougou.kaidian.common.constant;
/**
* ๅๅฎถไธญๅฟ้่ฏฏ็
*
* @author huang.tao
*
*/
public class ErrorConstant {
public static final String MODULE_SYSTEM = "01";
public static final String MODULE_COMMODITY = "02";
/** ๆช่ฎพ็ฝฎๅๅฎถ็ผ็ */
public static final String E_0001 = "0001";
/** ๆช่ฎพ็ฝฎไปๅบ็ผ็ */
public static final String E_0002 = "0002";
public static String getErrorCode(String module, String code) {
return module + "_" + code;
}
}
|
package com.lqs.hrm.entity;
import java.util.Date;
import java.util.List;
/**
* ่ๅทฅ่ๅคไฟกๆฏๅฎไฝ็ฑป
* @author luckyliuqs
*
*/
public class AttendanceEmployee {
/**
* This field was generated by MyBatis Generator. This field corresponds to the database column attendance_employee.ae_id
* @mbg.generated Mon May 25 19:54:19 CST 2020
*/
private Integer aeId;
/**
* ็ญพๅฐๆฅๆ
* This field was generated by MyBatis Generator. This field corresponds to the database column attendance_employee.date
* @mbg.generated Mon May 25 19:54:19 CST 2020
*/
private Date date;
/**
* ็ญพๅฐๆถ้ด
* This field was generated by MyBatis Generator. This field corresponds to the database column attendance_employee.sign_time
* @mbg.generated Mon May 25 19:54:19 CST 2020
*/
private Date signTime;
/**
* ็ญพ้ๆถ้ด
* This field was generated by MyBatis Generator. This field corresponds to the database column attendance_employee.logout_time
* @mbg.generated Mon May 25 19:54:19 CST 2020
*/
private Date logoutTime;
/**
* This field was generated by MyBatis Generator. This field corresponds to the database column attendance_employee.emp_jobId
* @mbg.generated Mon May 25 19:54:19 CST 2020
*/
private String empJobid;
/**
* This field was generated by MyBatis Generator. This field corresponds to the database column attendance_employee.status_id
* @mbg.generated Mon May 25 19:54:19 CST 2020
*/
private Integer statusId;
/**
* This method was generated by MyBatis Generator. This method returns the value of the database column attendance_employee.ae_id
* @return the value of attendance_employee.ae_id
* @mbg.generated Mon May 25 19:54:19 CST 2020
*/
public Integer getAeId() {
return aeId;
}
/**
* This method was generated by MyBatis Generator. This method sets the value of the database column attendance_employee.ae_id
* @param aeId the value for attendance_employee.ae_id
* @mbg.generated Mon May 25 19:54:19 CST 2020
*/
public void setAeId(Integer aeId) {
this.aeId = aeId;
}
/**
* This method was generated by MyBatis Generator. This method returns the value of the database column attendance_employee.date
* @return the value of attendance_employee.date
* @mbg.generated Mon May 25 19:54:19 CST 2020
*/
public Date getDate() {
return date;
}
/**
* This method was generated by MyBatis Generator. This method sets the value of the database column attendance_employee.date
* @param date the value for attendance_employee.date
* @mbg.generated Mon May 25 19:54:19 CST 2020
*/
public void setDate(Date date) {
this.date = date;
}
/**
* This method was generated by MyBatis Generator. This method returns the value of the database column attendance_employee.sign_time
* @return the value of attendance_employee.sign_time
* @mbg.generated Mon May 25 19:54:19 CST 2020
*/
public Date getSignTime() {
return signTime;
}
/**
* This method was generated by MyBatis Generator. This method sets the value of the database column attendance_employee.sign_time
* @param signTime the value for attendance_employee.sign_time
* @mbg.generated Mon May 25 19:54:19 CST 2020
*/
public void setSignTime(Date signTime) {
this.signTime = signTime;
}
/**
* This method was generated by MyBatis Generator. This method returns the value of the database column attendance_employee.logout_time
* @return the value of attendance_employee.logout_time
* @mbg.generated Mon May 25 19:54:19 CST 2020
*/
public Date getLogoutTime() {
return logoutTime;
}
/**
* This method was generated by MyBatis Generator. This method sets the value of the database column attendance_employee.logout_time
* @param logoutTime the value for attendance_employee.logout_time
* @mbg.generated Mon May 25 19:54:19 CST 2020
*/
public void setLogoutTime(Date logoutTime) {
this.logoutTime = logoutTime;
}
/**
* This method was generated by MyBatis Generator. This method returns the value of the database column attendance_employee.emp_jobId
* @return the value of attendance_employee.emp_jobId
* @mbg.generated Mon May 25 19:54:19 CST 2020
*/
public String getEmpJobid() {
return empJobid;
}
/**
* This method was generated by MyBatis Generator. This method sets the value of the database column attendance_employee.emp_jobId
* @param empJobid the value for attendance_employee.emp_jobId
* @mbg.generated Mon May 25 19:54:19 CST 2020
*/
public void setEmpJobid(String empJobid) {
this.empJobid = empJobid;
}
/**
* This method was generated by MyBatis Generator. This method returns the value of the database column attendance_employee.status_id
* @return the value of attendance_employee.status_id
* @mbg.generated Mon May 25 19:54:19 CST 2020
*/
public Integer getStatusId() {
return statusId;
}
/**
* This method was generated by MyBatis Generator. This method sets the value of the database column attendance_employee.status_id
* @param statusId the value for attendance_employee.status_id
* @mbg.generated Mon May 25 19:54:19 CST 2020
*/
public void setStatusId(Integer statusId) {
this.statusId = statusId;
}
/**
* ่ๅทฅไบบๅงๅ
*/
private String empName = "";
/**
* ็ถๆๅ็งฐ
*/
private String statusName = "";
/**
* ่ๅทฅๆๅฑ้จ้จList้ๅ
*/
private List<Department> departmentList;
/**
* ่ๅทฅๆๅฑ้จ้จๅ็งฐList้ๅ็Strๅฝขๅผ
*/
private String deptNameListStr;
/**
* ่ๅทฅๆๅฑ่ไฝid
*/
private List<Position> positionList;
/**
* ่ๅทฅๆๅฑ้จ่ไฝๅ็งฐList้ๅ็Strๅฝขๅผ
*/
private String positionNameListStr;
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getStatusName() {
return statusName;
}
public void setStatusName(String statusName) {
this.statusName = statusName;
}
public List<Department> getDepartmentList() {
return departmentList;
}
public void setDepartmentList(List<Department> departmentList) {
this.departmentList = departmentList;
}
public String getDeptNameListStr() {
return deptNameListStr;
}
public void setDeptNameListStr(String deptNameListStr) {
this.deptNameListStr = deptNameListStr;
}
public List<Position> getPositionList() {
return positionList;
}
public void setPositionList(List<Position> positionList) {
this.positionList = positionList;
}
public String getPositionNameListStr() {
return positionNameListStr;
}
public void setPositionNameListStr(String positionNameListStr) {
this.positionNameListStr = positionNameListStr;
}
}
|
package com.practice;
public class CustomExp extends RuntimeException {
public CustomExp(String msg) {
super(msg);
}
}
|
package com.cg.javafullstack.exception;
public class BalanceValidation {
void verify(int amount)
{
if(amount > 10000)
{
throw new DailyLimit("Darling pls withdraw less than 10k");
}
}
}
|
package com.java26.alg.zad4;
import java.util.*;
/*
- posiadaฤ (jako pole) mapฤ Studentรณw. //#(co powinno byฤ kluczem?)
- posiadaฤ metodฤ 'dodajStudenta(Student):void' do dodawania nowego studenta do dziennika
- posiadaฤ metodฤ 'usuลStudenta(Student):void' do usuwania studenta
- posiadaฤ metodฤ 'usuลStudenta(String):void' do usuwania studenta po jego numerze indexu
- posiadaฤ metodฤ 'zwrรณฤStudenta(String):Student' ktรณra jako parametr przyjmuje numer indexu studenta, a w wyniku zwraca konkretnego studenta.
- posiadaฤ metodฤ 'podajลredniฤ
Studenta(String):double' ktรณra przyjmuje indeks studenta i zwraca ลredniฤ
ocen studenta.
- posiadaฤ metodฤ 'podajStudentรณwZagroลผonych():List<Student>'
- posiadaฤ metodฤ 'posortujStudentรณwPoIndeksie():List<Student>' - ktรณra sortuje listฤ studentรณw po numerach indeksรณw, a nastฤpnie zwraca posortowanฤ
listฤ.
*/
public class Dziennik {
private Map<String, Student> studentMap = new HashMap<>();
public void dodajStudenta(Student student) {
studentMap.put(student.getNumerIndeksuStudenta(), student);
}
public void usunStudenta(Student student) {
studentMap.remove(student.getNumerIndeksuStudenta());
}
public void usunStudenta(String index) {
studentMap.remove(index);
}
public Optional<Student> zwrocStudenta1(String indeks){
if (studentMap.containsKey(indeks)){
return Optional.ofNullable(studentMap.get(indeks));
}
return Optional.empty();
}
public Student zwrocStudenta2_zle(String indeks) {
if (studentMap.containsKey(indeks)){
return studentMap.get(indeks);
}
return null;
}
//opcja 2 rzuc expetion
public Student zwrocStudenta2(String indeks) throws StudentNotFoundException{
if (studentMap.containsKey(indeks)){
return studentMap.get(indeks);
}
throw new StudentNotFoundException("Student with this id wasn't found");
}
public double podajSrednia(String indeks) throws StudentNotFoundException{
double sum =0.0;
Student studentKtoregoSredniaLiczmy=zwrocStudenta2(indeks);
for (Double ocena:studentKtoregoSredniaLiczmy.getListaOcenStudenta() ){
sum+=ocena;
}
return sum/studentKtoregoSredniaLiczmy.getListaOcenStudenta().size();
}
public List<Student> zwrocZagrozonych() {
List<Student> listaWynikowa = new ArrayList<>();
Set<String> kopiaIndeksow=new HashSet<>(studentMap.keySet());
// for (String indeks : studentMap.keySet()) {//na orginale
for (String indeks : kopiaIndeksow) {//na kopii
try {
if (podajSrednia((indeks)) <= 2.0) {
listaWynikowa.add(studentMap.get(indeks));
}
} catch (StudentNotFoundException e) {
System.out.println("Nie mozna znalesc studenta");
// e.printStackTrace();
}
}
return listaWynikowa;
}
public List<Student> zwrocPosortowanaListeStudentow(){
//kopiuje wszystkich studentow z mapy (wartosci) do listy
List<Student> studentList=new ArrayList<>(studentMap.values());
studentList.sort(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
//1 o1>02
//0 ==
//-1 o1<o2
int indeks1=Integer.parseInt((o1.getNumerIndeksuStudenta()));
int indeks2=Integer.parseInt((o2.getNumerIndeksuStudenta()));
return Integer.compare(indeks1,indeks2);
}
});
return studentList;
}
}
|
package com.github.vinja.omni;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import com.github.vinja.compiler.CompilerContext;
public class PackageInfo {
/**
* cache key is package name, the content is className list under that package
*/
private Map<String,Set<String>> cache = new HashMap<String,Set<String>>();
private Map<String,String> pkgLocationCache = new HashMap<String,String>();
/**
* cachekey is jar file path, value is "true" or "false".
*/
private Map<String, String> cachedPath = new HashMap<String,String>();
private Set<String> dstClassNames = new HashSet<String>();
public boolean isClassInDst(String className) {
return dstClassNames.contains(className);
}
public void addClasstoDstClass(String className) {
dstClassNames.add(className);
}
@SuppressWarnings("rawtypes")
public List<Class> findSubClass(CompilerContext ctx, String searchClassName) {
ClassLoader classLoader = ctx.getClassLoader();
List<Class> resultList = new ArrayList<Class>();
for (String pkgname : cache.keySet()) {
Set<String> classNames = cache.get(pkgname);
if (pkgname.startsWith("java") || pkgname.startsWith("com.sun")) continue;
for (String className : classNames) {
String binClassName = pkgname+"."+className;
Class aClass = null;
try {
aClass = classLoader.loadClass(binClassName);
} catch (Throwable e) {
}
if (aClass == null)
continue;
LinkedList<Class> classList = ClassInfoUtil.getAllSuperClass(aClass);
boolean isSuperior = false;
for (Class tmpClass : classList) {
if (tmpClass.getName().equals(className)) {
isSuperior = true;
break;
}
}
if (isSuperior ) {
resultList.add(aClass);
}
}
}
return resultList;
}
private Pattern getPattern(String name,boolean ignoreCase) {
String patStr = name.replace("*",".*") + ".*";
Pattern pattern = null;
if (ignoreCase) {
pattern = Pattern.compile(patStr, Pattern.CASE_INSENSITIVE);
} else {
pattern = Pattern.compile(patStr);
}
return pattern;
}
public List<String> findClass(String nameStart,boolean ignoreCase,boolean withLoc) {
List<String> result = new ArrayList<String>();
Pattern pattern = getPattern(nameStart,ignoreCase);
for (String pkgname : cache.keySet()) {
Set<String> classNames = cache.get(pkgname);
List<String> tmpList =getMatchedClassName(classNames, nameStart, pattern, pkgname);
for (String className : tmpList) {
if (cache.get(className) != null ) continue;
if (withLoc) {
String location = pkgLocationCache.get(className);
if (location == null) location = pkgLocationCache.get(pkgname);
result.add(getClassNameWithLoc(className, location));
} else {
result.add(className);
}
}
}
return result;
}
public List<String> findClass(String nameStart,boolean ignoreCase,boolean withLoc, Set<String> fullClassNames) {
List<String> result = new ArrayList<String>();
Pattern pattern = getPattern(nameStart,ignoreCase);
for (String fullClassName : fullClassNames) {
String[] splits = splitClassName(fullClassName);
String pkgName = splits[0];
String className = splits[1];
Set<String> classNames = new HashSet<String>();
classNames.add(className);
List<String> tmpList =getMatchedClassName(classNames, nameStart, pattern, pkgName);
for (String matchedName : tmpList) {
if (withLoc) {
String location = pkgLocationCache.get(matchedName);
if (location == null) location = pkgLocationCache.get(pkgName);
result.add(getClassNameWithLoc(className, location));
} else {
result.add(matchedName);
}
}
}
return result;
}
public List<String> findClassByQualifiedName(String name,boolean ignoreCase,boolean withLoc) {
String[] splits = splitClassName(name);
String pkgName = splits[0];
String className = splits[1];
Pattern pattern = getPattern(className, ignoreCase);
Set<String> classNames = cache.get(pkgName);
if (classNames == null) {
return new ArrayList<String>();
}
List<String> tmpList = getMatchedClassName(classNames, className, pattern, pkgName);
if (!withLoc) return tmpList;
List<String> resultList = new ArrayList<String>();
String location = pkgLocationCache.get(name);
if (location == null) location = pkgLocationCache.get(pkgName);
for (String tmpClassName :tmpList) {
resultList.add(getClassNameWithLoc(tmpClassName, location));
}
return resultList;
}
private String getClassNameWithLoc(String className,String location) {
if (location == null) return className;
String fileName = FilenameUtils.getName(location);
return className + " - " + fileName;
}
public List<String> getMatchedClassName(Set<String> set, String plainPat,
Pattern pattern,String pkgName) {
List<String> result = new ArrayList<String>();
for (String className : set) {
if ( pattern.matcher(className).matches()) {
if (pkgName.equals("")) {
result.add(className);
} else {
result.add(pkgName +"."+className);
}
}
}
return result;
}
private String[] splitClassName(String className) {
int dotPos = className.lastIndexOf(".");
if (dotPos < 0 ) return new String[] {"",className};
return new String[] {className.substring(0,dotPos) , className.substring(dotPos+1)};
}
public List<String> findPackage(String className) {
List<String> result = new ArrayList<String>();
for (String pkgname : cache.keySet()) {
if (cache.get(pkgname).contains(className)) {
result.add(pkgname+"."+className);
}
}
return result;
}
public void addClassNameToCache(String className,String classLocation) {
//don't cache class under sun or com.sun package
//if (className == null || className.startsWith("sun") || className.startsWith("com.sun")) return ;
if (className == null) return;
String[] tokens = className.split("\\.");
if (tokens == null ) return;
if (tokens.length < 2) {
Set<String> names=cache.get("");
if (names == null) {
names=new HashSet<String>();
cache.put("", names);
pkgLocationCache.put("", classLocation);
}
names.add(tokens[0]);
return;
}
int count = 0;
String key= tokens[0];
while ( true ) {
Set<String> names=cache.get(key);
if (names == null) {
names=new HashSet<String>();
cache.put(key, names);
pkgLocationCache.put(key, classLocation);
}
names.add(tokens[count+1]);
count = count + 1;
if (count >= tokens.length - 1 ) break;
key = key+"."+tokens[count];
}
pkgLocationCache.put(className, classLocation);
}
@SuppressWarnings("rawtypes")
public void cacheClassNameInDist(String outputDir,boolean recursive) {
File dir = new File(outputDir) ;
if (!dir.exists()) {
boolean suc = dir.mkdirs();
if (!suc) return;
}
if (!dir.isDirectory()) {
return;
}
Iterator it=FileUtils.iterateFiles(dir, new String[] {"class"} ,recursive);
while (it.hasNext()) {
File file = (File)it.next();
String relativeName = file.getAbsolutePath().substring(outputDir.length()+1);
String className = relativeName.replace('/', '.').replace('\\', '.').replace(".class", "");
addClassNameToCache(className,"src path");
addClasstoDstClass(className);
}
}
public void cacheClassNameInJar(String path) {
File file = new File(path);
if (! file.exists()) return;
String hadCached=cachedPath.get(path);
if (hadCached !=null && hadCached.equals("true")) return;
JarFile jarFile = null;
try {
jarFile = new JarFile(path);
Enumeration<JarEntry> entries = jarFile.entries();
while(entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
String entryName = entry.getName();
if (entryName.indexOf("$") > -1) continue;
if (!entryName.endsWith(".class")) continue;
String className = entryName.replace('/', '.').replace('\\', '.').replace(".class", "");
addClassNameToCache(className,path);
}
jarFile.close();
} catch (IOException e ) {
} finally {
if (jarFile !=null ) try {jarFile.close();} catch (Exception e) {};
}
cachedPath.put(path, "true");
return ;
}
public void cacheSystemRtJar() {
String javaHome=System.getProperty("java.home");
File rtjarFile=new File(FilenameUtils.concat(javaHome, "jre/lib/rt.jar"));
if (! rtjarFile.exists())
rtjarFile=new File(FilenameUtils.concat(javaHome, "lib/rt.jar"));
if (! rtjarFile.exists()) return ;
cacheClassNameInJar(rtjarFile.getPath());
}
public List<String> getClassesForPackage(String pkgname,ClassLoader classLoader) {
List<String> classNames=new ArrayList<String>();
File directory = null;
String fullPath;
String relPath = pkgname.replace('.', '/');
if (cache.get(pkgname) !=null) {
Set<String> classNameSet=cache.get(pkgname);
for (String name : classNameSet) {
classNames.add(name);
}
return classNames;
}
try {
Enumeration<URL> resources = classLoader.getResources((relPath));
if (resources == null) return null;
while (resources.hasMoreElements()) {
URL resource = resources.nextElement();
fullPath = resource.getFile();
directory = new File(fullPath);
if (directory.exists()) {
File[] files = directory.listFiles();
for (int i = 0; i < files.length; i++) {
String fileName=files[i].getName();
if (files[i].isDirectory()) {
classNames.add(fileName);
} else if (fileName.endsWith(".class")) {
String className = fileName.substring(0, fileName.length() - 6);
classNames.add(className);
}
}
}
else {
String jarPath = fullPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", "");
cacheClassNameInJar(jarPath);
Set<String> classNameSet=cache.get(pkgname);
for (String name : classNameSet) {
classNames.add(name);
}
}
}
} catch (Exception e ) {
}
return classNames;
}
}
|
package com.bytedance.sandboxapp.c.a.b.a.a;
import android.app.Activity;
import com.bytedance.sandboxapp.a.a.c.f;
import com.bytedance.sandboxapp.a.a.d.a;
import com.bytedance.sandboxapp.c.a.a.a;
import com.bytedance.sandboxapp.protocol.service.a.a.a;
import com.bytedance.sandboxapp.protocol.service.api.entity.a;
import com.tt.miniapp.permission.PermissionsManager;
import com.tt.miniapp.permission.PermissionsResultAction;
import com.tt.miniapphost.AppbrandContext;
import java.util.HashSet;
public final class b extends f {
public b(com.bytedance.sandboxapp.c.a.b paramb, a parama) {
super(paramb, parama);
}
public final void a(f.a parama, a parama1) {
a a1 = (a)((a)this).context.getService(a.class);
if (a1 == null || !a1.isSupportDxppManager()) {
a();
return;
}
com.bytedance.sandboxapp.protocol.service.a.a.a.b b2 = new com.bytedance.sandboxapp.protocol.service.a.a.a.b();
b2.a = parama.b.longValue();
b2.b = parama.c;
b2.c = parama.d;
b2.d = parama.e;
b2.e = parama.f;
b2.f = parama.g;
b2.g = parama.h;
b2.h = parama.i;
b2.i = parama.j;
Integer integer = parama.k;
byte b1 = 0;
if (integer != null) {
i = parama.k.intValue();
} else {
i = 0;
}
b2.j = i;
int i = b1;
if (parama.l != null)
i = parama.l.intValue();
b2.k = i;
if (parama.m != null) {
String str = parama.m.toString();
} else {
parama = null;
}
b2.l = (String)parama;
if (PermissionsManager.getInstance().hasPermission(((a)this).context.getApplicationContext(), "android.permission.WRITE_EXTERNAL_STORAGE")) {
a1.dxppAd(b2);
callbackOk(null);
return;
}
HashSet<String> hashSet = new HashSet();
hashSet.add("android.permission.WRITE_EXTERNAL_STORAGE");
PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult((Activity)AppbrandContext.getInst().getCurrentActivity(), hashSet, new PermissionsResultAction(this, a1, b2) {
public final void onDenied(String param1String) {
this.c.b();
}
public final void onGranted() {
this.a.dxppAd(this.b);
this.c.callbackOk(null);
}
});
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\bytedance\sandboxapp\c\a\b\a\a\b.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package com.tencent.mm.protocal;
import com.tencent.mm.protocal.c.g;
public class c$im extends g {
public c$im() {
super("showAllNonBaseMenuItem", "showAllNonBaseMenuItem", 92, false);
}
}
|
/**
* ImageDB.java
* created at:2011-5-11ไธๅ04:15:03
*
* Copyright (c) 2011, ๅไบฌ็ฑ็ฎ็งๆๆ้ๅ
ฌๅธ
*
* All right reserved
*/
package com.appdear.client.db;
import com.appdear.client.service.Constants;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
/**
* ๅพ็ๅญๅจ
*
* @author zqm
*/
public class ImageDB extends BaseDB {
public ImageDB(Context context) {
super(context);
}
/**
* ๆทปๅ ๅพ็
* @param url
* @param path
*/
public synchronized void add(String url, String path) {
SQLiteDatabase db = getDbHelper().getWritableDatabase();
try {
db.execSQL("insert into "+Constants.CACHE_IMAGE_TABLE_NAME+"(imgurl, imgpath) values(?, ? )", new String[]{url, path});
} catch(Exception e) {
} finally {
db.close();
}
}
/**
* ๅ ้คๅพ็
*
* @param imgurl
*/
public void delete(String imgUrl) {
SQLiteDatabase db = getDbHelper().getWritableDatabase();
try {
db.execSQL("delete from "+Constants.CACHE_IMAGE_TABLE_NAME+" where imgurl=?", new String[]{imgUrl});
} finally {
db.close();
}
}
/**
* ๆ็ดข
* @param imgUrl
* @return
*/
public synchronized String search(String imgUrl) {
SQLiteDatabase db =null;
try {
db = getDbHelper().getReadableDatabase();
String imgpath="";
Cursor cursor = db.rawQuery("select imgpath from "+Constants.CACHE_IMAGE_TABLE_NAME+" where imgurl = ?", new String[]{imgUrl});
while (cursor.moveToNext()){
imgpath = cursor.getString(0);
}
cursor.close();
return imgpath;
} catch (Exception e) {
db =null;
return "";
}finally {
if(db!=null)
db.close();
}
}
}
|
package com.tencent.mm.plugin.nearby.ui;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import com.tencent.mm.model.au;
import com.tencent.mm.plugin.nearby.ui.NearbySayHiListUI.6;
class NearbySayHiListUI$6$1 implements OnCancelListener {
final /* synthetic */ 6 lCD;
NearbySayHiListUI$6$1(6 6) {
this.lCD = 6;
}
public final void onCancel(DialogInterface dialogInterface) {
au.DF().c(NearbySayHiListUI.f(this.lCD.lCB));
}
}
|
import jade.core.Runtime;
import jade.core.Profile;
import jade.core.ProfileImpl;
import jade.wrapper.*;
public class StartSystem {
public static void main(String args[]) throws InterruptedException, StaleProxyException {
final Runtime runTime = Runtime.instance();
runTime.setCloseVM(true);
Profile mainProfile = new ProfileImpl(true);
AgentContainer mainContainer = runTime.createMainContainer(mainProfile);
AgentController rma = mainContainer.createNewAgent("rma", "jade.tools.rma.rma", null);
rma.start();
Thread.sleep(900);
Profile anotherProfile;
AgentContainer anotherContainer;
AgentController agent;
anotherProfile = new ProfileImpl(false);
anotherContainer = runTime.createAgentContainer(anotherProfile);
System.out.println("Starting up a Manager...");
agent = anotherContainer.createNewAgent("manager", "Agents.Manager", null);
agent.start();
Thread.sleep(900);
System.out.println("Starting up a MIN_MAX...");
agent = anotherContainer.createNewAgent("minmax1", "Agents.MIN_MAX", null);
agent.start();
Thread.sleep(900);
System.out.println("Starting up a MIN_MAX...");
agent = anotherContainer.createNewAgent("minmax2", "Agents.MIN_MAX", null);
agent.start();
Thread.sleep(900);
System.out.println("Starting up a MIN_MAX...");
agent = anotherContainer.createNewAgent("minmax3", "Agents.MIN_MAX", null);
agent.start();
Thread.sleep(900);
System.out.println("Starting up a MIN_MAX...");
agent = anotherContainer.createNewAgent("minmax4", "Agents.MIN_MAX", null);
agent.start();
Thread.sleep(900);
System.out.println("Starting up a Deviation...");
agent = anotherContainer.createNewAgent("Deviation1", "Agents.Deviation", null);
agent.start();
Thread.sleep(900);
agent = anotherContainer.createNewAgent("Deviation2", "Agents.Deviation", null);
agent.start();
Thread.sleep(900);
agent = anotherContainer.createNewAgent("Deviation3", "Agents.Deviation", null);
agent.start();
Thread.sleep(900);
agent = anotherContainer.createNewAgent("Deviation4", "Agents.Deviation", null);
agent.start();
Thread.sleep(900);
System.out.println("Starting up a Deviation...");
agent = anotherContainer.createNewAgent("client", "Agents.Client", null);
agent.start();
Thread.sleep(900);
}
}
|
package jneiva.hexbattle.componente;
public class Ataque extends Componente {
private int forca;
private int alcance;
public Ataque(int forca, int alcance) {
super();
this.forca = forca;
this.alcance = alcance;
}
public int getForca() {
return forca;
}
public int getAlcance() {
return alcance;
}
}
|
package com.nmhung.entity;
import lombok.Data;
import javax.persistence.*;
import java.util.List;
@Table
@Entity(name = "tblroom")
@Data
public class RoomEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private String location;
@Column(name = "total_desktop ")
private Integer totalDesktop ;
@OneToMany(mappedBy = "room")
private List<RoomTimeEntity> roomTime;
}
|
/**
*
*/
package fr.gtm.proxibanque.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import fr.gtm.proxibanque.dao.IAgenceDao;
import fr.gtm.proxibanque.dao.IConseillerDao;
import fr.gtm.proxibanque.modele.Agence;
import fr.gtm.proxibanque.modele.Conseiller;
/**
* Classe de la couche service : ServAgence utilisant la classe IAgenceDao et IConseillerDao
*
* @author Xavier Deboudt, Thomas Duval, Romain Sadoine, Jean Mathorel
*
*/
@Service
public class ServAgence {
@Autowired
private IAgenceDao agenceDao;
@Autowired
private IConseillerDao conseillerDao;
/**
* mรฉthode reprennant la mรฉthode save() de la dao Agence
*
* @param agence
*/
public void creationAgence(Agence agence) {
agenceDao.save(agence);
}
/**
*
* mรฉthode reprennant la mรฉthode addConseiller() de la dao Agence
*
* @param agence
* @param conseiller
*/
public void addConseiller(Agence agence, Conseiller conseiller) {
agenceDao.addConseiller(agence, conseiller);
}
/**
* mรฉthode reprennant la mรฉthode removeConseiller de la dao Agence
*
* @param agence
* @param conseiller
*/
public void removeConseiller(Agence agence, Conseiller conseiller) {
agenceDao.removeConseiller(agence, conseiller);
}
/**
* mรฉthode reprennant la mรฉthode findByIdAgence de la dao Agence
*
* @param idAgence
* @return
*/
public List<Conseiller> listeConseillers(Long idAgence) {
return conseillerDao.findByIdAgence(idAgence);
}
}
|
package modul5.ae10.paket.paket1;
class KlasseAA extends KlasseA {
}
|
package org.usfirst.frc.team5951.robot.auton;
import org.usfirst.frc.team5951.robot.commands.chassis.ShiftToStrongGear;
import edu.wpi.first.wpilibj.command.CommandGroup;
/**
*
*/
public class DropGearsLeftShoot extends CommandGroup {
public DropGearsLeftShoot() {
addSequential(new ShiftToStrongGear());
}
}
|
package com.orangefunction.tomcat.redissessions;
import java.io.IOException;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.orangefunction.tomcat.redissessions.RedisSessionManager.SessionPersistPolicy;
import redis.clients.util.SafeEncoder;
public class MultithreadingRedisSessionManagerTest extends AbstractRedisSessionManagerTest {
private static final long DELAY_PER_THREAD = 50L;
private static final int NUMBER_OF_THREADS = 25;
private ExecutorService service;
private CyclicBarrier waitForThreadsToReadSession;
private CyclicBarrier waitForCompletion;
private RedisSession s1;
@Before
public void setup2() {
service = Executors.newFixedThreadPool(NUMBER_OF_THREADS);
waitForThreadsToReadSession = new CyclicBarrier(NUMBER_OF_THREADS);
waitForCompletion = new CyclicBarrier(1 + NUMBER_OF_THREADS);
s1 = (RedisSession) createSession();
s1.setAttribute(KEY1, VALUE1);
mgr.add(s1);
mgr.afterRequest();
}
@After
public void tearDown2() {
if (null != service) {
service.shutdownNow();
}
}
@Test
public void testLastWinPolicy() throws IOException, InterruptedException, BrokenBarrierException, TimeoutException {
Assert.assertFalse(mgr.isFirstWin());
for (int i = 0; i < NUMBER_OF_THREADS; i++) {
final Integer threadNumber = i;
service.submit(new Runnable() {
@Override
public void run() {
try {
RedisSession s = (RedisSession) mgr.findSession(s1.getId());
System.out.println("Thread: " + threadNumber + " read the session: " + s);
// wait for all other threads to load the same session copy
waitForThreadsToReadSession.await(5, TimeUnit.SECONDS);
// make sure threads will update Redis in the same order they were started:
Thread.sleep(DELAY_PER_THREAD * threadNumber);
s.setAttribute(KEY1, threadNumber);
mgr.save(s, true);
mgr.afterRequest();
System.out.println("Thread: " + threadNumber + " saved the session: " + s + " with value: " + s.getAttribute(KEY1));
waitForCompletion.await();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
});
}
waitForCompletion.await(/*double just in case*/2L * DELAY_PER_THREAD * NUMBER_OF_THREADS, TimeUnit.MILLISECONDS);
RedisSession s = (RedisSession) mgr.findSession(s1.getId());
Assert.assertEquals(Integer.valueOf(NUMBER_OF_THREADS - 1), s.getAttribute(KEY1));
}
@Test
public void testFirstWinPolicy() throws IOException, InterruptedException, BrokenBarrierException, TimeoutException {
mgr.setSessionPersistPolicies(SessionPersistPolicy.FIRST_WIN.name());
Assert.assertTrue(mgr.isFirstWin());
String sequenceBefore = SafeEncoder.encode(mgr.loadSessionDataFromRedis(s1.getId()).sequence);
for (int i = 0; i < NUMBER_OF_THREADS; i++) {
final Integer threadNumber = i;
service.submit(new Runnable() {
@Override
public void run() {
try {
RedisSession s = (RedisSession) mgr.findSession(s1.getId());
System.out.println("Thread: " + threadNumber + " read the session: " + s);
// wait for all other threads to load the same session copy
waitForThreadsToReadSession.await(5, TimeUnit.SECONDS);
// make sure threads will update Redis in the same order they were started:
Thread.sleep(DELAY_PER_THREAD * threadNumber);
s.setAttribute(KEY1, threadNumber);
mgr.save(s, true);
mgr.afterRequest();
System.out.println("Thread: " + threadNumber + " saved the session: " + s + " with value: " + s.getAttribute(KEY1));
waitForCompletion.await();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
});
}
waitForCompletion.await(/*double just in case*/2L * DELAY_PER_THREAD * NUMBER_OF_THREADS, TimeUnit.MILLISECONDS);
String sequenceAfter = SafeEncoder.encode(mgr.loadSessionDataFromRedis(s1.getId()).sequence);
int seqIntBefore = Integer.valueOf(sequenceBefore);
int seqIntAfter = Integer.valueOf(sequenceAfter);
Assert.assertEquals("Sequence should increase by one", seqIntAfter, 1 + seqIntBefore);
RedisSession s = (RedisSession) mgr.findSession(s1.getId());
Assert.assertEquals(Integer.valueOf(0), s.getAttribute(KEY1));
}
}
|
package com.mysql.cj.jdbc.ha;
import com.mysql.cj.conf.ConnectionUrl;
import com.mysql.cj.conf.PropertyKey;
import com.mysql.cj.exceptions.CJException;
import com.mysql.cj.jdbc.ConnectionImpl;
import com.mysql.cj.jdbc.JdbcConnection;
import com.mysql.cj.jdbc.JdbcPropertySetImpl;
import com.mysql.cj.jdbc.exceptions.SQLError;
import com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping;
import com.mysql.cj.util.Util;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.SQLException;
import java.util.concurrent.Executor;
public class FailoverConnectionProxy extends MultiHostConnectionProxy {
private static final String METHOD_SET_READ_ONLY = "setReadOnly";
private static final String METHOD_SET_AUTO_COMMIT = "setAutoCommit";
private static final String METHOD_COMMIT = "commit";
private static final String METHOD_ROLLBACK = "rollback";
private static final int NO_CONNECTION_INDEX = -1;
private static final int DEFAULT_PRIMARY_HOST_INDEX = 0;
private int secondsBeforeRetryPrimaryHost;
private long queriesBeforeRetryPrimaryHost;
private boolean failoverReadOnly;
private int retriesAllDown;
private int currentHostIndex = -1;
private int primaryHostIndex = 0;
private Boolean explicitlyReadOnly = null;
private boolean explicitlyAutoCommit = true;
private boolean enableFallBackToPrimaryHost = true;
private long primaryHostFailTimeMillis = 0L;
private long queriesIssuedSinceFailover = 0L;
class FailoverJdbcInterfaceProxy extends MultiHostConnectionProxy.JdbcInterfaceProxy {
FailoverJdbcInterfaceProxy(Object toInvokeOn) {
super(toInvokeOn);
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String methodName = method.getName();
boolean isExecute = methodName.startsWith("execute");
if (FailoverConnectionProxy.this.connectedToSecondaryHost() && isExecute)
FailoverConnectionProxy.this.incrementQueriesIssuedSinceFailover();
Object result = super.invoke(proxy, method, args);
if (FailoverConnectionProxy.this.explicitlyAutoCommit && isExecute && FailoverConnectionProxy.this.readyToFallBackToPrimaryHost())
FailoverConnectionProxy.this.fallBackToPrimaryIfAvailable();
return result;
}
}
public static JdbcConnection createProxyInstance(ConnectionUrl connectionUrl) throws SQLException {
FailoverConnectionProxy connProxy = new FailoverConnectionProxy(connectionUrl);
return (JdbcConnection)Proxy.newProxyInstance(JdbcConnection.class.getClassLoader(), new Class[] { JdbcConnection.class }, connProxy);
}
private FailoverConnectionProxy(ConnectionUrl connectionUrl) throws SQLException {
super(connectionUrl);
JdbcPropertySetImpl connProps = new JdbcPropertySetImpl();
connProps.initializeProperties(connectionUrl.getConnectionArgumentsAsProperties());
this.secondsBeforeRetryPrimaryHost = ((Integer)connProps.getIntegerProperty(PropertyKey.secondsBeforeRetryMaster).getValue()).intValue();
this.queriesBeforeRetryPrimaryHost = ((Integer)connProps.getIntegerProperty(PropertyKey.queriesBeforeRetryMaster).getValue()).intValue();
this.failoverReadOnly = ((Boolean)connProps.getBooleanProperty(PropertyKey.failOverReadOnly).getValue()).booleanValue();
this.retriesAllDown = ((Integer)connProps.getIntegerProperty(PropertyKey.retriesAllDown).getValue()).intValue();
this.enableFallBackToPrimaryHost = (this.secondsBeforeRetryPrimaryHost > 0 || this.queriesBeforeRetryPrimaryHost > 0L);
pickNewConnection();
this.explicitlyAutoCommit = this.currentConnection.getAutoCommit();
}
MultiHostConnectionProxy.JdbcInterfaceProxy getNewJdbcInterfaceProxy(Object toProxy) {
return new FailoverJdbcInterfaceProxy(toProxy);
}
boolean shouldExceptionTriggerConnectionSwitch(Throwable t) {
String sqlState = null;
if (t instanceof com.mysql.cj.jdbc.exceptions.CommunicationsException || t instanceof com.mysql.cj.exceptions.CJCommunicationsException)
return true;
if (t instanceof SQLException) {
sqlState = ((SQLException)t).getSQLState();
} else if (t instanceof CJException) {
sqlState = ((CJException)t).getSQLState();
}
if (sqlState != null &&
sqlState.startsWith("08"))
return true;
return false;
}
boolean isMasterConnection() {
return connectedToPrimaryHost();
}
synchronized void pickNewConnection() throws SQLException {
if (this.isClosed && this.closedExplicitly)
return;
if (!isConnected() || readyToFallBackToPrimaryHost()) {
try {
connectTo(this.primaryHostIndex);
} catch (SQLException e) {
resetAutoFallBackCounters();
failOver(this.primaryHostIndex);
}
} else {
failOver();
}
}
synchronized ConnectionImpl createConnectionForHostIndex(int hostIndex) throws SQLException {
return createConnectionForHost(this.hostsList.get(hostIndex));
}
private synchronized void connectTo(int hostIndex) throws SQLException {
try {
switchCurrentConnectionTo(hostIndex, (JdbcConnection)createConnectionForHostIndex(hostIndex));
} catch (SQLException e) {
if (this.currentConnection != null) {
StringBuilder msg = (new StringBuilder("Connection to ")).append(isPrimaryHostIndex(hostIndex) ? "primary" : "secondary").append(" host '").append(this.hostsList.get(hostIndex)).append("' failed");
try {
this.currentConnection.getSession().getLog().logWarn(msg.toString(), e);
} catch (CJException ex) {
throw SQLExceptionsMapping.translateException(e, this.currentConnection.getExceptionInterceptor());
}
}
throw e;
}
}
private synchronized void switchCurrentConnectionTo(int hostIndex, JdbcConnection connection) throws SQLException {
boolean readOnly;
invalidateCurrentConnection();
if (isPrimaryHostIndex(hostIndex)) {
readOnly = (this.explicitlyReadOnly == null) ? false : this.explicitlyReadOnly.booleanValue();
} else if (this.failoverReadOnly) {
readOnly = true;
} else if (this.explicitlyReadOnly != null) {
readOnly = this.explicitlyReadOnly.booleanValue();
} else if (this.currentConnection != null) {
readOnly = this.currentConnection.isReadOnly();
} else {
readOnly = false;
}
syncSessionState(this.currentConnection, connection, readOnly);
this.currentConnection = connection;
this.currentHostIndex = hostIndex;
}
private synchronized void failOver() throws SQLException {
failOver(this.currentHostIndex);
}
private synchronized void failOver(int failedHostIdx) throws SQLException {
int prevHostIndex = this.currentHostIndex;
int nextHostIndex = nextHost(failedHostIdx, false);
int firstHostIndexTried = nextHostIndex;
SQLException lastExceptionCaught = null;
int attempts = 0;
boolean gotConnection = false;
boolean firstConnOrPassedByPrimaryHost = (prevHostIndex == -1 || isPrimaryHostIndex(prevHostIndex));
do {
try {
firstConnOrPassedByPrimaryHost = (firstConnOrPassedByPrimaryHost || isPrimaryHostIndex(nextHostIndex));
connectTo(nextHostIndex);
if (firstConnOrPassedByPrimaryHost && connectedToSecondaryHost())
resetAutoFallBackCounters();
gotConnection = true;
} catch (SQLException e) {
lastExceptionCaught = e;
if (shouldExceptionTriggerConnectionSwitch(e)) {
int newNextHostIndex = nextHost(nextHostIndex, (attempts > 0));
if (newNextHostIndex == firstHostIndexTried && newNextHostIndex == (newNextHostIndex = nextHost(nextHostIndex, true))) {
attempts++;
try {
Thread.sleep(250L);
} catch (InterruptedException interruptedException) {}
}
nextHostIndex = newNextHostIndex;
} else {
throw e;
}
}
} while (attempts < this.retriesAllDown && !gotConnection);
if (!gotConnection)
throw lastExceptionCaught;
}
synchronized void fallBackToPrimaryIfAvailable() {
ConnectionImpl connectionImpl;
JdbcConnection connection = null;
try {
connectionImpl = createConnectionForHostIndex(this.primaryHostIndex);
switchCurrentConnectionTo(this.primaryHostIndex, (JdbcConnection)connectionImpl);
} catch (SQLException e1) {
if (connectionImpl != null)
try {
connectionImpl.close();
} catch (SQLException sQLException) {}
resetAutoFallBackCounters();
}
}
private int nextHost(int currHostIdx, boolean vouchForPrimaryHost) {
int nextHostIdx = (currHostIdx + 1) % this.hostsList.size();
if (isPrimaryHostIndex(nextHostIdx) && isConnected() && !vouchForPrimaryHost && this.enableFallBackToPrimaryHost && !readyToFallBackToPrimaryHost())
nextHostIdx = nextHost(nextHostIdx, vouchForPrimaryHost);
return nextHostIdx;
}
synchronized void incrementQueriesIssuedSinceFailover() {
this.queriesIssuedSinceFailover++;
}
synchronized boolean readyToFallBackToPrimaryHost() {
return (this.enableFallBackToPrimaryHost && connectedToSecondaryHost() && (secondsBeforeRetryPrimaryHostIsMet() || queriesBeforeRetryPrimaryHostIsMet()));
}
synchronized boolean isConnected() {
return (this.currentHostIndex != -1);
}
synchronized boolean isPrimaryHostIndex(int hostIndex) {
return (hostIndex == this.primaryHostIndex);
}
synchronized boolean connectedToPrimaryHost() {
return isPrimaryHostIndex(this.currentHostIndex);
}
synchronized boolean connectedToSecondaryHost() {
return (this.currentHostIndex >= 0 && !isPrimaryHostIndex(this.currentHostIndex));
}
private synchronized boolean secondsBeforeRetryPrimaryHostIsMet() {
return (this.secondsBeforeRetryPrimaryHost > 0 && Util.secondsSinceMillis(this.primaryHostFailTimeMillis) >= this.secondsBeforeRetryPrimaryHost);
}
private synchronized boolean queriesBeforeRetryPrimaryHostIsMet() {
return (this.queriesBeforeRetryPrimaryHost > 0L && this.queriesIssuedSinceFailover >= this.queriesBeforeRetryPrimaryHost);
}
private synchronized void resetAutoFallBackCounters() {
this.primaryHostFailTimeMillis = System.currentTimeMillis();
this.queriesIssuedSinceFailover = 0L;
}
synchronized void doClose() throws SQLException {
this.currentConnection.close();
}
synchronized void doAbortInternal() throws SQLException {
this.currentConnection.abortInternal();
}
synchronized void doAbort(Executor executor) throws SQLException {
this.currentConnection.abort(executor);
}
public synchronized Object invokeMore(Object proxy, Method method, Object[] args) throws Throwable {
String methodName = method.getName();
if ("setReadOnly".equals(methodName)) {
this.explicitlyReadOnly = (Boolean)args[0];
if (this.failoverReadOnly && connectedToSecondaryHost())
return null;
}
if (this.isClosed && !allowedOnClosedConnection(method))
if (this.autoReconnect && !this.closedExplicitly) {
this.currentHostIndex = -1;
pickNewConnection();
this.isClosed = false;
this.closedReason = null;
} else {
String reason = "No operations allowed after connection closed.";
if (this.closedReason != null)
reason = reason + " " + this.closedReason;
throw SQLError.createSQLException(reason, "08003", null);
}
Object result = null;
try {
result = method.invoke(this.thisAsConnection, args);
result = proxyIfReturnTypeIsJdbcInterface(method.getReturnType(), result);
} catch (InvocationTargetException e) {
dealWithInvocationException(e);
}
if ("setAutoCommit".equals(methodName))
this.explicitlyAutoCommit = ((Boolean)args[0]).booleanValue();
if ((this.explicitlyAutoCommit || "commit".equals(methodName) || "rollback".equals(methodName)) && readyToFallBackToPrimaryHost())
fallBackToPrimaryIfAvailable();
return result;
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\com\mysql\cj\jdbc\ha\FailoverConnectionProxy.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
package day54_abstraction;
/*
we add abstract keyword to a class to make it an abstract class
we cannot object of Student class - meaning
student student = new Student (); -----ERROR will show
--> what can we do with this Student class? We can extend this class by sub class
Student class will Parent class for all other types of student related classes
*/
public abstract class Student {
public void code(String language) {
System.out.println("Student is coding using " + language);
}
public abstract void attendClass();
}
// we can add abstract method into abstract class
//abstract method --> is created using abstract keyword
//and does not have the implementation / method body
|
package com.tencent.mm.plugin.aa.a;
import android.app.Activity;
import android.os.Bundle;
import com.tencent.mm.a.g;
import com.tencent.mm.ak.o;
import com.tencent.mm.model.q;
import com.tencent.mm.model.s;
import com.tencent.mm.plugin.aa.a.b.c;
import com.tencent.mm.plugin.aa.b;
import com.tencent.mm.plugin.messenger.foundation.a.i;
import com.tencent.mm.protocal.c.y;
import com.tencent.mm.sdk.platformtools.ad;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.bl;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.aa;
import com.tencent.mm.storage.bd;
import com.tencent.mm.y.g.a;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public final class h {
private static synchronized void aJ(String str, String str2) {
boolean z = true;
synchronized (h.class) {
if (!bi.oW(str)) {
a gp = a.gp(str);
if (!(gp == null || bi.oW(gp.dyk))) {
long j;
c pe = b.VQ().pe(gp.dyk);
String str3 = "MicroMsg.AAUtil";
String str4 = "insertAAMsg, billNo: %s, chatroom: %s, oldRecord: %s, insertMsg: %s, localMsgId: %s";
Object[] objArr = new Object[5];
objArr[0] = gp.dyk;
objArr[1] = str2;
objArr[2] = pe;
if (pe == null || !pe.field_insertmsg) {
z = false;
}
objArr[3] = Boolean.valueOf(z);
if (pe != null) {
j = pe.field_localMsgId;
} else {
j = 0;
}
objArr[4] = Long.valueOf(j);
x.i(str3, str4, objArr);
if (pe == null) {
x.e("MicroMsg.AAUtil", "insertAAMsg, record is null!!");
} else if (!pe.field_insertmsg || pe.field_localMsgId <= 0) {
bd bdVar = new bd();
bdVar.ay(com.tencent.mm.model.bd.iD(str2));
bdVar.setType(436207665);
bdVar.setContent(q.GF() + ":\n" + str);
String u = g.u((bi.VF()).getBytes());
String fullPath = o.Pf().getFullPath(u);
o.Pf();
u = com.tencent.mm.ak.g.lM(u);
com.tencent.mm.ak.a.a Pj = o.Pj();
String str5 = gp.dxU;
com.tencent.mm.ak.a.a.c.a aVar = new com.tencent.mm.ak.a.a.c.a();
aVar.dXA = fullPath;
aVar.dXy = true;
Pj.a(str5, null, aVar.Pt());
bdVar.eq(u);
bdVar.eX(1);
bdVar.ep(str2);
bdVar.setStatus(3);
bdVar.setMsgId(com.tencent.mm.model.bd.i(bdVar));
x.i("MicroMsg.AAUtil", "finish insert aa msg");
a(gp.dyk, true, bdVar.field_msgId);
com.tencent.mm.y.g gVar = new com.tencent.mm.y.g();
gp.a(gVar);
gVar.field_msgId = bdVar.field_msgId;
com.tencent.mm.plugin.ac.a.bmg().b(gVar);
}
}
}
}
}
public static synchronized void a(String str, boolean z, long j) {
synchronized (h.class) {
if (!bi.oW(str)) {
x.i("MicroMsg.AAUtil", "insertOrUpdateAARecord, billNo: %s, insertMsg: %s", new Object[]{str, Boolean.valueOf(z)});
c cVar = new c();
cVar.field_billNo = str;
cVar.field_insertmsg = z;
cVar.field_localMsgId = j;
b.VQ().b(cVar);
}
}
}
public static synchronized void aK(String str, String str2) {
boolean z = true;
synchronized (h.class) {
if (!bi.oW(str)) {
a gp = a.gp(str);
String str3 = "MicroMsg.AAUtil";
String str4 = "checkIfInsertAAMsg, billNo: %s, appMsgContent: %s";
Object[] objArr = new Object[2];
objArr[0] = gp != null ? gp.dyk : "";
objArr[1] = str.trim().replace(" ", "");
x.d(str3, str4, objArr);
if (!(gp == null || bi.oW(gp.dyk))) {
boolean z2;
long j;
String str5 = gp.dyk;
c pe = b.VQ().pe(str5);
str4 = "MicroMsg.AAUtil";
String str6 = "checkIfInsertAAMsg, record==null: %s, billNo: %s, insertMsg: %s, chatroom: %s, localMsgId: %s";
Object[] objArr2 = new Object[5];
if (pe == null) {
z2 = true;
} else {
z2 = false;
}
objArr2[0] = Boolean.valueOf(z2);
objArr2[1] = str5;
if (pe == null || !pe.field_insertmsg) {
z = false;
}
objArr2[2] = Boolean.valueOf(z);
objArr2[3] = str2;
if (pe != null) {
j = pe.field_localMsgId;
} else {
j = 0;
}
objArr2[4] = Long.valueOf(j);
x.i(str4, str6, objArr2);
if (pe != null && pe.field_insertmsg && pe.field_localMsgId > 0 && ((i) com.tencent.mm.kernel.g.l(i.class)).bcY().dW(pe.field_localMsgId).field_msgId <= 0) {
x.i("MicroMsg.AAUtil", "checkIfInsertAAMsg, the oldMsgInfo has deleted, ignore this");
b.VQ().a(pe, new String[0]);
} else if (pe == null || !pe.field_insertmsg || pe.field_localMsgId <= 0) {
x.i("MicroMsg.AAUtil", "checkIfInsertAAMsg, insert new aa msg");
aJ(str, str2);
} else {
x.i("MicroMsg.AAUtil", "checkIfInsertAAMsg, update aa msg");
f(pe.field_localMsgId, str);
}
}
}
}
}
public static synchronized void v(String str, String str2, String str3) {
synchronized (h.class) {
x.i("MicroMsg.AAUtil", "setAARecordAfterLaunchAA, billNo: %s, chatroom: %s, msgContent==null:%s, oldRecord: %s", new Object[]{str, str2, Boolean.valueOf(bi.oW(str3)), b.VQ().pe(str)});
if (b.VQ().pe(str) == null) {
a(str, false, 0);
}
aK(str3, str2);
}
}
public static synchronized void c(String str, String str2, String str3, String str4, String str5) {
boolean z = true;
synchronized (h.class) {
x.d("MicroMsg.AAUtil", "insertPayMsgAfterPaySucc, launcherUsername: %s, billNo: %s, payMsgId: %s", new Object[]{str, str3, str4});
if (!(bi.oW(str) || bi.oW(str3) || bi.oW(str4))) {
com.tencent.mm.plugin.aa.a.b.a pd = b.VR().pd(str4);
String str6 = "MicroMsg.AAUtil";
String str7 = "insertPayMsgAfterPaySucc, launcherUsername: %s, chatroom: %s, payMsgId: %s, record: %s, insertmsg: %s";
Object[] objArr = new Object[5];
objArr[0] = str;
objArr[1] = str2;
objArr[2] = str4;
objArr[3] = pd;
if (pd == null || !pd.field_insertmsg) {
z = false;
}
objArr[4] = Boolean.valueOf(z);
x.i(str6, str7, objArr);
if (pd == null || !pd.field_insertmsg) {
String str8 = "weixin://weixinnewaa/opendetail?billno=" + str3 + "&launcherusername=" + str;
if (bi.oW(str5)) {
x.i("MicroMsg.AAUtil", "empty msgxml, insert local msgcontent");
if (str.equals(q.GF())) {
str5 = ad.getContext().getString(com.tencent.mm.plugin.wxpay.a.i.pay_sys_msg_tmpl_launch_by_myself, new Object[]{str8});
} else {
String displayName = ((com.tencent.mm.plugin.messenger.a.b) com.tencent.mm.kernel.g.l(com.tencent.mm.plugin.messenger.a.b.class)).getDisplayName(str, str2);
str5 = ad.getContext().getString(com.tencent.mm.plugin.wxpay.a.i.pay_sys_msg_tmpl_launch_by_other, new Object[]{displayName, str8});
}
} else {
x.d("MicroMsg.AAUtil", "insert msgxml: %s", new Object[]{str5});
}
a(str5, str2, pd, str4);
}
}
}
}
public static synchronized void w(String str, String str2, String str3) {
synchronized (h.class) {
try {
if (!(bi.oW(str) || bi.oW(str2) || bi.oW(str3))) {
x.i("MicroMsg.AAUtil", "checkIfInsertPaySysMsg, chatroom: %s, payMsgId: %s", new Object[]{str2, str3});
com.tencent.mm.plugin.aa.a.b.a pd = b.VR().pd(str3);
if (pd == null || !pd.field_insertmsg) {
x.i("MicroMsg.AAUtil", "checkIfInsertPaySysMsg, insert new msg");
a(str, str2, pd, str3);
} else {
bd dW = ((i) com.tencent.mm.kernel.g.l(i.class)).bcY().dW(pd.field_msgId);
x.i("MicroMsg.AAUtil", "checkIfInsertPaySysMsg, update old one, msgId: %s, dbMsginfo.id: %s", new Object[]{Long.valueOf(pd.field_msgId), Long.valueOf(dW.field_msgId)});
dW.setContent(str);
((i) com.tencent.mm.kernel.g.l(i.class)).bcY().a(pd.field_msgId, dW);
}
}
} catch (Exception e) {
x.e("MicroMsg.AAUtil", "checkIfInsertPaySysMsg error: %s", new Object[]{e.getMessage()});
}
}
return;
}
private static synchronized void a(String str, String str2, com.tencent.mm.plugin.aa.a.b.a aVar, String str3) {
synchronized (h.class) {
bd bdVar = new bd();
bdVar.eX(0);
bdVar.ep(str2);
bdVar.setStatus(3);
bdVar.setContent(str);
bdVar.ay(com.tencent.mm.model.bd.o(str2, System.currentTimeMillis() / 1000));
bdVar.setType(10000);
long T = ((i) com.tencent.mm.kernel.g.l(i.class)).bcY().T(bdVar);
x.i("MicroMsg.AAUtil", "insertPaySysMsg, inserted msgId: %s", new Object[]{Long.valueOf(T)});
if (aVar == null) {
aVar = new com.tencent.mm.plugin.aa.a.b.a();
}
if (T > 0) {
aVar.field_payMsgId = str3;
aVar.field_chatroom = str2;
aVar.field_insertmsg = true;
aVar.field_msgId = T;
b.VR().a(aVar);
}
}
}
public static synchronized void f(long j, String str) {
synchronized (h.class) {
if (j > 0) {
if (!bi.oW(str)) {
a gp = a.gp(str);
if (gp == null || bi.oW(gp.dyk)) {
x.e("MicroMsg.AAUtil", "updateAARecordMsgAfterReceive, parse app msg failed, msgId: %s", new Object[]{Long.valueOf(j)});
} else {
x.i("MicroMsg.AAUtil", "updateAARecordMsgAfterReceive, msgId: %s, billNo: %s", new Object[]{Long.valueOf(j), gp.dyk});
c pe = b.VQ().pe(gp.dyk);
if (pe != null) {
long j2 = pe.field_localMsgId;
bd dW = ((i) com.tencent.mm.kernel.g.l(i.class)).bcY().dW(j2);
if (dW.field_msgId > 0) {
dW.setContent(com.tencent.mm.model.bd.iB(dW.field_content) + ":\n" + str);
((i) com.tencent.mm.kernel.g.l(i.class)).bcY().a(j2, dW);
x.i("MicroMsg.AAUtil", "updateAARecordMsgAfterReceive, update success, oldMsgId: %s, billNo: %s", new Object[]{Long.valueOf(j2), pe.field_billNo});
} else {
x.e("MicroMsg.AAUtil", "updateAARecordMsgAfterReceive, cannot find old msg, insert new one, billNo: %s, oldMsgId: %s, newMsgId: %s, needUpdateInfo.msgId: %s", new Object[]{pe.field_billNo, Long.valueOf(pe.field_localMsgId), Long.valueOf(j), Long.valueOf(dW.field_msgId)});
}
} else {
pe = new c();
pe.field_localMsgId = j;
pe.field_billNo = gp.dyk;
pe.field_insertmsg = true;
b.VQ().a(pe);
x.i("MicroMsg.AAUtil", "updateAARecordMsgAfterReceive, insert new aa record, msgId: %s, billNo: %s", new Object[]{Long.valueOf(j), gp.dyk});
}
}
}
}
x.e("MicroMsg.AAUtil", "updateAARecordMsgAfterReceive, msgContent is null or msgId invalid, msgId: %s, %s", new Object[]{Long.valueOf(j), Boolean.valueOf(bi.oW(str))});
}
}
public static void g(long j, String str) {
x.i("MicroMsg.AAUtil", "do update sys msg, %s, %s", new Object[]{Long.valueOf(j), str});
bd dW = ((i) com.tencent.mm.kernel.g.l(i.class)).bcY().dW(j);
String pa = pa(str);
if (!bi.oW(pa)) {
dW.setContent(pa);
}
((i) com.tencent.mm.kernel.g.l(i.class)).bcY().a(j, dW);
}
public static boolean a(Activity activity, y yVar) {
if (yVar.qYW == 1) {
x.i("MicroMsg.AAUtil", "need realname verify");
Bundle bundle = new Bundle();
bundle.putString("realname_verify_process_jump_activity", ".ui.LaunchAAUI");
bundle.putString("realname_verify_process_jump_plugin", "aa");
String str = yVar.kRt;
str = yVar.kRu;
str = yVar.kRv;
return com.tencent.mm.plugin.wallet_core.id_verify.util.a.a(activity, bundle, 0);
} else if (yVar.qYW == 2) {
x.i("MicroMsg.AAUtil", "need upload credit");
return com.tencent.mm.plugin.wallet_core.id_verify.util.a.a(activity, yVar.kRt, yVar.kRw, yVar.kRu, yVar.kRv, false, null);
} else {
x.i("MicroMsg.AAUtil", "realnameGuideFlag = " + yVar.qYW);
return false;
}
}
private static String pa(String str) {
String str2;
UnsupportedEncodingException e;
Map z = bl.z(str, "sysmsg");
if (z == null) {
return "";
}
str2 = (String) z.get(".sysmsg.paymsg.appmsgcontent");
if (bi.oW(str2)) {
x.e("MicroMsg.AAUtil", "empty appmsgcontent!");
return "";
}
String str3 = "";
try {
str2 = URLDecoder.decode(str2, "UTF-8");
try {
x.d("MicroMsg.AAUtil", "msgContent: %s", new Object[]{str2});
return str2;
} catch (UnsupportedEncodingException e2) {
e = e2;
}
} catch (UnsupportedEncodingException e3) {
e = e3;
str2 = str3;
}
x.e("MicroMsg.AAUtil", e.getMessage());
return str2;
}
public static double a(String str, String str2, int i, int i2) {
try {
return new BigDecimal(bi.getDouble(str.trim(), 0.0d) == 0.0d ? "0" : str.trim()).divide(new BigDecimal(str2.trim()), i, i2).doubleValue();
} catch (Throwable e) {
x.printErrStackTrace("MicroMsg.AAUtil", e, "", new Object[0]);
return 0.0d;
}
}
public static long aL(String str, String str2) {
try {
double d = bi.getDouble(str, 0.0d);
double d2 = bi.getDouble(str2, 0.0d);
if (d == 0.0d) {
str = "0";
}
BigDecimal bigDecimal = new BigDecimal(str);
if (d2 == 0.0d) {
str2 = "0";
}
return bigDecimal.multiply(new BigDecimal(str2)).longValue();
} catch (Throwable e) {
x.printErrStackTrace("MicroMsg.AAUtil", e, "", new Object[0]);
return 0;
}
}
public static List<String> pb(String str) {
List<String> il;
if (bi.oW(str)) {
x.i("MicroMsg.AAUtil", "illegal chatroomName");
return new ArrayList();
} else if (s.fq(str)) {
try {
il = ((com.tencent.mm.plugin.chatroom.b.b) com.tencent.mm.kernel.g.l(com.tencent.mm.plugin.chatroom.b.b.class)).Ga().il(str);
if (il == null) {
return new ArrayList();
}
return il;
} catch (Exception e) {
x.e("MicroMsg.AAUtil", "getChatroomMemberList error! %s", new Object[]{e.getMessage()});
return new ArrayList();
}
} else {
il = new ArrayList();
il.add(q.GF());
il.add(str);
return il;
}
}
public static String VZ() {
com.tencent.mm.kernel.g.Ek();
return bi.oV((String) com.tencent.mm.kernel.g.Ei().DT().get(aa.a.sXI, null));
}
public static void pc(String str) {
String VZ = VZ();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(str);
stringBuilder.append(",");
if (!bi.oW(VZ)) {
String[] split = VZ.split(",");
int i = 1;
for (String str2 : split) {
if (!str2.equals(str) && i < 5) {
stringBuilder.append(str2);
stringBuilder.append(",");
i++;
}
}
}
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
x.d("MicroMsg.AAUtil", "recent group: %s", new Object[]{stringBuilder.toString()});
com.tencent.mm.kernel.g.Ek();
com.tencent.mm.kernel.g.Ei().DT().a(aa.a.sXI, stringBuilder.toString());
}
}
|
package View;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
/**
* It's a word counter machine.
* @author Salilthip 5710546640
*
*/
public class UMLReader {
/**
* For count the number of word from url.
* @param url is a source of String.
* @return the number of word
*/
public String readAllLine(URL url) {
InputStream in =null;
try {
in = url.openStream( );
} catch (IOException e) {
}
return readAllLine(in);
}
/**
* For count the number of word from InputStream.
* @param inputStream is a source of string.
* @return the number of syllables.
*/
public String readAllLine(InputStream inputStream){
String str ="";
Scanner scanner = new Scanner(inputStream);
while(scanner.hasNext()){
String wd = scanner.nextLine();
str+=wd+"\n";
}
return str;
}
public String fileName(String url) {
String[] res = url.split("/");
String[] rs = res[res.length-1].split("\\.");
return rs[0];
}
}
|
package ch.fhnw.oop2.departure.controller;
import ch.fhnw.oop2.departure.Main;
import ch.fhnw.oop2.departure.model.Departure;
import ch.fhnw.oop2.departure.model.DepartureProxy;
import ch.fhnw.oop2.departure.model.Timetable;
import ch.fhnw.oop2.departure.util.JavaFxUtils;
import javafx.collections.transformation.FilteredList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.stage.FileChooser;
import java.io.File;
import java.net.URL;
import java.util.Locale;
import java.util.ResourceBundle;
/**
* Created by ernst on 26.04.2016.
*/
public class MainController implements Initializable {
private ResourceBundle bundle;
private Main main;
private Timetable timetable;
@FXML
private TableView<Departure> tvDepartureTable;
@FXML
private TableColumn<Departure, String> tcId;
@FXML
private TableColumn<Departure, String> tcDepartureTime;
@FXML
private TableColumn<Departure, String> tcDestination;
@FXML
private TableColumn<Departure, String> tcPlatform;
@FXML
private TextField txtDepartureTime;
@FXML
private TextField txtDestination;
@FXML
private TextField txtPlatform;
@FXML
private TextField txtTrainNumber;
@FXML
private TextArea txtStops;
@FXML
private Button toggleLanguage;
@FXML
private TextField txtFilter;
@FXML
public void toggleLanguage(ActionEvent e) {
tvDepartureTable.getSelectionModel().select(null);
if (toggleLanguage.getText().equals("DE")) {
main.loadMainView(new Locale("de", "DE"));
} else {
main.loadMainView(new Locale("en", "EN"));
}
}
@FXML
public void redo(ActionEvent actionEvent) {
//TODO redo
JavaFxUtils.createAlert(bundle.getString("info"), bundle.getString("notImplemented"), bundle.getString("redoNotImplemented"));
}
@FXML
public void undo(ActionEvent actionEvent) {
//TODO undo
JavaFxUtils.createAlert(bundle.getString("info"), bundle.getString("notImplemented"), bundle.getString("undoNotImplemented"));
}
@FXML
public void clear(ActionEvent actionEvent) {
timetable.delete(tvDepartureTable.getSelectionModel().getSelectedItem());
}
@FXML
public void add(ActionEvent actionEvent) {
timetable.createDeparture();
tvDepartureTable.getSelectionModel().selectLast();
tvDepartureTable.scrollTo(tvDepartureTable.getItems().size() - 1);
}
@FXML
public void save(ActionEvent actionEvent) {
FileChooser fileChooser = new FileChooser();
if (timetable.getFile() != null && !timetable.getFile().getAbsolutePath().endsWith(".csv")) {
fileChooser.setInitialFileName(timetable.getFile().getPath());
}
fileChooser.setTitle("Save File");
fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Json", "*.json"));
File f = fileChooser.showSaveDialog(main.getPrimaryStage());
String result = timetable.saveJSON(f);
JavaFxUtils.createTextboxAlert(bundle.getString("saved"), bundle.getString("exported"),
bundle.getString("expand"), result);
}
@Override
public void initialize(URL location, ResourceBundle resources) {
bundle = resources;
toggleLanguage.setTooltip(new Tooltip(bundle.getString("tooltip")));
tcId.setCellValueFactory(cellData -> cellData.getValue().idProperty());
tcId.setCellFactory(TextFieldTableCell.forTableColumn());
tcId.setOnEditCommit(e -> timetable.getCurrentDeparture().setId(e.getNewValue()));
tcDepartureTime.setCellValueFactory(cellData -> cellData.getValue().departureTimeProperty());
tcDepartureTime.setCellFactory(TextFieldTableCell.forTableColumn());
tcDepartureTime.setOnEditCommit(e -> timetable.getCurrentDeparture().setDepartureTime(e.getNewValue()));
tcDestination.setCellValueFactory(cellData -> cellData.getValue().destinationProperty());
tcDestination.setCellFactory(TextFieldTableCell.forTableColumn());
tcDestination.setOnEditCommit(e ->timetable.getCurrentDeparture().setDestination(e.getNewValue()));
tcPlatform.setCellValueFactory(cellData -> cellData.getValue().platformProperty());
tcPlatform.setCellFactory(TextFieldTableCell.forTableColumn());
tcPlatform.setOnEditCommit(e ->timetable.getCurrentDeparture().setPlatform(e.getNewValue()));
JavaFxUtils.addFilter_OnlyNumbers(txtPlatform);
tvDepartureTable.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
timetable.setCurrentDeparture((Departure)newValue);
boolean disabled = newValue == null;
txtDepartureTime.setDisable(disabled);
txtTrainNumber.setDisable(disabled);
txtDestination.setDisable(disabled);
txtStops.setDisable(disabled);
txtPlatform.setDisable(disabled);
});
}
public void setTimetable(Timetable timetable) {
this.timetable = timetable;
DepartureProxy c = timetable.getCurrentDeparture();
c.trainNumberProperty().bindBidirectional(txtTrainNumber.textProperty());
c.departureTimeProperty().bindBidirectional(txtDepartureTime.textProperty());
c.destinationProperty().bindBidirectional(txtDestination.textProperty());
c.viaProperty().bindBidirectional(txtStops.textProperty());
c.platformProperty().bindBidirectional(txtPlatform.textProperty());
FilteredList<Departure> filteredData = new FilteredList<>(timetable.getDeparturesData(), p -> true);
txtFilter.textProperty().addListener((observable, oldValue, newValue) -> {
filteredData.setPredicate(departure -> {
if (newValue == null || newValue.isEmpty()) {
return true;
}
String lowerCaseFilter = newValue.toLowerCase();
return departure.getDepartureTime().toLowerCase().contains(lowerCaseFilter) ||
departure.getDestination().toLowerCase().contains(lowerCaseFilter) ||
departure.getId().toLowerCase().contains(lowerCaseFilter) ||
departure.getPlatform().toLowerCase().contains(lowerCaseFilter);
});
});
tvDepartureTable.setItems(filteredData);
}
public void setMain(Main main) {
this.main = main;
}
}
|
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Institpg
*/
@WebServlet("/Institpg")
public class Institpg extends HttpServlet {
private static final long serialVersionUID = 1L;
public Institpg() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String roll= request.getParameter("roll");
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/student", "root", "poori");
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from register where Rollno='"+roll+"'");
while(rs.next())
{
out.println("<html>");
out.println("<body>");
out.println("<h1 align='center'> <div style=\'background: skyblue;\'> Student Information </div></h1>");
out.println("<table border='1' align='center'>");
out.println("<tr><td> Student Name: "+rs.getString(1).concat(rs.getString(2))+"</td></tr>");
out.println("<tr><td> DOB: "+rs.getString(3)+"</td></tr>");
out.println("<tr><td>Last Completed Grade: "+rs.getString(4)+"</td></tr>");
out.println("<tr><td>School studied in 10th Grade: "+rs.getString(6)+"</td></tr>");
out.println("<tr><td>Phone: "+rs.getString(8)+"</td></tr>");
out.println("<tr><td>E-mail: "+rs.getString(9)+"</td></tr>");
out.println("</table>");
out.println("<button type = button><a href='http://localhost:3001/block-explorer'> Click here to view certificate </a></button><br><br>");
out.println("<a href='institlogin.jsp'>Logout </a> <br><br>");
}
}
catch(Exception e)
{
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
|
package codex.utils;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
/**
* ะะปะฐัั ะฒัะฟะพะผะพะณะฐัะตะปัะฝัั
ะผะตัะพะดะพะฒ ะดะปั ัะฐะฑะพัั ั ัะตััั.
*/
public class NetTools {
/**
* ะัะพะฒะตัะบะฐ ะดะพัััะฟะฝะพััะธ ัะตัะตะฒะพะณะพ ะฟะพััะฐ.
* @param host ะกะธะผะฒะพะปัะฝะพะต ะธะผั ั
ะพััะฐ ะธะปะธ IP-ะฐะดัะตั.
* @param port ะะพะผะตั ะฟะพััะฐ.
* @param timeout ะขะฐะนะผะฐัั ะฟะพะดะบะปััะตะฝะธั ะฒ ะผะธะปะปะธัะตะบัะฝะดะฐั
.
*/
public static boolean isPortAvailable(String host, int port, int timeout) throws IllegalStateException {
if (!checkPort(port)) {
throw new IllegalStateException("Invalid port number");
}
if (!checkAddress(host)) {
throw new IllegalStateException("Invalid host address: "+host);
}
try {
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress(host, port), timeout);
return true;
}
} catch (IOException e) {
return false;
}
}
public static boolean checkPort(int port) {
return !(port < 1 || port > 65535);
}
public static boolean checkAddress(String host) {
return
host.matches("^(([0-1]?[0-9]{1,2}\\.)|(2[0-4][0-9]\\.)|(25[0-5]\\.)){3}(([0-1]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))$") &&
host.matches("^[^\\s]+$");
}
}
|
package me.hp888.messenger.api.callback;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
/**
* @author hp888 on 07.11.2020.
*/
public final class CallbackManager {
private final Map<Long, Callback<?>> callbackMap = new HashMap<>();
public long addCallback(Callback<?> callback) {
long id;
do {
id = ThreadLocalRandom.current().nextLong(Long.MIN_VALUE, Long.MAX_VALUE);
} while (callbackMap.containsKey(id));
callbackMap.put(id, callback);
return id;
}
public Callback<?> getCallback(long id) {
return callbackMap.remove(id);
}
}
|
package com.qihoo.finance.chronus.core.log.annotation;
import com.alibaba.fastjson.JSONObject;
import com.qihoo.finance.chronus.common.NodeInfo;
import com.qihoo.finance.chronus.core.log.NodeLogBO;
import com.qihoo.finance.chronus.core.log.NodeLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;
import java.util.Collection;
@Slf4j
@Aspect
@Configuration
public class NodeLogAspect {
@Resource
private NodeInfo nodeInfo;
@Resource
private NodeLogService nodeLogService;
public NodeLogAspect() {
}
@Around("execution(* *(..)) && @annotation(nodeLog)")
public Object audit(ProceedingJoinPoint pjp, NodeLog nodeLog) throws Throwable {
NodeLogBO nodeLogBO = NodeLogBO.start(nodeInfo, nodeLog.value());
boolean sendLogFlag = true;
try {
Object result = pjp.proceed();
if (nodeLog.resultPutContent()) {
if (result instanceof Collection && CollectionUtils.isEmpty((Collection) result)) {
sendLogFlag = false;
} else {
nodeLogBO.stop(nodeLog.message(), JSONObject.toJSONString(result));
}
} else {
nodeLogBO.stop(nodeLog.message());
}
return result;
} catch (Throwable var13) {
nodeLogBO.stop(var13.getMessage());
throw var13;
} finally {
try {
if (sendLogFlag) {
nodeLogService.submitEvent(nodeLogBO);
}
} catch (Exception e) {
log.error("ไฟๅญไบไปถๆฅๅฟๅผๅธธ", e);
}
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package amazonviewer.model;
import java.util.ArrayList;
import java.util.Date;
/**
*
* @author i5
*/
public class Magazine extends Publication implements IVisualizable {
private int id;
private boolean readed;
private int timeReaded;
public int getTimeReaded() {
return timeReaded;
}
public void setTimeReaded(int timeReaded) {
this.timeReaded = timeReaded;
}
public int getId() {
return id;
}
public Magazine(String title, Date editionDate, String editorial){
super(title, editionDate, editorial);
}
@Override
public String toString(){
return "\n :: MAGAZINE ::" +
"\n Title: " + getTitle() +
"\n Editorial: " + getEditorial() +
"\n Edition Date: " + getEdititionDate();
}
/*iNTERFACES*/
@Override
public Date startToSee(Date dateI) {
return dateI;
}
@Override
public void stopToSee(Date dateI, Date dateF) {
if (dateF.getTime() > dateI.getTime()) {
setTimeReaded((int)(dateF.getTime() - dateI.getTime()));
}else {
setTimeReaded(0);
}
}
//Mostramos lista de revista
public static ArrayList<Magazine> makeMagazinesList(){
ArrayList<Magazine> magazines = new ArrayList();
for(int i=1; i<=5; i++){
magazines.add(new Magazine("Titulo "+i,new Date(),"PC Magazine"));
}
return magazines;
}
}
|
package io.github.rhythm2019.mawenCommunity.advice;
import cn.hutool.http.ContentType;
import com.alibaba.fastjson.JSON;
import io.github.rhythm2019.mawenCommunity.dto.Result;
import io.github.rhythm2019.mawenCommunity.exception.CustomizeErrorCode;
import io.github.rhythm2019.mawenCommunity.exception.CustomizeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@Slf4j
@ControllerAdvice
public class CustomizeExceptionHandler {
@ExceptionHandler(Exception.class)
ModelAndView handle(HttpServletRequest request, Throwable e, Model model, HttpServletResponse response) {
log.error("Meet Exception", e);
String contentType = request.getContentType();
if (ContentType.JSON.getValue().equals(contentType)){
Result<?> result;
if (e instanceof CustomizeException){
CustomizeException customizeException = (CustomizeException) e;
result = Result.failed(customizeException.getCode(), customizeException.getMessage());
}else{
result = Result.failed(CustomizeErrorCode.SERVER_ERROR.getCode(), CustomizeErrorCode.SERVER_ERROR.getMessage());
}
try {
response.setContentType("application/JSON");
response.setStatus(200);
response.setCharacterEncoding("UTF-8");
PrintWriter printWriter = response.getWriter();
printWriter.write(JSON.toJSONString(result));
printWriter.close();
} catch (IOException ex) {
ex.printStackTrace();
}
return null;
} else {
//HTML
if (e instanceof CustomizeException){
model.addAttribute("message",e.getMessage());
}else{
log.error("error:{}",e.getMessage());
model.addAttribute("message","ๆๅกๅจ็ธไบ๏ผๆญฃๅจๆขไฟฎๆจๆ็นๅๆฅๅง๏ผ");
}
return new ModelAndView("error");
}
}
private HttpStatus getStatus(HttpServletRequest request) {
Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
if (statusCode == null) {
return HttpStatus.INTERNAL_SERVER_ERROR;
}
return HttpStatus.valueOf(statusCode);
}
}
|
package com.gft.digitalbank.exchange.solution;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gft.digitalbank.exchange.actors.messages.BooksAndTransactions;
import com.gft.digitalbank.exchange.actors.messages.Shutdown;
import com.gft.digitalbank.exchange.domain.CancellationOrder;
import com.gft.digitalbank.exchange.domain.ModificationOrder;
import com.gft.digitalbank.exchange.domain.Order;
import com.gft.digitalbank.exchange.listener.ProcessingListener;
import com.gft.digitalbank.exchange.model.OrderBook;
import com.gft.digitalbank.exchange.model.SolutionResult;
import com.gft.digitalbank.exchange.model.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.concurrent.Await;
import scala.concurrent.Future;
import scala.concurrent.duration.Duration;
import javax.jms.*;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import static akka.pattern.Patterns.ask;
/**
* Created by krzysztof on 06/08/16.
*/
public class JmsToAkkaMessageDispatcher implements MessageListener {
private final static Logger LOG = LoggerFactory.getLogger(JmsToAkkaMessageDispatcher.class);
public static final String ORDER = "ORDER";
public static final String CANCEL = "CANCEL";
public static final String MODIFICATION = "MODIFICATION";
public static final String SHUTDOWN_NOTIFICATION = "SHUTDOWN_NOTIFICATION";
public static final String MESSAGE_TYPE = "messageType";
private static final int TIMEOUT_IN_MS = 15000;
private final Session session;
private final AtomicInteger activeBrokers;
private final ProcessingListener processingListener;
private final ActorSystem system;
private final ActorRef parentDispatcher;
private final ObjectMapper mapper = new ObjectMapper();
private int total = 0;
public JmsToAkkaMessageDispatcher(final Session session, final AtomicInteger activeBrokers,
final ProcessingListener processingListener, final ActorSystem system,
final ActorRef parentDispatcher) {
this.session = session;
this.activeBrokers = activeBrokers;
this.processingListener = processingListener;
this.system = system;
this.parentDispatcher = parentDispatcher;
}
@Override
public void onMessage(Message message) {
try {
String payload = ((TextMessage) message).getText();
String type = message.getStringProperty(MESSAGE_TYPE);
switch (type) {
case ORDER:
Order order = mapper.readValue(payload, Order.class);
parentDispatcher.tell(order, ActorRef.noSender());
total++;
break;
case CANCEL:
CancellationOrder cancellationOrder = mapper.readValue(payload, CancellationOrder.class);
LOG.info("received cancellation message:" + cancellationOrder);
parentDispatcher.tell(cancellationOrder, ActorRef.noSender());
total++;
break;
case MODIFICATION:
ModificationOrder modificationOrder = mapper.readValue(payload, ModificationOrder.class);
LOG.info("received modification message:" + modificationOrder);
parentDispatcher.tell(modificationOrder, ActorRef.noSender());
total++;
break;
case SHUTDOWN_NOTIFICATION:
LOG.debug("close JMS session...");
session.commit();
session.close();
if (activeBrokers.decrementAndGet() == 0) {
Set<OrderBook> orderBooks = new HashSet<>();
Set<Transaction> transactions = new HashSet<>();
Future<?> result = ask(parentDispatcher, new Shutdown(total), TIMEOUT_IN_MS);
Object r = Await.result(result, Duration.Inf());
LOG.info("result from akka:" + r);
if (r instanceof BooksAndTransactions) {
orderBooks = ((BooksAndTransactions) r).getOrderBooks();
transactions = ((BooksAndTransactions) r).getTransactions();
} else {
LOG.error("unrecognized result type:" + r);
}
system.shutdown();
processingListener.processingDone(
SolutionResult.builder()
.transactions(transactions) // transactions is a Set<Transaction>
.orderBooks(orderBooks) // orderBooks is a Set<OrderBook>
.build()
);
}
break;
default:
LOG.warn("received unrecognized message type:" + type);
}
// now we can commit
session.commit();
// don't rethrow any exceptions, just log them
} catch (Exception e) {
LOG.error("Some issue with dispatching messages to actor system:" + e);
}
}
}
|
package com.example.mpv.bb8;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.orbotix.ConvenienceRobot;
import com.orbotix.Sphero;
import com.orbotix.async.CollisionDetectedAsyncData;
import com.orbotix.calibration.api.CalibrationEventListener;
import com.orbotix.calibration.api.CalibrationImageButtonView;
import com.orbotix.calibration.api.CalibrationView;
import com.orbotix.common.DiscoveryAgentEventListener;
import com.orbotix.common.DiscoveryException;
import com.orbotix.common.ResponseListener;
import com.orbotix.common.Robot;
import com.orbotix.common.RobotChangedStateListener;
import com.orbotix.common.internal.AsyncMessage;
import com.orbotix.common.internal.DeviceResponse;
import com.orbotix.joystick.api.JoystickEventListener;
import com.orbotix.joystick.api.JoystickView;
import com.orbotix.le.DiscoveryAgentLE;
import com.orbotix.le.RobotRadioDescriptor;
import java.util.List;
public class MainActivity extends Activity implements View.OnClickListener, RobotChangedStateListener, ResponseListener {
private Handler mHandler = new Handler();
private static final String TAG = "MainActivity";
// Our current discovery agent that we will use to find BB8s
private DiscoveryAgentLE _discoveryAgent;
// The connected robot
private ConvenienceRobot _robot;
// The joystick that we will use to send roll commands to the robot
private JoystickView _joystick;
// The calibration view, used for setting the default heading of the robot
private CalibrationView _calibrationView;
//A button used for one finger calibration
private CalibrationImageButtonView _calibrationButtonView;
private TextView events;
private TextView score;
private long startGameTime;
private long endGameTime;
private int life;
private static final float ROBOT_VELOCITY = 0.6f;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
life = 100;
DiscoveryAgentLE.getInstance().addRobotStateListener( this );
events = (TextView) findViewById(R.id.events);
events = (TextView) findViewById(R.id.score);
events.setText(Integer.toString(life));
if( Build.VERSION.SDK_INT >= 23){
// Bluetooth permissions
}
startDiscovery();
}
/**
* onPause we sleep the robot
*/
@Override
protected void onPause() {
super.onPause();
if (_discoveryAgent != null) {
// When pausing, you want to make sure that you let go of the connection to the robot so that it may be
// accessed from within other applications. Before you do that, it is a good idea to unregister for the robot
// state change events so that you don't get the disconnection event while the application is closed.
// This is accomplished by using DiscoveryAgent#removeRobotStateListener().
_discoveryAgent.removeRobotStateListener(this);
// Here we are only handling disconnecting robots if the user selected a type of robot to connect to. If you
// didn't use the robot picker, you will need to check the appropriate discovery agent manually by using
// DiscoveryAgent.getInstance().getConnectedRobots()
for (Robot r : _discoveryAgent.getConnectedRobots()) {
// There are a couple ways to disconnect a robot: sleep and disconnect. Sleep will disconnect the robot
// in addition to putting it into standby mode. If you choose to just disconnect the robot, it will
// use more power than if it were in standby mode. In the case of Ollie, the main LED light will also
// turn a bright purple, indicating that it is on but disconnected. Unless you have a specific reason
// to leave a robot on but disconnected, you should use Robot#sleep()
r.sleep();
}
}
}
/**
* Sets up the joystick from scratch
*/
private void setupJoystick() {
// Get a reference to the joystick view so that we can use it to send roll commands
_joystick = (JoystickView) findViewById(R.id.joystickView);
// In order to get the events from the joystick, you need to implement the JoystickEventListener interface
// (or declare it anonymously) and set the listener.
_joystick.setJoystickEventListener(new JoystickEventListener() {
/**
* Invoked when the user starts touching on the joystick
*/
@Override
public void onJoystickBegan() {
// Here you can do something when the user starts using the joystick.
}
/**
* Invoked when the user moves their finger on the joystick
*
* @param distanceFromCenter The distance from the center of the joystick that the user is touching from 0.0 to 1.0
* where 0.0 is the exact center, and 1.0 is the very edge of the outer ring.
* @param angle The angle from the top of the joystick that the user is touching.
*/
@Override
public void onJoystickMoved(double distanceFromCenter, double angle) {
// Here you can use the joystick input to drive the connected robot. You can easily do this with the
// ConvenienceRobot#drive() method
// Note that the arguments do flip here from the order of parameters
if(_robot != null)
_robot.drive((float) angle, (float) distanceFromCenter);
}
/**
* Invoked when the user stops touching the joystick
*/
@Override
public void onJoystickEnded() {
// Here you can do something when the user stops touching the joystick. For example, we'll make it stop driving.
if(_robot != null)
_robot.stop();
}
});
}
/**
* Sets up the calibration gesture and button
*/
private void setupCalibration() {
// Get the view from the xml file
_calibrationView = (CalibrationView)findViewById(R.id.calibrationView);
// Set the glow. You might want to not turn this on if you're using any intense graphical elements.
_calibrationView.setShowGlow(true);
// Register anonymously for the calibration events here. You could also have this class implement the interface
// manually if you plan to do more with the callbacks.
_calibrationView.setCalibrationEventListener(new CalibrationEventListener() {
/**
* Invoked when the user begins the calibration process.
*/
@Override
public void onCalibrationBegan() {
// The easy way to set up the robot for calibration is to use ConvenienceRobot#calibrating(true)
if(_robot != null){
Log.v(TAG, "Calibration began!");
_robot.calibrating(true);
}
}
/**
* Invoked when the user moves the calibration ring
* @param angle The angle that the robot has rotated to.
*/
@Override
public void onCalibrationChanged(float angle) {
// The usual thing to do when calibration happens is to send a roll command with this new angle, a speed of 0
// and the calibrate flag set.
if(_robot != null)
_robot.rotate(angle);
}
/**
* Invoked when the user stops the calibration process
*/
@Override
public void onCalibrationEnded() {
// This is where the calibration process is "committed". Here you want to tell the robot to stop as well as
// stop the calibration process.
if(_robot != null) {
_robot.stop();
_robot.calibrating(false);
}
}
});
// Like the joystick, turn this off until a robot connects.
_calibrationView.setEnabled(false);
// To set up the button, you need a calibration view. You get the button view, and then set it to the
// calibration view that we just configured.
_calibrationButtonView = (CalibrationImageButtonView) findViewById(R.id.calibrateButton);
_calibrationButtonView.setCalibrationView(_calibrationView);
_calibrationButtonView.setEnabled(false);
}
private DiscoveryAgentEventListener _discoveryAgentEventListener = new DiscoveryAgentEventListener() {
@Override
public void handleRobotsAvailable(List<Robot> robots) {
Log.i("Sphero", "Found " + robots.size() + " robots");
for (Robot robot : robots) {
Log.i("Sphero", " " + robot.getName());
}
}
};
private RobotChangedStateListener _robotStateListener = new RobotChangedStateListener() {
@Override
public void handleRobotChangedState(Robot robot, RobotChangedStateNotificationType robotChangedStateNotificationType) {
switch (robotChangedStateNotificationType) {
case Online:
Toast.makeText(getApplicationContext(), robot.getName() + " is now Online!", Toast.LENGTH_SHORT).show();
stopDiscovery();
setupJoystick();
setupCalibration();
// Here, you need to route all the touch events to the joystick and calibration view so that they know about
// them. To do this, you need a way to reference the view (in this case, the id "entire_view") and attach
// an onTouchListener which in this case is declared anonymously and invokes the
// Controller#interpretMotionEvent() method on the joystick and the calibration view.
findViewById(R.id.entire_view).setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
_joystick.interpretMotionEvent(event);
_calibrationView.interpretMotionEvent(event);
return true;
}
});
// Don't forget to turn on UI elements
_joystick.setEnabled(true);
_calibrationView.setEnabled(true);
_calibrationButtonView.setEnabled(true);
Log.i("Sphero", "Robot " + robot.getName() + " Online!");
_robot = new Sphero(robot);
startGameTime = System.currentTimeMillis();
// Finally for visual feedback let's turn the robot green saying that it's been connected
_robot.setLed(0f, 1f, 0f);
_robot.enableCollisions(true); // Enabling the collisions detector
_robot.addResponseListener(new ResponseListener() {
@Override
public void handleResponse(DeviceResponse deviceResponse, Robot robot) {
}
@Override
public void handleStringResponse(String s, Robot robot) {
}
@Override
public void handleAsyncMessage(AsyncMessage asyncMessage, Robot robot) {
if( asyncMessage == null )
return;
//Check the asyncMessage type to see if it is a DeviceSensor message
if( asyncMessage instanceof CollisionDetectedAsyncData) {
//Toast.makeText(getApplicationContext(),"Colision detectadaaaaa",Toast.LENGTH_LONG).show();
new Thread(new Runnable() {
@Override
public void run() {
_robot.setLed(1f, 0f, 0f);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
_robot.setLed(0f, 1f, 0f);
}
}
).start();
final CollisionDetectedAsyncData collisionData = (CollisionDetectedAsyncData) asyncMessage;
float collisionSpeed =((CollisionDetectedAsyncData) asyncMessage).getImpactSpeed();
// Toast.makeText(getApplicationContext(),Float.toString(collisionSpeed),Toast.LENGTH_SHORT).show();
float c= (collisionSpeed * 10);
//Toast.makeText(getApplicationContext(),Float.toString(c),Toast.LENGTH_SHORT).show();
//Toast.makeText(getApplicationContext(),Integer.toString(Math.round(c)),Toast.LENGTH_SHORT).show();
life=life-Math.round(c);
if(life<0)
life=0;
Toast.makeText(getApplicationContext(),Integer.toString(life),Toast.LENGTH_SHORT).show();
events.setText(Integer.toString(life));
if(life==0) {
Toast.makeText(getApplicationContext(), "YOUUU ARE DEADDDDDD", Toast.LENGTH_SHORT).show();
endGameTime = System.currentTimeMillis() - startGameTime;
int sec=(int)(endGameTime/1000);
Toast.makeText(getApplicationContext(),"Tiempo: "+ Integer.toString(sec), Toast.LENGTH_SHORT).show();
//score.setText(Integer.toString(sec));
}
// eventos.setText(((CollisionDetectedAsyncData) asyncMessage).getImpactPower().toString());
//events.setText(asyncMessage.toString());
}
}
});
break;
case Offline:
break;
case Connecting:
Toast.makeText(getApplicationContext(), "Connecting to " + robot.getName(), Toast.LENGTH_SHORT).show();
break;
case Connected:
Toast.makeText(getApplicationContext(), "Connected to " + robot.getName(), Toast.LENGTH_SHORT).show();
break;
// Handle other cases
case Disconnected:
// When a robot disconnects, it is a good idea to disable UI elements that send commands so that you
// do not have to handle the user continuing to use them while the robot is not connected
_joystick.setEnabled(false);
_calibrationView.setEnabled(false);
_calibrationButtonView.setEnabled(false);
break;
case FailedConnect:
break;
}
}
};
private void startDiscovery() {
try {
_discoveryAgent = DiscoveryAgentLE.getInstance();
// You first need to set up so that the discovery agent will notify you when it finds robots.
// To do this, you need to implement the DiscoveryAgentEventListener interface (or declare
// it anonymously) and then register it on the discovery agent with DiscoveryAgent#addDiscoveryListener()
_discoveryAgent.addDiscoveryListener(_discoveryAgentEventListener);
// Second, you need to make sure that you are notified when a robot changes state. To do this,
// implement RobotChangedStateListener (or declare it anonymously) and use
// DiscoveryAgent#addRobotStateListener()
_discoveryAgent.addRobotStateListener(_robotStateListener);
// Creating a new radio descriptor to be able to connect to the BB8 robots
RobotRadioDescriptor robotRadioDescriptor = new RobotRadioDescriptor();
robotRadioDescriptor.setNamePrefixes(new String[]{"BB-"});
_discoveryAgent.setRadioDescriptor(robotRadioDescriptor);
// Then to start looking for a BB8, you use DiscoveryAgent#startDiscovery()
// You do need to handle the discovery exception. This can occur in cases where the user has
// Bluetooth off, or when the discovery cannot be started for some other reason.
_discoveryAgent.startDiscovery(this);
} catch (DiscoveryException e) {
Log.e("Sphero", "Discovery Error: " + e);
e.printStackTrace();
}
}
private void stopDiscovery() {
// When a robot is connected, this is a good time to stop discovery. Discovery takes a lot of system
// resources, and if left running, will cause your app to eat the user's battery up, and may cause
// your application to run slowly. To do this, use DiscoveryAgent#stopDiscovery().
_discoveryAgent.stopDiscovery();
// It is also proper form to not allow yourself to re-register for the discovery listeners, so let's
// unregister for the available notifications here using DiscoveryAgent#removeDiscoveryListener().
_discoveryAgent.removeDiscoveryListener(_discoveryAgentEventListener);
_discoveryAgent.removeRobotStateListener(_robotStateListener);
_discoveryAgent = null;
}
@Override
public void handleResponse(DeviceResponse deviceResponse, Robot robot) {
}
@Override
public void handleStringResponse(String s, Robot robot) {
}
@Override
public void handleAsyncMessage(AsyncMessage asyncMessage, Robot robot) {
}
@Override
public void onClick(View v) {
if (_robot == null)
return;
switch (v.getId()) {
/*case R.id.procedimiento1: {
eventos.setText("Giro Loco Loco");
_robot.drive(45, 0);
android.os.SystemClock.sleep(75);
_robot.drive(90, 0);
android.os.SystemClock.sleep(75);
_robot.drive(135, 0);
android.os.SystemClock.sleep(75);
_robot.drive(180, 0);
android.os.SystemClock.sleep(75);
_robot.drive(225, 0);
android.os.SystemClock.sleep(75);
_robot.drive(270, 0);
android.os.SystemClock.sleep(75);
_robot.drive(324, 0);
android.os.SystemClock.sleep(75);
_robot.drive(360, 0);
android.os.SystemClock.sleep(75);
//_robot.drive(0, 0);
//android.os.SystemClock.sleep(75);
// _robot.drive(360, 0);
//android.os.SystemClock.sleep(75);
break;
}
case R.id.procedimiento2: {
eventos.setText("Giro Loco Loco 2");
_robot.enableStabilization(false);
_robot.addResponseListener(this);
for (int i=0;i<15;i++) {
_robot.drive(45, 0.0000f);
android.os.SystemClock.sleep(75);
_robot.drive(90, 0.0000f);
android.os.SystemClock.sleep(75);
_robot.drive(135, 0.0000f);
android.os.SystemClock.sleep(75);
_robot.drive(180, 0.0000f);
android.os.SystemClock.sleep(75);
_robot.drive(225, 0.0000f);
android.os.SystemClock.sleep(75);
_robot.drive(270, 0.0000f);
android.os.SystemClock.sleep(75);
_robot.drive(324, 0.0000f);
android.os.SystemClock.sleep(75);
_robot.drive(360, 0.0000f);
android.os.SystemClock.sleep(75);
}
break;
}
case R.id.procedimiento3:
eventos.setText("AVANCE INFINITO!");
for(int i=0;i<20;i++){
_robot.drive(0, 0.6f);
android.os.SystemClock.sleep(75);
}
break;
case R.id.procedimiento4:
eventos.setText("HALT!");
//_robot.drive(180, 0.6f);
android.os.SystemClock.sleep(35);
for(int i=0;i<20;i++){
_robot.drive(180, 0.6f);
android.os.SystemClock.sleep(75);
}
break;
case R.id.detener:
eventos.setText("HALT!");
_robot.drive(360, 0);
break;*/
}
}
@Override
public void handleRobotChangedState(Robot robot, RobotChangedStateNotificationType robotChangedStateNotificationType) {
}
}
|
package com.github.ezauton.core.localization.sensors;
/**
* A sensor which can record revolutions/s and revolutions as a distance
*/
public interface RotationalDistanceSensor extends Tachometer {
/**
* @return revolutions
*/
double getPosition();
}
|
package com.tencent.mm.plugin.account.bind.ui;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import com.tencent.mm.kernel.g;
import com.tencent.mm.plugin.appbrand.jsapi.i.d;
class FindMContactLearmMoreUI$4 implements OnCancelListener {
final /* synthetic */ FindMContactLearmMoreUI eHR;
FindMContactLearmMoreUI$4(FindMContactLearmMoreUI findMContactLearmMoreUI) {
this.eHR = findMContactLearmMoreUI;
}
public final void onCancel(DialogInterface dialogInterface) {
if (FindMContactLearmMoreUI.e(this.eHR) != null) {
g.DF().b(d.CTRL_INDEX, FindMContactLearmMoreUI.e(this.eHR));
FindMContactLearmMoreUI.f(this.eHR);
}
}
}
|
package com.saptarshi.rest;
public class Authenticationinfo {
private String name;
private String email;
private String password ;
private String group;
public void setName(String s) {
name = s;
}
public void setEmail(String s){
email = s;
}
public void setPassword(String s) {
password = s;
}
public void setGroup(String s) {
group = s;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public String getPassword() {
return password;
}
public String getGroup() {
return group;
}
}
|
package XBridge.Bridge;
public class BridgeTest {
public static void main(String[] args) {
//Creating 3+2=5 instances of bottom classes
ColorImplementation[] colors = new ColorImplementation[]
{new ColorRedImplementation(), new ColorBlueImplementation(), new ColorGreenImplementation()};
for (ColorImplementation color: colors
) {
ShapeAbstraction shape = new Circle(color);
shape.draw();
}
for (ColorImplementation color: colors
) {
ShapeAbstraction shape = new Square(color);
shape.draw();
}
}
}
|
package com.example.appBack.Tablas.Student.infrastructure.repositorio.port;
import com.example.appBack.Tablas.Student.domain.Student;
public interface SaveUpdateStudentPort {
Student updateStudent(String id, Student sdto) throws Exception;
}
|
package com.github.rahmnathan.commute.provider;
public interface CommuteProvider {
String getCommuteTime(String startLocation, String endLocation);
}
|
package su.svn.testpostgre;
import java.sql.*;
import java.io.*;
import javax.naming.*;
import javax.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyTestPostgreSQL extends HttpServlet {
String connectionData = "Not Connected";
int count = -1;
public void init() {
try {
Context ctx = new InitialContext();
if(ctx == null )
throw new Exception("Boom - No Context");
// /jdbc/postgres is the name of the resource above
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/PostgresMyDB");
if (ds != null) {
Connection connection = ds.getConnection();
if(connection != null) {
connectionData = "Got Connection " + connection.toString();
Statement stmt = connection.createStatement();
ResultSet rst = stmt.executeQuery(
"SELECT * FROM checkout LIMIT 1"
);
if(rst.next()) {
connectionData = rst.getString(1);
count++;
}
connection.close();
}
}
}
catch(Exception e) {
e.printStackTrace();
}
}
public String getConnectionData() { return connectionData; }
public int getCount() { return count;}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<head>");
out.println("<title>My Test PostgreSQL</title>");
out.println("</head>");
out.println("<body>");
out.println("<h3>My Test PostgreSQL</h3>");
out.println(
"Get data from PostgresDB: " + getConnectionData() + " count: " + getCount()
);
out.println("</body>");
out.println("</html>");
}
/**
* We are going to perform the same operations for POST requests
* as for GET methods, so this method just sends the request to
* the doGet method.
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
doGet(request, response);
}
}
|
package useless;
import biorimp.optmodel.mappings.metaphor.MetaphorCode;
import biorimp.optmodel.operators.RefOperMutation;
import biorimp.optmodel.space.RefactoringOperationSpace;
import edu.wayne.cs.severe.redress2.entity.refactoring.RefactoringOperation;
import edu.wayne.cs.severe.redress2.main.MainPredFormulasBIoRIPM;
import java.util.List;
public class TestRefactorRepair {
public static void main(String[] argss) {
// TODO Auto-generated method stub
//Getting the Metaphor
String userPath = System.getProperty("user.dir");
String[] args = {"-l", "Java", "-p", userPath + "\\test_data\\code\\optimization\\src", "-s", "java/optmodel/fitness "};
MainPredFormulasBIoRIPM init = new MainPredFormulasBIoRIPM();
init.main(args);
MetaphorCode metaphor = new MetaphorCode(init, 0);
System.out.println("*** Generating a genome of x genes randomly ***");
//Creating the Space
RefactoringOperationSpace refactorSpace = new RefactoringOperationSpace(10000);
//Visualizing the get() Space
List<RefactoringOperation> refactor = refactorSpace.get();
if (refactor != null)
for (RefactoringOperation refOper : refactor) {
System.out.println("Random Refactor: " + refOper.toString());
}
//ListRefOperMutation mutation = new ListRefOperMutation(0.05);
RefOperMutation mutation = new RefOperMutation(0.5);
System.out.println("*** Applying the mutation ***");
List<RefactoringOperation> mutated = mutation.apply(refactor);
System.out.println("Mutated array ");
if (mutated != null)
for (RefactoringOperation refOper : mutated) {
System.out.println("Mutated Refactor: " + refOper.toString());
}
int refss = 0;
if (!refactorSpace.feasible(mutated)) {
List<RefactoringOperation> mutatedN = refactorSpace.repair(mutated);
System.out.println("Mutated array Repaired ");
if (mutatedN != null)
for (RefactoringOperation refOper : mutatedN) {
System.out.println("Repaired Refactor: " + refss + refOper.toString());
refss++;
}
}
}
}
|
package SebastianMiklaszewski.Excercises.Infrastructure.Entity;
import SebastianMiklaszewski.Excercises.Core.Exception.NotEnoughMoneyException;
import SebastianMiklaszewski.Excercises.Core.ValueObject.Money;
import SebastianMiklaszewski.Excercises.Core.ValueObject.MoneyValue;
public class Wallet {
private Money money;
public Wallet(Money money) {
this.money = money;
}
public void withdraw(MoneyValue toWithdraw) throws NotEnoughMoneyException {
this.money = new Money(
new MoneyValue(this.money.getMoneyValue().getValue().subtract(toWithdraw.getValue())),
this.money.getCurrency()
);
}
}
|
package assemAssist.controller.ordercontrollers;
import java.util.LinkedList;
import java.util.List;
import assemAssist.controller.ShouldQuitException;
import assemAssist.model.facade.Facade;
import assemAssist.model.facade.OrderHandler;
import assemAssist.model.order.Customer;
import assemAssist.model.order.order.Order;
import assemAssist.view.CLI;
/**
* A class representing a ViewOrderDetailsController. It is used by a
* {@link Customer} (garage holder) to view the details of his {@link Order}s.
*
* @author SWOP Group 3
* @version 3.0
*/
public class ViewOrderDetailsController extends VehicleOrderController {
/**
* Creates a ViewOrderDetailsController using the given Facade, Command Line
* and Customer.
*
* @param facade
* Facade to be used
* @param cli
* Command Line to be used
* @param customer
* Customer to be used for viewing/placing orders
* @throws IllegalArgumentException
* Thrown when the given facade, cli or customer is not valid
*/
public ViewOrderDetailsController(Facade facade, CLI cli, Customer customer)
throws IllegalArgumentException {
super(facade, cli, customer);
}
/**
* Runs the View Vehicle Order Details scenario. Here the user chooses an
* Order, and the details of the Order and its model are displayed.
*/
public void run() {
runViewOrders();
OrderHandler orderhandler = getFacade().getOrderHandler();
List<Order> pendingorders = orderhandler.getPendingOrders(getCustomer());
List<Order> completedorders = orderhandler.getCompletedOrders(getCustomer());
List<String> ordertypes = new LinkedList<>();
ordertypes.add("Pending order");
ordertypes.add("Completed Order");
List<String> menu = new LinkedList<>();
menu.add("View other order");
menu.add("Quit");
getUI().displayList(ordertypes);
int input;
try {
input = getChoiceForList(ordertypes,
"For which order type would you like to select an order? (0 to quit)");
}
catch (ShouldQuitException exc) {
return;
}
List<Order> chosenlist = pendingorders;
String chosenQuestion = "For which pending order would you like to see the details? (0 to quit)";
if (input == 2) {
chosenQuestion = "For which completed order would you like to see the details? (0 to quit)";
chosenlist = completedorders;
}
try {
input = getChoiceForList(chosenlist, chosenQuestion);
}
catch (ShouldQuitException exc) {
return;
}
Order order = chosenlist.get(input - 1);
getUI().display("Details for the chosen order:");
getUI().displayOrder(order);
getUI().displayEmptyLine();
getUI().display("Would you like to view the details of another order?");
getUI().displayList(menu);
input = getUI().askNumberInput("Input your choice.");
if (input == 1) {
run();
}
}
}
|
package com.imesne.office.excel.write;
import com.imesne.office.excel.model.ExcelCell;
import com.imesne.office.excel.utils.ExcelKitUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* ๅๅ
ๆ ผๆไฝ
* ๅๅ
ๆ ผไธ้่ฆๅคๆญๆฏๅฆ่ฟฝๅ ๏ผๅ ไธบๅๅ
ๆ ผ้ฝๆฏๆฐๅๅปบ็๏ผไธๆฏๆๅๅ
ๆ ผ้้ข็ๅ
ๅฎน่ฟฝๅ
* <p>
* Created by liyd on 17/7/5.
*/
public class ExcelCellWriterImpl extends AbstractConfigWriter implements ExcelCellWriter {
public Cell writeExcelTitleCell(Workbook workbook, Sheet sheet, Row row, ExcelCell excelCell) {
Cell cell = this.writeExcelCell(workbook, sheet, row, excelCell);
Font font = workbook.createFont();
font.setBold(true);
RichTextString richStringCellValue = cell.getRichStringCellValue();
richStringCellValue.applyFont(font);
return cell;
}
public Cell writeExcelCell(Workbook workbook, Sheet sheet, Row row, ExcelCell excelCell) {
Integer cellIndex = excelCell.getCellNum() - 1;
Cell cell = this.getCell(row, cellIndex);
// ๅคๆญๅผ็็ฑปๅๅ่ฟ่กๅผบๅถ็ฑปๅ่ฝฌๆข
if (excelCell.getValue() == null) {
cell.setCellValue("");
} else if (excelCell.getValue() instanceof Date) {
// ่ฎพ็ฝฎๆฅๆ
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateValue = dateFormat.format((Date) excelCell.getValue());
dateValue = StringUtils.replace(dateValue, " 00:00:00", "");
cell.setCellValue(dateValue);
} else if (excelCell.getValue() instanceof byte[]) {
Drawing<?> drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, cellIndex, row.getRowNum(), cellIndex + 1, row.getRowNum() + 1);
drawing.createPicture(anchor, workbook.addPicture((byte[]) excelCell.getValue(), XSSFWorkbook.PICTURE_TYPE_JPEG));
} else if (excelCell.getValue() instanceof String[]) {
// ่ฎพ็ฝฎไธๆๅ่กจ
String[] values = (String[]) excelCell.getValue();
DataValidationHelper dvHelper = sheet.getDataValidationHelper();
DataValidationConstraint dvConstraint = dvHelper.createExplicitListConstraint(values);
CellRangeAddressList addressList = new CellRangeAddressList(row.getRowNum(), row.getRowNum(), cellIndex, cellIndex);
DataValidation dataValidation = dvHelper.createValidation(dvConstraint, addressList);
sheet.addValidationData(dataValidation);
//้ป่ฎคๆพ็คบ
cell.setCellValue(values[0]);
} else {
String value = excelCell.getValue().toString();
boolean matcher = value.matches("^\\d+(\\.\\d+)?$");
// ๆฏๆฐๅญๅนถไธ้ฟๅบฆๅฐไบ12ๆถ๏ผๅฝไฝdoubleๅค็๏ผๅฝ้ฟๅบฆๅคงไบ็ญไบ12ๆถๆฐๅญไผๆพ็คบๆ็งๅญฆ่ฎกๆฐๆณ๏ผๆไปฅๅฏผๆๅญ็ฌฆไธฒ
if (matcher && value.length() < 12) {
cell.setCellValue(Double.parseDouble(value));
} else {
cell.setCellValue(value);
}
}
if (excelCell.getWidth() != null) {
// ่ฎพ็ฝฎๅพ็ๆๅจๅๅฎฝๅบฆ,้่ฆๅไฝๆข็ฎ
int pixel = ExcelKitUtils.pixel2WidthUnits(excelCell.getWidth());
sheet.setColumnWidth(cellIndex, pixel);
}
if (this.getExcelWriterConfig().getExcelWriteProcessor() != null) {
this.getExcelWriterConfig().getExcelWriteProcessor().processCell(excelCell, cell, workbook, sheet, row);
}
return cell;
}
private Cell getCell(Row row, int cellIndex) {
ExcelWriterConfig excelWriterConfig = this.getExcelWriterConfig();
Cell cell = null;
if (excelWriterConfig.isAppend()) {
cell = row.getCell(cellIndex);
}
if (!excelWriterConfig.isAppend() || cell == null) {
cell = row.createCell(cellIndex);
}
return cell;
}
}
|
package ttyy.com.coder.scanner.decode;
/**
* author: admin
* date: 2017/03/14
* version: 0
* mail: secret
* desc: DecodeCallback
*/
public interface DecodeCallback {
void onDecodeSuccess(String message);
void onDecodeFail(String message);
}
|
package com.example.pdffiles;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ActionBar;
import android.os.Bundle;
import com.github.barteksc.pdfviewer.PDFView;
public class pdfShow extends AppCompatActivity {
PDFView pdfView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf_show);
pdfView=findViewById(R.id.pdflist);
String item = getIntent().getStringExtra("pdf");
if (item.equals("Android Development"))
{
pdfView.fromAsset("Head_First_Android_Development_2015.pdf").load();
}
if (item.equals("C Programming"))
{
pdfView.fromAsset("computer_programming.pdf").load();
}
if (item.equals("Compiler Design"))
{
pdfView.fromAsset("Compiler_Design_by_Aho_Ullman.pdf").load();
}
if (item.equals("Java"))
{
pdfView.fromAsset("Head_First_Java_2nd_Edition.pdf").load();
}
if (item.equals("Microeconomics"))
{
pdfView.fromAsset("microeconomics.pdf").load();
}
}
}
|
package com.tencent.mm.plugin.appbrand.jsapi.lbs;
import com.tencent.mm.plugin.appbrand.l;
import com.tencent.mm.plugin.report.service.h;
import org.json.JSONObject;
public final class d extends a {
private static final int CTRL_INDEX = 340;
private static final String NAME = "enableLocationUpdate";
private volatile f fQX;
public final void a(l lVar, JSONObject jSONObject, int i) {
h.mEJ.e(840, 9, 1);
synchronized (this) {
if (this.fQX == null) {
this.fQX = new f(lVar);
this.fQX.start();
}
}
boolean optBoolean = jSONObject.optBoolean("enable");
if (optBoolean || i(lVar)) {
if (!optBoolean) {
this.fQX.Dd(2);
} else if (i(lVar)) {
this.fQX.Dd(1);
} else {
h.mEJ.e(840, 11, 1);
lVar.E(i, f("fail:system permission denied", null));
}
h.mEJ.e(840, 10, 1);
lVar.E(i, f("ok", null));
return;
}
lVar.E(i, f("ok", null));
}
}
|
package SeleniumSessions;
import java.util.ArrayList;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import io.github.bonigarcia.wdm.WebDriverManager;
public class DropDownTest {
public static void main(String[] args) {
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
driver.get("https://www.facebook.com/");
WebElement day = driver.findElement(By.id("day"));
WebElement year = driver.findElement(By.id("year"));
WebElement month = driver.findElement(By.id("month"));
String date = "20-Dec-1996";
String datVal[] = date.split("-");
DropDownUtil.selectValueFromDropDownByText(day, datVal[0]);
DropDownUtil.selectValueFromDropDownByText(day, datVal[1]);
DropDownUtil.selectValueFromDropDownByText(day, datVal[2]);
ArrayList<String> monthList = DropDownUtil.getDropDownValues(month);
System.out.println(monthList);
ArrayList<String> dayList = DropDownUtil.getDropDownValues(day);
System.out.println(dayList);
ArrayList<String> yearList = DropDownUtil.getDropDownValues(year);
System.out.println(yearList);
}
}
|
package org.lxy.set;
import java.util.HashSet;
import org.lxy.bean.Student;
/**
* @author menglanyingfei
* @date 2017-3-18
*/
public class Demo01_HashSet {
/**
* @param args
*/
public static void main(String[] args) {
HashSet<String> hs = new HashSet<String>();
hs.add("a");
hs.add("a");
hs.add("b");
hs.add("c");
System.out.println(hs); // [b, c, a]
HashSet<Student> hs1 = new HashSet<Student>();
hs1.add(new Student(20, "li"));
hs1.add(new Student(20, "li"));
hs1.add(new Student(20, "wang"));
System.out.println(hs1); // [Student [age=20, name=li], Student [age=20, name=wang]]
}
}
|
package com.canfield010.mygame.item.armor.boots;
import com.canfield010.mygame.item.armor.Armor;
import javax.imageio.ImageIO;
import java.awt.*;
import java.io.File;
public class IronBoots extends Armor {
public static Image image;
public IronBoots() {
super("Iron Boots", 0.30F, Type.BOOTS);
}
public static void setImage() {
try {
image = ImageIO.read(new File("img/grass.png"));
} catch (Exception e) {
System.out.println(e);
}
}
public Image getImage() {
return image;
};
}
|
package br.com.treinar.academico.ClasseObjeto;
public class Pessoa {
int idade;
char sexo;
String nome;
}
|
package com.website.views.pages;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;
import org.mindrot.jbcrypt.BCrypt;
import com.website.persistence.AuthorService;
import com.website.tools.navigation.Redirector;
import com.website.tools.navigation.SessionManager;
import com.website.views.WebPages;
/**
* The connection web page view.</br>
* This {@link Named} class is bound with the same named xhtml file.
*
* @author Jรฉrรฉmy Pansier
*/
@Named
@RequestScoped
public class Connection {
/** The service managing the author persistence. */
@Inject
private AuthorService authorService;
/** The web page. */
public static final WebPages WEB_PAGE = WebPages.CONNECTION;
/** The author name used to log in. */
private String authorName;
/** The password. */
private String password;
/**
* @return the web page
*/
public WebPages getWebPage() {
return WEB_PAGE;
}
/**
* Gets the author name used to log in.
*
* @return the author name used to log in
*/
public String getAuthorName() {
return authorName;
}
/**
* Sets the author name used to log in.
*
* @param authorName the new author name used to log in
*/
public void setAuthorName(final String authorName) {
this.authorName = authorName;
}
/**
* Gets the password.
*
* @return the password
*/
public String getPassword() {
return password;
}
/**
* Sets the password.
*
* @param password the new password
*/
public void setPassword(final String password) {
this.password = password;
}
/**
* Logs the website user in.
*/
public void login() {
SessionManager.trackUser(authorName);
if (!authorService.isAuthor(authorName)) {
Redirector.redirect(WEB_PAGE.createJsfUrl(), true, "Utilisateur inconnu ou mot de passe incorrect");
return;
}
final String storedPassword = authorService.findPasswordByAuthorName(authorName);
if (!BCrypt.checkpw(password, storedPassword)) {
Redirector.redirect(WEB_PAGE.createJsfUrl(), true, "Utilisateur inconnu ou mot de passe incorrect");
return;
}
Redirector.redirect(WebPages.EVENTS_LIST.createJsfUrl(), false, "Connection rรฉussie");
}
}
|
package code;
import java.util.Scanner;
import errors.ZeroDivideException;
import interpretator.Interpretator;
public class InNumberFunction extends Instruction {
private SpecyficValue inValue;
@SuppressWarnings("resource")
@Override
public void execute() throws NumberFormatException, ZeroDivideException{
inValue = new SpecyficValue();
String input = null;
Scanner scaner = new Scanner(System.in);
input = scaner.nextLine();
int intInput;
double doubleInput;
int numerator, denumerator;
Interpretator.printLine(input, true);
try
{
intInput = Integer.parseInt(input);
inValue.setIntValue(intInput);
inValue.setType(Type.LiczbaNaturalna);
return;
}
catch(NumberFormatException e){}
try
{
doubleInput = Double.parseDouble(input);
inValue.setDoubleValue(doubleInput);
inValue.setType(Type.LiczbaZmiennoprzecinkowa);
return;
}
catch(NumberFormatException e){}
String[] inputStrings = input.split("/");
numerator = Integer.parseInt(inputStrings[0]);
denumerator = Integer.parseInt(inputStrings[1]);
inValue.setNumerator(numerator);
inValue.setDenumerator(denumerator);
inValue.setType(Type.UlamekZwykly);
}
@Override
public SpecyficValue getValue() {
return inValue;
}
}
|
package com.tencent.mm.plugin.account.bind.ui;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import com.tencent.mm.plugin.account.bind.ui.FindMContactIntroUI.4;
class FindMContactIntroUI$4$2 implements OnClickListener {
final /* synthetic */ 4 eHO;
FindMContactIntroUI$4$2(4 4) {
this.eHO = 4;
}
public final void onClick(DialogInterface dialogInterface, int i) {
}
}
|
package com.ds.algo.matters.array;
public class KadensAlgo {
public static void main(String[] args){
int[] input = {-2, -3, 4, -1, -2, 1, 5, -3};
System.out.println(maxSubarraySum(input, 8));
}
/** This method will find largest contiguous array of maximum sum **/
private static int maxSubarraySum(int arr[], int n){
int localMax = arr[0];
int globalMax = arr[0];
for(int i = 1; i < n; i++){
localMax = Math.max(arr[i], arr[i] + localMax);
globalMax = Math.max(globalMax, localMax);
}
return globalMax;
}
}
|
package com.rc.panels;
import com.rc.app.Launcher;
import com.rc.res.Colors;
import com.rc.components.GBC;
import com.rc.components.RCButton;
import com.rc.components.VerticalFlowLayout;
import com.rc.db.model.ContactsUser;
import com.rc.db.model.Room;
import com.rc.db.service.ContactsUserService;
import com.rc.db.service.RoomService;
import com.rc.utils.AvatarUtil;
import com.rc.utils.FontUtil;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
/**
* Created by song on 2017/6/15.
*
* <p>ไธๅพ #UserInfoPanel# ๅฏนๅบ็ไฝ็ฝฎ</p>
*
* ๅฝๅจ้่ฎฏๅฝไธญ้ๅฎๆไธช็จๆทๆถ๏ผUserInfoPanelไผๆพ็คบ่ฏฅ็จๆท็่ฏฆ็ปไฟกๆฏ
*
* <P>ๆจ่ไฝฟ็จMenloๆConsolasๅญไฝ</P>
* โโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
* โ โโโโโโโ โ Room Title โก โ
* โ โ โ name โก โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
* โ โโโโโโโ โ โ
* โโโโโโโโโโโโโโโโโโโโโโโโโโค โ
* โ search โ โ
* โโโโโโโโโโโโโโโโโโโโโโโโโโค โ
* โ โ โ โ โ โ โ โ
* โโโโโโโโโโโโโโโโโโโโโโโโโโค โ
* โ โโโโ name 14:01โ #UserInfoPanel# โ
* โ โโโโ message 99+โ โ
* โโโโโโโโโโโโโโโโโโโโโโโโโโค โ
* โ โ โ
* โ โ โ
* โ โ โ
* โ Room โ โ
* โ โ โ
* โ โ โ
* โ List โ โ
* โ โ โ
* โ โ โ
* โ โ โ
* โโโโโโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
*/
public class UserInfoPanel extends ParentAvailablePanel
{
private JPanel contentPanel;
private JLabel imageLabel;
private JLabel nameLabel;
private RCButton button;
private String username;
private RoomService roomService = Launcher.roomService;
private ContactsUserService contactsUserService = Launcher.contactsUserService;
public UserInfoPanel(JPanel parent)
{
super(parent);
initComponents();
initView();
setListeners();
}
private void initComponents()
{
contentPanel = new JPanel();
contentPanel.setLayout(new VerticalFlowLayout(VerticalFlowLayout.CENTER, 0, 20, true, false));
imageLabel = new JLabel();
ImageIcon icon = new ImageIcon(AvatarUtil.createOrLoadUserAvatar("song").getScaledInstance(100,100, Image.SCALE_SMOOTH));
imageLabel.setIcon(icon);
nameLabel = new JLabel();
nameLabel.setText("Song");
nameLabel.setFont(FontUtil.getDefaultFont(20));
button = new RCButton("ๅๆถๆฏ", Colors.MAIN_COLOR, Colors.MAIN_COLOR_DARKER, Colors.MAIN_COLOR_DARKER);
button.setBackground(Colors.PROGRESS_BAR_START);
button.setPreferredSize(new Dimension(200, 40));
button.setFont(FontUtil.getDefaultFont(16));
}
private void initView()
{
this.setLayout(new GridBagLayout());
JPanel avatarNamePanel = new JPanel();
avatarNamePanel.setLayout(new FlowLayout(FlowLayout.CENTER, 15, 0));
avatarNamePanel.add(imageLabel, BorderLayout.WEST);
avatarNamePanel.add(nameLabel, BorderLayout.CENTER);
//add(avatarNamePanel, new GBC(0,0).setAnchor(GBC.CENTER).setWeight(1,1).setInsets(0,0,0,0));
//add(button, new GBC(0,1).setAnchor(GBC.CENTER).setWeight(1,1).setInsets(0,0,0,0));
contentPanel.add(avatarNamePanel);
contentPanel.add(button);
add(contentPanel, new GBC(0,0).setWeight(1,1).setAnchor(GBC.CENTER).setInsets(0,0,250,0));
}
public void setUsername(String username)
{
this.username = username;
nameLabel.setText(username);
ImageIcon icon = new ImageIcon(AvatarUtil.createOrLoadUserAvatar(username).getScaledInstance(100,100, Image.SCALE_SMOOTH));
imageLabel.setIcon(icon);
}
private void setListeners()
{
button.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
openOrCreateDirectChat();
super.mouseClicked(e);
}
});
}
private void openOrCreateDirectChat()
{
ContactsUser user = contactsUserService.find("username", username).get(0);
String userId = user.getUserId();
Room room = roomService.findRelativeRoomIdByUserId(userId);
// ๆฟ้ดๅทฒๅญๅจ๏ผ็ดๆฅๆๅผ๏ผๅฆๅๅ้่ฏทๆฑๅๅปบๆฟ้ด
if (room != null)
{
ChatPanel.getContext().enterRoom(room.getRoomId());
}else
{
createDirectChat(user.getUsername());
}
if (room.getHidden())
{
room.setHidden(false);
roomService.update(room);
RoomsPanel.getContext().notifyDataSetChanged(false);
}
}
/**
* ๅๅปบ็ดๆฅ่ๅคฉ
*
* @param username
*/
private void createDirectChat(String username)
{
//todo ๅๅปบ่ๅคฉ
}
}
|
package com.mythosapps.time15;
import android.test.suitebuilder.annotation.SmallTest;
import com.mythosapps.time15.types.Time15;
import junit.framework.TestCase;
/**
* Created by andreas on 14.03.16.
*/
@SmallTest
public class Time15Test extends TestCase {
public void testToMinutes() {
Time15 t = new Time15(2, 30);
assertEquals(150, t.toMinutes());
}
public void testToMinutesPos() {
Time15 t = Time15.fromMinutes(150);
assertEquals(2, t.getHours());
assertEquals(30, t.getMinutes());
assertEquals(150, t.toMinutes());
}
public void testToMinutesNeg() {
Time15 t = Time15.fromMinutes(-150);
assertEquals(-2, t.getHours());
assertEquals(30, t.getMinutes());
assertEquals(-150, t.toMinutes());
}
public void testToMinutesPosSmall() {
Time15 t = Time15.fromMinutes(15);
assertEquals(0, t.getHours());
assertEquals(15, t.getMinutes());
assertEquals(15, t.toMinutes());
}
public void testToMinutesNegSmall() {
Time15 t = Time15.fromMinutes(-15);
assertEquals(0, t.getHours());
assertEquals(15, t.getMinutes());
assertEquals(-15, t.toMinutes());
}
public void testPlusPos() {
Time15 t = Time15.fromMinutes(150);
Time15 add = new Time15(2, 45);
t.plus(add);
assertEquals(5, t.getHours());
assertEquals(15, t.getMinutes());
assertEquals(315, t.toMinutes());
}
public void testPlusNeg() {
Time15 t = Time15.fromMinutes(-150);
Time15 add = new Time15(-2, 45);
t.plus(add);
assertEquals(-5, t.getHours());
assertEquals(15, t.getMinutes());
assertEquals(-315, t.toMinutes());
}
public void testToDecimalPositive() {
checkToDecimal(1, 30, "1.50");
checkToDecimal(1, 15, "1.25");
checkToDecimal(10, 45, "10.75");
checkToDecimal(0, 0, "0.00");
}
public void testToDecimalNegative() {
checkToDecimal(-1, 30, "-1.50");
checkToDecimal(-1, 15, "-1.25");
checkToDecimal(-10, 45, "-10.75");
checkToDecimal(-4, 0, "-4.00");
}
private void checkToDecimal(int hours, int minutes, String decimalFormat) {
Time15 t = new Time15(hours, minutes);
String s = t.toDecimalFormat();
assertEquals(decimalFormat, s);
}
public void testFromDecimalPositive() {
checkFromDecimal(1, 30, "1.50");
checkFromDecimal(1, 15, "1.25");
checkFromDecimal(10, 45, "10.75");
checkFromDecimal(0, 0, "0.00");
}
public void testFromDecimalNegative() {
checkFromDecimal(-1, 30, "-1.50");
checkFromDecimal(-1, 15, "-1.25");
checkFromDecimal(-10, 45, "-10.75");
checkFromDecimal(-4, 0, "-4.00");
}
private void checkFromDecimal(int hours, int minutes, String decimalFormat) {
Time15 t = Time15.fromDecimalFormat(decimalFormat);
assertEquals(hours, t.getHours());
assertEquals(minutes, t.getMinutes());
}
}
|
package my.sheshenya.samplespringdatarest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Component;
@SpringBootApplication
public class SampleSpringDataRestApplication {
public static void main(String[] args) {
SpringApplication.run(SampleSpringDataRestApplication.class, args);
}
@Autowired
private FooRepository fooRepository;
@Component
class DataSetup implements ApplicationRunner{
@Override
public void run(ApplicationArguments args) throws Exception {
fooRepository.save(Foo.builder().name("First").email("f@ggg.com").build());
fooRepository.save(Foo.builder().name("Second").email("s@ggg.com").build());
fooRepository.save(Foo.builder().name("Thirdth").email("t@ggg.com").build());
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.