text stringlengths 10 2.72M |
|---|
/*
* 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 projects.wsn1.nodes.timers;
import projects.wsn1.nodes.messages.WsnMsg;
import projects.wsn1.nodes.nodeImplementations.SimpleNode;
import projects.wsn1.nodes.nodeImplementations.SinkNode;
import sinalgo.nodes.Node;
import sinalgo.nodes.timers.Timer;
public class WsnMessageTimer extends Timer {
private WsnMsg message = null;
public WsnMessageTimer(WsnMsg message) {
this.message = message;
}
@Override
public void fire() {
try {
((SimpleNode)node).setFlag(false);
((SimpleNode)node).sendDirect(message, ((SimpleNode)node).getProximoNoAteEstacaoBase());
}catch(ClassCastException e) {
((SinkNode)node).broadcast(message);
}
}
}
|
package presentation;
import business.implementation.ReviewManagement;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import java.sql.SQLException;
public class TableExample extends JFrame {
public TableExample() throws SQLException {
JTable table = new JTable(new ReviewManagement().getPendingReviews());
//Add the table to the frame
this.add(new JScrollPane(table));
this.setTitle("Table Example");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
}
public static void main(String[] args) throws SQLException {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
new TableExample();
} catch (SQLException e) {
e.printStackTrace();
}
}
});
}
} |
//package com.k2data.k2app.log4j;
//
//import org.apache.logging.log4j.core.LogEvent;
//import org.apache.logging.log4j.core.config.plugins.Plugin;
//import org.apache.logging.log4j.core.pattern.ConverterKeys;
//import org.apache.logging.log4j.core.pattern.LogEventPatternConverter;
//
///**
// * 自定义 log4j2 输出
// *
// * @author lidong9144@163.com 17-3-22.
// */
//@Plugin(name="ThreadIdPatternLayout", category = "Converter")
//@ConverterKeys({"tId"})
//public class ThreadIdPatternLayout extends LogEventPatternConverter {
//
// /**
// * Constructs an instance of LoggingEventPatternConverter.
// *
// * @param name name of converter.
// * @param style CSS style for output.
// */
// protected ThreadIdPatternLayout(String name, String style) {
// super(name, style);
// }
//
// @Override
// public void format(LogEvent event, StringBuilder toAppendTo) {
// toAppendTo.append(Thread.currentThread().getId());
// }
//
//}
|
package uk.ac.ebi.intact.view.webapp.it;
import org.junit.Test;
import org.openqa.selenium.By;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class GoBrowserIT extends IntactViewIT {
@Test
public void filterByGoAfterSearchShouldAppendGoQuery() throws Exception {
goToTheQueryPage("17461779");
browseByGeneOntology();
clickOnResponseToStress();
assertThat(numberOfResultsDisplayed(), is(equalTo(19)));
assertThat(searchQuery(), is(equalTo("( 17461779 ) AND pxref:\"GO:0006950\"")));
}
private void clickOnResponseToStress() {
expandAndClickOnNode(1, 2);
}
private void expandAndClickOnNode(int parent, int node) {
expandNode(parent);
clickOnNode(parent+"_"+node);
}
private void browseByGeneOntology() {
driver.findElement(By.id("mainPanels:goBrowseBtn")).click();
}
private void expandNode(int node) {
driver.findElement(By.xpath("//li[@id='mainPanels:goTree:"+node+"']/div/span/span")).click();
waitUntilLoadingIsComplete();
}
private void clickOnNode(String nodeId) {
driver.findElement(By.xpath("//li[@id='mainPanels:goTree:"+nodeId+"']/div/span/span[2]")).click();
waitUntilLoadingIsComplete();
}
}
|
package com.jh.share.service;
import java.util.Collection;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import com.jh.share.model.Analysis;
public interface AnalysisService {
Collection<Analysis> findAll();
Analysis findOne(Long id);
Analysis create(Analysis analysis);
Analysis update(Analysis analysis);
void delete(Long id);
void evictCache();
Page<Analysis> findAll(Pageable pageable);
Analysis fineByFileId(String fileid);
Collection<Analysis> findAllByOrderByCurrentPriceAsc();
Collection<Analysis> findAllByOrderByInsertDateDesc();
Long removeByFileId(String fileId);
}
|
package com.soa.ws;
import javax.jws.WebService;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@WebService(endpointInterface = "com.soa.ws.Analyzer")
public class AnalyzerImpl implements Analyzer {
@Override
public Info analyze(String s) {
Info info = new Info();
info.setCapitalAmount(countMatches(s, "[A-Z]"));
info.setCharAmount(s.length());
info.setLowerAmount(countMatches(s, "[a-z]"));
info.setNumberAmount(countMatches(s, "[0-9]"));
info.setSpaceAmount(countMatches(s, " "));
return info;
}
private int countMatches(String s, String regex) {
int amount = 0;
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(s);
while (matcher.find()) {
amount++;
}
return amount;
}
}
|
package slimeknights.tconstruct.tools.modifiers;
import net.minecraft.nbt.NBTTagCompound;
import slimeknights.tconstruct.library.modifiers.ModifierAspect;
import slimeknights.tconstruct.library.tools.ToolNBT;
import slimeknights.tconstruct.library.utils.HarvestLevels;
import slimeknights.tconstruct.library.utils.TagUtil;
public class ModEmerald extends ToolModifier {
public ModEmerald() {
super("emerald", 0x41f384);
addAspects(new ModifierAspect.SingleAspect(this), new ModifierAspect.DataAspect(this), ModifierAspect.freeModifier);
}
@Override
public void applyEffect(NBTTagCompound rootCompound, NBTTagCompound modifierTag) {
ToolNBT data = TagUtil.getToolStats(rootCompound);
ToolNBT base = TagUtil.getOriginalToolStats(rootCompound);
data.durability += base.durability / 2;
if(data.harvestLevel < HarvestLevels.DIAMOND) {
data.harvestLevel++;
}
TagUtil.setToolTag(rootCompound, data.get());
}
}
|
package com.example.androidquizapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.ArrayList;
import java.util.List;
public class Splash extends AppCompatActivity
{
public static List<String> studCatList = new ArrayList<>();
FirebaseFirestore firestore;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
firestore = FirebaseFirestore.getInstance();
Toast.makeText(this, "Welcome User!!", Toast.LENGTH_LONG).show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run()
{
loadData();
}
},2000);
}
public void loadData()
{
studCatList.clear();
firestore.collection("QUIZ").document("subjects").get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task)
{
if(task.isSuccessful())
{
DocumentSnapshot doc = task.getResult();
if(doc.exists())
{
long count = (long)doc.get("count");
for(int i=1;i<=count;i++)
{
String subName = doc.getString("sub"+String.valueOf(i));
studCatList.add(subName);
}
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
}
else
{
Toast.makeText(Splash.this, "Error in loading the data", Toast.LENGTH_SHORT).show();
}
}
});
}
} |
public class OfxReader {
public static void main(String[] args) {
String path = "/home/rodrigovidal/Documentos/materiais_de_estudo/extrato.ofx";
try {
InputStream entrada = new FileInputStream(path);
new OfxReader().lerOfx(entrada);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public void lerOfx(InputStream entrada) {
AggregateUnmarshaller<ResponseEnvelope> a = new AggregateUnmarshaller<>(ResponseEnvelope.class);
try {
ResponseEnvelope re = a.unmarshal(entrada);
//SignonResponse sr = re.getSignonResponse();
MessageSetType type = MessageSetType.banking;
ResponseMessageSet message = re.getMessageSet(type);
if (message != null) {
List<BankStatementResponseTransaction> bank = ((BankingResponseMessageSet) message).getStatementResponses();
for (BankStatementResponseTransaction b : bank) {
System.out.println("cc: " + b.getMessage().getAccount().getAccountNumber());
System.out.println("ag: " + b.getMessage().getAccount().getBranchId());
System.out.println("balanço final: " + b.getMessage().getLedgerBalance().getAmount());
System.out.println("dataDoArquivo: " + b.getMessage().getLedgerBalance().getAsOfDate());
List<Transaction> list = b.getMessage().getTransactionList().getTransactions();
System.out.println("TRANSAÇÕES\n");
for (Transaction transaction : list) {
System.out.println("tipo: " + transaction.getTransactionType().name());
System.out.println("id: " + transaction.getId());
System.out.println("data: " + transaction.getDatePosted());
System.out.println("valor: " + transaction.getAmount());
System.out.println("descricao: " + transaction.getMemo() + "\n");
}
}
}
} catch (IOException | OFXParseException e) {
e.printStackTrace();
}
}
}
//DEPENDENCIAS
// https://mvnrepository.com/artifact/org.javassist/javassist 3.26.0-GA
// https://mvnrepository.com/artifact/org.reflections/reflections 0.9.11
// https://mvnrepository.com/artifact/commons-logging/commons-logging 1.2
// https://mvnrepository.com/artifact/be.cyberelf.nanoxml/nanoxml 2.2.3
// https://mvnrepository.com/artifact/com.webcohesion.ofx4j/ofx4j 1.17
// https://mvnrepository.com/artifact/com.google.guava/guava 28.1-jre
|
package com.clicky.semarnat;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.widget.TextView;
import com.clicky.semarnat.data.Documentos;
import com.clicky.semarnat.data.MateriaPrima;
import com.parse.FindCallback;
import com.parse.GetCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
/**
*
* Created by Clicky on 4/5/15.
*
*/
public class TitularReporteInfoActivity extends ActionBarActivity{
private static String EXTRA_REPORTEID = "reporteId";
private static String EXTRA_DOCUMENTOID = "docId";
private SimpleDateFormat format;
private TextView txtAgente, txtReporte, txtFechaReporte, txtTipo, txtFolioAut, txtFechaExp,
txtFechaVen, txtCatNombre, txtCatDireccion, txtTransportistaNombre, txtMarca, txtModelo,
txtPlacas, txtMateriaTipo, txtDesc, txtCant, txtVol, txtUnidad;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_titular_reporte_info);
String docId = getIntent().getExtras().getString(EXTRA_DOCUMENTOID);
String reporteId = getIntent().getExtras().getString(EXTRA_REPORTEID);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
txtAgente = (TextView)findViewById(R.id.txt_profepa_nombre);
txtFechaReporte = (TextView)findViewById(R.id.txt_fecha_reporte);
txtReporte = (TextView)findViewById(R.id.txt_reporte);
txtTipo = (TextView)findViewById(R.id.txt_tipo);
txtFolioAut = (TextView)findViewById(R.id.txt_folio_aut);
txtFechaExp = (TextView)findViewById(R.id.txt_fecha_exp);
txtFechaVen = (TextView)findViewById(R.id.txt_fecha_ven);
txtCatNombre = (TextView)findViewById(R.id.txt_cat_nombre);
txtCatDireccion = (TextView)findViewById(R.id.txt_cat_domicilio);
txtTransportistaNombre = (TextView)findViewById(R.id.txt_transportista_nombre);
txtMarca = (TextView)findViewById(R.id.txt_marca);
txtModelo = (TextView)findViewById(R.id.txt_modelo);
txtPlacas = (TextView)findViewById(R.id.txt_placas);
txtMateriaTipo = (TextView)findViewById(R.id.txt_materia_tipo);
txtDesc = (TextView)findViewById(R.id.txt_desc);
txtCant = (TextView)findViewById(R.id.txt_cant);
txtVol = (TextView)findViewById(R.id.txt_volumen);
txtUnidad = (TextView)findViewById(R.id.txt_unidad);
format = new SimpleDateFormat("dd-mm-yyyy", Locale.US);
findFolio(reporteId, docId);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.push_right_in,R.anim.push_right_out);
}
private void findFolio(String reporte, String documento){
ParseQuery<ParseObject> query1 = ParseQuery.getQuery("Inspecciones");
query1.include("Inspector");
query1.whereEqualTo("objectId",reporte);
query1.fromLocalDatastore();
query1.getFirstInBackground(new GetCallback<ParseObject>() {
public void done(ParseObject reporte, ParseException e) {
if (e == null) {
if (reporte != null) {
getSupportActionBar().setTitle(reporte.getString("Reporte"));
txtAgente.setText(reporte.getParseObject("Inspector").getString("Nombre"));
txtFechaReporte.setText(format.format(reporte.getCreatedAt()));
txtReporte.setText(reporte.getString("Detalles"));
}
} else {
// There was an error.
Log.i("ResultFragment", "findFolio: Error finding document: " + e.getMessage());
}
}
});
ParseQuery<Documentos> query = Documentos.getQuery();
query.include("Titular");
query.include("Transportista");
query.include("CAT");
query.whereEqualTo("objectId", documento);
query.fromLocalDatastore();
query.getFirstInBackground(new GetCallback<Documentos>() {
public void done(Documentos doc, ParseException e) {
if (e == null) {
if(doc != null) {
// Results were successfully found from the local datastore.
txtTipo.setText(doc.getTipo());
txtFolioAut.setText(doc.getFolioAuto());
txtFechaExp.setText(format.format(doc.getFechaExp()));
txtFechaVen.setText(format.format(doc.getFechaVen()));
txtCatNombre.setText(doc.getCAT().getString("Nombre"));
txtCatDireccion.setText(doc.getCAT().getString("Domicilio"));
txtTransportistaNombre.setText(doc.getTransportista().getString("Chofer"));
txtMarca.setText(doc.getTransportista().getString("Marca"));
txtModelo.setText(doc.getTransportista().getString("Modelo"));
txtPlacas.setText(doc.getTransportista().getString("Placas"));
}
} else {
// There was an error.
Log.i("ResultFragment", "findFolio: Error finding document: " + e.getMessage());
}
}
});
ParseQuery<MateriaPrima> query2 = MateriaPrima.getQuery();
query2.whereEqualTo("Documentos", ParseObject.createWithoutData("Documentos", documento));
query2.fromLocalDatastore();
query2.findInBackground(new FindCallback<MateriaPrima>() {
public void done(final List<MateriaPrima> scoreList, ParseException e) {
if (e == null) {
// Results were successfully found from the local datastore.
if(!scoreList.isEmpty()) {
MateriaPrima materia = scoreList.get(0);
txtMateriaTipo.setText(materia.getTipo());
txtDesc.setText(materia.getDescripcion());
txtCant.setText(materia.getCantidad().toString());
txtVol.setText(materia.getVolumen());
txtUnidad.setText(materia.getUnidad());
}
} else {
// There was an error.
Log.i("ResultFragment", "findFolio: Error finding document: " + e.getMessage());
}
}
});
}
}
|
package org.eson.ble_sdk.control;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.text.TextUtils;
import org.eson.ble_sdk.BLESdk;
import org.eson.ble_sdk.control.listener.BLEConnectionListener;
import org.eson.ble_sdk.control.listener.BLEStateChangeListener;
import org.eson.ble_sdk.util.BLELog;
import java.util.ArrayList;
import java.util.List;
/**
* @作者 xiaoyunfei
* @日期: 2017/3/5
* @说明: 设备连接
*/
class BLEConnection implements BLEConnectionListener, BLEStateChangeListener {
private BluetoothAdapter bluetoothAdapter = null;
private static BLEConnection bleConnection = null;
//单连设备
private BluetoothGatt bluetoothGatt = null;
private String lastConnectMac = "";
//多连设备
private List<BluetoothGatt> gattList;
private List<String> deviceList;
//回调接口
private BLEConnectionListener bleConnectionListener = null;
private BLEStateChangeListener stateChangeListener = null;
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//| |
//| |
//| BLEConnection 单例实现
//| |
//| |
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
private BLEConnection() {
bluetoothAdapter = BLESdk.get().getBluetoothAdapter();
}
public static BLEConnection get() {
if (bleConnection == null) {
bleConnection = new BLEConnection();
}
return bleConnection;
}
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//| |
//| |
//| BLEConnection 提供给外部的方法,设备连接相关
//| |
//| |
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
/**
* 连接设备,单设备连接
*
* @param deviceAddress
*
* @return
*/
public BluetoothGatt connectToDevice(Context context, String deviceAddress,
BluetoothGattCallback gattCallback) {
if (TextUtils.isEmpty(lastConnectMac)) {
//之前未连接过设备
lastConnectMac = deviceAddress;
} else {
//之前未连接过设备,
//判断当前需要连接设备是否与之前连接的设备为同一个设备
if (deviceAddress.equals(lastConnectMac)) {
//为同一个设备时,
// 判断设备是否正为连接状态
if (isConnect(lastConnectMac)) {
//设备为已连接的状态,
//回调正在连接,用户不需要做其他的事情
onConnected(lastConnectMac);
return bluetoothGatt;
} else {
//设备为未连接的状态
//设备重连
if (bluetoothGatt != null) {
bluetoothGatt.connect();
return bluetoothGatt;
}
}
} else {
//不同设备,
// 判断之前设备是否正为连接状态
if (isConnect(lastConnectMac)) {
//设备为已连接的状态,
//断开之前的设备连接
bluetoothGatt.disconnect();
}
bluetoothGatt.close();
bluetoothGatt = null;
//把需要连接的设备赋值给 lastConnectMac
lastConnectMac = deviceAddress;
}
}
//建立新的设备连接
BLELog.e("create new bluetoothGatt");
BluetoothDevice bluetoothDevice = bluetoothAdapter.getRemoteDevice(lastConnectMac);
bluetoothGatt = bluetoothDevice.connectGatt(context, false, gattCallback);
return bluetoothGatt;
}
/**
* 连接设备, 多设备连接
*
* @param deviceAddress
*/
public List<BluetoothGatt> connectToMoreDevice(Context context, String deviceAddress,
BluetoothGattCallback gattCallback) {
//初始化连接列表
if (gattList == null) {
gattList = new ArrayList<>();
deviceList = new ArrayList<>();
}
//先判断需要连接的设备是否已存在列表中
if (isExist(deviceAddress)) {
//如果已连接过此设备,获取连接过的 BluetoothGatt
BluetoothGatt gatt = getGattByAddress(deviceAddress);
if (gatt != null) {
//如果gatt 为null,重新建立连接
} else {
//如果gatt 不为null,判断当前的连接状态
if (!isConnect(gatt, deviceAddress)) {
//已断开,重连
gatt.connect();
} else {
//是连接中,返回已连接的状态
onConnected(deviceAddress);
}
return gattList;
}
}
BluetoothDevice bluetoothDevice = bluetoothAdapter.getRemoteDevice(deviceAddress);
BluetoothGatt gatt = bluetoothDevice.connectGatt(context, false, gattCallback);
gattList.add(gatt);
////未连接过设备,添加新的连接
deviceList.add(deviceAddress);
return gattList;
}
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//| |
//| |
//| BLEConnection 提供给外部的方法,设备断开连接相关
//| |
//| |
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
/**
* 断开设备连接
* 单连设备时可用
*/
public void disConnect() {
gattDisconnect(bluetoothGatt);
bluetoothGatt = null;
}
/**
* 断开设备连接
* 连设备时可用
*
* @param deviceAddress
*/
public void disConnect(String deviceAddress) {
BluetoothGatt gatt = getGattByAddress(deviceAddress);
if (gatt == null) {
return;
}
gattDisconnect(gatt);
gattList.remove(gatt);
deviceList.remove(deviceAddress);
}
/**
* 断开所以设备连接
* 多连设备时可用
*/
public void disConnectAll() {
if (deviceList == null) {
return;
}
for (String s : deviceList) {
disConnect(s);
}
}
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//| |
//| |
//| BLEConnection 提供给外部的方法,判断设备连接状态
//| |
//| |
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
/**
* 获取当前设备是否为正在连接或已连接状态
*
* @param deviceAddress
*
* @return
*/
public boolean isConnect(String deviceAddress) {
return isConnect(bluetoothGatt, deviceAddress);
}
/**
* 根据设备地址获取 BluetoothGatt 连接
*
* @param deviceAddress
*
* @return
*/
public BluetoothGatt getGattByAddress(String deviceAddress) {
BluetoothGatt bluetoothGatt = null;
if (gattList == null) {
return null;
}
for (BluetoothGatt gatt : gattList) {
String mac = gatt.getDevice().getAddress();
if (deviceAddress.equals(mac)) {
bluetoothGatt = gatt;
break;
}
}
return bluetoothGatt;
}
public boolean isConnect(BluetoothGatt gatt, String deviceAddress) {
boolean isConnect = false;
//bluetoothGatt 为null
if (gatt == null) {
return isConnect;
}
BluetoothDevice bluetoothDevice = bluetoothAdapter.getRemoteDevice(deviceAddress);
int state = BLESdk.get().getBluetoothManager().getConnectionState(bluetoothDevice, BluetoothProfile.GATT);
if (state == BluetoothGatt.STATE_CONNECTED) {
isConnect = true;
}
return isConnect;
}
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//| |
//| |
//| BLEConnection 提供给外部的方法,设置回调接口
//| |
//| |
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
/***
* 设置设备连接回调
* @param connectListener
*/
public void setBleConnectListener(BLEConnectionListener connectListener) {
bleConnectionListener = connectListener;
}
/**
* 设置设备的状态监听
*
* @param stateChangedListener
*/
public void setBleStateChangedListener(BLEStateChangeListener stateChangedListener) {
this.stateChangeListener = stateChangedListener;
}
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//| |
//| |
//| BLEConnection 的内部方法,不提供外部访问
//| |
//| |
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
/**
* 判断此设备是否在连接列表里面
*
* @param device
*
* @return
*/
private boolean isExist(String device) {
boolean isExist = false;
if (deviceList.size() == 0) {
return isExist;
}
if (deviceList == null) {
return false;
}
for (String s : deviceList) {
if (s.equals(device)) {
isExist = true;
break;
}
}
return isExist;
}
private void gattDisconnect(BluetoothGatt gatt) {
if (gatt == null) {
return;
}
gatt.disconnect();
gatt.close();
}
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//| |
//| |
//| BLEConnectionListener 的接口实现
//| |
//| |
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
@Override
public void onConnected(String address) {
if (bleConnectionListener != null) {
bleConnectionListener.onConnected(address);
}
}
@Override
public void onConnectError(String address, int errorCode) {
if (bleConnectionListener != null) {
bleConnectionListener.onConnectError(address, errorCode);
}
}
@Override
public void onConnectSuccess(String address) {
if (bleConnectionListener != null) {
bleConnectionListener.onConnectSuccess(address);
}
}
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//| |
//| |
//| BLEStateChangeListener 的接口实现
//| |
//| |
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
//| |
//|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
@Override
public void onStateConnected(String address) {
if (stateChangeListener != null) {
stateChangeListener.onStateConnected(address);
}
}
@Override
public void onStateConnecting(String address) {
if (stateChangeListener != null) {
stateChangeListener.onStateConnecting(address);
}
}
@Override
public void onStateDisConnecting(String address) {
if (stateChangeListener != null) {
stateChangeListener.onStateDisConnecting(address);
}
}
@Override
public void onStateDisConnected(String address) {
if (stateChangeListener != null) {
stateChangeListener.onStateDisConnected(address);
}
}
}
|
public class Ch8_10 {
//forms LinkedList
static class LinkedList{
int value;
LinkedList next;
LinkedList(int value, LinkedList next){
this.value = value;
this.next = next;
}
}
//shifts a list to the right by amount "shift" - takes O(n) time and O(1) space complexity
static LinkedList cyclicRightShift(LinkedList head, int shift){
if(shift == 0){
return head;
}
LinkedList p1 = head;
LinkedList shiftedHead = p1;
for(int i = 0; i < shift; i++){
p1 = p1.next;
}
while(p1.next != null){
p1 = p1.next;
shiftedHead = shiftedHead.next;
}
LinkedList beforeShiftedHead = shiftedHead; //one position before the shifted head
shiftedHead = shiftedHead.next;
beforeShiftedHead.next = null;
p1.next = head; //reconnects the list from the tail end
return shiftedHead;
}
public static void main(String []args){
LinkedList list = new LinkedList(1, new LinkedList(2, new LinkedList(3, new LinkedList(4, new LinkedList(5, null)))));
System.out.print("Original List: ");
LinkedList temp = list;
while(temp != null){
System.out.print(temp.value + " ");
temp = temp.next;
}
System.out.println();
int shift = 3;
LinkedList shiftList = cyclicRightShift(list, shift);
System.out.print("Shifted by " + shift + ": ");
while(shiftList != null){
System.out.print(shiftList.value + " ");
shiftList = shiftList.next;
}
}
}
|
package filamentengine.content;
import java.util.LinkedList;
import java.util.List;
import nu.xom.Element;
import nu.xom.Elements;
import org.lwjgl.util.vector.Vector3f;
import filamentengine.io.xml.XMLIOHelper;
import filamentengine.io.xml.XMLSerializeable;
public abstract class EntityModel implements XMLSerializeable {
public final Vector3f pos = new Vector3f();
protected final List<EntityModel> children = new LinkedList<EntityModel>();
protected abstract EntityModel getBlankModel();
@Override
public Element writeToElement() {
Element ele = new Element(getElementName());
// pos
ele.appendChild(XMLIOHelper.vector3fWrite(pos, "pos"));
// children
for (EntityModel child : children) {
ele.appendChild(child.writeToElement());
}
return ele;
}
@Override
public void assembleFromElement(Element entity) {
// pos
Element posEle = entity.getChildElements("pos").get(0);
pos.set(XMLIOHelper.vector3fRead(posEle));
// children
children.clear();
Elements childs = entity.getChildElements(getElementName());
for (int i = 0; i < childs.size(); i++) {
EntityModel c = getBlankModel();
c.assembleFromElement(childs.get(i));
children.add(c);
}
}
public void setPos(final float x, final float y, final float z) {
applyPosDelta(x - pos.x, y - pos.y, z - pos.z);
}
public void applyPosDelta(final float x, final float y, final float z) {
pos.x += x;
pos.y += y;
pos.z += z;
for (EntityModel child : children) {
child.applyPosDelta(x, y, z);
}
}
}
|
package Strategy;
public class SalePrice implements PriceStrategy {
public void calculatePrice(Integer price) {
System.out.println(price * 0.5);
}
}
|
package com.ywd.blog.entity;
import java.util.Date;
public class TimeLun {
private Integer id;
private String context;
private Date saydate;
private String picture;
private Integer syear;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getContext() {
return context;
}
public void setContext(String context) {
this.context = context;
}
public Date getSaydate() {
return saydate;
}
public void setSaydate(Date saydate) {
this.saydate = saydate;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
public Integer getSyear() {
return syear;
}
public void setSyear(Integer syear) {
this.syear = syear;
}
}
|
package com.edasaki.rpg.treegens;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import com.google.common.collect.Lists;
import net.minecraft.server.v1_10_R1.Block;
import net.minecraft.server.v1_10_R1.BlockLeaves;
import net.minecraft.server.v1_10_R1.BlockLogAbstract;
import net.minecraft.server.v1_10_R1.BlockPosition;
import net.minecraft.server.v1_10_R1.Blocks;
import net.minecraft.server.v1_10_R1.IBlockData;
import net.minecraft.server.v1_10_R1.Material;
import net.minecraft.server.v1_10_R1.MathHelper;
import net.minecraft.server.v1_10_R1.World;
import net.minecraft.server.v1_10_R1.WorldGenTreeAbstract;
public class BigTreeGen extends WorldGenTreeAbstract {
private Random rand;
private World worldObj;
static class Position extends BlockPosition {
private final int posHeight;
public Position(BlockPosition posBlock, int posHeight) {
super(posBlock.getX(), posBlock.getY(), posBlock.getZ());
// this.posHeight = posHeight;
this.posHeight = posBlock.getY();
}
public int height() {
return this.posHeight;
}
}
private BlockPosition basePos = BlockPosition.ZERO;
int heightLimit;
int height;
double leafSegmentHeight = 0.618D;
double branchSlope = 0.381D;
double scaleWidth = 1.0D;
double leafDensity = 1.25D;
int trunkSize = 2;
int leafBlobSize = 4;
List<Position> leafNodes;
public BigTreeGen(boolean paramBoolean) {
super(paramBoolean);
}
/**
* Generates a list of leaf nodes for the tree, to be populated by generateLeaves.
*/
void generateLeafNodeList() {
this.height = ((int) (this.heightLimit * this.leafSegmentHeight));
if (this.height >= this.heightLimit) {
this.height = (this.heightLimit - 1);
}
int leafNodeCount = (int) (1 + Math.pow(this.leafDensity * this.heightLimit / 13.0D, 2.0D));
if (leafNodeCount < 1) {
leafNodeCount = 1;
}
int leafLowestLayer = this.basePos.getY() + this.height;
int leafLayerHeight = this.heightLimit - this.leafBlobSize;
this.leafNodes = Lists.newArrayList();
this.leafNodes.add(new Position(this.basePos.up(leafLayerHeight), leafLowestLayer));
for (; leafLayerHeight >= 0; leafLayerHeight--) {
float layerSize = layerSize(leafLayerHeight);
if (layerSize >= 0.0F) {
for (int k = 0; k < leafNodeCount; k++) {
double radius = this.scaleWidth * layerSize * (this.rand.nextFloat() + 0.328D);
double angle = this.rand.nextFloat() * 2.0F * 3.141592653589793D;
double xOffset = radius * Math.sin(angle) + 0.5D;
double zOffset = radius * Math.cos(angle) + 0.5D;
BlockPosition leafBlobCenter = this.basePos.a(xOffset, leafLayerHeight - 1, zOffset);
BlockPosition leafBlobTop = leafBlobCenter.up(this.leafBlobSize);
if (checkBlockLine(leafBlobCenter, leafBlobTop) == -1) {
int xDiff = this.basePos.getX() - leafBlobCenter.getX();
int zDiff = this.basePos.getZ() - leafBlobCenter.getZ();
double botY = leafBlobCenter.getY() - Math.sqrt(xDiff * xDiff + zDiff * zDiff) * this.branchSlope;
int i6 = botY > leafLowestLayer ? leafLowestLayer : (int) botY;
BlockPosition leafBlobBot = new BlockPosition(this.basePos.getX(), i6, this.basePos.getZ());
if (checkBlockLine(leafBlobBot, leafBlobCenter) == -1) {
this.leafNodes.add(new Position(leafBlobCenter, leafBlobBot.getY()));
}
}
}
}
}
}
void genTreeLayer(BlockPosition paramBlockPosition, float paramFloat, IBlockData paramIBlockData) {
int n = (int) (paramFloat + 0.618D);
for (int i1 = -n; i1 <= n; i1++) {
for (int i2 = -n; i2 <= n; i2++) {
if (Math.pow(Math.abs(i1) + 0.5D, 2.0D) + Math.pow(Math.abs(i2) + 0.5D, 2.0D) <= paramFloat * paramFloat) {
BlockPosition localBlockPosition = paramBlockPosition.a(i1, 0, i2);
Material localMaterial = this.worldObj.getType(localBlockPosition).getMaterial();
if ((localMaterial == Material.AIR) || (localMaterial == Material.LEAVES)) {
a(this.worldObj, localBlockPosition, paramIBlockData);
}
}
}
}
}
/**
* Gets the rough size of a layer of the tree.
*/
float layerSize(int paramInt) {
if (paramInt < this.heightLimit * (0.35F + Math.random() * 0.30F)) {
return -1.0F;
}
float f1 = this.heightLimit / 2.0F;
float f2 = f1 - paramInt;
float f3 = MathHelper.c(f1 * f1 - f2 * f2);
if (f2 == 0.0F) {
f3 = f1;
} else if (Math.abs(f2) >= f1) {
return 0.0F;
}
return f3 * 0.5F;
}
private float leafSize(int leafBlobLayer) {
if ((leafBlobLayer < 0) || (leafBlobLayer >= this.leafBlobSize)) {
return -1.0f;
}
if ((leafBlobLayer == 0) || (leafBlobLayer == this.leafBlobSize - 1)) {
return 2.0f;
}
return 3.0f;
}
/**
* Generates the leaves surrounding an individual entry in the leafNodes list.
*/
void generateLeafNode(BlockPosition nodeCenter) {
for (int currLayer = 0; currLayer < this.leafBlobSize; currLayer++) {
genTreeLayer(nodeCenter.up(currLayer), leafSize(currLayer), Blocks.LEAVES.getBlockData().set(BlockLeaves.CHECK_DECAY, Boolean.valueOf(false)));
}
}
void placeBlockLine(BlockPosition paramBlockPosition1, BlockPosition paramBlockPosition2, Block paramBlock) {
BlockPosition localBlockPosition1 = paramBlockPosition2.a(-paramBlockPosition1.getX(), -paramBlockPosition1.getY(), -paramBlockPosition1.getZ());
int n = b(localBlockPosition1);
if (n == 0)
return;
float f1 = localBlockPosition1.getX() / n;
float f2 = localBlockPosition1.getY() / n;
float f3 = localBlockPosition1.getZ() / n;
for (int i1 = 0; i1 <= n; i1++) {
BlockPosition localBlockPosition2 = paramBlockPosition1.a(0.5F + i1 * f1, 0.5F + i1 * f2, 0.5F + i1 * f3);
BlockLogAbstract.EnumLogRotation localEnumLogRotation = b(paramBlockPosition1, localBlockPosition2);
a(this.worldObj, localBlockPosition2, paramBlock.getBlockData().set(BlockLogAbstract.AXIS, localEnumLogRotation));
}
}
private int b(BlockPosition paramBlockPosition) {
int i1 = MathHelper.a(paramBlockPosition.getX());
int n = MathHelper.a(paramBlockPosition.getY());
int i2 = MathHelper.a(paramBlockPosition.getZ());
if ((i2 > n) && (i2 > i1))
return i2;
if (i1 > n) {
return i1;
}
return n;
}
private BlockLogAbstract.EnumLogRotation b(BlockPosition paramBlockPosition1, BlockPosition paramBlockPosition2) {
BlockLogAbstract.EnumLogRotation localEnumLogRotation = BlockLogAbstract.EnumLogRotation.Y;
int n = Math.abs(paramBlockPosition2.getX() - paramBlockPosition1.getX());
int i1 = Math.abs(paramBlockPosition2.getZ() - paramBlockPosition1.getZ());
int i2 = Math.max(n, i1);
if (i2 > 0) {
if (n == i2) {
localEnumLogRotation = BlockLogAbstract.EnumLogRotation.X;
} else if (i1 == i2) {
localEnumLogRotation = BlockLogAbstract.EnumLogRotation.Z;
}
}
return localEnumLogRotation;
}
/**
* Generates the leaf portion of the tree as specified by the leafNodes list.
*/
void generateLeaves() {
for (Position localPosition : this.leafNodes) {
generateLeafNode(localPosition);
}
}
/**
* Places the trunk for the big tree that is being generated. Able to generate double-sized trunks by changing a
* field that is always 1 to 2.
*/
void generateTrunk() {
BlockPosition trunkBase = this.basePos;
BlockPosition trunkTop = this.basePos.up(this.height);
Block trunkBlock = Blocks.LOG;
placeBlockLine(trunkBase, trunkTop, trunkBlock);
if (this.trunkSize == 2) {
placeBlockLine(trunkBase.east(), trunkTop.east(), trunkBlock);
placeBlockLine(trunkBase.east().south(), trunkTop.east().south(), trunkBlock);
placeBlockLine(trunkBase.south(), trunkTop.south(), trunkBlock);
}
}
void generateTrunkBase() {
if (trunkSize == 2) {
BlockPosition trunkBase = this.basePos;
/*
* xxxx
* xb.x
* x..x
* xxxx
*/
BlockPosition[] arr = {
trunkBase.north().west(),
trunkBase.north(),
trunkBase.north().east(),
trunkBase.north().east().east(),
trunkBase.west(),
trunkBase.east().east(),
trunkBase.south().west(),
trunkBase.south().east().east(),
trunkBase.south().south().west(),
trunkBase.south().south(),
trunkBase.south().south().east(),
trunkBase.south().south().east().east()
};
for (BlockPosition temp : arr) {
if (Math.random() < 0.6)
placeBlockLine(temp, temp.up((int) (Math.random() * 4) + 1), Blocks.LOG);
}
}
if (trunkSize == 1) {
BlockPosition trunkBase = this.basePos;
/*
* xxx
* xbx
* xxx
*/
BlockPosition[] arr = {
trunkBase.north().west(),
trunkBase.north(),
trunkBase.north().east(),
trunkBase.west(),
trunkBase.east(),
trunkBase.south().west(),
trunkBase.south(),
trunkBase.south().east(),
};
for (BlockPosition temp : arr) {
if (Math.random() < 0.25)
placeBlockLine(temp, temp.up((int) (Math.random() * 2) + 1), Blocks.LOG);
}
}
}
void generateTrunkRoots() {
BlockPosition trunkBase = this.basePos;
boolean thick = trunkSize > 1;
int count = (int) (Math.random() * (thick ? 5 : 3)) + 1;
for (int k = 0; k < count; k++) {
BlockPosition pos = trunkBase;
if (thick) {
switch ((int) (Math.random() * 4)) {
case 0:
default:
break;
case 1:
pos = pos.east();
break;
case 2:
pos = pos.east().south();
break;
case 3:
pos = pos.south();
break;
}
}
int height = (int) (Math.random() * 2 + (thick ? 1 : 0)); // either 1 or 2 blocks above grass
//dest should be equal or less
int destHeight = Math.random() < 0.5 ? 1 : 0; // either in grass or on grass
int dx = (int) ((Math.random() < 0.5 ? 1 : -1) * (trunkSize + Math.random() * (thick ? 3 : 2)));
int dz = (int) ((Math.random() < 0.5 ? 1 : -1) * (trunkSize + Math.random() * (thick ? 3 : 2)));
int min = height - destHeight;
if (dx < min)
dx = min;
if (dz < min)
dz = min;
BlockPosition start = new BlockPosition(pos.getX(), pos.getY() + height, pos.getZ());
BlockPosition dest = new BlockPosition(pos.getX() + dx, pos.getY() + destHeight, pos.getZ() + dz);
int[] diffs = new int[] { dest.getX() - start.getX(), dest.getY() - start.getY(), dest.getZ() - start.getZ() };
boolean xPos = diffs[0] >= 0;
boolean yPos = diffs[1] >= 0;
boolean zPos = diffs[2] >= 0;
diffs[0] = Math.abs(diffs[0]);
diffs[1] = Math.abs(diffs[1]);
diffs[2] = Math.abs(diffs[2]);
BlockPosition last = start;
while (diffs[0] > 0 || diffs[1] > 0 || diffs[2] > 0) {
boolean changed = false;
if (diffs[0] > 0 && Math.random() < 0.6) {
diffs[0]--;
start = start.a(xPos ? 1 : -1, 0, 0);
changed = true;
}
if (diffs[1] > 0 && Math.random() < (thick ? 0.35 : 0.6)) {
diffs[1]--;
start = start.a(0, yPos ? 1 : -1, 0);
changed = true;
}
if (diffs[2] > 0 && Math.random() < 0.6) {
diffs[2]--;
start = start.a(0, 0, zPos ? 1 : -1);
changed = true;
}
if (changed) {
BlockLogAbstract.EnumLogRotation localEnumLogRotation = b(start, last);
last = start;
a(this.worldObj, start, Blocks.LOG.getBlockData().set(BlockLogAbstract.AXIS, localEnumLogRotation));
}
}
}
}
/**
* Generates additional wood blocks to fill out the bases of different leaf nodes that would otherwise degrade.
*/
void generateLeafNodeBases() {
for (Position pos : this.leafNodes) {
// int n = (int)(pos.height() * 0.7);
int n = pos.height() - (int) (Math.random() * 4);
// connect node to center, same height
BlockPosition blockPos = new BlockPosition(this.basePos.getX(), n, this.basePos.getZ());
if (!blockPos.equals(pos)) {
if (Math.random() > 0.30)
continue;
// shorter branches by 0.6
int tempX = this.basePos.getX() + (int) ((pos.getX() - this.basePos.getX()) * 0.7);
int tempZ = this.basePos.getZ() + (int) ((pos.getZ() - this.basePos.getZ()) * 0.7);
BlockPosition tempPos = new BlockPosition(tempX, n, tempZ);
placeBlockLine(blockPos, tempPos, Blocks.LOG);
}
}
}
/**
* Checks a line of blocks in the world from the first coordinate to triplet to the second,
* returning the distance (in blocks) before a non-air, non-leaf block is encountered and/or the
* end is encountered.
*/
int checkBlockLine(BlockPosition paramBlockPosition1, BlockPosition paramBlockPosition2) {
BlockPosition localBlockPosition1 = paramBlockPosition2.a(-paramBlockPosition1.getX(), -paramBlockPosition1.getY(), -paramBlockPosition1.getZ());
int n = b(localBlockPosition1);
float f1 = localBlockPosition1.getX() / n;
float f2 = localBlockPosition1.getY() / n;
float f3 = localBlockPosition1.getZ() / n;
if (n == 0) {
return -1;
}
for (int i1 = 0; i1 <= n; i1++) {
BlockPosition localBlockPosition2 = paramBlockPosition1.a(0.5F + i1 * f1, 0.5F + i1 * f2, 0.5F + i1 * f3);
if (!this.worldObj.getType(localBlockPosition2).getBlock().getBlockData().getMaterial().isSolid())
continue;
if (!a(this.worldObj.getType(localBlockPosition2).getBlock())) {
return i1;
}
}
return -1;
}
/**
* Returns a boolean indicating whether or not the current location for the tree, spanning
* basePos to to the height limit, is valid.
*/
private boolean validTreeLocation() {
Block localBlock = this.worldObj.getType(this.basePos.down()).getBlock();
if ((localBlock != Blocks.DIRT) && (localBlock != Blocks.GRASS) && (localBlock != Blocks.FARMLAND)) {
return false;
}
int n = checkBlockLine(this.basePos, this.basePos.up(this.heightLimit - 1));
if (n == -1) {
return true;
}
if (n < 6) {
return false;
}
this.heightLimit = n;
return true;
}
private static ArrayList<GenData[]> history = new ArrayList<GenData[]>();
private static class GenData {
World world;
BlockPosition blockPos;
IBlockData ibd;
IBlockData orig;
}
private ArrayList<GenData> localHist = new ArrayList<GenData>();
public static boolean undo() {
if (history.size() < 1)
return false;
GenData[] arr = history.remove(history.size() - 1);
for (GenData gd : arr) {
gd.world.setTypeAndData(gd.blockPos, gd.orig, 2);
}
return true;
}
@Override
protected void a(World world, BlockPosition blockPos, IBlockData ibd) {
GenData gd = new GenData();
gd.world = world;
gd.blockPos = blockPos;
gd.ibd = ibd;
gd.orig = world.getChunkAtWorldCoords(blockPos).getBlockData(blockPos);
localHist.add(gd);
// super.a(world, blockPos, ibd);
}
private void executeQueued() {
for (GenData gd : localHist)
super.a(gd.world, gd.blockPos, gd.ibd);
}
public boolean generate(World paramWorld, Random paramRandom, BlockPosition paramBlockPosition) {
this.worldObj = paramWorld;
this.basePos = paramBlockPosition;
this.rand = new Random(paramRandom.nextLong());
if (this.heightLimit == 0) {
this.heightLimit = (int) (Math.random() * 20) + 13;
}
if (this.heightLimit < 19)
this.trunkSize = 1;
this.scaleWidth = 0.9 + (this.height / 100.0 * 1.5);
if (!validTreeLocation()) {
return false;
}
generateLeafNodeList();
generateLeaves();
generateTrunk();
generateLeafNodeBases();
generateTrunkRoots();
generateTrunkBase();
history.add(localHist.toArray(new GenData[localHist.size()]));
executeQueued();
return true;
}
}
|
package function_support;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import extras.ErrorTypeEnum;
import extras.MerchantsException;
/**
* @author Aderick
*
* Responsible for reading a file.
*/
public class MerchantFileReader {
/**
* Read a file and returns a list of its lines.
*
* @param filePath
* @return
* @throws MerchantsException
*/
public static List<String> readFile(String filePath) throws MerchantsException{
File fn = new File(filePath);
List<String> result = new ArrayList<String>();
try {
BufferedReader br = new BufferedReader(new FileReader(fn));
String line = null;
while ((line = br.readLine()) != null)
{
result.add(line);
}
br.close();
} catch (IOException e) {
throw new MerchantsException(ErrorTypeEnum.FileReading, "fail");
}
return result;
}
/**
* Get the file path from a sentence.
*
* @param input
* @return
*/
public static String getFilePathFromQuery(String input) {
return input.substring(5, input.length());
}
}
|
public class Chess {
public static void queens(int[] board, int index) {
if(index == board.length) {
if(check(board))
dump(board);
} else {
for(int i = 0; i < 8; i++) {
board[index] = i;
queens(board, index + 1);
}
}
}
public static boolean check(int[] board) {
boolean[] columns = new boolean[8];
for(int a : board)
if(!columns[a])
columns[a] = true;
else
return false;
boolean flg1 = true, flg2 = true;
for(int i = 0; i < 8; i++)
for(int j = i + 1; j < 8; j++)
if(Math.abs(board[i] - board[j]) == j - i)
return false;
return true;
}
public static void dump(int[] board) {
for(int y = 0; y < board.length; y++) {
for(int x = 0; x < board.length; x++)
if(board[x] == y)
System.out.print("Q ");
else
System.out.print("- ");
System.out.println();
}
System.out.println();
}
public static void main(String[] args) {
int[] board = new int[8];
queens(board, 0);
}
}
|
/*---------------------------------------------------------------------
*
* Copyright 2011 TransUnion LLC. All Rights Reserved.
*
* No part of this work may be reproduced or distributed in any form or by any
* means, electronic or otherwise, now known or hereafter developed, including,
* but not limited to, the Internet, without the explicit prior written consent
* from TransUnion LLC.
*
* Requests for permission to reproduce or distribute any part of, or all of,
* this work should be mailed to:
*
* Law Department TransUnion 555 West Adams Chicago, Illinois 60661
* www.transunion.com
*
* ---------------------------------------------------------------------*/
package net.tompy.common;
import java.io.File;
import org.springframework.context.ApplicationContext;
public class ApplicationContextCreator
{
private static PropertyConfigurationManager propsManager;
public static ApplicationContext createContext( String[] args ) throws CommonException
{
String propertiesFile = null;
String[] commandLineArgs = null;
if ( args.length > 0 )
{
propertiesFile = System.getenv( CommonConstants.PROP_HOME ) + File.separator + args[ 0 ];
commandLineArgs = new String[ args.length - 1 ];
System.arraycopy( args, 1, commandLineArgs, 0, args.length - 1 );
}
else
{
throw new CommonException( "Missing properties file in command line arguments list." );
}
return createContext( propertiesFile, commandLineArgs );
}
public static ApplicationContext createContext( String propertiesFile, String[] args ) throws CommonException
{
ArgumentListPropertyConfigurer.setProperties( propertiesFile, args );
String springMain = ArgumentListPropertyConfigurer.getProperties().getProperty( CommonConstants.SPRING_MAIN );
if ( null == springMain )
{
throw new CommonException( "No [" + CommonConstants.SPRING_MAIN + "] property" );
}
if ( null != propsManager )
{
ArgumentListPropertyConfigurer.setProps( propsManager.preContextCreation( ArgumentListPropertyConfigurer.getProperties() ) );
}
ApplicationContext returnContext = new CommonClassPathXmlApplicationContext( springMain );
if ( null != propsManager )
{
ArgumentListPropertyConfigurer.setProps( propsManager.postContextCreation( ArgumentListPropertyConfigurer.getProperties() ) );
}
return returnContext;
}
public static void registerPropertyManager( PropertyConfigurationManager manager )
{
propsManager = manager;
}
}
|
package com.raymon.api.demo.threadcoreknowledgedemo.stopthread.volatiledemo;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
/**
* @author :Raymon
* @date :Created in 2020/1/8
* @description: 用中断来修复刚才无尽等待的问题
*/
public class WrongWayVolatileFixed {
public static void main(String[] args) throws InterruptedException {
WrongWayVolatileFixed wrongWayVolatileFixed = new WrongWayVolatileFixed();
ArrayBlockingQueue storage = new ArrayBlockingQueue(10);
Provider provider = wrongWayVolatileFixed.new Provider(storage);
Thread providerThread = new Thread(provider);
providerThread.start();
Thread.sleep(1000);
Customer customer = wrongWayVolatileFixed.new Customer(storage);
while (customer.needMoreNums()){
System.out.println(customer.storage.take() + "被消费了");
Thread.sleep(1000);
}
System.out.println("消费者不需要更多的数据了");
/**
* 用interrupt让生产者停止
*/
providerThread.interrupt();
System.out.println(provider.canceled);
}
class Provider implements Runnable{
volatile boolean canceled = false;
BlockingQueue storage;
public Provider(BlockingQueue storage) {
this.storage = storage;
}
@Override
public void run() {
int num = 0;
try {
while (num <= 100000 && !Thread.currentThread().isInterrupted()){
if (num % 100 == 0){
storage.put(num);
System.out.println(num + "是100的倍数,被放到仓库中");
}
num++;
Thread.sleep(1);
}
}catch (InterruptedException e) {
//可以写其他停止的逻辑
e.printStackTrace();
}finally {
System.out.println("生产者结束运行");
}
}
}
class Customer{
BlockingQueue storage;
public Customer(BlockingQueue storage) {
this.storage = storage;
}
public boolean needMoreNums() {
if (Math.random() > 0.95){
return false;
}
return true;
}
}
}
|
package ProductosAgotados;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import Conexion.Conectar;
public class ProductosAgotados {
JTextField hola = null;
Conectar conex = new Conectar();
java.sql.Connection con = conex.conexion(hola);
java.sql.Statement list;
ResultSet rs;
int contador = 0;
public void calcular() throws SQLException{
list = con.createStatement();//<=
String sqlsString = "select nombre from productos where cantidad <= 5 ";
ResultSet resultSet = list.executeQuery(sqlsString);
while (resultSet.next()) {
contador++;
}
}
public int contador(){
return contador;
}
}
|
package com.mahang.weather.common;
import android.content.Context;
/**
* Created by Justwen on 2018/2/4.
*/
public class ApplicationContextHolder {
private static Context sContext;
public static Context getContext() {
return sContext;
}
public static void setContext(Context context) {
sContext = context.getApplicationContext();
}
}
|
package com.niksoftware.snapseed.controllers;
import android.view.View;
import com.niksoftware.snapseed.controllers.adapters.StaticStyleItemListAdapter;
import com.niksoftware.snapseed.core.NativeCore;
import com.niksoftware.snapseed.core.filterparameters.FilterParameter;
import com.niksoftware.snapseed.util.TrackerData;
import com.niksoftware.snapseed.views.BaseFilterButton;
import com.niksoftware.snapseed.views.ItemSelectorView;
import com.niksoftware.snapseed.views.ItemSelectorView.OnClickListener;
import com.niksoftware.snapseed.views.ItemSelectorView.OnVisibilityChangeListener;
public class Ambiance2Controller extends EmptyFilterController {
private static final int[] FILTER_PARAMETERS = new int[]{12, 0, 2, 656};
private static final int[] STYLE_PREVIEW_RES_IDS = new int[]{R.drawable.icon_fo_nature_default, R.drawable.icon_fo_nature_active, R.drawable.icon_fo_people_default, R.drawable.icon_fo_people_active, R.drawable.icon_fo_fine_default, R.drawable.icon_fo_fine_active, R.drawable.icon_fo_strong_default, R.drawable.icon_fo_strong_active};
private ItemSelectorView itemSelectorView;
private BaseFilterButton styleButton;
private OnClickListener styleClickListener;
private StaticStyleItemListAdapter styleListAdapter;
private class StyleSelectorOnClickListener implements OnClickListener {
private StyleSelectorOnClickListener() {
}
public boolean onItemClick(Integer itemId) {
if (!itemId.equals(Ambiance2Controller.this.styleListAdapter.getActiveItemId())) {
FilterParameter param = Ambiance2Controller.this.getFilterParameter();
TrackerData.getInstance().usingParameter(3, false);
param.setParameterValueOld(3, itemId.intValue());
NativeCore.contextAction(param, 6);
Ambiance2Controller.this.changeParameter(param, 3, itemId.intValue(), true, null);
Ambiance2Controller.this.styleListAdapter.setActiveItemId(itemId);
Ambiance2Controller.this.itemSelectorView.refreshSelectorItems(Ambiance2Controller.this.styleListAdapter, true);
}
return true;
}
public boolean onContextButtonClick() {
return false;
}
}
public void init(ControllerContext context) {
super.init(context);
addParameterHandler();
this.styleListAdapter = new StaticStyleItemListAdapter(getFilterParameter(), 3, STYLE_PREVIEW_RES_IDS);
this.styleClickListener = new StyleSelectorOnClickListener();
this.itemSelectorView = getItemSelectorView();
this.itemSelectorView.setOnVisibilityChangeListener(new OnVisibilityChangeListener() {
public void onVisibilityChanged(boolean isVisible) {
Ambiance2Controller.this.styleButton.setSelected(isVisible);
}
});
}
public void cleanup() {
getEditingToolbar().itemSelectorWillHide();
this.itemSelectorView.setVisible(false, false);
this.itemSelectorView.cleanup();
this.itemSelectorView = null;
super.cleanup();
}
public int getFilterType() {
return 100;
}
public int[] getGlobalAdjustmentParameters() {
return FILTER_PARAMETERS;
}
public boolean showsParameterView() {
return true;
}
public boolean initLeftFilterButton(BaseFilterButton button) {
if (button == null) {
this.styleButton = null;
return false;
}
this.styleButton = button;
this.styleButton.setStateImages((int) R.drawable.icon_tb_style_default, (int) R.drawable.icon_tb_style_active, 0);
this.styleButton.setText(getButtonTitle(R.string.style));
this.styleButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Ambiance2Controller.this.styleListAdapter.setActiveItemId(Integer.valueOf(Ambiance2Controller.this.getFilterParameter().getParameterValueOld(3)));
Ambiance2Controller.this.itemSelectorView.reloadSelector(Ambiance2Controller.this.styleListAdapter, Ambiance2Controller.this.styleClickListener);
Ambiance2Controller.this.itemSelectorView.setVisible(true, true);
}
});
return true;
}
public int getHelpResourceId() {
return R.xml.overlay_two_gestures;
}
}
|
package br.assembleia.service.impl;
import br.assembleia.dao.DepartamentoDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import br.assembleia.entidades.Departamento;
import br.assembleia.service.DepartamentoService;
import java.util.List;
@Service
@Transactional
public class DepartamentoServiceImpl implements DepartamentoService {
@Autowired
private DepartamentoDAO dao;
@Override
public void salvar(Departamento departamento) throws IllegalArgumentException {
dao.salvar(departamento);
}
@Override
public List<Departamento> listarTodos() {
return dao.listarTodos();
}
@Override
public void editar(Departamento departamento) {
dao.editar(departamento);
}
@Override
public void deletar(Departamento departamento) {
dao.deletar(departamento);
}
@Override
public Departamento getById(Long id) {
return dao.getById(id);
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package implement;
import Entity.data_pengajar;
import Error.data_pengajarException;
import Service.data_pengajarDao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author MY PC
*/
public class data_pengajarDaoImpl implements data_pengajarDao {
private Connection connection;
public data_pengajarDaoImpl(Connection connection) {
this.connection = connection;
}
private final String insertData_pengajar = "INSERT INTO DATA_PENGAJAR VALUES (?,?,?)";
@Override
public void insertData_pengajar(data_pengajar data_pengajar) throws data_pengajarException {
PreparedStatement statement = null;
try {
connection.setAutoCommit(false);
statement = connection.prepareStatement(insertData_pengajar);
statement.setInt(1, data_pengajar.getIdpengajar());
statement.setString(2, data_pengajar.getNama());
statement.setString(3, data_pengajar.getJk());
statement.executeUpdate();
connection.commit();
} catch (SQLException exception) {
try {
connection.rollback();
} catch (SQLException ex) {
}
throw new data_pengajarException(exception.getMessage());
} finally {
try {
connection.setAutoCommit(true);
} catch (SQLException ex) {
}
if (statement != null) {
try {
statement.close();
} catch (SQLException exception) {
}
}
}
}
private final String updateData_pengajar = "UPDATE DATA_PENGAJAR SET NAMA=?,JK=? WHERE IDPENGAJAR=?";
@Override
public void updateData_pengajar(data_pengajar data_pengajar) throws data_pengajarException {
PreparedStatement statement = null;
try {
connection.setAutoCommit(false);
statement = connection.prepareStatement(updateData_pengajar);
statement.setString(1, data_pengajar.getNama());
statement.setString(2, data_pengajar.getJk());
statement.setInt(3, data_pengajar.getIdpengajar());
statement.executeUpdate();
connection.commit();
} catch (SQLException e) {
try {
connection.rollback();
} catch (SQLException ex) {
}
throw new data_pengajarException(e.getMessage());
} finally {
try {
connection.setAutoCommit(true);
} catch (SQLException ex) {
}
if (statement != null) {
try {
statement.close();
} catch (SQLException exception) {
}
}
}
}
private final String deleteData_pengajar = "DELETE FROM DATA_PENGAJAR WHERE IDPENGAJAR=?";
@Override
public void deleteData_pengajar(Integer idpengajar) throws data_pengajarException {
PreparedStatement statement = null;
try {
connection.setAutoCommit(false);
statement = connection.prepareStatement(deleteData_pengajar);
statement.setInt(1, idpengajar);
statement.executeUpdate();
connection.commit();
} catch (SQLException e) {
try {
connection.rollback();
} catch (SQLException ex) {
}
throw new data_pengajarException(e.getMessage());
} finally {
try {
connection.setAutoCommit(true);
} catch (SQLException ex) {
}
if (statement != null) {
try {
statement.close();
} catch (SQLException exception) {
}
}
}
}
private final String selectAll = "SELECT * FROM DATA_PENGAJAR";
@Override
public List<data_pengajar> selectAllData_pengajar() throws data_pengajarException {
Statement statement = null;
List<data_pengajar> list = new ArrayList<data_pengajar>();
try {
statement = connection.createStatement();
ResultSet result = statement.executeQuery(selectAll);
while (result.next()) {
data_pengajar data_pengajar = new data_pengajar();
data_pengajar.setIdpengajar(result.getInt("IDPENGAJAR"));
data_pengajar.setNama(result.getString("NAMA"));
data_pengajar.setJk(result.getString("JK"));
list.add(data_pengajar);
}
return list;
} catch (SQLException exception) {
throw new data_pengajarException(exception.getMessage());
} finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException exception) {
}
}
}
}
private final String getByIdpengajar = "SELECT * FROM DATA_PENGAJAR WHERE IDPENGAJAR = ?";
@Override
public data_pengajar getData_pengajar(Integer idpengajar) throws data_pengajarException {
PreparedStatement statement = null;
try {
connection.setAutoCommit(false);
statement = connection.prepareStatement(getByIdpengajar);
statement.setInt(1, idpengajar);
ResultSet result = statement.executeQuery();
data_pengajar data_pengajar = null;
if (result.next()) {
data_pengajar = new data_pengajar();
data_pengajar.setIdpengajar(result.getInt("IDPENGAJAR"));
data_pengajar.setNama(result.getString("NAMA"));
data_pengajar.setJk(result.getString("JK"));
} else {
throw new data_pengajarException("Data pengajar dengan ID pengajar "
+ idpengajar + " tidak ditemukan");
}
connection.commit();
return data_pengajar;
} catch (SQLException e) {
try {
connection.rollback();
} catch (SQLException ex) {
}
throw new data_pengajarException(e.getMessage());
} finally {
try {
connection.setAutoCommit(true);
} catch (SQLException ex) {
}
if (statement != null) {
try {
statement.close();
} catch (SQLException exception) {
}
}
}
}
}
|
package com.esum.wp.ebms.reload.struts.action;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.esum.ebmsutil.util.ReloadXTrusAdmin;
import com.esum.wp.ebms.config.XtrusConfig;
import com.esum.wp.ebms.pkistore.PkiStore;
import com.esum.wp.ebms.pkistore.service.IPkiStoreService;
import com.esum.wp.ebms.reload.model.Result;
import com.esum.wp.ebms.tld.XtrusLangTag;
public class ComponentReloadAction extends Action{
protected IPkiStoreService pkiStoreService;
public void setPkiStoreService(IPkiStoreService pkiStoreService) {
this.pkiStoreService = pkiStoreService;
}
private Logger log = LoggerFactory.getLogger(this.getClass());
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
String configId = request.getParameter("configId");
if(log.isDebugEnabled()){
log.debug("===== Start reload ");
log.debug("===== Config ID : " + configId);
}
Result result = new Result();
try{
ReloadXTrusAdmin reload = new ReloadXTrusAdmin();
if(configId.equals(XtrusConfig.EBMS_PARTY_INFO_TABLE_ID)){
reload.reloadPartyInfo(null, null);
}else if(configId.equals(XtrusConfig.EBMS_ROUTING_INFO_TABLE_ID)){
reload.reloadRoutingInfo(null);
}else if(configId.equals(XtrusConfig.EBMS_ROUTING_PATH_TABLE_ID)){
reload.reloadRoutingPath(null);
}else if(configId.equals(XtrusConfig.EBMS_SERVICE_INFO_TABLE_ID)){
reload.reloadServiceInfo(null);
}else if(configId.equals(XtrusConfig.PKI_STORE_TABLE_ID)
|| configId.equals(XtrusConfig.XML_DSIG_INFO_TABLE_ID)
){
List<PkiStore> nodes = (List<PkiStore>) pkiStoreService.selectPkiNodeList(new PkiStore());
if(nodes != null){
for(PkiStore node : nodes){
reload.reloadInfoRecord(XtrusConfig.XDE_COMPONENT_ID, node.getNode_id(), configId, null);
}
}
}
}catch(Exception e){
result.setSuccess(false);
result.setMessage( XtrusLangTag.getMessage("error.reload"));
e.printStackTrace();
}
/*etc*/
//ssl
if(log.isDebugEnabled()){
log.debug("===== End reload ");
}
JSONObject jsonObject = JSONObject.fromObject(result);
response.setContentType("text/x-json;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write(jsonObject.toString());
return null;
}
}
|
/**
* MIT License
* <p>
* Copyright (c) 2019-2022 nerve.network
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package network.nerve.converter.core.heterogeneous.callback;
import io.nuls.base.data.NulsHash;
import io.nuls.base.data.Transaction;
import io.nuls.core.exception.NulsException;
import io.nuls.core.log.logback.NulsLogger;
import network.nerve.converter.constant.ConverterErrorCode;
import network.nerve.converter.core.api.ConverterCoreApi;
import network.nerve.converter.core.business.AssembleTxService;
import network.nerve.converter.core.heterogeneous.callback.interfaces.ITxConfirmedProcessor;
import network.nerve.converter.core.heterogeneous.callback.management.CallBackBeanManager;
import network.nerve.converter.core.heterogeneous.docking.interfaces.IHeterogeneousChainDocking;
import network.nerve.converter.core.heterogeneous.docking.management.HeterogeneousDockingManager;
import network.nerve.converter.enums.HeterogeneousChainTxType;
import network.nerve.converter.enums.ProposalTypeEnum;
import network.nerve.converter.model.bo.Chain;
import network.nerve.converter.model.bo.HeterogeneousAddress;
import network.nerve.converter.model.bo.HeterogeneousConfirmedVirtualBank;
import network.nerve.converter.model.po.ConfirmedChangeVirtualBankPO;
import network.nerve.converter.model.po.HeterogeneousConfirmedChangeVBPo;
import network.nerve.converter.model.po.MergedComponentCallPO;
import network.nerve.converter.model.po.ProposalPO;
import network.nerve.converter.model.txdata.*;
import network.nerve.converter.rpc.call.TransactionCall;
import network.nerve.converter.storage.CfmChangeBankStorageService;
import network.nerve.converter.storage.HeterogeneousConfirmedChangeVBStorageService;
import network.nerve.converter.storage.MergeComponentStorageService;
import network.nerve.converter.storage.ProposalStorageService;
import network.nerve.converter.utils.ConverterUtil;
import network.nerve.converter.utils.VirtualBankUtil;
import org.web3j.utils.Numeric;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author: Mimi
* @date: 2020-02-18
*/
public class TxConfirmedProcessorImpl implements ITxConfirmedProcessor {
private Chain nerveChain;
/**
* 异构链chainId
*/
private int hChainId;
private AssembleTxService assembleTxService;
private HeterogeneousDockingManager heterogeneousDockingManager;
private HeterogeneousConfirmedChangeVBStorageService heterogeneousConfirmedChangeVBStorageService;
private ProposalStorageService proposalStorageService;
private MergeComponentStorageService mergeComponentStorageService;
private CfmChangeBankStorageService cfmChangeBankStorageService;
private ConverterCoreApi converterCoreApi;
// 重复收集计时器
private Map<String, AtomicInteger> countHash = new HashMap<>();
public TxConfirmedProcessorImpl(Chain nerveChain, int hChainId, CallBackBeanManager callBackBeanManager) {
this.nerveChain = nerveChain;
this.hChainId = hChainId;
this.assembleTxService = callBackBeanManager.getAssembleTxService();
this.heterogeneousDockingManager = callBackBeanManager.getHeterogeneousDockingManager();
this.heterogeneousConfirmedChangeVBStorageService = callBackBeanManager.getHeterogeneousConfirmedChangeVBStorageService();
this.proposalStorageService = callBackBeanManager.getProposalStorageService();
this.mergeComponentStorageService = callBackBeanManager.getMergeComponentStorageService();
this.cfmChangeBankStorageService = callBackBeanManager.getCfmChangeBankStorageService();
this.converterCoreApi = callBackBeanManager.getConverterCoreApi();
}
private NulsLogger logger() {
return nerveChain.getLogger();
}
/**
* 管理员变更: 收集完所有异构链组件的管理员变更确认交易,再组装发送交易
* 提现: 直接组装发送交易
*
* @param txType 交易类型 - WITHDRAW/CHANGE 提现/管理员变更
* @param nerveTxHash 本链交易hash
* @param txHash 异构链交易hash
* @param blockHeight 异构链交易确认高度
* @param txTime 异构链交易时间
* @param multiSignAddress 当前多签地址
* @param signers 交易签名地址列表
*/
@Override
public void txConfirmed(HeterogeneousChainTxType txType, String nerveTxHash, String txHash, Long blockHeight, Long txTime, String multiSignAddress, List<HeterogeneousAddress> signers) throws Exception {
NulsHash nerveHash = NulsHash.fromHex(nerveTxHash);
// 检查是否由提案发起的确认交易
NulsHash nerveProposalHash = proposalStorageService.getExeBusiness(nerveChain, nerveTxHash);
ProposalPO proposalPO = null;
ProposalTypeEnum proposalType = null;
if (nerveProposalHash != null) {
proposalPO = proposalStorageService.find(nerveChain, nerveProposalHash);
proposalType = proposalPO != null ? ProposalTypeEnum.getEnum(proposalPO.getType()) : null;
}
boolean isProposal = proposalPO != null;
switch (txType) {
case WITHDRAW:
if (isProposal) {
logger().info("提案执行确认[{}], proposalHash: {}, ETH txHash: {}", proposalType, nerveProposalHash.toHex(), txHash);
this.createCommonConfirmProposalTx(proposalType, nerveProposalHash, null, txHash, proposalPO.getAddress(), signers, txTime);
break;
}
// 正常提现的确认交易
ConfirmWithdrawalTxData txData = new ConfirmWithdrawalTxData();
txData.setHeterogeneousChainId(hChainId);
txData.setHeterogeneousHeight(blockHeight);
txData.setHeterogeneousTxHash(txHash);
txData.setWithdrawalTxHash(nerveHash);
txData.setListDistributionFee(signers);
assembleTxService.createConfirmWithdrawalTx(nerveChain, txData, txTime);
break;
case CHANGE:
// 查询合并数据库,检查变更交易是否合并
List<String> nerveTxHashList = new ArrayList<>();
MergedComponentCallPO mergedTx = mergeComponentStorageService.findMergedTx(nerveChain, nerveTxHash);
if (mergedTx == null) {
nerveTxHashList.add(nerveTxHash);
} else {
nerveTxHashList.addAll(mergedTx.getListTxHash());
}
int mergeCount = nerveTxHashList.size();
Long realTxTime = txTime;
for (String realNerveTxHash : nerveTxHashList) {
// 为空时,表示没有add和remove的直接确认交易,则确认交易的时间使用原始变更交易的时间
if (txTime == null) {
Transaction realNerveTx = TransactionCall.getConfirmedTx(nerveChain, NulsHash.fromHex(realNerveTxHash));
realTxTime = realNerveTx.getTime();
}
HeterogeneousConfirmedVirtualBank bank = new HeterogeneousConfirmedVirtualBank(realNerveTxHash, hChainId, multiSignAddress, txHash, realTxTime, signers);
this.checkProposal(realNerveTxHash, txHash, realTxTime, signers);
this.confirmChangeTx(realNerveTxHash, bank, mergeCount);
}
break;
case RECOVERY:
ConfirmResetVirtualBankTxData reset = new ConfirmResetVirtualBankTxData();
reset.setHeterogeneousChainId(hChainId);
reset.setResetTxHash(nerveHash);
reset.setHeterogeneousTxHash(txHash);
if (txTime == null) {
Transaction realNerveTx = TransactionCall.getConfirmedTx(nerveChain, nerveHash);
txTime = realNerveTx.getTime();
}
assembleTxService.createConfirmResetVirtualBankTx(nerveChain, reset, txTime);
break;
case UPGRADE:
if (isProposal) {
logger().info("提案执行确认[多签合约升级], proposalHash: {}, ETH txHash: {}", nerveProposalHash.toHex(), txHash);
this.createUpgradeConfirmProposalTx(nerveProposalHash, txHash, proposalPO.getAddress(), multiSignAddress, signers, txTime);
}
break;
}
}
@Override
public void pendingTxOfWithdraw(String nerveTxHash, String heterogeneousTxHash) throws Exception {
if (!converterCoreApi.isSupportNewMechanismOfWithdrawalFee()) {
return;
}
// 提现待确认交易组装并发出
WithdrawalHeterogeneousSendTxData txData = new WithdrawalHeterogeneousSendTxData();
txData.setNerveTxHash(nerveTxHash);
txData.setHeterogeneousTxHash(heterogeneousTxHash);
txData.setHeterogeneousChainId(hChainId);
Transaction nerveTx = converterCoreApi.getNerveTx(nerveTxHash);
assembleTxService.withdrawalHeterogeneousSendTx(nerveChain, txData, nerveTx.getTime());
}
private void checkProposal(String nerveTxHash, String txHash, Long txTime, List<HeterogeneousAddress> signers) throws NulsException {
NulsHash nerveHash = NulsHash.fromHex(nerveTxHash);
// 检查是否由提案发起的确认交易
NulsHash nerveProposalHash = proposalStorageService.getExeBusiness(nerveChain, nerveTxHash);
ProposalPO proposalPO = null;
if (nerveProposalHash != null) {
proposalPO = proposalStorageService.find(nerveChain, nerveProposalHash);
}
if (proposalPO != null) {
logger().info("提案执行确认[撤销银行资格], proposalHash: {}, ETH txHash: {}", nerveProposalHash.toHex(), txHash);
this.createCommonConfirmProposalTx(ProposalTypeEnum.EXPELLED, nerveProposalHash, nerveHash, txHash, proposalPO.getAddress(), signers, txTime);
}
}
private int confirmChangeTx(String nerveTxHash, HeterogeneousConfirmedVirtualBank bank, int mergeCount) throws Exception {
AtomicInteger count = countHash.get(nerveTxHash);
if (count == null) {
count = new AtomicInteger(0);
countHash.put(nerveTxHash, count);
}
logger().info("收集异构链变更确认, NerveTxHash: {}", nerveTxHash);
HeterogeneousConfirmedChangeVBPo vbPo = heterogeneousConfirmedChangeVBStorageService.findByTxHash(nerveTxHash);
if (vbPo == null) {
vbPo = new HeterogeneousConfirmedChangeVBPo();
vbPo.setNerveTxHash(nerveTxHash);
vbPo.setHgCollection(new HashSet<>());
}
Set<HeterogeneousConfirmedVirtualBank> vbSet = vbPo.getHgCollection();
int hChainSize = heterogeneousDockingManager.getAllHeterogeneousDocking().size();
// 检查重复添加
if (!vbSet.add(bank)) {
// 检查是否已经确认
ConfirmedChangeVirtualBankPO po = cfmChangeBankStorageService.find(nerveChain, nerveTxHash);
if (po != null) {
Transaction confirmedTx = TransactionCall.getConfirmedTx(nerveChain, po.getConfirmedChangeVirtualBank());
ConfirmedChangeVirtualBankTxData txData = ConverterUtil.getInstance(confirmedTx.getTxData(), ConfirmedChangeVirtualBankTxData.class);
List<HeterogeneousConfirmedVirtualBank> listConfirmed = txData.getListConfirmed();
for (HeterogeneousConfirmedVirtualBank virtualBank : listConfirmed) {
heterogeneousDockingManager.getHeterogeneousDocking(virtualBank.getHeterogeneousChainId()).txConfirmedCompleted(virtualBank.getHeterogeneousTxHash(), nerveChain.getLatestBasicBlock().getHeight(), nerveTxHash);
}
// 清理计数器
countHash.remove(nerveTxHash);
return 0;
}
logger().info("重复收集异构链变更确认, NerveTxHash: {}", nerveTxHash);
// 每重复收集5次,再检查是否收集完成
if (count.incrementAndGet() % 5 != 0) {
logger().info("当前 count: {}", count.get());
return 2;
}
}
// 收集完成,组装广播交易
if (vbSet.size() == hChainSize) {
logger().info("完成收集异构链变更确认, 创建确认交易, NerveTxHash: {}, 变更合并交易数量: {}", nerveTxHash, mergeCount);
List<HeterogeneousConfirmedVirtualBank> hList = new ArrayList<>(vbSet);
VirtualBankUtil.sortListByChainId(hList);
assembleTxService.createConfirmedChangeVirtualBankTx(nerveChain, NulsHash.fromHex(nerveTxHash), hList, hList.get(0).getEffectiveTime());
heterogeneousConfirmedChangeVBStorageService.save(vbPo);
// 清理计数器
countHash.remove(nerveTxHash);
return 1;
} else {
logger().info("当前已收集的异构链变更确认交易数量: {}, 所有异构链数量: {}, 变更合并交易数量: {}", vbSet.size(), hChainSize, mergeCount);
heterogeneousConfirmedChangeVBStorageService.save(vbPo);
}
return 0;
}
private void createCommonConfirmProposalTx(ProposalTypeEnum proposalType, NulsHash proposalTxHash, NulsHash proposalExeHash, String heterogeneousTxHash, byte[] address, List<HeterogeneousAddress> signers, long heterogeneousTxTime) throws NulsException {
ProposalExeBusinessData businessData = new ProposalExeBusinessData();
businessData.setProposalTxHash(proposalTxHash);
businessData.setProposalExeHash(proposalExeHash);
businessData.setHeterogeneousChainId(hChainId);
businessData.setHeterogeneousTxHash(heterogeneousTxHash);
businessData.setAddress(address);
businessData.setListDistributionFee(signers);
ConfirmProposalTxData txData = new ConfirmProposalTxData();
txData.setType(proposalType.value());
try {
txData.setBusinessData(businessData.serialize());
} catch (IOException e) {
throw new NulsException(ConverterErrorCode.SERIALIZE_ERROR);
}
// 发布提案确认交易
assembleTxService.createConfirmProposalTx(nerveChain, txData, heterogeneousTxTime);
}
private void createUpgradeConfirmProposalTx(NulsHash nerveProposalHash, String heterogeneousTxHash, byte[] address, String multiSignAddress, List<HeterogeneousAddress> signers, long heterogeneousTxTime) throws NulsException {
ConfirmUpgradeTxData businessData = new ConfirmUpgradeTxData();
businessData.setNerveTxHash(nerveProposalHash);
businessData.setHeterogeneousChainId(hChainId);
businessData.setHeterogeneousTxHash(heterogeneousTxHash);
businessData.setAddress(address);
IHeterogeneousChainDocking docking = heterogeneousDockingManager.getHeterogeneousDocking(hChainId);
// 兼容非以太系地址 update by pierre at 2021/11/16
businessData.setOldAddress(docking.getAddressBytes(multiSignAddress));
businessData.setListDistributionFee(signers);
ConfirmProposalTxData txData = new ConfirmProposalTxData();
txData.setType(ProposalTypeEnum.UPGRADE.value());
try {
txData.setBusinessData(businessData.serialize());
} catch (IOException e) {
throw new NulsException(ConverterErrorCode.SERIALIZE_ERROR);
}
// 发布提案确认交易
assembleTxService.createConfirmProposalTx(nerveChain, txData, heterogeneousTxTime);
}
}
|
package com.liao.controller;
import com.liao.pojo.User;
import com.liao.server.User2Server;
import com.liao.server.impl.User2SerperImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import javax.servlet.http.HttpSession;
/**
* Created with IntelliJ IDEA.
*
* @Author: liaojinhu
* @Date: 2021/06/22/22:47
* @Description:
*/
@Controller
public class UserController {
//@GetMapping是一个组合注解,是@RequestMapping(method = RequestMethod.GET)的缩写
@GetMapping({"/", "/login"})
public String login() {
return "login";
}
//@PostMapping是一个组合注解,是@RequestMapping(method = RequestMethod.POST)的缩写
@PostMapping("/main")
public String toindex(User user, HttpSession session, Model model) {
if (StringUtils.hasLength(user.getUserName()) && "123456".equals(user.getPassword())) {
//把登陆成功的用户保存起来
session.setAttribute("loginUser", user);
//登录成功重定向到main.html; 重定向防止表单重复提交
return "redirect:/index.html";
} else {
model.addAttribute("msg", "账号密码错误");
//回到登录页面
return "login";
}
}
@GetMapping("/index.html")
public String index(HttpSession session, Model model) {
// 是否登录。 拦截器,过滤器
/*
Object loginUser = session.getAttribute("loginUser");
if(loginUser != null){
return "index";
}else {
//回到登录页面
model.addAttribute("msg","请重新登录");
return "login";
}
*/
return "index";
}
}
|
package ru.otus.sua.L12.webserver;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.resource.Resource;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
@Slf4j
public class WebserverConfiguration {
//
static final String DB_SERVICE_CONTEXT_PARAMETER_NAME = "DBService";
static final String TEMPLATE_SERVICE_CONTEXT_PARAMETER_NAME = "TemplateService";
static final String DEFAULT_USER_NAME = "anonymous";
static final String DEFAULT_ADMIN_USER_NAME = "admin";
static final String LOGIN_SESSION_PARAMETER_NAME = "login";
//
static final String LOGIN_SERVLET_PATH = "/login";
static final int PORT = 8090;
private static final String ADMIN_SERVLET_PATH = "/admin";
private static final String LOGOUT_SERVLET_PATH = "/logout";
private static final String STATIC_CONTENT = "web/static_content";
public static ServletContextHandler getConfiguration() {
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
context.setBaseResource(getWebRootResource());
context.setWelcomeFiles(new String[]{"index.html"});
context.addServlet(LoginServlet.class, LOGIN_SERVLET_PATH);
context.addServlet(LogoutServlet.class, LOGOUT_SERVLET_PATH);
context.addServlet(AdminServlet.class, ADMIN_SERVLET_PATH);
// Lastly, the default servlet for root content (always needed, to satisfy servlet spec)
// It is important that this is last.
ServletHolder holderPwd = new ServletHolder("default", DefaultServlet.class);
holderPwd.setInitParameter("dirAllowed", "true");
context.addServlet(holderPwd, "/");
return context;
}
private static Resource getWebRootResource() {
ClassLoader classLoader = WebserverConfiguration.class.getClassLoader();
URL f = classLoader.getResource(STATIC_CONTENT + "/index.html");
if (f == null) throw new RuntimeException("Unable to find WebRoot directory.");
Resource resource;
URI webRootUri;
try {
webRootUri = f.toURI().resolve("./").normalize();
resource = Resource.newResource(webRootUri);
} catch (MalformedURLException | URISyntaxException e) {
log.error(e.getMessage());
throw new RuntimeException("Unable to find WebRoot directory..");
}
log.info("WebRoot is: " + webRootUri);
return resource;
}
}
|
package com.example.peterscheelke.mtgcollectionmanager.DatabaseManagement;
import android.support.annotation.NonNull;
import com.example.peterscheelke.mtgcollectionmanager.Cards.Card;
import java.util.ArrayList;
import java.util.List;
// Used to create complicated search queries
class QueryBuilder {
// Table names
private static final String CARDS = "Cards";
private static final String TYPES = "Types";
private static final String SUBTYPES = "Subtypes";
private static final String COLORS = "Colors";
private static final String COLOR_IDENTITIES = "ColorIdentities";
// Columns
private static final String CARD_COLUMNS = "Name, Quantity";
// Query strings
private static final String BASE_QUERY = "SELECT DISTINCT %1$s FROM %2$s";
private static final String JOIN_QUERY = "SELECT DISTINCT %1$s FROM (%2$s) AS temp JOIN %3$s ON Card = Name";
private static final String SELECT_QUERY = "SELECT DISTINCT %1$s FROM %2$s WHERE %3$s = ?";
QueryBuilder() {
}
Query CreateQuery(Card card) {
String columns = CARD_COLUMNS;
String queryString = String.format(BASE_QUERY, columns, CARDS);
List<String> searches = new ArrayList<>();
List<String> parameters = new ArrayList<>();
queryString = GetQueryFromCardArgs(card, queryString, searches, parameters);
queryString = getQueryFromJoins(card, columns, queryString, parameters);
if (this.HasWhere(card)) {
queryString += " AND Quantity >= CAST(? AS INT)";
} else {
queryString += " WHERE Quantity >= CAST(? AS INT)";
}
parameters.add(Integer.toString(card.CollectionQuantity));
Query query = new Query();
query.query = queryString + ";";
query.parameters = parameters.toArray(new String[0]);
return query;
}
private boolean HasWhere(Card card) {
if (card != null) {
if (card.Name.length() > 0) {
return true;
} else if (card.ManaCost.length() > 0) {
return true;
} else if (card.CMC >= 0.0) {
return true;
} else if (card.CompleteType.length() > 0) {
return true;
} else if (card.Text.length() > 0) {
return true;
} else if (card.Power.length() > 0) {
return true;
} else if (card.Toughness.length() > 0) {
return true;
} else if (card.Types != null && card.Types.size() > 0) {
return true;
} else if (card.Subtypes != null && card.Subtypes.size() > 0) {
return true;
} else if (card.Colors != null && card.Colors.size() > 0) {
return true;
} else if (card.ColorIdentity != null && card.ColorIdentity.size() > 0) {
return true;
}
}
return false;
}
@NonNull
private String GetQueryFromCardArgs(Card card, String queryString, List<String> searches, List<String> parameters) {
if (card != null) {
if (card.Name.length() > 0) {
searches.add("Name LIKE ?");
parameters.add("%" + card.Name + "%");
}
if (card.ManaCost.length() > 0) {
searches.add("ManaCost = ?");
parameters.add(card.ManaCost);
}
if (card.CMC >= 0.0) {
searches.add("CMC = CAST(? AS NUMERIC)");
parameters.add(card.CMC.toString());
}
if (card.CompleteType.length() > 0) {
searches.add("CompleteType LIKE ?");
parameters.add("%" + card.CompleteType + "%");
}
if (card.Text.length() > 0) {
searches.add("Text LIKE ?");
parameters.add("%" + card.Text + "%");
}
if (card.Power.length() > 0) {
searches.add("Power = ?");
parameters.add(card.Power);
}
if (card.Toughness.length() > 0) {
searches.add("Toughness = ?");
parameters.add(card.Toughness);
}
boolean hasWhere = false;
StringBuilder whereClause = new StringBuilder();
for (String search : searches) {
if (!hasWhere) {
hasWhere = true;
whereClause.append(" WHERE ");
} else {
whereClause.append(" AND ");
}
whereClause.append(search);
}
queryString += whereClause.toString();
}
return queryString;
}
private String getQueryFromJoins(Card card, String columns, String queryString, List<String> parameters) {
if (card != null) {
if (card.Types != null && card.Types.size() > 0) {
queryString = String.format(JOIN_QUERY, columns, queryString, TYPES);
queryString += " WHERE Name IN (" + String.format(SELECT_QUERY, "Card", "Types", "Type") + ")";
parameters.add(card.Types.get(0));
for (int i = 1; i < card.Types.size(); ++i) {
queryString += " AND Name IN (" + String.format(SELECT_QUERY, "Card", "Types", "Type") + ")";
parameters.add(card.Types.get(i));
}
}
if (card.Subtypes != null && card.Subtypes.size() > 0) {
queryString = String.format(JOIN_QUERY, columns, queryString, SUBTYPES);
queryString += " WHERE Name IN (" + String.format(SELECT_QUERY, "Card", "Subtypes", "Subtype") + ")";
parameters.add(card.Subtypes.get(0));
for (int i = 1; i < card.Subtypes.size(); ++i) {
queryString += " AND Name IN (" + String.format(SELECT_QUERY, "Card", "Subtypes", "Subtype") + ")";
parameters.add(card.Subtypes.get(i));
}
}
if (card.Colors != null && card.Colors.size() > 0) {
queryString = String.format(JOIN_QUERY, columns, queryString, COLORS);
queryString += " WHERE Name IN (" + String.format(SELECT_QUERY, "Card", "Colors", "Color") + ")";
parameters.add(card.Colors.get(0).toString());
for (int i = 1; i < card.Colors.size(); ++i) {
queryString += " AND Name IN (" + String.format(SELECT_QUERY, "Card", "Colors", "Color") + ")";
parameters.add(card.Colors.get(i).toString());
}
}
if (card.ColorIdentity != null && card.ColorIdentity.size() > 0) {
queryString = String.format(JOIN_QUERY, columns, queryString, COLOR_IDENTITIES);
queryString += " WHERE Name IN (" + String.format(SELECT_QUERY, "Card", "ColorIdentities", "ColorIdentity") + ")";
parameters.add(card.ColorIdentity.get(0).toString());
for (int i = 1; i < card.ColorIdentity.size(); ++i) {
queryString += " AND Name IN (" + String.format(SELECT_QUERY, "Card", "ColorIdentities", "ColorIdentity") + ")";
parameters.add(card.ColorIdentity.get(i).toString());
}
//private static final String JOIN_QUERY = "SELECT DISTINCT %1$s FROM (%2$s) AS temp JOIN %3$s ON Card = Name";
queryString = String.format(JOIN_QUERY, columns, queryString, " (SELECT Card, Count(Card) AS ColorCount FROM ColorIdentities GROUP BY Card) AS ColorCounts");
queryString += " WHERE ColorCount <= CAST(? AS INT)";
parameters.add(Integer.toString(card.ColorIdentity.size()));
}
}
return queryString;
}
}
|
package uiElements.combinedElement;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JPanel;
import lang.Text;
import ui.selectImages.SelectImagesPanel;
import ui.selectImages.event.EventRemoveImage;
import uiElements.Button;
import uiElements.ImageScaled;
import uiElements.Panel;
import uiElements.Spinner;
import uiElements.TextLine;
public class LoadedImageFrame extends JPanel{
private ImageScaled imageThumbnail;
private ControlFrame controlFrame;
private SelectImagesPanel selectImagePanel;
private String file;
public LoadedImageFrame(SelectImagesPanel parent, String file, int w, int h){
super();
setupLayout(w, h);
this.selectImagePanel = parent;
this.file = file;
imageThumbnail = new ImageScaled(file, w, h/2);
imageThumbnail.setHorizontalAlignment(JLabel.CENTER);
controlFrame = new ControlFrame();
this.add(imageThumbnail);
this.add(controlFrame);
}
public String getFile(){
return file;
}
public double getAngle(){
return controlFrame.getAngle();
}
private void setupLayout(int w, int h){
this.setLayout(new GridLayout(2,1));
this.setBackground(Color.WHITE);
this.setBorder(BorderFactory.createLineBorder(Color.black));
this.setSize(w, h);
this.setPreferredSize(new Dimension(w, h));
this.setMinimumSize(new Dimension(w, h));
}
private class ControlFrame extends Panel{
private TextLine path;
private Spinner angleSpinner;
private Button deleteButton;
private Panel anglePanel;
public ControlFrame(){
super(new GridLayout(3,1));
angleSpinner = new Spinner(0.0, -360.0, 360.0, 0.1);
anglePanel = new Panel(new TextLine("Angle ° "), angleSpinner);
path = new TextLine(LoadedImageFrame.this.file, true);
deleteButton = new Button(""+Text.BT_RMV_IMAGE, new EventRemoveImage(selectImagePanel, LoadedImageFrame.this));
this.add(anglePanel);
this.add(path);
this.add(deleteButton);
}
public double getAngle(){
return (double) angleSpinner.getValue();
}
}
}
|
package com.appirio.service.member.resources;
import com.appirio.service.member.api.MemberSearch;
import com.appirio.service.member.manager.MemberSearchManager;
import com.appirio.supply.ErrorHandler;
import com.appirio.supply.dataaccess.QueryResult;
import com.appirio.tech.core.api.v3.request.QueryParameter;
import com.appirio.tech.core.api.v3.request.annotation.APIQueryParam;
import com.appirio.tech.core.api.v3.request.annotation.AllowAnonymous;
import com.appirio.tech.core.api.v3.response.ApiResponse;
import com.appirio.tech.core.api.v3.response.ApiResponseFactory;
import com.appirio.tech.core.api.v3.response.Result;
import com.appirio.tech.core.auth.AuthUser;
import com.codahale.metrics.annotation.Timed;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.SecurityContext;
/**
* Resource for Leaderboards search migrate the leaderboards functionality written in node and running in Lambda to
* member service. Here is the source for the lambda node.js function:
* https://github.com/appirio-tech/tc-lambda-leaderboards/blob/dev/src/index.js
*
* @author TCSCODER
*/
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("leaderboards")
public class LeaderboardsResource {
/**
* The totalCount key for metadata
*/
private static final String TOTAL_COUNT = "totalCount";
/**
* Logger for the class
*/
private static final Logger LOGGER = LoggerFactory.getLogger(LeaderboardsResource.class);
/**
* Member search manager
*/
private MemberSearchManager memberSearchManager;
/**
* Constructor to initialize Member search manager
*
* @param memberSearchManager
* Member search manager
*/
public LeaderboardsResource(MemberSearchManager memberSearchManager) {
this.memberSearchManager = memberSearchManager;
}
/**
* Get member search result
*
* @param request
* Member Search Request @APIQueryParam(repClass = MemberSearch.class)
* @APIQueryParam(repClass = MemberSearchRequest.class)
* @param securityContext
* the security context
* @return ApiResponse Api response
*/
@GET
@Timed
@AllowAnonymous
public ApiResponse getLeaderboards(@APIQueryParam(repClass = MemberSearch.class) QueryParameter queryParam,
@Context SecurityContext securityContext) {
try {
LOGGER.debug("getLeaderboards, filter : " + queryParam.getFilter().getFields());
AuthUser authUser = (AuthUser) securityContext.getUserPrincipal();
// get skill leaderboards by utilizing member search manager
QueryResult<List<Object>> queryResult = memberSearchManager.searchLeaderboards(queryParam, authUser);
// return the response
ApiResponse response = ApiResponseFactory.createResponse(queryResult.getData());
Result result = response.getResult();
Map<String, Integer> metadata = new HashMap<>();
metadata.put(TOTAL_COUNT, queryResult.getRowCount());
response.setResult(result.getSuccess(), result.getStatus(), metadata, result.getContent());
return response;
} catch (Throwable ex) {
return ErrorHandler.handle(ex, LOGGER);
}
}
}
|
package com.servlet;
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 java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Search
*/
@WebServlet("/search")
public class Search extends HttpServlet {
private static final long serialVersionUID = 1L;
public Search() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
String productId = request.getParameter("productId");
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/product","root","password");
Statement statement = conn.createStatement();
ResultSet resSet = statement.executeQuery("select * from product where productId = " + productId + "");
ArrayList al = null;
ArrayList pid_list = new ArrayList();
while (resSet.next()) {
al = new ArrayList();
al.add(resSet.getInt(1));
al.add(resSet.getString(2));
al.add(resSet.getString(3));
System.out.println("al :: " + al);
pid_list.add(al);
}
request.setAttribute("piList", pid_list);
RequestDispatcher view = request.getRequestDispatcher("/productDisplay.jsp");
view.forward(request, response);
conn.close();
System.out.println("Disconnected!");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
package org.jboss.devcon;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.infinispan.client.hotrod.impl.transport.TransportFactory;
import org.infinispan.client.hotrod.impl.transport.tcp.TcpTransportFactory;
/**
* TcpTransportFactory that will inform listeners about server list change.
* ugly solution to get hooked to HotRod client's updateServers event.
*/
public class HookedTcpTransportFactory extends TcpTransportFactory {
public static ServerListUpdateNotifier NOTIFIER = new ServerListUpdateNotifier();
public interface ServerListListener {
public void updateServers(TransportFactory tf, Collection<InetSocketAddress> currentServerList);
}
public static class ServerListUpdateNotifier {
private List<ServerListListener> listeners = new ArrayList<ServerListListener>();
public void addListener(ServerListListener listener) {
listeners.add(listener);
}
public void removeListener(ServerListListener listener) {
listeners.add(listener);
}
public void notify(TransportFactory tf, Collection<InetSocketAddress> currentServerList) {
for (ServerListListener listener : listeners) {
listener.updateServers(tf, currentServerList);
}
}
}
@Override
public void updateServers(Collection<InetSocketAddress> newServers) {
super.updateServers(newServers);
NOTIFIER.notify(this, getServers());
}
}
|
package com.zju.courier.service.impl;
import com.zju.courier.dao.ApInfoDao;
import com.zju.courier.dao.LoadDao;
import com.zju.courier.pojo.LoadForMap;
import com.zju.courier.service.APLoadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class APLoadServiceImpl implements APLoadService {
@Autowired
private LoadDao loadDao;
@Autowired
private ApInfoDao apInfoDao;
@Override
public List<LoadForMap> list() {
return loadDao.list();
}
}
|
import java.io.*;
import java.util.stream.*;
public class OpenTest {
public static void main(String[] args) {
// file path
String spath = "D:\\Text1.dat";
FileReader fread = null;
BufferedReader txtReader = null;
try {
String sCurrentline;
fread = new FileReader(spath);
txtReader = new BufferedReader(fread);
while ((sCurrentline = txtReader.readLine()) != null)
{
System.out.println(sCurrentline);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (txtReader != null)
txtReader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
|
package com.ai_traders.examples.jersey_spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.inject.Singleton;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Integration of jersey and spring.
* This rest controller is a singleton spring bean with an autowired depency
* from spring
*
* Original author Geoffroy Warin (http://geowarin.github.io)
* see https://github.com/jersey/jersey/blob/2.25.x/examples/helloworld-spring-annotations/src/main/java/org/glassfish/jersey/examples/hello/spring/annotations/SpringRequestResource.java
*/
@Singleton
@Path("spring")
@Service
public class SpringRequestResource {
AtomicInteger counter = new AtomicInteger();
@Autowired
private GreetingService greetingService;
@GET
@Produces(MediaType.TEXT_PLAIN)
public String getHello() {
return greetingService.greet("world " + counter.incrementAndGet());
}
public void setGreetingService(GreetingService greetingService) {
this.greetingService = greetingService;
}
} |
package com.lab1;
import java.util.Scanner;
public class Lab1Bai3 {
public static void main(String[] args) {
int a;
int b;
int c;
Scanner scanner = new Scanner(System.in);
System.out.println("Nhap canh a: ");
a = scanner.nextInt();
System.out.println("Nhap canh b: ");
b = scanner.nextInt();
System.out.println("Nhap canh c: ");
c = scanner.nextInt();
double v = a * b *c;
System.out.println("The tich cua khoi lap phuong = " + v);
}
} |
package com.zs.common.cmd;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class StreamGobbler extends Thread {
InputStream is;
String type;
MsgListener msgListener;
StreamGobbler(InputStream is, String type) {
this(is, type, null);
}
StreamGobbler(InputStream is, String type, MsgListener msgListener) {
this.is = is;
this.type = type;
this.msgListener = msgListener;
}
public void run() {
try {
Log.d("StreamGobbler","thead start " + type);
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
if (msgListener != null){
msgListener.onMsg(line);
}
Log.d("StreamGobbler",type +" >" + line);
}
} catch (IOException ioe) {
Log.d("StreamGobbler","thead err");
ioe.printStackTrace();
}
Log.d("StreamGobbler","thead done " + type);
}
public interface MsgListener{
void onMsg(String line);
}
}
|
package app.com.thetechnocafe.eventos.Utils;
import android.content.Context;
import android.content.SharedPreferences;
/**
* Created by gurleensethi on 21/11/16.
*/
public class SharedPreferencesUtils {
private static final String SHARED_PREFERENCES_FILE = "preferences";
private static final String SHARED_PREFERENCES_USERNAME = "username";
private static final String SHARED_PREFERENCES_PASSWORD = "password";
private static final String SHARED_PREFERENCES_LOGIN_STATE = "login_state";
private static final String SHARED_PREFERENCES_FULL_NAME = "full_name";
private static final String SHARED_PREFERENCES_PHONE_NUMBER = "phone_number";
private static final String SHARED_PREFERENCS_WALKTHROUGH_STATE = "walk_through";
private static final String TOGGLE_STATE = "toggle_button_state";
/**
* Change the username in sharedpreferences
*/
public static void setUsername(Context context, String username) {
//Get shared preferences file
SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_FILE, Context.MODE_PRIVATE);
//Get editor
SharedPreferences.Editor editor = sharedPreferences.edit();
//Add username
editor.putString(SHARED_PREFERENCES_USERNAME, username);
editor.commit();
}
/**
* Get the username from shared preferences
*/
public static String getUsername(Context context) {
//Get shared preferences file
SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_FILE, Context.MODE_PRIVATE);
return sharedPreferences.getString(SHARED_PREFERENCES_USERNAME, null);
}
/**
* Change the password in sharedpreferences
*/
public static void setPassword(Context context, String password) {
//Get shared preferences file
SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_FILE, Context.MODE_PRIVATE);
//Get editor
SharedPreferences.Editor editor = sharedPreferences.edit();
//Add username
editor.putString(SHARED_PREFERENCES_PASSWORD, password);
editor.commit();
}
/**
* Get the password from shared preferences
*/
public static String getPassword(Context context) {
//Get shared preferences file
SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_FILE, Context.MODE_PRIVATE);
return sharedPreferences.getString(SHARED_PREFERENCES_PASSWORD, null);
}
/**
* Set login state in shared preferences
*/
public static void setLoginState(Context context, boolean isLoggedIn) {
//Get shared preferences file
SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_FILE, Context.MODE_PRIVATE);
//Get editor
SharedPreferences.Editor editor = sharedPreferences.edit();
//Add value to editor
editor.putBoolean(SHARED_PREFERENCES_LOGIN_STATE, isLoggedIn);
editor.commit();
}
/**
* Get login state from shared preferences
*/
public static boolean getLoginState(Context context) {
//Get shared preferences file
SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_FILE, Context.MODE_PRIVATE);
return sharedPreferences.getBoolean(SHARED_PREFERENCES_LOGIN_STATE, false);
}
/**
* Set full name in shared preferences
*/
public static void setFullName(Context context, String fullName) {
//Get shared preferences file
SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_FILE, Context.MODE_PRIVATE);
//Get editor
SharedPreferences.Editor editor = sharedPreferences.edit();
//Add value to editor
editor.putString(SHARED_PREFERENCES_FULL_NAME, fullName);
editor.commit();
}
/**
* Get full name from shared preferences
*/
public static String getFullName(Context context) {
//Get shared preferences file
SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_FILE, Context.MODE_PRIVATE);
return sharedPreferences.getString(SHARED_PREFERENCES_FULL_NAME, null);
}
/**
* Set login state in shared preferences
*/
public static void setPhoneNumber(Context context, String phoneNumber) {
//Get shared preferences file
SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_FILE, Context.MODE_PRIVATE);
//Get editor
SharedPreferences.Editor editor = sharedPreferences.edit();
//Add value to editor
editor.putString(SHARED_PREFERENCES_PHONE_NUMBER, phoneNumber);
editor.commit();
}
/**
* Get login state from shared preferences
*/
public static String getPhoneNumber(Context context) {
//Get shared preferences file
SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_FILE, Context.MODE_PRIVATE);
return sharedPreferences.getString(SHARED_PREFERENCES_PHONE_NUMBER, null);
}
public static void setRating(Context context, String eventId, int rating) {
SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_FILE, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(eventId, rating);
editor.commit();
}
public static int getRating(Context context, String eventId) {
SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_FILE, Context.MODE_PRIVATE);
return sharedPreferences.getInt(eventId, 0);
}
public static void setSharedPreferencsWalkthroughState(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_FILE, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(SHARED_PREFERENCS_WALKTHROUGH_STATE, true);
editor.commit();
}
public static boolean getSharedPreferencsWalkthroughState(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_FILE, Context.MODE_PRIVATE);
return sharedPreferences.getBoolean(SHARED_PREFERENCS_WALKTHROUGH_STATE, false);
}
//Toggle State of Event Attending or Not Attending
public static void setSharedPreferencesToggleState(Context context, String id, boolean state) {
SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_FILE, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(id + TOGGLE_STATE, state);
editor.commit();
}
public static boolean getSharedPreferencesToggleState(Context context, String id) {
SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_FILE, Context.MODE_PRIVATE);
return sharedPreferences.getBoolean(id + TOGGLE_STATE, false);
}
}
|
package com.zhj.xmpp;
import android.content.ContentValues;
import android.database.Cursor;
import android.test.AndroidTestCase;
import com.zhj.xmpp.DB.SmsOpenHelper;
import com.zhj.xmpp.provider.SmsProvider;
/*
* @创建者 Administrator
* @创建时间 2015/9/1 11:00
* @描述 ${TODO}
*
* @更新者 $Author$
* @更新时间 $Date$
* @更新描述 ${TODO}
*/
public class TestSmsProvider extends AndroidTestCase {
public void testInsert() {
/**
public static final String FROM_ACCOUNT = "from_account";//消息从哪里来
public static final String TO_ACCOUNT = "to_account";//消息到哪里去
public static final String BODY = "body";//消息内容
public static final String STATUS = "status";//消息状态
public static final String TYPE = "type";//消息的类型
public static final String TIME = "time";//消息创建的时间
public static final String SESSION_ACCOUNT = "session_account";//消息的会话者(非当前登录用户)
*/
ContentValues values = new ContentValues();
values.put(SmsOpenHelper.SMSTABLE.FROM_ACCOUNT, "billy@itheima.com");
values.put(SmsOpenHelper.SMSTABLE.TO_ACCOUNT, "xiaoli@itheima.com");
values.put(SmsOpenHelper.SMSTABLE.BODY, "小丽,今晚约吗?");
values.put(SmsOpenHelper.SMSTABLE.STATUS, "offline");
values.put(SmsOpenHelper.SMSTABLE.TYPE, "chat");
values.put(SmsOpenHelper.SMSTABLE.TIME, "2015年9月1日11:02:45");
values.put(SmsOpenHelper.SMSTABLE.SESSION_ACCOUNT, "xiaoli@itheima.com");
getContext().getContentResolver().insert(SmsProvider.SMS_URI, values);
}
public void testDelete() {
getContext().getContentResolver().delete(SmsProvider.SMS_URI, SmsOpenHelper.SMSTABLE.FROM_ACCOUNT + "=?",
new String[] { "billy@itheima.com" });
}
public void testUpdate() {
ContentValues values = new ContentValues();
values.put(SmsOpenHelper.SMSTABLE.FROM_ACCOUNT, "billy@itheima.com");
values.put(SmsOpenHelper.SMSTABLE.TO_ACCOUNT, "xiaoli@itheima.com");
values.put(SmsOpenHelper.SMSTABLE.BODY, "小丽,今晚约吗?我想你很久了");
values.put(SmsOpenHelper.SMSTABLE.STATUS, "offline");
values.put(SmsOpenHelper.SMSTABLE.TYPE, "chat");
values.put(SmsOpenHelper.SMSTABLE.TIME, "2015年9月1日11:07:01");
values.put(SmsOpenHelper.SMSTABLE.SESSION_ACCOUNT, "xiaoli@itheima.com");
getContext().getContentResolver().update(SmsProvider.SMS_URI, values,
SmsOpenHelper.SMSTABLE.FROM_ACCOUNT + "=?", new String[] { "billy@itheima.com" });
}
public void testQuery() {
Cursor c =
getContext().getContentResolver().query(SmsProvider.SMS_URI, null,
SmsOpenHelper.SMSTABLE.FROM_ACCOUNT + "=?", new String[] { "admin@itheima.com" }, null);
int columnCount = c.getColumnCount();
// 遍历输出所有的列
while (c.moveToNext()) {
for (int i = 0; i < columnCount; i++) {
System.out.print(c.getString(i) + " ");
}
System.out.println("");
}
// 1 billy@itheima.com xiaoli@itheima.com 小丽,今晚约吗? offline chat 2015年9月1日11:02:45 xiaoli@itheima.com
}
}
|
package tags;
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import java.io.*;
import java.sql.*;
public class SaveTagHandler extends SimpleTagSupport{
private String fname;
private String lname;
private String uname;
public void setFname(String fname){
this.fname = fname;
}
public void setLname(String lname){
this.lname = lname;
}
public void setUname(String uname){
this.uname = uname;
}
StringWriter sw = new StringWriter();
public void doTag() throws JspException, IOException{
Connection con = null;
Statement stmt = null;
try{
DriverManager.registerDriver (new oracle.jdbc.OracleDriver());
con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "user1", "pass");
stmt = con.createStatement();
}
catch(Exception e){
System.out.println("<h1>Error</h1>");
return;
}
try{
stmt.executeUpdate("DROP TABLE EMPLOYEE_TABLE");
}
catch(SQLException e){
}
try{
stmt.executeUpdate("CREATE TABLE EMPLOYEE_TABLE(fname VARCHAR2(50), lname VARCHAR2(50),uname VARCHAR2(50))");
}
catch(SQLException e){
}
try{
PreparedStatement ps = null;
try{
ps = con.prepareStatement("INSERT into EMPLOYEE_TABLE values(?,?,?)");
ps.setString(1, fname);
ps.setString(2, lname);
ps.setString(3, uname);
int i = ps.executeUpdate();
}
catch (Exception e2){
System.out.println(e2);
}
finally{
ps.close();
}
}
catch (Exception e2){
JspWriter out = getJspContext().getOut();
out.println(e2);
}
}
}
|
/*
* (C) Copyright IBM Corp. 2020.
*
* 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.ibm.cloud.cloudant.v1.model;
import com.ibm.cloud.cloudant.v1.model.GetGeoOptions;
import com.ibm.cloud.cloudant.v1.utils.TestUtilities;
import com.ibm.cloud.sdk.core.service.model.FileWithMetadata;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
/**
* Unit test class for the GetGeoOptions model.
*/
public class GetGeoOptionsTest {
final HashMap<String, InputStream> mockStreamMap = TestUtilities.createMockStreamMap();
final List<FileWithMetadata> mockListFileWithMetadata = TestUtilities.creatMockListFileWithMetadata();
@Test
public void testGetGeoOptions() throws Throwable {
GetGeoOptions getGeoOptionsModel = new GetGeoOptions.Builder()
.db("testString")
.ddoc("testString")
.index("testString")
.bbox("testString")
.bookmark("testString")
.format("legacy")
.g("testString")
.includeDocs(true)
.lat(Double.valueOf("-90"))
.limit(Long.valueOf("0"))
.lon(Double.valueOf("-180"))
.nearest(true)
.radius(Double.valueOf("0"))
.rangex(Double.valueOf("0"))
.rangey(Double.valueOf("0"))
.relation("contains")
.skip(Long.valueOf("0"))
.stale("ok")
.build();
assertEquals(getGeoOptionsModel.db(), "testString");
assertEquals(getGeoOptionsModel.ddoc(), "testString");
assertEquals(getGeoOptionsModel.index(), "testString");
assertEquals(getGeoOptionsModel.bbox(), "testString");
assertEquals(getGeoOptionsModel.bookmark(), "testString");
assertEquals(getGeoOptionsModel.format(), "legacy");
assertEquals(getGeoOptionsModel.g(), "testString");
assertEquals(getGeoOptionsModel.includeDocs(), Boolean.valueOf(true));
assertEquals(getGeoOptionsModel.lat(), Double.valueOf("-90"));
assertEquals(getGeoOptionsModel.limit(), Long.valueOf("0"));
assertEquals(getGeoOptionsModel.lon(), Double.valueOf("-180"));
assertEquals(getGeoOptionsModel.nearest(), Boolean.valueOf(true));
assertEquals(getGeoOptionsModel.radius(), Double.valueOf("0"));
assertEquals(getGeoOptionsModel.rangex(), Double.valueOf("0"));
assertEquals(getGeoOptionsModel.rangey(), Double.valueOf("0"));
assertEquals(getGeoOptionsModel.relation(), "contains");
assertEquals(getGeoOptionsModel.skip(), Long.valueOf("0"));
assertEquals(getGeoOptionsModel.stale(), "ok");
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testGetGeoOptionsError() throws Throwable {
new GetGeoOptions.Builder().build();
}
} |
package com.metoo.view.web.tools;
import java.util.List;
import java.util.Map;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.metoo.core.tools.CommUtil;
import com.metoo.foundation.domain.BuyGift;
import com.metoo.foundation.domain.Goods;
import com.metoo.foundation.domain.OrderForm;
import com.metoo.foundation.service.IBuyGiftService;
import com.metoo.foundation.service.IGoodsService;
import com.metoo.foundation.service.IOrderFormService;
import com.metoo.manage.admin.tools.OrderFormTools;
/**
*
* <p>
* Title: BuyGiftViewTools.java
* </p>
*
* <p>
* Description: 满就送信息管理工具
* </p>
*
* <p>
* Copyright: Copyright (c) 2015
* </p>
*
* <p>
* Company: 沈阳网之商科技有限公司 www.koala.com
* </p>
*
* @author jinxinzhe
*
* @date 2014-10-24
*
* @version koala_b2b2c 2015
*/
@Component
public class BuyGiftViewTools {
@Autowired
private IBuyGiftService buyGiftService;
@Autowired
private IGoodsService goodsService;
@Autowired
private OrderFormTools orderFormTools;
@Autowired
private IOrderFormService orderFormService;
public void update_gift_invoke(OrderForm order) {
if (order != null) {
if (order.getGift_infos() != null
&& !order.getGift_infos().equals("")) {
List<Map> maps = Json.fromJson(List.class,
order.getGift_infos());
for (Map map : maps) {
BuyGift bg = this.buyGiftService.getObjById(CommUtil
.null2Long(map.get("buyGify_id")));
if (bg != null) {
List<Map> gifts = Json.fromJson(List.class,
bg.getGift_info());
for (Map gift : gifts) {
String goods_id = gift.get("goods_id").toString();
if (goods_id.equals(map.get("goods_id").toString())) {
if (gift.get("storegoods_count").toString()
.equals("1")) {
Goods goods = this.goodsService
.getObjById(CommUtil
.null2Long(goods_id));
goods.setGoods_inventory(goods
.getGoods_inventory() - 1);
this.goodsService.update(goods);
if(goods.getGoods_inventory()==0){
bg.setGift_status(20);
List<Map> g_maps = Json.fromJson(List.class, bg.getGift_info());
maps.addAll(Json.fromJson(List.class, bg.getGift_info()));
for (Map m : g_maps) {
Goods g_goods = this.goodsService.getObjById(CommUtil.null2Long(m
.get("goods_id")));
if (g_goods != null) {
g_goods.setOrder_enough_give_status(0);
g_goods.setOrder_enough_if_give(0);
g_goods.setBuyGift_id(null);
this.goodsService.update(g_goods);
}
}
}
} else {
if (gift.get("goods_count") != null) {
gift.put(
"goods_count",
CommUtil.null2Int(gift
.get("goods_count")) - 1);
if(CommUtil.null2Int(gift.get("goods_count"))==0){
bg.setGift_status(20);
List<Map> g_maps = Json.fromJson(List.class, bg.getGift_info());
maps.addAll(Json.fromJson(List.class, bg.getGift_info()));
for (Map m : g_maps) {
Goods g_goods = this.goodsService.getObjById(CommUtil.null2Long(m
.get("goods_id")));
if (g_goods != null) {
g_goods.setOrder_enough_give_status(0);
g_goods.setOrder_enough_if_give(0);
g_goods.setBuyGift_id(null);
this.goodsService.update(g_goods);
}
}
}
}
}
}
}
bg.setGift_info(Json.toJson(gifts, JsonFormat.compact()));
this.buyGiftService.update(bg);
}
}
}
if (order.getOrder_main() == 1
&& !CommUtil.null2String(order.getChild_order_detail())
.equals("")) {
List<Map> cmaps = this.orderFormTools.queryGoodsInfo(order
.getChild_order_detail());
for (Map child_map : cmaps) {
OrderForm child_order = this.orderFormService
.getObjById(CommUtil.null2Long(child_map
.get("order_id")));
this.update_gift_invoke(child_order);
}
}
}
}
}
|
package util;
import dao.GameDao;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import model.Game;
@FacesConverter(forClass = Game.class)
public class GameConversor implements Converter {
@Override
public Object getAsObject(FacesContext fc, UIComponent uic, String numeroSerie) {
if(numeroSerie != null && numeroSerie.trim().length() > 0) {
GameDao gameDao = new GameDao();
return gameDao.buscarGame(numeroSerie);
}
return null;
}
@Override
public String getAsString(FacesContext fc, UIComponent uic, Object gameObjeto) {
if(gameObjeto != null) {
Game game = (Game) gameObjeto;
return game.getNumeroSerie();
}
return null;
}
}
|
package test.ts;
public class ts_002 {
}
|
package gui;
import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.text.Font;
import javafx.scene.control.*;
import javafx.geometry.*;
/**
* Window with text and buttons containing a message.
*
* @author Lykke Levin
* @version 1.0
*
*/
public class ConfirmBox {
public boolean answer = false;
public Stage window = new Stage();
public Font font = new Font("Tw Cen MT", 18);
/**
* Creates a window containing a message.
* @param title String title of the window from the classes that uses ConfirmBox.
* @param message String message to display in the window from the classes that uses ConfirmBox.
* @return answer Boolean that returns an answer.
*/
public boolean display(String title, String message) {
window.initModality(Modality.APPLICATION_MODAL);
window.setTitle(title);
window.setMinWidth(150);
window.setMaxWidth(600);
window.setHeight(200);
window.setOnCloseRequest(e -> closeProgram());
Label label = new Label();
label.setFont(font);
label.setText(message);
label.setWrapText(true);
Button buttonOk = new Button("Ja");
Button buttonNotOk = new Button("Nej");
buttonOk.setFont(font);
buttonNotOk.setFont(font);
buttonOk.setOnAction(e -> {
answer = true;
closeProgram();
});
buttonNotOk.setOnAction(e -> {
answer = false;
closeProgram();
});
VBox layout = new VBox(10);
layout.setPadding(new Insets(10, 10, 10, 10));
layout.getChildren().addAll(label, buttonOk, buttonNotOk);
layout.setAlignment(Pos.CENTER);
Scene scene = new Scene(layout);
window.setScene(scene);
window.showAndWait();
return answer;
}
/**
* Method that closes the window.
*/
public void closeProgram() {
window.close();
}
}
|
package be.openclinic.adt;
import be.openclinic.common.OC_Object;
import net.admin.AdminPerson;
import java.util.Date;
/**
* User: Frank Verbeke
* Date: 10-sep-2006
* Time: 21:32:46
*/
public class Diagnosis extends OC_Object{
private Encounter encounter;
private String code;
private AdminPerson author;
private int certainty;
private int gravity;
private Date date;
public Encounter getEncounter() {
return encounter;
}
public void setEncounter(Encounter encounter) {
this.encounter = encounter;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public AdminPerson getAuthor() {
return author;
}
public void setAuthor(AdminPerson author) {
this.author = author;
}
public int getCertainty() {
return certainty;
}
public void setCertainty(int certainty) {
this.certainty = certainty;
}
public int getGravity() {
return gravity;
}
public void setGravity(int gravity) {
this.gravity = gravity;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
|
package cn.okay.page.okaymall.loginbefore;
import cn.okay.page.officialwebsite.OffciaHomePage;
import cn.okay.page.okaymall.partsmoudle.PartsClassificationPage;
import cn.okay.page.okaymall.shopmoudle.MyOrderPage;
import cn.okay.page.okaymall.shopmoudle.ShopCarPage;
import cn.okay.testbase.AbstractPage;
import cn.okay.tools.WaitTool;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.testng.Assert;
/**
* Created by yutz on 2018/2/28.
* 商城首页
*/
public class MallHomePage extends AbstractPage {
@FindBy(css=".index-argument")
WebElement recommendMoudle;
@FindBy(linkText = "首页")
WebElement homePageLink;
@FindBy(linkText = "OKAY智能终端")
WebElement OKAYIntelligentTerminalLink;
@FindBy(linkText = "配件")
WebElement partsLink;
@FindBy(linkText = "官网")
WebElement offciaLink;
WebElement firstImgBanner=driver.findElements(By.cssSelector(".only a")).get(0);
@FindBy(css = ".clearfix a[href='/index.php?m=OkayMall&c=index&a=downapp']")
WebElement dowloadAppMoudle;
@FindBy(css = ".clearfix a[href='/index.php?m=OkayMall&c=index&a=intelligence']")
WebElement artificialIntelligenceMoudle;
@FindBy(css = ".clearfix a[href='/index.php?m=OkayMall&c=index&a=coach']")
WebElement distanceTeachingMoudle;
@FindBy(css = ".clearfix a[href='/index.php?m=OkayMall&c=Goods&a=accessoriescate']")
WebElement partsMoudle;
@FindBy(css = ".clearfix a[href='/index.php?m=OkayMall&c=Goods&a=getMainOkaypad&goodId=207']")
WebElement terminalStudentBtn;
@FindBy(css = ".clearfix a[href='/index.php?m=OkayMall&c=Goods&a=getMainOkaypad&goodId=130']")
WebElement terminalTeacherBtn;
@FindBy(css = "a[href='/index.php?m=OkayMall&c=Orders&a=okayMallOrders']")
WebElement myOrder;
@FindBy(css=".user-icon")
WebElement userBtn;
@FindBy(css = ".cartsicon")
WebElement shopCarBtn;
public MallHomePage(WebDriver driver) {
super(driver);
WaitTool.waitFor(driver,WaitTool.DEFAULT_WAIT_4_ELEMENT,recommendMoudle);
}
public MallHomePage clickHomePageLink() throws Exception {
return click(homePageLink,MallHomePage.class);
}
public PartsClassificationPage clickPartsLink() throws Exception {
return click(partsLink,PartsClassificationPage.class);
}
public OffciaHomePage clickOfficaLink() throws Exception {
clickAndSwitchWindow(offciaLink);
return new OffciaHomePage(driver);
}
public AppDowloadPage clickDowloadMoudle() throws Exception {
return click(dowloadAppMoudle,AppDowloadPage.class);
}
public ArtificialIntelligencePage clickIntelligentTerminalMoudle() throws Exception {
return click(artificialIntelligenceMoudle,ArtificialIntelligencePage.class);
}
public DistanceTeachingPage clickDistanceTeachingMoudle() throws Exception {
return click(distanceTeachingMoudle,DistanceTeachingPage.class);
}
public PartsClassificationPage clickPartsMoudle() throws Exception {
return click(partsMoudle,PartsClassificationPage.class);
}
public TerminalStudentPage clickImg() throws Exception {
clickAndSwitchWindow(firstImgBanner);
return new TerminalStudentPage(driver);
}
public TerminalStudentPage clickStudentTerminal() throws Exception {
moveToElement(driver,OKAYIntelligentTerminalLink);
log.info("智能终端S4.0的显示效果是:"+terminalStudentBtn.isDisplayed());
Assert.assertTrue(terminalStudentBtn.isDisplayed());
return click(terminalStudentBtn,TerminalStudentPage.class);
}
public TerminalTeacherPage clickTeacherTerminal() throws Exception {
moveToElement(driver,OKAYIntelligentTerminalLink);
log.info("智能终端T1.0的显示效果是:"+terminalTeacherBtn.isDisplayed());
Assert.assertTrue(terminalTeacherBtn.isDisplayed());
return click(terminalTeacherBtn,TerminalTeacherPage.class);
}
public ShopCarPage homePageToShopPage() throws Exception {
return click(shopCarBtn,ShopCarPage.class);
}
//在购物车非空时,标记购物车数字的元素才会出现并且返回true,否则就返回false
public boolean shopCarNoNull(){
try {
driver.findElement(By.cssSelector("span[class='goods-amount goods-amount-p']"));
return true;
}
catch (Exception e){
return false;
}
}
public MyOrderPage homePageToMyOrderPage() throws Exception {
moveToElement(driver,userBtn);
return click(myOrder,MyOrderPage.class);
}
}
|
package fr.cea.nabla.interpreter.nodes.expression.constant;
import com.oracle.truffle.api.dsl.Cached;
import com.oracle.truffle.api.dsl.NodeChild;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.nodes.ExplodeLoop;
import fr.cea.nabla.interpreter.nodes.expression.NablaExpressionNode;
import fr.cea.nabla.interpreter.values.NV0Int;
import fr.cea.nabla.interpreter.values.NV1Int;
import fr.cea.nabla.interpreter.values.NV1IntJava;
@NodeChild(value = "value", type = NablaExpressionNode.class)
@NodeChild(value = "size", type = NablaExpressionNode.class)
public abstract class NablaInt1ConstantNode extends NablaExpressionNode {
@Specialization(guards = {"cachedSize == size.getData()", "isZero(value.getData())"})
protected NV1Int doDefaultCached(VirtualFrame frame, NV0Int value, NV0Int size, //
@Cached("size.getData()") int cachedSize, //
@Cached("getDefaultResult(cachedSize)") NV1Int result) {
return result;
}
@Specialization(guards = "cachedSize == size.getData()")
public NV1Int doCached(VirtualFrame frame, NV0Int value, NV0Int size, //
@Cached("value.getData()") int cachedValue, //
@Cached("size.getData()") int cachedSize, //
@Cached("getResult(cachedValue, cachedSize)") NV1Int result) {
return result;
}
protected boolean isZero(int d) { return d == 0; }
protected NV1Int getDefaultResult(int size) {
final int[] computedValues = new int[size];
return new NV1IntJava(computedValues);
}
@ExplodeLoop
protected NV1Int getResult(int value, final int size) {
final int[] computedValues = new int[size];
for (int i = 0; i < size; i++) {
computedValues[i] = value;
}
return new NV1IntJava(computedValues);
}
}
|
package com.vitaltech.bioink;
import android.content.Context;
import android.opengl.GLSurfaceView;
import android.util.AttributeSet;
public class Menu extends GLSurfaceView {
public Menu(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public Menu(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
}
|
package com.utils.streamjava7.collection;
import java.util.Iterator;
import java.util.List;
public interface Pipeline<T> extends Iterable<T> {
void add(T elem);
void addAll(Pipeline<T> that);
T head();
Pipeline<T> tail();
Pipeline<T> merge(final Pipeline<T> that);
T[] pipeline();
Boolean isNotEmpty();
List<T> toList();
@Override
Iterator<T> iterator();
void replace(final Pipeline<T> pipeline);
}
|
import java.util.Scanner;
public class TruongPhong extends NhanVien{
Scanner scanner = new Scanner(System.in);
public double luongTrachNhiem;
public double getLuongTrachNhiem() {
return luongTrachNhiem;
}
public void setLuongTrachNhiem(double luongTrachNhiem) {
this.luongTrachNhiem = luongTrachNhiem;
}
public TruongPhong() {
super();
// TODO Auto-generated constructor stub
}
public TruongPhong(double luongTrachNhiem) {
super();
this.luongTrachNhiem = luongTrachNhiem;
}
public double thuNhap() {
thuNhap = luong + luongTrachNhiem;
return thuNhap;
}
public void nhap() {
super.nhap();
System.out.println("Nhập doanh số bán hàng:");
this.luongTrachNhiem =Double.parseDouble(scanner.nextLine());
}
public void xuat() {
super.xuat();
System.out.println("Mức Lương Trách Nhiệm: "+luongTrachNhiem);
System.out.println("Thu Nhập: "+thuNhap());
System.out.println("Doanh Số Bán Hàng: "+super.thueThuNhap());
}
}
|
package mcls;
import single.SingletonClass;
public class MyClass {
private int number;
public MyClass() {
number =12;
}
/*
* public int getNumber() { return number; }
*/
public void method() {
SingletonClass sc = SingletonClass.getInstance();
this.number = sc.snumber ;
}
}
|
package com.Hackerrank.algos.sorting;
import java.util.Scanner;
public class CountingSort3 {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc=new Scanner(System.in);
int[] count=new int[100];
int n=sc.nextInt();
int val;
for(int i=0;i<n;i++){
val=sc.nextInt();
sc.next();
count[val] += 1;
}
System.out.print(count[0]+" ");
for(int i=1;i<100;i++){
count[i]+=count[i-1];
System.out.print(count[i]+" ");
}
}
} |
package training.security;
public interface SecureEntity {
public boolean isDeletable();
public void setDeletable(boolean deletable);
}
|
package hwarang.artg.funding.service;
import java.util.List;
import hwarang.artg.funding.model.OrderVO;
public interface FundingOrderService {
public OrderVO select(int order_seq_num);
public int insertOrder(OrderVO order);
public List<OrderVO> selectAll(String member_id);
}
|
package ouyang.model;
import android.database.Cursor;
import android.provider.BaseColumns;
import com.activeandroid.Model;
import com.activeandroid.annotation.Column;
import com.activeandroid.annotation.Table;
import java.io.Serializable;
/**
* Created by zuxiang on 2015/2/8.
*/
@Table(name = "foods")
public class Food extends Model implements Serializable {
@Column(name = "Name")
public String name;
@Column(name = "Price")
public float price;
@Column(name = BaseColumns._ID)
public int ID;
@Column(name = "pk_id")
public int pk_id;
@Column(name = "cid")
public int cid;
public Food(String foodName, float price) {
this.name = foodName;
this.price = price;
}
public Food() {
}
public static Food getFood(Cursor cursor) {
Food food = new Food();
food.cid = cursor.getInt(cursor.getColumnIndex("cid"));
food.name = cursor.getString(cursor.getColumnIndex("Name"));
food.price = cursor.getFloat(cursor.getColumnIndex("Price"));
food.pk_id = cursor.getInt(cursor.getColumnIndex("pk_id"));
return food;
}
}
|
package com.trump.auction.pals.domain;
import lombok.Data;
import java.util.Date;
@Data
public class ThirdPartyAsk {
private Integer id;
private String userId;
private Integer assetOrderId;
private String orderType;
private String orderNo;
private String act;
private String reqParams;
private String returnParams;
private Date notifyTime;
private String notifyParams;
private Date addTime;
private String addIp;
private Date updateTime;
private Integer status;
private String tableLastName;//表面后缀
@Override
public String toString() {
return "RiskOrders [userId=" + userId + ", orderType=" + orderType + ", act=" + act + ", addIp=" + addIp + ", addTime=" + addTime + ", id=" + id + ", notifyParams=" + notifyParams + ", notifyTime=" + notifyTime + ", orderNo=" + orderNo + ", reqParams=" + reqParams + ", returnParams=" + returnParams + ", status=" + status + ", updateTime=" + updateTime + ", tableLastName=" + tableLastName + "]";
}
}
|
/*
* Faça uma função que copie o conteúdo de um vetor em um segundo vetor.
*/
package AP22_05_vetor;
import static AP22_05_vetor.ExemploVetor.input;
import java.util.Scanner;
/**
*
* @author rodrigo.rsantos17
*/
public class Exercicio1 {
static Scanner input = new Scanner (System.in);
static int tamanhoVetor(){
System.out.print("Digite o tamnaho do vetor: ");
int t=input.nextInt();
return t;
}
static int[] Vetor(int t){
int vetor[] = new int [t];
return vetor;
}
static int[] lotaVetor(int[] vetor){
for(int i=0;i<vetor.length;i++){
System.out.print("digite um número: ");
vetor[i] = input.nextInt();
}
return vetor;
}
static int[] recebe(int[] vetor,int t){
int[] vetor2=new int[t];
for(int i=0;i<vetor.length;i++){
vetor2[i]=vetor[i];
}
return vetor2;
}
static void imprimirVetor(int[] vetor){
for(int i=0;i<vetor.length;i++){
System.out.println("["+i+"]: "+vetor[i]);
}
}
public static void main(String[] args) {
int t=tamanhoVetor();
int[] vetor=Vetor(t);
vetor=lotaVetor(vetor);
int[] vetor2=recebe(vetor, t);
imprimirVetor(vetor2);
}
}
|
package io.github.cottonmc.libcd.api.tweaker;
import net.minecraft.class_1799;
import net.minecraft.class_2960;
/**
* Some ItemStacks, like vanilla potions, have entirely different functions and names based on NBT.
* Because of that, it's hard to use those stacks in recipes.
* CottonTweaker uses a "[getter id]->[entry id]" syntax to get those recipes
*/
public interface TweakerStackFactory {
/**
* Get an ItemStack from a registered processor
* @param entry The Identifier of the entry to get
* @return the proper ItemStack for the given Identifier, or an empty stack if the entry doesn't exist
*/
class_1799 getSpecialStack(class_2960 entry);
}
|
package com.example.bookspace;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.bookspace.model.RetrofitClient;
import com.example.bookspace.model.books.Book;
import com.example.bookspace.model.books.GetBookResponse;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class BookPageActivity extends AppCompatActivity {
public String status;
public int bookId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_books_page);
Intent inten = getIntent();
bookId = inten.getIntExtra("bookId", 11);
//region настраиваем toolbar
Toolbar basicToolbar = findViewById(R.id.basicToolbar);
setSupportActionBar(basicToolbar);
getSupportActionBar().setTitle(R.string.bookPage);
basicToolbar.setNavigationIcon(R.drawable.ic_arrow_back);
//endregion
//region устанавливаем обработчик нажатия для back arrow иконки
basicToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), user_page.class));
}
});
//endregion
final Bundle bundle = new Bundle();
bundle.putInt("bookId", bookId);
final FragmentManager fragmentManager = getSupportFragmentManager();
String fragmentToLoad = inten.getStringExtra("fragmentToLoad");
if(fragmentToLoad != null){
switch (fragmentToLoad){
case "noticeFragment":
BookNoticeFragment bookNoticeFragment = new BookNoticeFragment();
bookNoticeFragment.setArguments(bundle);
fragmentManager.beginTransaction().add(R.id.bookPageFragmentContainer, bookNoticeFragment).commit();
break;
default:
BookAboutFragment bookAboutFragment = new BookAboutFragment();
bookAboutFragment.setArguments(bundle);
fragmentManager.beginTransaction().add(R.id.bookPageFragmentContainer, bookAboutFragment).commit();
break;
}
}
else{
BookAboutFragment bookAboutFragment = new BookAboutFragment();
bookAboutFragment.setArguments(bundle);
fragmentManager.beginTransaction().add(R.id.bookPageFragmentContainer, bookAboutFragment).commit();
}
}
private final int IDD_LIST_Status = 1;
public void editStatus(View v) {
if (v.getId() == R.id.editStatusButton) {
showDialog(IDD_LIST_Status);
}
}
protected Dialog onCreateDialog ( int id){
if (id == IDD_LIST_Status) {
final String[] statusName = {getText(R.string.bookRead).toString(),
getText(R.string.bookReading).toString(),
getText(R.string.bookWillRead).toString()};
SharedPreferences prefs = getSharedPreferences("AppPreferences", MODE_PRIVATE);
final String token = prefs.getString("token", "token is null");
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.bookChoose); // заголовок для диалога
builder.setCancelable(true);
builder.setItems(statusName, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
switch (statusName[item]) {
case "Read":
status = "DN";
break;
case "Reading":
status = "IP";
break;
case "Will Read":
status = "WR";
break;
case "Прочитав":
status = "DN";
break;
case "Читаю":
status = "IP";
break;
case "Хочу прочитати":
status = "WR";
break;
}
Call<ResponseBody> call7 = RetrofitClient
.getInstance()
.getBookSpaceAPI()
.setStatus("Bearer " + token, bookId, status);
call7.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(BookPageActivity.this, getText(R.string.wrongRes), Toast.LENGTH_LONG).show();
}
});
Toast.makeText(getApplicationContext(), getText(R.string.bookSelected) + " " + statusName[item],
Toast.LENGTH_SHORT).show();
}
});
return builder.create();
}
return null;
}
public void showRatingDialog(View view) {
final AlertDialog.Builder ratingdialog = new AlertDialog.Builder(this);
ratingdialog.setTitle("Rate it!");
View linearlayout = getLayoutInflater().inflate(R.layout.ratingdialog, null);
ratingdialog.setView(linearlayout);
SharedPreferences prefs = getSharedPreferences("AppPreferences", MODE_PRIVATE);
final String token_rate = prefs.getString("token", "token is null");
final TextView textGrade = findViewById(R.id.textGrade);
final RatingBar rating = linearlayout.findViewById(R.id.ratingbar);
ratingdialog.setCancelable(false);
ratingdialog.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Call<ResponseBody> call8 = RetrofitClient
.getInstance()
.getBookSpaceAPI()
.setRate("Bearer " + token_rate, bookId, Math.round(rating.getRating()));
call8.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(BookPageActivity.this, getText(R.string.wrongRes), Toast.LENGTH_LONG).show();
}
});
try{
Thread.sleep(100);
}
catch (InterruptedException e){
}
Call<GetBookResponse> call_getRate = RetrofitClient
.getInstance()
.getBookSpaceAPI()
.getBook("Bearer " + token_rate, bookId);
call_getRate.enqueue(new Callback<GetBookResponse>() {
@Override
public void onResponse(Call<GetBookResponse> call, Response<GetBookResponse> response) {
Book resp = response.body().getBook();
textGrade.setText(String.valueOf(resp.getRate()));
}
@Override
public void onFailure(Call<GetBookResponse> call, Throwable t) {
Toast.makeText(BookPageActivity.this, getText(R.string.wrongRes), Toast.LENGTH_LONG).show();
}
});
dialog.dismiss();
}
})
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
ratingdialog.create();
ratingdialog.show();
}
public void onButtonBarClicked(View view){
final Bundle bundle = new Bundle();
bundle.putInt("bookId", bookId);
final FragmentManager fragmentManager = getSupportFragmentManager();
if(view.getId() == R.id.aboutButton){
BookAboutFragment bookAboutFragment = new BookAboutFragment();
bookAboutFragment.setArguments(bundle);
fragmentManager.beginTransaction().replace(R.id.bookPageFragmentContainer, bookAboutFragment).commit();
}
else if(view.getId() == R.id.reviewsButton){
BookReviewsFragment bookReviewsFragment = new BookReviewsFragment();
bookReviewsFragment.setArguments(bundle);
fragmentManager.beginTransaction().replace(R.id.bookPageFragmentContainer, bookReviewsFragment).addToBackStack(null).commit();
}
else if(view.getId() == R.id.noticeButton){
BookNoticeFragment bookNoticeFragment = new BookNoticeFragment();
bookNoticeFragment.setArguments(bundle);
fragmentManager.beginTransaction().replace(R.id.bookPageFragmentContainer, bookNoticeFragment).addToBackStack(null).commit();
}
}
}
|
package gov.nih.mipav.view.renderer.J3D.model.file;
import gov.nih.mipav.view.renderer.J3D.model.structures.*;
import gov.nih.mipav.model.file.*;
import javax.media.j3d.*;
import javax.vecmath.*;
/**
* This structure contains the information that describes how an XML surface (see surface.xsd and FileSurfaceXML.java)
* is stored on disk.
*
* @see FileIO
* @see FileInfoXML
* @see FileSurfaceXML
*/
public class FileInfoSurfaceXML_J3D extends FileInfoSurfaceXML {
//~ Static fields/initializers -------------------------------------------------------------------------------------
/** Material properties of the surface:. */
private Material m_kMaterial = null;
/** Surface triangle mesh:. */
private ModelTriangleMesh[] m_kMesh = null;
//~ Constructors ---------------------------------------------------------------------------------------------------
/**
* Main constructor for FileInfoSurfaceXML.
*
* @param name String file name
* @param directory String file directory
* @param format int file format (data type)
*/
public FileInfoSurfaceXML_J3D(String name, String directory, int format) {
super(name, directory, format);
m_kMaterial = new Material();
m_kMaterial.setCapability(Material.ALLOW_COMPONENT_READ);
m_kMaterial.setCapability(Material.ALLOW_COMPONENT_WRITE);
}
//~ Methods --------------------------------------------------------------------------------------------------------
/*
* Prepares the class for cleanup.
*/
public void finalize() {
m_kMaterial = null;
m_kMesh = null;
super.finalize();
}
/**
* Returns the material properties for the surface:
*
* @return DOCUMENT ME!
*/
public Material getMaterial() {
return m_kMaterial;
}
/**
* Returns the ModelTriangleMesh representing the surface:
*
* @return DOCUMENT ME!
*/
public ModelTriangleMesh[] getMesh() {
return m_kMesh;
}
/**
* Sets the ambient color of the surface:
*
* @param kColor DOCUMENT ME!
*/
public void setAmbient(Color3f kColor) {
m_kMaterial.setAmbientColor(kColor);
}
/**
* Sets the diffuse color of the surface:
*
* @param kColor DOCUMENT ME!
*/
public void setDiffuse(Color3f kColor) {
m_kMaterial.setDiffuseColor(kColor);
}
/**
* Sets the emissive color of the surface:
*
* @param kColor DOCUMENT ME!
*/
public void setEmissive(Color3f kColor) {
m_kMaterial.setEmissiveColor(kColor);
}
/**
* Sets the material properties for the surface:
*
* @param kMaterial DOCUMENT ME!
*/
public void setMaterial(Material kMaterial) {
m_kMaterial = kMaterial;
}
/**
* Sets the ModelTriangleMesh representing the surface:
*
* @param kMesh DOCUMENT ME!
*/
public void setMesh(ModelTriangleMesh[] kMesh) {
m_kMesh = kMesh;
}
/**
* Creates the ModelTriangleMesh for the surface:
*
* @param kVertices Mesh coordinates
* @param kNormals Mesh normals (may be null)
* @param kColors Mesh colors (may be null)
* @param aiConnectivity Mesh index connectivity array
*/
public void setMesh(Point3f[] kVertices, Vector3f[] kNormals, Color4f[] kColors, int[] aiConnectivity) {
int i;
if ( m_kMesh == null ) {
m_kMesh = new ModelTriangleMesh[1];
} else {
ModelTriangleMesh[] mesh = new ModelTriangleMesh[m_kMesh.length];
for (i = 0; i < m_kMesh.length; i++) {
mesh[i] = m_kMesh[i];
}
m_kMesh = new ModelTriangleMesh[meshIndex + 1];
for (i = 0; i < meshIndex; i++) {
m_kMesh[i] = mesh[i];
}
}
m_kMesh[meshIndex++] = new ModelTriangleMesh(kVertices, kNormals, kColors, aiConnectivity);
}
/**
* Sets the surface shininess:
*
* @param fShininess DOCUMENT ME!
*/
public void setShininess(float fShininess) {
m_kMaterial.setShininess(fShininess);
}
/**
* Sets the specular color of the surface:
*
* @param kColor DOCUMENT ME!
*/
public void setSpecular(Color3f kColor) {
m_kMaterial.setSpecularColor(kColor);
}
/**
* Used to propogate all FileInfoSurfaceXML private variables to other FileInfosSurfaceXML.
*
* @param fInfo FileInfoSurfaceXML file info to be copied into
*/
public void updateFileInfos(FileInfoXML fInfo) {
if (this == fInfo) {
return;
}
super.updateFileInfos(fInfo);
((FileInfoSurfaceXML_J3D) fInfo).setMaterial(this.getMaterial());
((FileInfoSurfaceXML_J3D) fInfo).setMesh(this.getMesh());
}
}
|
package saPosla;
public class UrlConfig {
public static final String GMAIL = "http:/gmail.com";
public static String FACEBOOK = "https://www.facebook.com/";
}
|
package friend.group.bank.obj;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class FgbApplicationTests {
@Test
void contextLoads() {
}
}
|
package com.masters.security;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
public class SecurityUtils {
public SecurityUtils() {
}
//TODO NEED TO ADD ALREADYLOGIN USER!!!
public static String getCurrentUserLogin(){
SecurityContext context = SecurityContextHolder.getContext();
Authentication auth = context.getAuthentication();
return null;
}
}
|
package ffm.slc.model.enums;
/**
* Previous definition of Ethnicity combining Hispanic/Latino and Race.
*/
public enum OldEthnicityType {
AMERICAN_INDIAN_OR_ALASKAN_NATIVE("American Indian Or Alaskan Native"),
ASIAN_OR_PACIFIC_ISLANDER("Asian Or Pacific Islander"),
BLACK_NOT_OF_HISPANIC_ORIGIN("Black, Not Of Hispanic Origin"),
HISPANIC("Hispanic"),
WHITE_NOT_OF_HISPANIC_ORIGIN("White, Not Of Hispanic Origin");
private String prettyName;
OldEthnicityType(String prettyName) {
this.prettyName = prettyName;
}
@Override
public String toString() {
return prettyName;
}
}
|
package class1;
public class VD1 {
public static void main(String[] args) {
int a = 5;
int b = 7;
int c= a + b;
System.out.println("Tong:" +c);
}
}
|
package se.erik.lexicon.intra.enums;
import com.fasterxml.jackson.annotation.JsonGetter;
public enum DecisionType {
APL("apl"),FUB("fub"),EDUCATION("education"),NONE("none");
private String name;
private DecisionType(String name) {
this.name = name;
}
@Override
public String toString() {
return getName();
}
@JsonGetter
public String getName() {
return this.name;
}
}
|
package com.sb.movietvdl;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;
import androidx.appcompat.app.AppCompatDelegate;
import com.sb.movietvdl.Utils.LogUtil;
import com.sb.movietvdl.Utils.StaticResource;
import com.sb.movietvdl.config.MConfig;
import com.sb.movietvdl.helper.Fetcher;
import com.sb.movietvdl.ui.Activities.MainActivity;
import org.wlf.filedownloader.FileDownloadConfiguration;
import org.wlf.filedownloader.FileDownloadConfiguration.Builder;
import org.wlf.filedownloader.FileDownloader;
import org.wlf.filedownloader.FileDownloadConfiguration;
import java.io.File;
/*
* Created by Sharn25
* Dated 17-06-2020
*/
public class MovieTVDLApplication extends Application {
//int
private int cur_theme;
private int parallel_download;
//boolean
private boolean isDarkTheme;
private static boolean isThemeChanged;
public static boolean isupdatechecked;
//SharedPref
private SharedPreferences.Editor editor = null;
//constants
private final static String TAG = "MovieTVDLApplication";
@Override
public void onCreate() {
super.onCreate();
initStaticResource();
initConfig();
initFileDownloader();
}
@Override
public void onTerminate() {
super.onTerminate();
releaseFileDownloader();
}
private void initStaticResource(){
SharedPreferences MySetting = getSharedPreferences(StaticResource.PREF_SETTING,0);
editor = MySetting.edit();
cur_theme = MySetting.getInt("cur_theme",-1);
isDarkTheme = MySetting.getBoolean("isDarkTheme",false);
parallel_download = MySetting.getInt("parallel_download",3);
LogUtil.l(TAG +"_OnCreate","cur_theme: " + cur_theme,true);
if(cur_theme==-1) {
editor.putInt("cur_theme", StaticResource.LIGHT_THEME);
editor.putBoolean("isDarkTheme",false);
editor.putInt("parallel_download",parallel_download);
editor.commit();
cur_theme = StaticResource.LIGHT_THEME;
}
StaticResource.CUR_THEME = cur_theme;
setCur_theme(cur_theme);
StaticResource.PARALLEL_DOWNLOAD = parallel_download;
LogUtil.l(TAG,"App cur_theme: " +cur_theme,true);
}
private void setCur_theme(int theme){
AppCompatDelegate.setDefaultNightMode(theme);
}
private void initConfig(){
File fAppDir = new File(this.getExternalFilesDir(".mtvdl"),"");
File fAppdirconfig =new File(fAppDir,".mtv_dlconfig");
if(fAppdirconfig.exists()) {
MConfig.setConfig(MConfig.load(fAppdirconfig));
LogUtil.l(TAG+"_init","GetFAppDir : " + MConfig.getConfig().appdir,false);
LogUtil.l(TAG+"_init","GetdestDir : " + MConfig.getConfig().destdir,true);
LogUtil.i(TAG+"_init","Saved config Loaded.",true);
}else {
File destDir=new File(Environment.getExternalStorageDirectory(),"Download");
if(MConfig.getConfig()!=null){
MConfig.getConfig().file = fAppdirconfig;
MConfig.getConfig().appdir = fAppDir.getAbsolutePath();
MConfig.getConfig().destdir = destDir.getAbsolutePath();
MConfig.getConfig().source = 0;
MConfig.getConfig().isDarkTheme = isDarkTheme;
MConfig.getConfig().isPlayerAsk = true;
MConfig.getConfig().save();
}/*
//an_con.tempdir=fTmpDir.getAbsolutePath();
an_con.Default_Location=true;
an_con.Default_downloader=true;
an_con.tablesize=70;
an_con.maxdownloads=5;
fetcher.db(this);*/
LogUtil.l(TAG+"_init","destDir : " + MConfig.getConfig().destdir,true);
LogUtil.i(TAG+"_init","New Config saved and Loaded",true);
}
}
// init FileDownloader
private void initFileDownloader() {
LogUtil.l("AnimeDLApplication","initFileDownloader",true);
// 1.create FileDownloadConfiguration.Builder
Builder builder = new Builder(this);
// 2.config FileDownloadConfiguration.Builder
builder.configFileDownloadDir(MConfig.getConfig().destdir); // config the download path
// builder.configFileDownloadDir("/storage/sdcard1/FileDownloader");
// allow 3 download tasks at the same time
builder.configDownloadTaskSize(StaticResource.PARALLEL_DOWNLOAD);
// config retry download times when failed
builder.configRetryDownloadTimes(5);
// enable debug mode
//builder.configDebugMode(true);
// config connect timeout
builder.configConnectTimeout(25000); // 25s
// 3.init FileDownloader with the configuration
FileDownloadConfiguration configuration = builder.build(); // build FileDownloadConfiguration with the builder
FileDownloader.init(configuration);
}
// release FileDownloader
private void releaseFileDownloader() {
FileDownloader.release();
}
}
|
package com.example.demo.controller;
import com.example.demo.model.Todo;
import com.example.demo.service.TodoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.List;
@RestController
@RequestMapping("/v1/todo")
public class TodoController {
@Autowired
TodoService todoService;
@GetMapping("/all")
List<Todo> list() {
return todoService.findAll();
/*
Todo prueba() {
Todo todo = new Todo();
todo.setId(1);
todo.setTitle("Hola");
todo.setComments("Prueba comments");
todo.setDueDate(new Date());
todo.setFinished(false);
return todo;
*/
}
@PostMapping("/create")
Todo pruebaPost(@RequestBody Todo todo) {
todoService.insert(todo);
return todo;
}
@PostMapping("/update")
Todo updateTodo(@RequestBody Todo todo) {
todoService.update(todo);
return todo;
}
@GetMapping("/find/{id}")
Todo findBody(@PathVariable("id") int id){
Todo todo = todoService.getById(id);
return todo;
}
}
|
package com.graph;
/*
* 用于图中两个节点之间添加连接(包含了稀疏图和稠密图)
*/
public interface Graph {
public void addEdge(int v, int w);
public void show();
public int getN();
public GraphIterator getIterator(int v);
}
|
package wawi.fachlogik.sachbearbeitersteuerung.bestellungsverwaltung.service;
import java.util.ArrayList;
import java.util.List;
import wawi.fachlogik.sachbearbeitersteuerung.grenzklassen.BestellungGrenz;
import wawi.fachlogik.sachbearbeitersteuerung.grenzklassen.ProduktGrenz;
/**
*
* @author Christian
*/
public interface IBestellungsVerwaltung {
/*
* LF60
*/
public ArrayList<BestellungGrenz> alleBestellungenAnzeigen();
public ArrayList<BestellungGrenz> neueBestellungenAnzeigen();
public BestellungGrenz bestellungAnzeigen(int bestellungsId);
public boolean produktEntfernen(int bestellungsId, int produktId);
public boolean produktHinzufuegen(int bestellungsId, int produktId, int anzahl);
public boolean produktAnzahlAendern(int bestellungsId, int produktId, int anzahl);
public int getAnzahlProdukte(int bid, int pid);
public ArrayList<ProduktGrenz> alleProdukteAnzeigen(int bestellungsID);
public ArrayList<ProduktGrenz> alleProdukteAnzeigen();
/*
* LF80
*/
public boolean bestellungBezahltMarkieren(int bestellungsId);
/*
* LF65
*/
public List<BestellungGrenz> abgerechneteBestellungenAnzeigen();
public boolean bestellungStornieren(int bestellungsid);
}
|
package com.TPFinal.Model;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
@Entity
public class OrdenDeTrabajo {
@Id
@GeneratedValue
private long idOrdenTbjo;
private String patente,fechaIngreso,marca,detalleFalla;
private boolean abierto;
private float importeFinal;
@ManyToOne
@JoinColumn(name = "idPropietario")
private Propietario propietario;
@OneToMany(mappedBy = "orden")
private List<RepeOrden> listaRepeOrden;
public long getIdOrdenTbjo() {
return idOrdenTbjo;
}
public void setIdOrdenTbjo(long idOrdenTbjo) {
this.idOrdenTbjo = idOrdenTbjo;
}
public String getPatente() {
return patente;
}
public void setPatente(String patente) {
this.patente = patente;
}
public String getFechaIngreso() {
return fechaIngreso;
}
public void setFechaIngreso(String fechaIngreso) {
this.fechaIngreso = fechaIngreso;
}
public String getMarca() {
return marca;
}
public void setMarca(String marca) {
this.marca = marca;
}
public String getDetalleFalla() {
return detalleFalla;
}
public void setDetalleFalla(String detalleFalla) {
this.detalleFalla = detalleFalla;
}
public boolean isAbierto() {
return abierto;
}
public void setAbierto(boolean abierto) {
this.abierto = abierto;
}
public Propietario getPropietario() {
return propietario;
}
public void setPropietario(Propietario propietario) {
this.propietario = propietario;
}
public List<RepeOrden> getListaRepeOrden() {
return listaRepeOrden;
}
public void setListaRepeOrden(List<RepeOrden> listaRepeOrden) {
this.listaRepeOrden = listaRepeOrden;
}
public float getImporteFinal() {
return importeFinal;
}
public void setImporteFinal(float importeFinal) {
this.importeFinal = importeFinal;
}
}
|
package com.utils.file;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>
* Excel导入导出工具类
* </p>
*
* @author memory 2017年6月21日 上午10:17:22
* @version V1.0
* @modificationHistory=========================逻辑或功能性重大变更记录
* @modify by user: {修改人} 2017年6月21日
* @modify by reason:{方法名}:{原因}
*/
public class ExcelUtil {
private static Logger logger = LoggerFactory.getLogger(ExcelUtil.class);
/**
* 判断excel文件后缀名,生成不同的workbook
*
* @author memory 2017年6月21日 上午10:18:44
* @param is
* @param excelFileName
* @return
* @throws IOException
*/
private Workbook createWorkbook(InputStream is, String excelFileName) throws IOException {
if (excelFileName.endsWith(".xls")) {
return new HSSFWorkbook(is);
} else if (excelFileName.endsWith(".xlsx")) {
return new XSSFWorkbook(is);
}
return null;
}
/**
* @Title: getSheet
* @Description: 根据sheet索引号获取对应的sheet
* @param @param workbook
* @param @param sheetIndex
* @param @return
* @return Sheet
* @throws
*/
private Sheet getSheet(Workbook workbook, int sheetIndex) {
return workbook.getSheetAt(0);
}
/**
* @param <T>
* @Title: importDataFromExcel
* @Description: 将sheet中的数据保存到list中, 1、调用此方法时,vo的属性个数必须和excel文件每行数据的列数相同且一一对应,vo的所有属性都为String 2、在调用此方法时,需声明
* private File excelFile; 3、页面的file控件name需对应File的文件名
* @param @param vo javaBean
* @param @param is 输入流
* @param @param excelFileName 原始文件的文件名
* @param @return
* @return List<Object>
* @throws
*/
public <T> List<T> importDataFromExcel(Class<T> type, InputStream is, String excelFileName) {
List<T> list = new ArrayList<T>();
try {
// 创建工作簿
Workbook workbook = this.createWorkbook(is, excelFileName);
// 创建工作表sheet
Sheet sheet = this.getSheet(workbook, 0);
// 获取sheet中数据的行数
int rows = sheet.getPhysicalNumberOfRows();
// 获取表头单元格个数
int cells = sheet.getRow(0).getPhysicalNumberOfCells();
for (int i = 1; i < rows; i++) {// 第一行为标题栏,从第二行开始取数据
// 利用反射,给JavaBean的属性进行赋值
T vo = org.springframework.beans.BeanUtils.instantiate(type);
Field[] fields = vo.getClass().getDeclaredFields();
Row row = sheet.getRow(i);
int index = 0;
while (index < cells) {
Cell cell = row.getCell(index);
if (null == cell) {
cell = row.createCell(index);
}
cell.setCellType(Cell.CELL_TYPE_STRING);
String value = null == cell.getStringCellValue() ? "" : cell.getStringCellValue();
Field field = fields[index];
String fieldName = field.getName();
String methodName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
Method setMethod = vo.getClass().getMethod(methodName, new Class[] { String.class });
setMethod.invoke(vo, new Object[] { value });
index++;
}
if (!isHasValues(vo)) {// 判断对象属性是否有值
list.add(vo);
}
}
} catch (Exception e) {
logger.error(e.getMessage());
e.printStackTrace();
} finally {
try {
is.close();// 关闭流
} catch (Exception e2) {
logger.error(e2.getMessage());
e2.printStackTrace();
}
}
return list;
}
/**
* @Title: isHasValues
* @Description: 判断一个对象所有属性是否有值,如果一个属性有值(分空),则返回true
* @param @param object
* @param @return
* @return boolean
* @throws
*/
private boolean isHasValues(Object object) {
Field[] fields = object.getClass().getDeclaredFields();
boolean flag = false;
for (int i = 0; i < fields.length; i++) {
String fieldName = fields[i].getName();
String methodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
Method getMethod;
try {
getMethod = object.getClass().getMethod(methodName);
Object obj = getMethod.invoke(object);
if (null != obj && "".equals(obj)) {
flag = true;
break;
}
} catch (Exception e) {
logger.error(e.getMessage());
}
}
return flag;
}
/**
* 将数据导出到excel中
* @param list
* @param headers
* @param title
* @param os
*/
public <T> void exportDataToExcel(List<T> list, String[] headers, String title, OutputStream os) {
HSSFWorkbook workbook = new HSSFWorkbook();
// 生成一个表格
HSSFSheet sheet = workbook.createSheet(title);
// 设置表格默认列宽15个字节
sheet.setDefaultColumnWidth(15);
// 生成一个样式
HSSFCellStyle style = this.getCellStyle(workbook);
// 生成一个字体
HSSFFont font = this.getFont(workbook);
// 把字体应用到当前样式
style.setFont(font);
// 生成表格标题
HSSFRow row = sheet.createRow(0);
row.setHeight((short) 300);
HSSFCell cell = null;
for (int i = 0; i < headers.length; i++) {
cell = row.createCell(i);
cell.setCellStyle(style);
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
// 将数据放入sheet中
for (int i = 0; i < list.size(); i++) {
row = sheet.createRow(i + 1);
T t = list.get(i);
// 利用反射,根据JavaBean属性的先后顺序,动态调用get方法得到属性的值
Field[] fields = t.getClass().getFields();
try {
for (int j = 0; j < fields.length; j++) {
cell = row.createCell(j);
Field field = fields[j];
String fieldName = field.getName();
String methodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
Method getMethod = t.getClass().getMethod(methodName, new Class[] {});
Object value = getMethod.invoke(t, new Object[] {});
if (null == value)
value = "";
cell.setCellValue(value.toString());
}
} catch (Exception e) {
logger.error(e.getMessage());
}
}
try {
workbook.write(os);
} catch (Exception e) {
logger.error(e.getMessage());
} finally {
try {
os.flush();
os.close();
} catch (IOException e) {
logger.error(e.getMessage());
}
}
}
/**
* @Title: getCellStyle
* @Description: 获取单元格格式
* @param @param workbook
* @param @return
* @return HSSFCellStyle
* @throws
*/
private HSSFCellStyle getCellStyle(HSSFWorkbook workbook) {
HSSFCellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setLeftBorderColor(HSSFCellStyle.BORDER_THIN);
style.setRightBorderColor(HSSFCellStyle.BORDER_THIN);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
return style;
}
/**
* @Title: getFont
* @Description: 生成字体样式
* @param @param workbook
* @param @return
* @return HSSFFont
* @throws
*/
private HSSFFont getFont(HSSFWorkbook workbook) {
HSSFFont font = workbook.createFont();
font.setColor(HSSFColor.WHITE.index);
font.setFontHeightInPoints((short) 12);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
return font;
}
public boolean isIE(HttpServletRequest request) {
return request.getHeader("USER-AGENT").toLowerCase().indexOf("msie") > 0 ? true : false;
}
}
|
package com.cn.ouyjs.thread.lock.productAndCustomer;
import org.apache.commons.collections4.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author ouyjs
* @date 2019/8/9 10:39
*
* 注意事项:
* Condition对象将Object中的 wait() notify() notifyAll()封装
* Condition 中的方法对应 await对应 Object中的wait Condition也继承了Object 所以也有wait方法 注意注意注意!!!!
* Condition 中的方法对应 signal Object中的notify
* Condition 中的方法对应 signalAll Object中的notifyAll
*/
public class Warehouse {
private ReentrantLock lock = new ReentrantLock();
Condition customerCondition = lock.newCondition();
Condition produceCondition = lock.newCondition();
private List<Goods> goodsList = new ArrayList<>();
private Integer capacity;
Warehouse(Integer capacity) {
this.capacity = capacity;
}
public void addGoods(Goods goods) {
try {
lock.lock();
while (this.getSize() >= capacity) {
System.out.println("仓库满了,不能添加商品");
produceCondition.await();
}
goodsList.add(goods);
System.out.println("add thread name:" + Thread.currentThread().getName() + " number:" + this.getSize());
customerCondition.signal();
} catch (InterruptedException e) {
System.out.println("中断异常");
} finally {
lock.unlock();
}
}
public void removeGoods() {
try {
lock.lock();
while (this.getSize() <= 0) {
System.out.println("当前仓库为空");
customerCondition.await();
}
goodsList.remove(this.getSize() - 1);
System.out.println("remove thread name:" + Thread.currentThread().getName() + " number:" + this.getSize());
produceCondition.signal();
} catch (InterruptedException e) {
System.out.println("中断异常");
} finally {
lock.unlock();
}
}
public Integer getSize() {
if (CollectionUtils.isNotEmpty(goodsList)) {
return goodsList.size();
}
return 0;
}
public List<Goods> getGoodsList() {
return goodsList;
}
public void setGoodsList(List<Goods> goodsList) {
this.goodsList = goodsList;
}
public Integer getCapacity() {
return capacity;
}
public void setCapacity(Integer capacity) {
this.capacity = capacity;
}
}
|
package com.hwj.dao;
import com.hwj.entity.FileShare;
import com.hwj.service.IBaseService;
public interface IFileShareDao extends IBaseService<FileShare> {
}
|
package com.yuan.iliya.crud.dao.impl;
import com.yuan.iliya.crud.dao.Dao;
import com.yuan.iliya.crud.entity.Customer;
import com.yuan.iliya.crud.utils.JDBCUtils;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
/**
* All Rights Reserved, Designed By Iliya Kaslana
*
* @author Iliya Kaslana
* @version 1.0
* @date 2018/6/15 19:21
* @copyright ©2018
*/
public class DaoImpl implements Dao {
public void save(Customer customer) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = JDBCUtils.getConnection();
String sql = "insert into t_customer(age,email,name) values(?,?,?)";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setObject(1,customer.getAge());
preparedStatement.setObject(2,customer.getEmail());
preparedStatement.setObject(3,customer.getName());
preparedStatement.executeUpdate();
}catch (Exception e){
e.printStackTrace();
}finally {
JDBCUtils.close(connection,preparedStatement);
}
}
public void update(Customer customer) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = JDBCUtils.getConnection();
String sql = "update t_customer set age = ?, email = ?, name = ? where id = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setObject(1,customer.getAge());
preparedStatement.setObject(2,customer.getEmail());
preparedStatement.setObject(3,customer.getName());
preparedStatement.setObject(4,customer.getId());
preparedStatement.executeUpdate();
}catch (Exception e){
e.printStackTrace();
}finally {
JDBCUtils.close(connection,preparedStatement);
}
}
public void delete(Serializable id) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = JDBCUtils.getConnection();
String sql = "delete from t_customer where id = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setObject(1,id);
preparedStatement.executeUpdate();
}catch (Exception e){
e.printStackTrace();
}finally {
JDBCUtils.close(connection,preparedStatement);
}
}
public Customer getCustomer(Serializable id) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
Customer customer = null;
try {
connection = JDBCUtils.getConnection();
String sql = "select * from t_customer where id = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setObject(1,id);
resultSet = preparedStatement.executeQuery();
customer = new Customer();
if (resultSet.next()){
customer.setId(resultSet.getInt(1));
customer.setAge(resultSet.getInt(2));
customer.setEmail(resultSet.getString(3));
customer.setName(resultSet.getString(4));
}
}catch (Exception e){
e.printStackTrace();
}finally {
JDBCUtils.close(connection,preparedStatement);
}
return customer;
}
public List<Customer> getCustomerForList() {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
List<Customer> customers = new ArrayList<Customer>();
try {
connection = JDBCUtils.getConnection();
String sql = "select * from t_customer";
preparedStatement = connection.prepareStatement(sql);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
Customer customer = new Customer();
customer.setId(resultSet.getInt(1));
customer.setAge(resultSet.getInt(2));
customer.setEmail(resultSet.getString(3));
customer.setName(resultSet.getString(4));
customers.add(customer);
}
}catch (Exception e){
e.printStackTrace();
}finally {
JDBCUtils.close(connection,preparedStatement);
}
return customers;
}
}
|
package io.tourist.token.writer;
import io.tourist.token.model.TokenCounterNode;
import io.tourist.token.serializer.TokenCounterNodeSerializer;
/**
* The console token counter node writer class.
*/
public final class ConsoleTokenCounterNodeWriter implements TokenCounterNodeWriter {
/** The serializer. */
private TokenCounterNodeSerializer serializer;
/*
* (non-Javadoc)
*
* @see
* io.tourist.token.writer.TokenCounterNodeWriter#write(io.tourist.token.
* model.TokenCounterNode)
*/
@Override
public synchronized void write(final TokenCounterNode tokenCounterNode) {
System.out.println(this.serializer.serialize(tokenCounterNode));
}
/**
* Sets the serializer.
*
* @param serializer
* the new serializer
*/
public void setSerializer(final TokenCounterNodeSerializer serializer) {
this.serializer = serializer;
}
}
|
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.exporter.internal.grpc;
import io.grpc.ManagedChannel;
import io.opentelemetry.exporter.internal.marshal.Marshaler;
import java.net.URI;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
final class GrpcExporterUtil {
private static final boolean USE_OKHTTP;
static {
boolean useOkhttp = true;
// Use the OkHttp exporter unless grpc-stub is on the classpath.
try {
Class.forName("io.grpc.stub.AbstractStub");
useOkhttp = false;
} catch (ClassNotFoundException e) {
// Fall through
}
USE_OKHTTP = useOkhttp;
}
static <T extends Marshaler> GrpcExporterBuilder<T> exporterBuilder(
String type,
long defaultTimeoutSecs,
URI defaultEndpoint,
Supplier<Function<ManagedChannel, MarshalerServiceStub<T, ?, ?>>> stubFactory,
String grpcServiceName,
String grpcEndpointPath) {
if (USE_OKHTTP) {
return new OkHttpGrpcExporterBuilder<>(
type, grpcEndpointPath, defaultTimeoutSecs, defaultEndpoint);
} else {
return new DefaultGrpcExporterBuilder<>(
type, stubFactory.get(), defaultTimeoutSecs, defaultEndpoint, grpcServiceName);
}
}
static void logUnimplemented(Logger logger, String type, @Nullable String fullErrorMessage) {
String envVar;
switch (type) {
case "span":
envVar = "OTLP_TRACES_EXPORTER";
break;
case "metric":
envVar = "OTLP_METRICS_EXPORTER";
break;
case "log":
envVar = "OTLP_LOGS_EXPORTER";
break;
default:
throw new IllegalStateException(
"Unrecognized type, this is a programming bug in the OpenTelemetry SDK");
}
logger.log(
Level.SEVERE,
"Failed to export "
+ type
+ "s. Server responded with UNIMPLEMENTED. "
+ "This usually means that your collector is not configured with an otlp "
+ "receiver in the \"pipelines\" section of the configuration. "
+ "If export is not desired and you are using OpenTelemetry autoconfiguration or the javaagent, "
+ "disable export by setting "
+ envVar
+ "=none. "
+ "Full error message: "
+ fullErrorMessage);
}
private GrpcExporterUtil() {}
}
|
package org.apache.bookkeeper.stats;
import com.twitter.common.stats.Stats;
import java.net.InetSocketAddress;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Provides an instance of a bookkeeper client stats logger and a per channel
* bookie client stats logger
*/
public class ClientStatsProvider {
private static AtomicInteger loggerIndex = new AtomicInteger(0);
private static final ConcurrentMap<InetSocketAddress, PCBookieClientStatsLogger> pcbookieLoggerMap
= new ConcurrentHashMap<InetSocketAddress, PCBookieClientStatsLogger>();
public static BookkeeperClientStatsLogger getStatsLoggerInstance() {
Logger.getLogger(Stats.class.getName()).setLevel(Level.SEVERE);
return new BookkeeperClientStatsImpl("bookkeeper_client_" + loggerIndex.getAndIncrement());
}
/**
* @param addr
* @return Get the instance of the per channel bookie client logger responsible for this addr.
*/
public static PCBookieClientStatsLogger getPCBookieStatsLoggerInstance(InetSocketAddress addr) {
Logger.getLogger(Stats.class.getName()).setLevel(Level.SEVERE);
String statName = new StringBuilder("per_channel_bookie_client_")
.append(addr.getHostName().replace('.', '_').replace('-', '_'))
.append("_")
.append(addr.getPort())
.toString();
PCBookieClientStatsLogger logger = pcbookieLoggerMap
.putIfAbsent(addr, new PCBookieClientStatsImpl(statName));
if (null == logger) {
return pcbookieLoggerMap.get(addr);
} else {
return logger;
}
}
}
|
package cz.jiripinkas.jba.service;
import java.util.Date;
import java.util.List;
import javax.transaction.Transactional;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;
import cz.jiripinkas.jba.entity.Commit;
import cz.jiripinkas.jba.entity.User;
import cz.jiripinkas.jba.repository.CommitRepository;
import cz.jiripinkas.jba.repository.StatusRepository;
import cz.jiripinkas.jba.repository.UserRepository;
@Service
@Transactional
public class CommitService {
private static final Logger logger = Logger.getLogger(CommitService.class);
@Autowired
private CommitRepository commitRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private StatusRepository statusRepository;
@Transactional
public void save(Commit commit, String name) {
/*
* // TODO Auto-generated method stub SimpleDateFormat sdf = new
* SimpleDateFormat(""); sdf.format(new
* Date(System.currentTimeMillis()));
*/
User user = userRepository.findByName(name);
user.setBalance(user.getBalance() + commit.getAmount()/10);
userRepository.save(user);
commit.setDateCommit(new Date(System.currentTimeMillis()));
commit.setUser(user);
commit.setStatus(statusRepository.findOne(1)); // Awaiting submission
commitRepository.saveAndFlush(commit);
}
@Transactional
public User getAllCommitments(User user) {
// TODO Auto-generated method stub
List<Commit> commits = commitRepository.findByUser(user);
user.setCommits(commits);
return user;
}
public List<Commit> getTableData() {
// TODO Auto-generated method stub
return commitRepository.findAll(
new PageRequest(0, 20, Direction.DESC, "dateCommit"))
.getContent();
}
public void updateCommitTable(Commit tmp) {
// TODO Auto-generated method stub
logger.info("inside updateCommitTable service");
Integer idtmp = tmp.getId();
Commit commit = commitRepository.findOne(idtmp);
commit.setAmount(tmp.getAmount());
commit.setDateCommit(tmp.getDateCommit());
commit.setDateConf(tmp.getDateConf());
commit.setStatus(tmp.getStatus());
commit.setUser(tmp.getUser());
commitRepository.save(commit);
}
public void setChequeUploadDate(Commit commit) {
// TODO Auto-generated method stub
commit.setDateChequeUploaded(new Date(System.currentTimeMillis()));
commitRepository.save(commit);
}
public void setConfDate(Commit commit, Date date) {
// TODO Auto-generated method stub
commit.setDateConf(date);
commitRepository.save(commit);
}
public void setStatus(Commit commit, int status) {
// TODO Auto-generated method stub
logger.info("Inside SetStatusCommit()");
commit.setStatus(statusRepository.findOne(status));
commitRepository.save(commit);
logger.info("Outside SetStatusCommit()");
}
/*
* @Transactional public List<Commit> findByUserAndStatus(User user, Status
* status) { // TODO Auto-generated method stub return
* commitRepository.findByUser_IdAndStatus_Id(user.getId(),status.getId());
*
* }
*/
}
|
package com.example.qunxin.erp.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import com.example.qunxin.erp.R;
/**
* Created by qunxin on 2019/8/12.
*/
public class KucunyujingActivity extends AppCompatActivity implements View.OnClickListener {
View backBtn;
View saveBtn;
EditText editText;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kucunyujing);
initView();
}
void initView(){
backBtn=findViewById(R.id.kucunyujing_back);
saveBtn=findViewById(R.id.kucunyujing_save);
editText=findViewById(R.id.kucunyujing_number);
backBtn.setOnClickListener(this);
saveBtn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.kucunyujing_back:
finish();
break;
case R.id.kucunyujing_save:
String number=editText.getText().toString();
Intent intent=new Intent();
intent.putExtra("number",number);
setResult(4,intent);
finish();
break;
}
}
}
|
package alien4cloud.tosca.normative;
/**
* @author Minh Khang VU
*/
public interface Unit {
double getMultiplier();
}
|
package com.tzl.controller;
import com.tzl.client.PersonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Configuration
public class InvokerController {
@Autowired
private PersonClient personClient;
@GetMapping(value = "/invokerHello")
public String invokerHello(){
return personClient.hello();
}
}
|
/*
* This file is part of BlueMap, licensed under the MIT License (MIT).
*
* Copyright (c) Blue (Lukas Rieger) <https://bluecolored.de>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package de.bluecolored.bluemap.api.markers;
import de.bluecolored.bluemap.api.debug.DebugDump;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
/**
* A set of {@link Marker}s that are displayed on the maps in the web-app.
*/
@DebugDump
public class MarkerSet {
private String label;
private boolean toggleable, defaultHidden;
private int sorting;
private final ConcurrentHashMap<String, Marker> markers;
/**
* Empty constructor for deserialization.
*/
@SuppressWarnings("unused")
private MarkerSet() {
this("");
}
/**
* Creates a new {@link MarkerSet}.
*
* @param label the label of the {@link MarkerSet}
*
* @see #setLabel(String)
*/
public MarkerSet(String label) {
this(label, true, false);
}
/**
* Creates a new {@link MarkerSet}.
*
* @param label the label of the {@link MarkerSet}
* @param toggleable if the {@link MarkerSet} is toggleable
* @param defaultHidden the default visibility of the {@link MarkerSet}
*
* @see #setLabel(String)
* @see #setToggleable(boolean)
* @see #setDefaultHidden(boolean)
*/
public MarkerSet(String label, boolean toggleable, boolean defaultHidden) {
this.label = Objects.requireNonNull(label);
this.toggleable = toggleable;
this.defaultHidden = defaultHidden;
this.sorting = 0;
this.markers = new ConcurrentHashMap<>();
}
/**
* Getter for the label of this {@link MarkerSet}.
* <p>The label is used in the web-app to name the toggle-button of this {@link MarkerSet} if it is toggleable.
* ({@link #isToggleable()})</p>
*
* @return the label of this {@link MarkerSet}
*/
public String getLabel() {
return label;
}
/**
* Sets the label of this {@link MarkerSet}.
* <p>The label is used in the web-app to name the toggle-button of this {@link MarkerSet} if it is toggleable.
* ({@link #isToggleable()})</p>
*
* @param label the new label
*/
public void setLabel(String label) {
this.label = Objects.requireNonNull(label);
}
/**
* Checks if the {@link MarkerSet} is toggleable.
* <p>If this is <code>true</code>, the web-app will display a toggle-button for this {@link MarkerSet} so the user
* can choose to enable/disable all markers of this set.</p>
*
* @return whether this {@link MarkerSet} is toggleable
*/
public boolean isToggleable() {
return toggleable;
}
/**
* Changes if this {@link MarkerSet} is toggleable.
* <p>If this is <code>true</code>, the web-app will display a toggle-button for this {@link MarkerSet} so the user
* can choose to enable/disable all markers of this set.</p>
*
* @param toggleable whether this {@link MarkerSet} should be toggleable
*/
public void setToggleable(boolean toggleable) {
this.toggleable = toggleable;
}
/**
* Checks if this {@link MarkerSet} is hidden by default.
* <p>This is basically the default-state of the toggle-button from {@link #isToggleable()}.
* If this is <code>true</code> the markers of this marker set will initially be hidden and can be displayed
* using the toggle-button.</p>
*
* @return whether this {@link MarkerSet} is hidden by default
* @see #isToggleable()
*/
public boolean isDefaultHidden() {
return defaultHidden;
}
/**
* Sets if this {@link MarkerSet} is hidden by default.
* <p>This is basically the default-state of the toggle-button from {@link #isToggleable()}. If this is
* <code>true</code> the markers of this marker set will initially be hidden and can be displayed using the toggle-button.</p>
*
* @param defaultHidden whether this {@link MarkerSet} should be hidden by default
* @see #isToggleable()
*/
public void setDefaultHidden(boolean defaultHidden) {
this.defaultHidden = defaultHidden;
}
/**
* Returns the sorting-value that will be used by the webapp to sort the marker-sets.<br>
* A lower value makes the marker-set sorted first (in lists and menus), a higher value makes it sorted later.<br>
* If multiple marker-sets have the same sorting-value, their order will be arbitrary.<br>
* This value defaults to 0.
* @return This marker-sets sorting-value
*/
public int getSorting() {
return sorting;
}
/**
* Sets the sorting-value that will be used by the webapp to sort the marker-sets ("default"-sorting).<br>
* A lower value makes the marker-set sorted first (in lists and menus), a higher value makes it sorted later.<br>
* If multiple marker-sets have the same sorting-value, their order will be arbitrary.<br>
* This value defaults to 0.
* @param sorting the new sorting-value for this marker-set
*/
public void setSorting(int sorting) {
this.sorting = sorting;
}
/**
* Getter for a (modifiable) {@link Map} of all {@link Marker}s in this {@link MarkerSet}.
* The keys of the map are the id's of the {@link Marker}s.
*
* @return a {@link Map} of all {@link Marker}s of this {@link MarkerSet}.
*/
public Map<String, Marker> getMarkers() {
return markers;
}
/**
* Convenience method to add a {@link Marker} to this {@link MarkerSet}.<br>
* Shortcut for: <code>getMarkers().get(String)</code>
* @see Map#get(Object)
*/
public Marker get(String key) {
return getMarkers().get(key);
}
/**
* Convenience method to add a {@link Marker} to this {@link MarkerSet}.<br>
* Shortcut for: <code>getMarkers().put(String,Marker)</code>
* @see Map#put(Object, Object)
*/
public Marker put(String key, Marker marker) {
return getMarkers().put(key, marker);
}
/**
* Convenience method to remove a {@link Marker} from this {@link MarkerSet}.<br>
* Shortcut for: <code>getMarkers().remove(String)</code>
* @see Map#remove(Object)
*/
public Marker remove(String key) {
return getMarkers().remove(key);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MarkerSet markerSet = (MarkerSet) o;
if (toggleable != markerSet.toggleable) return false;
if (defaultHidden != markerSet.defaultHidden) return false;
if (!label.equals(markerSet.label)) return false;
return markers.equals(markerSet.markers);
}
@Override
public int hashCode() {
int result = label.hashCode();
result = 31 * result + (toggleable ? 1 : 0);
result = 31 * result + (defaultHidden ? 1 : 0);
result = 31 * result + markers.hashCode();
return result;
}
/**
* Creates a Builder for {@link MarkerSet}s.
* @return a new Builder
*/
public static Builder builder() {
return new Builder();
}
public static class Builder {
private String label;
private Boolean toggleable, defaultHidden;
private Integer sorting;
/**
* Sets the label of the {@link MarkerSet}.
* <p>The label is used in the web-app to name the toggle-button of the {@link MarkerSet} if it is toggleable.
* ({@link #toggleable(Boolean)})</p>
*
* @param label the new label
* @return this builder for chaining
*/
public Builder label(String label) {
this.label = label;
return this;
}
/**
* Changes if the {@link MarkerSet} is toggleable.
* <p>If this is <code>true</code>, the web-app will display a toggle-button for the {@link MarkerSet}
* so the user can choose to enable/disable all markers of this set.</p>
*
* @param toggleable whether the {@link MarkerSet} should be toggleable
* @return this builder for chaining
*/
public Builder toggleable(Boolean toggleable) {
this.toggleable = toggleable;
return this;
}
/**
* Sets if this {@link MarkerSet} is hidden by default.
* <p>This is basically the default-state of the toggle-button from {@link #toggleable(Boolean)}.
* If this is <code>true</code> the markers of this marker set will initially be hidden and can be displayed
* using the toggle-button.</p>
*
* @param defaultHidden whether this {@link MarkerSet} should be hidden by default
* @return this builder for chaining
* @see #isToggleable()
*/
public Builder defaultHidden(Boolean defaultHidden) {
this.defaultHidden = defaultHidden;
return this;
}
/**
* Sets the sorting-value that will be used by the webapp to sort the marker-sets ("default"-sorting).<br>
* A lower value makes the marker-set sorted first (in lists and menus), a higher value makes it sorted later.<br>
* If multiple marker-sets have the same sorting-value, their order will be arbitrary.<br>
* This value defaults to 0.
* @param sorting the new sorting-value for this marker-set
*/
public Builder sorting(Integer sorting) {
this.sorting = sorting;
return this;
}
/**
* Creates a new {@link MarkerSet} with the current builder-settings.<br>
* The minimum required settings to build this marker-set are:
* <ul>
* <li>{@link #setLabel(String)}</li>
* </ul>
* @return The new {@link MarkerSet}-instance
*/
public MarkerSet build() {
MarkerSet markerSet = new MarkerSet(
checkNotNull(label, "label")
);
if (toggleable != null) markerSet.setToggleable(toggleable);
if (defaultHidden != null) markerSet.setDefaultHidden(defaultHidden);
if (sorting != null) markerSet.setSorting(sorting);
return markerSet;
}
@SuppressWarnings("SameParameterValue")
<O> O checkNotNull(O object, String name) {
if (object == null) throw new IllegalStateException(name + " has to be set and cannot be null");
return object;
}
}
}
|
package ProjectManagement;
public class Job implements Comparable<Job>,JobReport_{
private String name;
private String projectname;
private String username;
private Project project;
private User user;
private String jobstatus;
private int runtime;
private int createtime;
private int arrivaltime;
private int endtime;
private int priority;
Job(String name,String project,String user,String run)
{
this.name=name;
this.username=user;
this.projectname=project;
jobstatus="REQUESTED";
endtime=0;
arrivaltime=0;
priority=0;
createtime++;
runtime=Integer.parseInt(run);
project=null;
user=null;
}
public String jobName()
{
return name;
}
public String projectName()
{
return projectname;
}
public String userName()
{
return username;
}
public void setCreatetime(int a) { createtime = a;}
public int getCreatetime() { return createtime;}
public int getRunTime()
{
return runtime;
}
public int getEndtime() { return endtime; }
public void setUser(User u)
{
user=u;
}
public User getUser() { return user; }
public void setProject(Project p)
{
priority=p.getPriority();
project=p;
}
public Project getProject()
{
return project;
}
public void setPriority(int a) { priority=a; }
public int getPriority() { return priority; }
public void setStatus()
{
jobstatus="COMPLETED";
}
public String getStatus()
{
return jobstatus;
}
public void setArrivalTime(int gt) { arrivaltime=gt; }
public void setEndTime(int g)
{
endtime=g;
}
@Override
public int compareTo(Job job)
{
int y=this.getPriority()-job.getPriority();
if(y==0)
y=job.getCreatetime()-this.getCreatetime();
return y;
}
public String toString()
{
String end="null";
if(endtime>0)
end=endtime+"";
String ss=("Job{user='"+user.name()+"', project='"+project.projectName()+"', jobstatus="+jobstatus+
", execution_time="+runtime+", end_time="+end+", name='"+name+"'}");
return ss;
}
@Override
public String user() {
return username;
}
@Override
public String project_name() {
return projectname;
}
@Override
public int budget() {
return project.getBudget();
}
@Override
public int arrival_time() {
return arrivaltime;
}
@Override
public int completion_time() {
return endtime;
}
} |
package dao;
import org.apache.log4j.Logger;
public class Log {
private static Logger log;
public Log() {
// TODO Auto-generated constructor stub
log = Logger.getLogger(Log.class);
}
public void setInfo(String message){
log.info(message);
}
public void setError(String message){
log.error(message);
}
public void setFatal(String message){
log.fatal(message);
}
public void setDebug(String message){
log.debug(message);
}
}
|
package Game;
public class Deck{
private Card [] cards = new Card [53];
private int counter;
public Card [] getCards(){
return cards;
}
public int getBrojac(){
return counter;
}
public Deck() {
for ( int i = 0; i < 53; i++) {
cards[i] = new Card(i);
}
mixingCards();
}
public String toString() {
String cardsToString = "";
for (int i = 0; i < 53; i++) {
cardsToString = cardsToString + (cards[i].toString());
}
return cardsToString;
}
public void mixingCards(){
Card temp;
for (int i = 0; i < cards.length; i++){
int first = (int)(Math.random() * 52);
int second = (int)(Math.random() * 52);
temp = cards[first];
cards[first] = cards[second];
cards[second] = temp;
}
}
public Card getNext(){
if (counter+1 < 52){
return cards[counter++];
}
else {
return null;
}
}
}
|
import java.lang.reflect.Array;
import java.util.Arrays;
public class Pila {
private Integer pila[] = new Integer[500];
private Integer posicionPila = 0;
Pila() {
posicionPila = 0;
}
public void popPila() {
if (pila[0]==null) {
Leer.mostrarEnPantalla("La pila esta vacia");
} else {
posicionPila--;
System.out.println(pila[posicionPila]);
System.out.println("el valor en la posicion "+(posicionPila+1)+ " se ha eliminado");
pila[posicionPila] = null;
}
}
public void addPila(Integer numero) {
pila[posicionPila] = numero;
posicionPila++;
}
public void copyPila(){
}
public void invPila() {
Integer aux[] = new Integer[posicionPila];
Integer cont=0;
for (int i = posicionPila-1; i >= 0; i--) {
for (int j = 0; j < 1; j++) {
aux[cont] = pila[i];
}
cont+=1;
}
for (int i = 0; i <= posicionPila - 1; i++) {
pila[i] = aux[i];
}
}
public void visualizar() {
for (int i = 0; i < posicionPila; i++) {
System.out.println(pila[i]);
}
}
}
|
package kodlama.io.hrms.core.utilities.adapters;
import org.springframework.stereotype.Service;
import kodlama.io.hrms.mernis.FakeMernis;
@Service
public class MernisServiceAdapter implements ValidationService {
@Override
public boolean userValidate(long nationalId, String firstName, String lastName, int birthDate) {
FakeMernis checkUser = new FakeMernis();
boolean result = true;
try {
result = checkUser.userValidate(nationalId, firstName, lastName, birthDate);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
|
package com.uchain.uvm.program.listener;
public interface ProgramListenerAware {
void setProgramListener(ProgramListener listener);
}
|
package com.javatechie.springcloud.function.api;
import java.util.function.Function;
public class Test implements Function<String, String> {
@Override
public String apply(String t){
return "Serverless functional programming : example by";
}
}
|
package code.service;
import code.dao.TestDao;
import code.dao.TestRepository;
import code.util.SqlUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
/**
* Created by lm1 on 2017/1/3.
*/
@Service
public class TestServiceImp implements TestService {
@Autowired
private TestDao testDao;
@Autowired
private TestRepository testRepository;
private static Logger logger=Logger.getLogger(TestServiceImp.class);
public Map testQuery(){
Map resultMap=new HashMap();
resultMap.put("items",testDao.queryForList(SqlUtil.getSql("sql.select.query2")));
resultMap.put("warns",testDao.queryForList(SqlUtil.getSql("sql.select.query1")));
logger.info("this is a info message 2017-223");
logger.debug("this is a debug message 2017-223");
logger.error("this is a error message 2017-223");
return resultMap;
}
public Map jpaQuery(){
Map resultMap=new HashMap();
resultMap.put("data",testRepository.findAll());
return resultMap;
}
public Map queryAllgps(){
Map resultMap=new HashMap();
resultMap.put("items",testDao.queryForList(SqlUtil.getSql("sql.select.queryallgps")));
return resultMap;
}
public List gouTest(){
List resultList=new ArrayList();
resultList=testDao.queryForList(SqlUtil.getSql("info"));
System.out.println("resultList="+resultList);
return resultList;
}
public List gouTest1(String pn,String sn){
List resultList=new ArrayList();
String sql="select p.pn,s.sn,i.picture,l.devicenumber,p.description,to_char(l.latitude) as latitude ,to_char(l.longitude) as longitude "
+ "from snrreg s left join pnrreg p on s.partid=p.partid left join tools_gps_device_info i on i.partserid=s.partserid"
+ " left join tools_gps_device_location l on l.devicenumber=i.devicenumber"
+ " where l.devicenumber is not null and p.pn like '%"+pn+"%' and s.sn like '%"+sn+"%' order by i.devicenumber";
resultList=testDao.queryForList(sql);
System.out.println("resultList="+resultList);
return resultList;
}
}
|
package gov.polisen.orm.models;
public class PermissionsOnCaseKey {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column permissions_on_cases.device_id
*
* @mbggenerated Fri Apr 25 17:12:46 CEST 2014
*/
private Integer deviceId;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column permissions_on_cases.case_id
*
* @mbggenerated Fri Apr 25 17:12:46 CEST 2014
*/
private Integer caseId;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column permissions_on_cases.user_id
*
* @mbggenerated Fri Apr 25 17:12:46 CEST 2014
*/
private Integer userId;
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table permissions_on_cases
*
* @mbggenerated Fri Apr 25 17:12:46 CEST 2014
*/
public PermissionsOnCaseKey(Integer deviceId, Integer caseId, Integer userId) {
this.deviceId = deviceId;
this.caseId = caseId;
this.userId = userId;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column permissions_on_cases.device_id
*
* @return the value of permissions_on_cases.device_id
*
* @mbggenerated Fri Apr 25 17:12:46 CEST 2014
*/
public Integer getDeviceId() {
return deviceId;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column permissions_on_cases.case_id
*
* @return the value of permissions_on_cases.case_id
*
* @mbggenerated Fri Apr 25 17:12:46 CEST 2014
*/
public Integer getCaseId() {
return caseId;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column permissions_on_cases.user_id
*
* @return the value of permissions_on_cases.user_id
*
* @mbggenerated Fri Apr 25 17:12:46 CEST 2014
*/
public Integer getUserId() {
return userId;
}
} |
package com.vopt.fleetapp.repositories;
import com.vopt.fleetapp.models.Contact;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ContactRepository extends JpaRepository<Contact,Integer> {
}
|
package com.prakash.shopapi.io;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Base class to run API.
*
* @author Prakash Gour
*/
@SpringBootApplication
public class ShopsApiGradleApplication {
public static void main(String[] args) {
SpringApplication.run(ShopsApiGradleApplication.class, args);
}
}
|
/**
* Copyright (C) 2008 Atlassian
*
* 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.atlassian.theplugin.idea.jira;
import com.intellij.openapi.ui.DialogWrapper;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
public class GetUserNameDialog extends DialogWrapper {
private JTextField userName;
private JPanel panel;
public GetUserNameDialog(String issueKey) {
super(false);
init();
setOKActionEnabled(false);
userName.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
update();
}
public void removeUpdate(DocumentEvent e) {
update();
}
public void changedUpdate(DocumentEvent e) {
update();
}
private void update() {
setOKActionEnabled(userName.getText().length() > 0);
}
});
setTitle("New Assignee For " + issueKey);
}
public String getName() {
return userName.getText();
}
protected JComponent createCenterPanel() {
return panel;
}
public JComponent getPreferredFocusedComponent() {
return userName;
}
{
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
$$$setupUI$$$();
}
/**
* Method generated by IntelliJ IDEA GUI Designer
* >>> IMPORTANT!! <<<
* DO NOT edit this method OR call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
panel = new JPanel();
panel.setLayout(new GridBagLayout());
final JLabel label1 = new JLabel();
label1.setText("User Name");
GridBagConstraints gbc;
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(12, 12, 12, 0);
panel.add(label1, gbc);
userName = new JTextField();
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(0, 12, 0, 12);
panel.add(userName, gbc);
final JLabel label2 = new JLabel();
label2.setFont(new Font(label2.getFont().getName(), label2.getFont().getStyle(), 10));
label2.setHorizontalAlignment(0);
label2.setHorizontalTextPosition(0);
label2.setText("Warning: user name is sent to JIRA without validation");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 2;
gbc.weightx = 1.0;
panel.add(label2, gbc);
}
/**
* @noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return panel;
}
}
|
package org.abrahamalarcon.datastream.controller;
import org.abrahamalarcon.datastream.dom.DatastoreMessage;
import org.abrahamalarcon.datastream.dom.response.DatastoreResponse;
import org.abrahamalarcon.datastream.service.DatastoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.stereotype.Controller;
@Controller
public class WebsocketController
{
@Autowired SimpMessageSendingOperations messagingTemplate;
@Autowired DatastoreService datastoreService;
@MessageMapping("/notifyme/{clientId}/{eventId}/{uuid}")
public void subscribeToEvent(@DestinationVariable String clientId,
@DestinationVariable String eventId,
@DestinationVariable String uuid,
@Payload DatastoreMessage message) throws Exception
{
String toReply = "/queue/" + clientId + "/" + eventId;
try
{
DatastoreResponse response = datastoreService.pull(message, eventId);
response.setUuid(uuid);
messagingTemplate.convertAndSend(toReply, response);
}
catch(Exception e)
{
Object obj = new Object(){ public String getMessage(){return e.getMessage();} public String getUuid(){ return uuid;}};
messagingTemplate.convertAndSend(toReply, obj);
}
}
}
|
package com.example.jiaheng.mapsensor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* A simple {@link Fragment} subclass.
*/
public class DataFragment extends Fragment implements SensorService.OnSensorDateTransferListener {
private TextView status;
private TextView direction;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_data, null);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
status = (TextView) view.findViewById(R.id.phone_status);
direction = (TextView) view.findViewById(R.id.phone_direction);
SensorService.registerOnSensorDateTransferListener(this);
}
@Override
public void onSensorDataTransfer(float x, float y, float z) {
status.setText("Y value: " + y);
direction.setText("X value: " + x + getDirection(x));
}
private String getDirection(double x) {
if (x < 5 || 355 < x) {
return " (North)";
} else if (40 < x && x < 50) {
return " (NorthEast)";
} else if (85 < x && x < 95) {
return " (East)";
} else if (130 < x && x < 140) {
return " (SouthEast)";
} else if (175 < x && x < 185) {
return " (South)";
} else if (220 < x && x < 230) {
return " (SouthWest)";
} else if (265 < x && x < 275) {
return " (West)";
} else if (310 < x && x < 320) {
return " (NorthWest)";
} else {
return "";
}
}
@Override
public void onDestroy() {
super.onDestroy();
SensorService.unregisterOnSensorDateTransferListener(this);
}
private static DataFragment dataFragment;
public static DataFragment getInstance() {
if (dataFragment == null) {
dataFragment = new DataFragment();
}
return dataFragment;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.