text
stringlengths 10
2.72M
|
|---|
package mb.tianxundai.com.toptoken.bean;
/**
* Created by daibin on 2018/10/29.
*/
public class AddressBIBean {
private String head;
public String getHead() {
return head;
}
public void setHead(String head) {
this.head = head;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String name;
}
|
package com.example.newadapter;
import java.util.ArrayList;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class AdapterActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_adapter);
final ListView listview = (ListView) findViewById(R.id.listview);
String[] values = new String[] {"Android", "iPhone", "WindowsMobile"};
final ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < values.length; ++i){
list.add(values[i]);
}
final StableArrayAdapter adapter = new StableArrayAdapter(this, values);
listview.setAdapter(adapter);
}
private class StableArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public StableArrayAdapter(Context context, String[] values){
super(context, R.layout.elements, values);
this.context = context;
this.values = values;
}
@Override
public View getView(int position, View contentview, ViewGroup parent){
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.elements, parent, false);
TextView textview = (TextView) rowView.findViewById(R.id.Title);
ImageView imageview = (ImageView) rowView.findViewById(R.id.icon);
textview.setText(values[position]);
return rowView;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.adapter, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
package sundayhomework;
public class DifferentStringClasses {
public static void main(String[] args) {
// TODO Auto-generated method stub
String strManupulation = new String();
strManupulation = "JavaTechnology:123";
String strManupulation2 ="Technology";
// Method Name ChatAt()
//Returns the character of the given index
System.out.println("Character Index :"+strManupulation.charAt(5));
// Compare is use to compare two string .
// 0 means both strings are equals.
System.out.println("Comparison :"+strManupulation.compareTo(strManupulation2));
// Get the sub Sting from the given String
System.out.println(" Substring of the string :"+strManupulation.substring(4, 10));
//Find the Length of the String
System.out.println("Find the lenght of the string: "+strManupulation.length());
//change everything to lowercase
System.out.println("change to lowercase: "+strManupulation.toLowerCase());
}
}
|
package com.csalazar.formularioventas.activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import com.csalazar.formularioventas.R;
import com.csalazar.formularioventas.adapter.ListImagenAdapter;
import com.csalazar.formularioventas.controlador.ConsultaCliente;
import com.csalazar.formularioventas.controlador.ConsultaCorrelativo;
import com.csalazar.formularioventas.modelo.Cliente;
import com.csalazar.formularioventas.modelo.Correlativo;
import com.csalazar.formularioventas.modelo.Imagen;
import java.util.ArrayList;
import java.util.List;
public class ImagenActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private ListImagenAdapter listImagenAdapter;
private Context context;
private List<Imagen> imagenesList;
private Cliente cliente;
private ConsultaCliente consultaCliente;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_imagen);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
// .setAction("Action", null).show();
guardarCliente(view);
}
});
cliente = getIntent().getParcelableExtra("clienteNuevo");
initComponents();
}
private void initComponents(){
context = this;
recyclerView = (RecyclerView) findViewById(R.id.rv_imagenes);
GridLayoutManager gridLayoutManager = new GridLayoutManager(context,3);
recyclerView.setLayoutManager(gridLayoutManager);
imagenesList = new ArrayList<>();
imagenesList.add(new Imagen(R.drawable.usuario));
listImagenAdapter = new ListImagenAdapter(context, imagenesList);
recyclerView.setAdapter(listImagenAdapter);
}
private void guardarCliente(View view){
consultaCliente = new ConsultaCliente(this);
consultaCliente.InsertCliente(cliente);
Intent intent = new Intent();
this.setResult(ImagenActivity.RESULT_OK, intent);
finish();
}
}
|
package com.sda.company.components;
import com.github.javafaker.Faker;
import com.sda.company.model.Company;
import java.util.ArrayList;
import java.util.List;
// aici se fac companiile fake pentru a popula baza de date
public class CustomFakerCompany {
public List<Company> createDummyCompanyList() {
Faker faker = new Faker();
List<Company> companyList = new ArrayList<>();
for (int i = 0; i < 100; i++) {
Company company = new Company();
company.setName(faker.company().name());
company.setAddress(faker.address().fullAddress());
company.setPhoneNumber(faker.phoneNumber().phoneNumber());
company.setEmail(faker.bothify("?????##@gmail.com"));
company.setRegistrationNumber(String.valueOf(faker.number().randomNumber(11, true)));
companyList.add(company);
}
return companyList;
}
}
|
package com.aliam3.polyvilleactive.stepdefs;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import java.util.ArrayList;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpStatus;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import com.aliam3.polyvilleactive.MemoryRule;
import com.aliam3.polyvilleactive.model.gamification.Reward;
import com.aliam3.polyvilleactive.model.user.User;
import com.aliam3.polyvilleactive.service.JourneyService;
import com.aliam3.polyvilleactive.service.RewardService;
import com.aliam3.polyvilleactive.service.UserService;
import io.cucumber.java8.Fr;
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
@RunWith(value = Cucumber.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
@CucumberOptions(plugin = {"pretty"}, features = "src/test/resources/features", glue= {"com.aliam3.polyvilleactive.stepdefs"})
public class RewardStepDefs implements Fr{
@Autowired
UserService userService;
@Autowired
RewardService rewardService;
@Autowired
private MockMvc mvc;
MvcResult result;
int idReward;
User u;
public RewardStepDefs() {
Etantdonné("Un utilisateur est connecté à l'application mobile avec un id égal à {int}",
(Integer id) -> {
userService.users = new ArrayList<>();
u= new User(id, "test", "test", "test@gmail.com");
});
Et("une recompense de {string} coutant {int} points",(String nomRecompense, Integer cout)->{
rewardService.rewards.clear();
idReward=1000;
Reward r= new Reward(idReward, nomRecompense, cout);
rewardService.rewards.add(r);
});
Et("possede {int} points",(Integer cout)->{
u.addScore(cout);
userService.users.add(u);
});
Quand("il veut acheter la reduction {string}", (String nomRecompense)->{
result=mvc.perform(get("/spendpoints?uid="+u.getId()+"&rid="+idReward).contentType("application/json")
).andReturn();
});
Alors("il recoit un code", ()->{
assertEquals(200, result.getResponse().getStatus());
assertEquals(10, result.getResponse().getContentAsString().length());
});
Alors("il recoit une erreur car pas assez de point", ()->{
assertEquals(400, result.getResponse().getStatus());
assertEquals("Not enough points", result.getResponse().getContentAsString());
});
Alors("son nombre de point est de {int}", (Integer points)->{
assertEquals(points, u.getPoints());
});
}
}
|
package com.gsccs.sme.plat.site.service;
import java.util.List;
import java.util.UUID;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.gsccs.sme.plat.site.dao.LinkMapper;
import com.gsccs.sme.plat.site.model.LinkExample;
import com.gsccs.sme.plat.site.model.LinkExample.Criteria;
import com.gsccs.sme.plat.site.model.LinkT;
/**
* 友情链接业务
*
* @创建时间:2015.4.1
*/
@Service
public class LinkServiceImpl implements LinkService {
@Autowired
private LinkMapper linkMapper;
/**
* 添加
*
* @param link
* @return
*/
public String add(LinkT link) {
link.setId(UUID.randomUUID().toString());
link.setIsok("1");
linkMapper.insert(link);
return link.getId();
}
/**
* 根据id查询
*
* @param id
* @return
*/
public LinkT findById(String id) {
return linkMapper.selectByPrimaryKey(id);
}
/**
* 检验是否已存在页面标识
*
* @param siteid
* @param type
* @param isClass
* @return
*/
public boolean hasPagemark(String siteid, String type, boolean isClass,
String pagemark) {
LinkExample example = new LinkExample();
Criteria criteria = example.createCriteria();
criteria.andSiteEqualTo(siteid);
criteria.andTypeEqualTo(type);
criteria.andPagemarkEqualTo(pagemark);
if (isClass) {
criteria.andSql(" (parid is null or parid = '') ");
} else {
criteria.andSql(" (parid is not null and parid != '') ");
}
return linkMapper.countByExample(example) > 0;
}
/**
* 分页查询
*/
public List<LinkT> find(LinkT link, String order, int currPage, int pageSize) {
LinkExample example = new LinkExample();
Criteria criteria = example.createCriteria();
proSearchParam(link, criteria);
if (order != null && order.trim().length() > 0) {
example.setOrderByClause(order);
}
example.setCurrPage(currPage);
example.setPageSize(pageSize);
List<LinkT> listLink= linkMapper.selectPageByExample(example);
for(LinkT linkT:listLink){
if(StringUtils.isNotEmpty(linkT.getParid())){
linkT.setTypestr(linkMapper.selectByPrimaryKey(linkT.getParid()).getName());
}
}
return listLink;
}
/**
* 分页查询
*/
public List<LinkT> findAll(LinkT link, String order) {
LinkExample example = new LinkExample();
Criteria criteria = example.createCriteria();
proSearchParamAll(link, criteria);
if (order != null && order.trim().length() > 0) {
example.setOrderByClause(order);
}
return linkMapper.selectByExample(example);
}
/**
* 统计
*
* @param info
* @return
*/
public int count(LinkT link) {
LinkExample example = new LinkExample();
Criteria criteria = example.createCriteria();
proSearchParam(link, criteria);
return linkMapper.countByExample(example);
}
//获取分类列表
public void proSearchParamAll(LinkT link, Criteria criteria) {
criteria.andParidIsNull();
}
/**
* 处理查询条件
*
* @param info
* @param criteria
*/
public void proSearchParam(LinkT link, Criteria criteria) {
if (link != null) {
if (link.getName() != null && link.getName().trim().length() > 0) {
criteria.andNameLike("%" + link.getName().trim() + "%");
}
if (link.getPagemark() != null
&& link.getPagemark().trim().length() > 0) {
criteria.andPagemarkLike("%" + link.getPagemark().trim() + "%");
}
if ("1".equals(link.getIsclass())) {
criteria.andSql(" (parid is null or parid = '') ");
} else {
criteria.andSql(" (parid is not null and parid != '') ");
}
/*
* if (link.getClassName()!=null &&
* link.getClassName().trim().length()>0) { criteria.andSql(
* " (parid in (select id from cms_link where name like '%"
* +link.getClassName()+"%')) ");; }
*/
if (link.getIsok() != null && link.getIsok().trim().length() > 0) {
criteria.andIsokEqualTo(link.getIsok());
}
if (link.getParid() != null && link.getParid().trim().length() > 0) {
criteria.andParidEqualTo(link.getParid());
}
if (link.getType() != null && link.getType().trim().length() > 0) {
criteria.andTypeEqualTo(link.getType());
}
}
}
/**
* 删除分类
*
* @param id
*/
public void delClass(String id) {
if (id != null && id.trim().length() > 0) {
// 先删除子链接
LinkExample example = new LinkExample();
Criteria criteria = example.createCriteria();
criteria.andParidEqualTo(id);
linkMapper.deleteByExample(example);
// 删除此分类
linkMapper.deleteByPrimaryKey(id);
}
}
/**
* 删除
*
* @param id
*/
public void del(String id) {
if (id != null && id.trim().length() > 0) {
// 删除此分类
linkMapper.deleteByPrimaryKey(id);
}
}
@Override
public void update(LinkT link) {
if (null != link) {
linkMapper.updateByPrimaryKey(link);
}
}
}
|
package com.example.my.practice_bbb7;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Url;
/**
* Created by My on 2016/10/17.
*/
public interface MyretrofitApi {
@GET
Call<ResponseBody>getHttp();
@POST
Call<ResponseBody>downLoad(@Url String url);
@POST
Call<ResponseBody>upLoad(@Url String url);
}
|
package lab2;
import java.text.DecimalFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.Map.Entry.comparingByValue;
import static java.util.stream.Collectors.toMap;
public class lab2 {
// static int[][] scheme = {{0, 0}, {0, 0}};
// static int[][] scheme = {
// {0, 0, 1, 1, 1, 0},
// {0, 0, 1, 1, 0, 1},
// {0, 0, 0, 1, 1, 1},
// {0, 0, 0, 0, 1, 1},
// {0, 0, 0, 0, 0, 0},
// {0, 0, 0, 0, 0, 0}
// };
// static double[] P = {0.66, 0.04, 0.55, 0.63, 0.86, 0.58};
// static double[] P = {0.66, 0.04, 0.55, 0.63, 0.86, 0.58, 0.7, 0.02};
// static int[][] scheme = {
// {0, 1, 1, 0, 0, 0, 0, 0},
// {0, 0, 0, 1, 1, 0, 0, 0},
// {0, 0, 0, 1, 0, 1, 0, 1},
// {0, 0, 0, 0, 1, 1, 0, 1},
// {0, 0, 0, 0, 0, 1, 1, 0},
// {0, 0, 0, 0, 0, 0, 1, 1},
// {0, 0, 0, 0, 0, 0, 0, 0},
// {0, 0, 0, 0, 0, 0, 0, 0}
// };
// static double[] P = {0.5,0.6, 0.7, 0.8, 0.85, 0.9, 0.92, 0.94};
// static double[] P = {0.5, 0.6};
static int t = 10;
public static double Psystem;
public static void main(String[] args) {
int[][] scheme = {
{0, 0, 1, 1, 1, 0},
{0, 0, 1, 1, 0, 1},
{0, 0, 0, 1, 1, 1},
{0, 0, 0, 0, 1, 1},
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0}
};
double[] P = {0.66, 0.04, 0.55, 0.63, 0.86, 0.58};
if (t <= 0) {
System.out.println("Час має бути більше 0.");
System.exit(0);
} else if (scheme.length != P.length) {
System.out.println("Неправильно введені дані.");
System.exit(0);
} else if (scheme.length == 0) {
System.out.println("Матриця порожня.");
System.exit(0);
}
for (double v : P) {
if (v > 1 || v <= 0) {
System.out.println("P має бути від 0 до 1.");
System.exit(0);
}
}
ArrayList<ArrayList<Integer>> table = createAllPossibleWay(scheme);
System.out.println("Всі можливі стани системи:");
HashSet<ArrayList<Integer>> allState = calculateAllState(table, scheme);
System.out.println("-------------------------------");
ArrayList<Double> Pstate = calculatePstate(allState, P);
System.out.println("-------------------------------");
System.out.println("Psystem: " + Psystem);
// double lambda = calculateLambda();
// System.out.println("lambda: " + lambda);
// double T = 1 / lambda;
// System.out.println("T: " + T + " год");
}
//
// private static double calculateLambda() {
// return -Math.log(Psystem) / t;
// }
public static HashSet<ArrayList<Integer>> calculateAllState(ArrayList<ArrayList<Integer>> table, int [][] scheme) {
HashSet<ArrayList<Integer>> result = new HashSet<>();
for (int i = 0; i < table.size(); i++) {
ArrayList<Integer> state = new ArrayList<>(table.get(i));
result.add(new ArrayList<>(state));
addState(result, state, scheme);
}
// for (ArrayList<Integer> p : result) {
// System.out.println(p);
// }
return result;
}
private static void addState(HashSet<ArrayList<Integer>> result, ArrayList<Integer> state, int [][] scheme) {
for (int j = 0; j < scheme.length; j++) {
if (!state.contains(j + 1)) {
state.add(j + 1);
ArrayList<Integer> ad = new ArrayList<>(state);
Collections.sort(ad);
result.add(ad);
addState(result, state, scheme);
state.remove(state.size() - 1);
}
}
}
public static ArrayList<Double> calculatePstate(HashSet<ArrayList<Integer>> allState, double [] P) {
ArrayList<Double> result = new ArrayList<>();
Psystem = 0;
for (ArrayList<Integer> i : allState) {
double Pstate = 1.0;
for (int j = 0; j < P.length; j++) {
if (i.contains(j + 1)) {
Pstate *= P[j];
} else {
Pstate *= ((double) 1 - P[j]);
}
}
result.add(Pstate);
Psystem += Pstate;
// System.out.println(i + " : Pstate = " + Pstate);
}
return result;
}
public static ArrayList<ArrayList<Integer>> createAllPossibleWay(int [][] scheme) {
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
Map<ArrayList<Integer>, Integer> resultMap = new HashMap<>();
HashSet<Integer> dots = new HashSet<>();
for (int i = 0; i < scheme.length; i++) {
if (scheme.length != scheme[i].length) {
System.out.println("Матриця має бути квадратна.");
System.exit(0);
}
for (int j = 0; j < scheme[i].length; j++) {
if (scheme[i][j] != 1 && scheme[i][j] != 0) {
System.out.println("Неправильний ввід суміжно матриці. Має бути або 0 або 1.");
System.exit(0);
}
if (i == 0) {
if (scheme[i][j] == 1) {
if (i == j) {
System.out.println("Неправильно введені дані.");
System.exit(0);
}
dots.add(i);
dots.add(j);
ArrayList<Integer> allWay = new ArrayList<>();
allWay.add(i + 1);
allWay.add(j + 1);
addPoint(result, allWay, j, dots, true, scheme);
if (count) {
result.add(new ArrayList<>(allWay));
}
} else {
boolean add = false;
if (j != 0) {
for (int k = 0; k < scheme[j].length; k++) {
if (scheme[j][k] == 1 && !dots.contains(j)) {
if (k == j) {
System.out.println("Неправильно введені дані.");
System.exit(0);
}
add = true;
dots.add(k);
ArrayList<Integer> allWay = new ArrayList<>();
allWay.add(j + 1);
allWay.add(k + 1);
addPoint(result, allWay, k, dots, true, scheme);
if (count) {
result.add(new ArrayList<>(allWay));
}
}
}
if (add) {
dots.add(j);
}
}
}
}
}
}
for (int i = 0; i < scheme.length; i++) {
if (!dots.contains(i)) {
ArrayList<Integer> finish = new ArrayList<>();
finish.add(i + 1);
result.add(finish);
}
}
// for (ArrayList<Integer> integers : result) {
// resultMap.put(integers, integers.size());
// System.out.println(integers);
// }
// result = findAllPosibleWay(resultMap);
return result;
}
private static ArrayList<ArrayList<Integer>> findAllPosibleWay(Map<ArrayList<Integer>, Integer> resultMap) {
Map<ArrayList<Integer>, Integer> sorted = resultMap
.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue())
.collect(
toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2,
LinkedHashMap::new));
ArrayList<ArrayList<Integer>> keysArr = new ArrayList<>(sorted.keySet());
// System.out.println(keysArr);
for (int i = 0; i < keysArr.size() - 1; i++) {
for (int l = i; l < keysArr.size() - 1; l++) {
// System.out.println("l " + l);
// System.out.println(keysArr.get(i));
// System.out.println(keysArr.get(l + 1));
int count = 0;
for (int j = 0; j < keysArr.get(i).size(); j++) {
for (int k = 0; k < keysArr.get(l + 1).size(); k++) {
if (keysArr.get(i).get(j).equals(keysArr.get(l + 1).get(k))) {
count++;
}
}
}
if (keysArr.get(l + 1).size() - 1 == count && keysArr.get(i).size() != keysArr.get(l + 1).size()) {
// System.out.println(count);
// System.out.println(keysArr.get(l + 1).size() - 1 );
// System.out.println(keysArr.get(l + 1).size());
// System.out.println(l+1);
// System.out.println(keysArr.get(i));
// System.out.println(keysArr.get(l+1));
keysArr.remove(l + 1);
// System.out.println(keysArr);
l--;
}
}
}
// System.out.println(keysArr);
return keysArr;
}
static boolean flag = true;
static boolean count;
private static void addPoint(ArrayList<ArrayList<Integer>> result, ArrayList<Integer> way,
int index, HashSet<Integer> dots, boolean b, int [][] scheme) {
count = b;
for (int i = 0; i < scheme[index].length; i++) {
if (scheme[index][i] == 1) {
way.add(i + 1);
dots.add(i);
flag = true;
addPoint(result, way, i, dots, false, scheme);
if (flag) {
result.add(new ArrayList<>(way));
flag = false;
}
way.remove(way.size() - 1);
}
}
}
}
|
package com.bofsoft.laio.customerservice.Activity.Money;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import com.alibaba.fastjson.JSON;
import com.bofsoft.laio.common.CommandCodeTS;
import com.bofsoft.laio.customerservice.Activity.BaseVehicleActivity;
import com.bofsoft.laio.customerservice.Config.Config;
import com.bofsoft.laio.customerservice.DataClass.BaseResponseStatusData;
import com.bofsoft.laio.customerservice.R;
import com.bofsoft.laio.customerservice.Widget.Widget_Image_Text_Btn;
import com.bofsoft.laio.tcp.DataLoadTask;
import com.bofsoft.sdk.widget.base.Event;
import org.json.JSONObject;
/**
* 余额转出
*
* @author admin
*/
public class BalanceOutActivity extends BaseVehicleActivity implements OnClickListener {
private EditText mEdtOutAccount;
private EditText mEdtPayPasswd;
private Widget_Image_Text_Btn mBtnOut;
private double TransAmount; // 转出金额
private String Password = ""; // 支付密码
private double LimitMinAmount = 0.00;
@Override
public void messageBack(int code, String result) {
switch (code) {
case CommandCodeTS.CMD_SUBMITACCOUNTBALANCETRANSFER_INTF:
submitResult(result);
break;
default:
super.messageBack(code, result);
break;
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState, true);
setContentView(R.layout.activity_balance_out);
Intent intent = getIntent();
TransAmount = intent.getDoubleExtra("BalanceOut", 0);
initView();
}
public void initView() {
mEdtOutAccount = (EditText) findViewById(R.id.edtOutAmount);
mEdtPayPasswd = (EditText) findViewById(R.id.edtPayPasswd);
mBtnOut = (Widget_Image_Text_Btn) findViewById(R.id.btn_Out);
mEdtOutAccount.setText("" + TransAmount);
mEdtOutAccount.setFocusable(false);
if (TransAmount <= LimitMinAmount) {
mBtnOut.setBackgroundResource(R.mipmap.button_send_unclick);
mBtnOut.setEnabled(false);
} else {
mBtnOut.setEnabled(true);
mBtnOut.setBackgroundResource(R.mipmap.button_send);
}
mBtnOut.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_Out:
// String amount = mEdtOutAccount.getText().toString().trim();
// Password = mEdtPayPasswd.getText().toString().trim();
// if (amount.equals("")) {
// showPrompt("请输入您要转出的金额");
// return;
// }
// if (Password.equals("")) {
// showPrompt("请输入您的支付密码");
// return;
// }
try {
// TransAmount = Double.valueOf(amount);
submitBalanceOut();
} catch (NumberFormatException e) {
e.printStackTrace();
showPrompt("请输入正确的金额");
}
break;
default:
break;
}
}
public void submitBalanceOut() {
// Password String 支付密码
// TransAmount Double 转出金额
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("TransAmount", TransAmount);
jsonObject.put("Password", Password);
} catch (Exception e) {
e.printStackTrace();
}
showWaitDialog();
DataLoadTask.getInstance().loadData(CommandCodeTS.CMD_SUBMITACCOUNTBALANCETRANSFER_INTF,
jsonObject.toString(), this);
}
public void submitResult(String result) {
closeWaitDialog();
BaseResponseStatusData data = JSON.parseObject(result, BaseResponseStatusData.class);
if (data.getCode() == 0) {
showPrompt(data.getContent());
} else {
showPrompt(data.getContent(), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
setResult(RESULT_OK);
BalanceOutActivity.this.finish();
}
});
}
}
@Override
protected void setTitleFunc() {
setTitle("余额转出");
}
@Override
protected void setActionBarButtonFunc() {
addLeftButton(Config.abBack.clone());
}
@Override
protected void actionBarButtonCallBack(int id, View v, Event e) {
switch (id) {
case 0:
finish();
break;
}
}
}
|
/*
* Created on 2006-1-19
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.aof.webapp.action.prm.payment;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.aof.component.prm.payment.PaymentMasterService;
import com.aof.component.prm.payment.ProjPaymentTransaction;
import com.aof.core.persistence.Persistencer;
import com.aof.core.persistence.hibernate.Hibernate2Session;
import com.aof.core.persistence.jdbc.SQLExecutor;
import com.aof.core.persistence.jdbc.SQLResults;
import com.aof.core.persistence.util.EntityUtil;
import com.aof.util.Constants;
import com.aof.webapp.action.BaseAction;
/**
* @author CN01558
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class ConfirmPaymentAction extends BaseAction {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
Session hs = Hibernate2Session.currentSession();
String action = request.getParameter("formAction");
String status = request.getParameter("status");
if(action==null){
action = "view";
}
if(status==null){
status = "Post";
}
if(action.equals("view")){
doView(status, hs, request);
}
if(action.equals("pay")){
doPay(hs, request);
doView(status, hs, request);
}
if(action.equals("cancel")){
doCancel(hs, request);
doView(status, hs, request);
}
return mapping.findForward("success");
}
public void doView(String status, Session hs, HttpServletRequest request)
throws HibernateException{
SQLExecutor sqlExec = new SQLExecutor(
Persistencer.getSQLExecutorConnection(
EntityUtil.getConnectionByName("jdbc/aofdb")));
String invCode = request.getParameter("invCode");
String paymentCode = request.getParameter("paymentCode");
String project = request.getParameter("project");
String vendor = request.getParameter("vendor");
String dateStart = request.getParameter("dateStart");
String dateEnd = request.getParameter("dateEnd");
String statement = "";
statement += " select ppt.pay_tran_id tran_id, ";
statement += " ppm.pay_code invoice_id, ";
statement += " pp.pay_id payment_id, ";
statement += " pp.pay_code payment_code, ";
statement += " proj_mstr.proj_id proj_id, ";
statement += " proj_mstr.proj_name proj_name, ";
statement += " proj_mstr.proj_contract_no contract_no, ";
statement += " proj_mstr.contracttype con_type, ";
statement += " p.description vendor, ";
statement += " ppt.pay_amount pay_amount, ";
statement += " curr.curr_name curr_name, ";
statement += " curr.curr_rate rate, ";
statement += " ppt.post_status status, ";
statement += " ppt.post_date post_date, ";
statement += " ppt.pay_date pay_date, ";
statement += " ppt.create_date create_date, ";
statement += " ppt.export_date export_date ";
statement += " from Proj_Payment_Transaction ppt ";
statement += " inner join Proj_Payment pp on ppt.payment_id=pp.pay_id ";
statement += " inner join Proj_Payment_Mstr ppm on ppt.invoice_id=ppm.pay_code ";
statement += " inner join Proj_mstr proj_mstr on pp.pay_proj_id=proj_mstr.proj_id ";
statement += " inner join party p on pp.pay_addr=p.party_id ";
statement += " inner join Currency curr on ppt.currency=curr.curr_id ";
statement += " where 1=1";
if(!status.equals("All")){
statement += " and ppt.post_status='"+status+"' ";
}
if(invCode!=null && !invCode.trim().equals("")){
statement += " and ppm.pay_code like '%"+invCode+"%' ";
}
if(paymentCode!=null && !paymentCode.trim().equals("")){
statement += " and pp.pay_code like '%"+paymentCode+"%' ";
}
if(project!=null && !project.trim().equals("")){
statement += " and (proj_mstr.proj_id like '%"+project+"%' or proj_mstr.proj_name like '%"+project+"%') ";
}
if(vendor!=null && !vendor.trim().equals("")){
statement += " and (p.description like '%"+vendor+"%' or p.party_id like '%"+vendor+"%') ";
}
if(dateStart!=null && !dateStart.trim().equals("")){
statement += " and ppt.pay_date>='"+dateStart+"' ";
}
if(dateEnd!=null && !dateEnd.trim().equals("")){
statement += " and ppt.pay_date<='"+dateEnd+"' ";
}
System.out.println(statement);
SQLResults sr = sqlExec.runQueryCloseCon(statement);
request.setAttribute("result", sr);
}
public void doPay(Session hs, HttpServletRequest request)
throws HibernateException{
String[] idArray = request.getParameterValues("chk");
for(int i=0; i<idArray.length; i++){
Long id = new Long(Long.parseLong(idArray[i]));
ProjPaymentTransaction ppt = (ProjPaymentTransaction)hs.load(ProjPaymentTransaction.class, id);
ppt.setPostStatus(Constants.POST_PAYMENT_TRANSACTION_STATUS_PAID);
PaymentMasterService service = new PaymentMasterService();
service.resetInvoicPayStatus(ppt.getInvoice());
ppt.setPayDate(new Date());
hs.update(ppt);
}
hs.flush();
}
public void doCancel(Session hs, HttpServletRequest request)
throws HibernateException{
Long id = new Long(Long.parseLong(request.getParameter("tranId")));
ProjPaymentTransaction ppt = (ProjPaymentTransaction)hs.load(ProjPaymentTransaction.class, id);
ppt.setPostStatus(Constants.POST_PAYMENT_TRANSACTION_STATUS_REJECTED);
hs.update(ppt);
hs.flush();
}
}
|
package com.example.android.quantitanti.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.android.quantitanti.R;
import com.example.android.quantitanti.database.CostEntry;
import com.example.android.quantitanti.helpers.Helper;
import java.util.List;
import static com.example.android.quantitanti.DailyExpensesActivity.currency1;
import static com.example.android.quantitanti.DailyExpensesActivity.currency2;
import static com.example.android.quantitanti.database.CostEntry.CATEGORY_1;
import static com.example.android.quantitanti.database.CostEntry.CATEGORY_2;
import static com.example.android.quantitanti.database.CostEntry.CATEGORY_3;
import static com.example.android.quantitanti.database.CostEntry.CATEGORY_4;
import static com.example.android.quantitanti.database.CostEntry.CATEGORY_5;
import static com.example.android.quantitanti.database.CostEntry.CATEGORY_6;
import static com.example.android.quantitanti.database.CostEntry.CATEGORY_7;
import static com.example.android.quantitanti.database.CostEntry.CATEGORY_8;
import static com.example.android.quantitanti.database.CostEntry.CATEGORY_9;
public class DailyCostAdapter extends RecyclerView.Adapter<DailyCostAdapter.DailyCostViewHolder> {
// Member variable to handle item clicks
final private DailyItemClickListener mDailyItemClickListener;
// Class variables for the List that holds cost data and the Context
private List<CostEntry> mCostEntries;
private Context mContext;
//private ImageView imgv_category;
public DailyCostAdapter(DailyItemClickListener listener, Context context) {
mDailyItemClickListener = listener;
mContext = context;
}
/**
* Called when ViewHolders are created to fill a RecyclerView.
*
* @return A new DailyCostViewHolder that holds the view for daily costs
*/
@NonNull
@Override
public DailyCostViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
//Inflate the layout to the view
View view = LayoutInflater.from(mContext)
.inflate(R.layout.one_cost_item_view, parent, false);
return new DailyCostViewHolder(view);
}
/**
* Called by the RecyclerView to display data at a specified position in the Cursor.
*
* @param holder The ViewHolder to bind Cursor data to
* @param position The position of the data in the Cursor
*/
@Override
public void onBindViewHolder(@NonNull DailyCostViewHolder holder, int position) {
// Determine the values of the wanted data
CostEntry costEntry = mCostEntries.get(position);
//individual cost on particular day
String oneCostCategory = costEntry.getCategory();
String oneCostName = costEntry.getName();
int oneCostValue = costEntry.getCost();
String oneCostValueString = Helper.fromIntToDecimalString(oneCostValue);
//Set values
holder.tv_costDescription.setText(oneCostName);
holder.tv_costValue.setText(currency1 + oneCostValueString + currency2);
// setting imgv depending on category
switch (oneCostCategory) {
case CATEGORY_1:
holder.imgv_category.setBackgroundResource(R.drawable.car);
break;
case CATEGORY_2:
holder.imgv_category.setBackgroundResource(R.drawable.clothes);
break;
case CATEGORY_3:
holder.imgv_category.setBackgroundResource(R.drawable.food);
break;
case CATEGORY_4:
holder.imgv_category.setBackgroundResource(R.drawable.utilities);
break;
case CATEGORY_5:
holder.imgv_category.setBackgroundResource(R.drawable.groceries);
break;
case CATEGORY_6:
holder.imgv_category.setBackgroundResource(R.drawable.education);
break;
case CATEGORY_7:
holder.imgv_category.setBackgroundResource(R.drawable.sport);
break;
case CATEGORY_8:
holder.imgv_category.setBackgroundResource(R.drawable.cosmetics);
break;
case CATEGORY_9:
holder.imgv_category.setBackgroundResource(R.drawable.other);
break;
default:
break;
}
}
/**
* Returns the number of items to display.
*/
@Override
public int getItemCount() {
if (mCostEntries == null) {
return 0;
}
return mCostEntries.size();
}
public List<CostEntry> getDailyCosts() {
return mCostEntries;
}
/**
* When data changes, this method updates the list of costEntries
* and notifies the adapter to use the new values on it
*/
public void setmDailyCosts(List<CostEntry> costEntries) {
mCostEntries = costEntries;
notifyDataSetChanged();
}
public interface DailyItemClickListener {
void onDailyItemClickListener(int itemId);
}
public class DailyCostViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
ImageView imgv_category;
TextView tv_costDescription;
TextView tv_costValue;
/**
* Constructor for the DailyCostViewHolders.
*
* @param itemView The view inflated in onCreateViewHolder
*/
public DailyCostViewHolder(@NonNull View itemView) {
super(itemView);
// TextViews for itemView
imgv_category = itemView.findViewById(R.id.imgv_category);
tv_costDescription = itemView.findViewById(R.id.tv_costDescription);
tv_costValue = itemView.findViewById(R.id.tv_costValue);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int elementId = mCostEntries.get(getAdapterPosition()).getId();
mDailyItemClickListener.onDailyItemClickListener(elementId);
}
}
}
|
/*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.messaging.handler.invocation.reactive;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.core.KotlinDetector;
import org.springframework.core.MethodParameter;
import org.springframework.core.ReactiveAdapter;
import org.springframework.core.ReactiveAdapterRegistry;
import org.springframework.core.ResolvableType;
import org.springframework.core.codec.Encoder;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.lang.Nullable;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.MessagingException;
import org.springframework.util.Assert;
import org.springframework.util.MimeType;
/**
* Base class for a return value handler that encodes return values to
* {@code Flux<DataBuffer>} through the configured {@link Encoder}s.
*
* <p>Subclasses must implement the abstract method
* {@link #handleEncodedContent} to handle the resulting encoded content.
*
* <p>This handler should be ordered last since its {@link #supportsReturnType}
* returns {@code true} for any method parameter type.
*
* @author Rossen Stoyanchev
* @since 5.2
*/
public abstract class AbstractEncoderMethodReturnValueHandler implements HandlerMethodReturnValueHandler {
private static final ResolvableType VOID_RESOLVABLE_TYPE = ResolvableType.forClass(Void.class);
private static final ResolvableType OBJECT_RESOLVABLE_TYPE = ResolvableType.forClass(Object.class);
private static final String COROUTINES_FLOW_CLASS_NAME = "kotlinx.coroutines.flow.Flow";
protected final Log logger = LogFactory.getLog(getClass());
private final List<Encoder<?>> encoders;
private final ReactiveAdapterRegistry adapterRegistry;
protected AbstractEncoderMethodReturnValueHandler(List<Encoder<?>> encoders, ReactiveAdapterRegistry registry) {
Assert.notEmpty(encoders, "At least one Encoder is required");
Assert.notNull(registry, "ReactiveAdapterRegistry is required");
this.encoders = Collections.unmodifiableList(encoders);
this.adapterRegistry = registry;
}
/**
* The configured encoders.
*/
public List<Encoder<?>> getEncoders() {
return this.encoders;
}
/**
* The configured adapter registry.
*/
public ReactiveAdapterRegistry getAdapterRegistry() {
return this.adapterRegistry;
}
@Override
public boolean supportsReturnType(MethodParameter returnType) {
// We could check canEncode but we're probably last in order anyway
return true;
}
@Override
public Mono<Void> handleReturnValue(
@Nullable Object returnValue, MethodParameter returnType, Message<?> message) {
if (returnValue == null) {
return handleNoContent(returnType, message);
}
DataBufferFactory bufferFactory = (DataBufferFactory) message.getHeaders()
.getOrDefault(HandlerMethodReturnValueHandler.DATA_BUFFER_FACTORY_HEADER,
DefaultDataBufferFactory.sharedInstance);
MimeType mimeType = (MimeType) message.getHeaders().get(MessageHeaders.CONTENT_TYPE);
Flux<DataBuffer> encodedContent = encodeContent(
returnValue, returnType, bufferFactory, mimeType, Collections.emptyMap());
return new ChannelSendOperator<>(encodedContent, publisher ->
handleEncodedContent(Flux.from(publisher), returnType, message));
}
private Flux<DataBuffer> encodeContent(
@Nullable Object content, MethodParameter returnType, DataBufferFactory bufferFactory,
@Nullable MimeType mimeType, Map<String, Object> hints) {
ResolvableType returnValueType = ResolvableType.forMethodParameter(returnType);
ReactiveAdapter adapter = getAdapterRegistry().getAdapter(returnValueType.resolve(), content);
Publisher<?> publisher;
ResolvableType elementType;
if (adapter != null) {
publisher = adapter.toPublisher(content);
Method method = returnType.getMethod();
boolean isUnwrapped = (method != null && KotlinDetector.isSuspendingFunction(method) &&
!COROUTINES_FLOW_CLASS_NAME.equals(returnValueType.toClass().getName()));
ResolvableType genericType = (isUnwrapped ? returnValueType : returnValueType.getGeneric());
elementType = getElementType(adapter, genericType);
}
else {
publisher = Mono.justOrEmpty(content);
elementType = (returnValueType.toClass() == Object.class && content != null ?
ResolvableType.forInstance(content) : returnValueType);
}
if (elementType.resolve() == void.class || elementType.resolve() == Void.class) {
return Flux.from(publisher).cast(DataBuffer.class);
}
Encoder<?> encoder = getEncoder(elementType, mimeType);
return Flux.from(publisher).map(value ->
encodeValue(value, elementType, encoder, bufferFactory, mimeType, hints));
}
private ResolvableType getElementType(ReactiveAdapter adapter, ResolvableType type) {
if (adapter.isNoValue()) {
return VOID_RESOLVABLE_TYPE;
}
else if (type != ResolvableType.NONE) {
return type;
}
else {
return OBJECT_RESOLVABLE_TYPE;
}
}
@Nullable
@SuppressWarnings("unchecked")
private <T> Encoder<T> getEncoder(ResolvableType elementType, @Nullable MimeType mimeType) {
for (Encoder<?> encoder : getEncoders()) {
if (encoder.canEncode(elementType, mimeType)) {
return (Encoder<T>) encoder;
}
}
return null;
}
@SuppressWarnings("unchecked")
private <T> DataBuffer encodeValue(
Object element, ResolvableType elementType, @Nullable Encoder<T> encoder,
DataBufferFactory bufferFactory, @Nullable MimeType mimeType,
@Nullable Map<String, Object> hints) {
if (encoder == null) {
encoder = getEncoder(ResolvableType.forInstance(element), mimeType);
if (encoder == null) {
throw new MessagingException(
"No encoder for " + elementType + ", current value type is " + element.getClass());
}
}
return encoder.encodeValue((T) element, bufferFactory, elementType, mimeType, hints);
}
/**
* Subclasses implement this method to handle encoded values in some way
* such as creating and sending messages.
* @param encodedContent the encoded content; each {@code DataBuffer}
* represents the fully-aggregated, encoded content for one value
* (i.e. payload) returned from the HandlerMethod.
* @param returnType return type of the handler method that produced the data
* @param message the input message handled by the handler method
* @return completion {@code Mono<Void>} for the handling
*/
protected abstract Mono<Void> handleEncodedContent(
Flux<DataBuffer> encodedContent, MethodParameter returnType, Message<?> message);
/**
* Invoked for a {@code null} return value, which could mean a void method
* or method returning an async type parameterized by void.
* @param returnType return type of the handler method that produced the data
* @param message the input message handled by the handler method
* @return completion {@code Mono<Void>} for the handling
*/
protected abstract Mono<Void> handleNoContent(MethodParameter returnType, Message<?> message);
}
|
package cn.test.java8.java8LambadaException;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import java.util.Arrays;
import java.util.HashSet;
/**
* Created by xiaoni on 2019/8/22.
*/
@Slf4j
public class LambadaOutOfBoundsException {
public static void main(String[] args) {
BigBox bigBox = new BigBox();
bigBox.setBoxes(Arrays.asList(new Box("abc", 1L), new Box("def", 2L)));
bigBox.getBoxes().forEach(box -> {
log.info(JSON.toJSONString(box));
});
log.info(new HashSet<String>(Arrays.asList("aaa", "bbb")).toString());
}
}
|
package Cars4x4;
import carInterface.IMotor;
import carInterface.IRelacionesDiferenciales;
import carInterface.ISuspension;
public class CarroDiesel extends Car{
private final IMotor motor;
private final IRelacionesDiferenciales relacion;
private final ISuspension suspension;
//Inyeccion de dependencia
public CarroDiesel(IMotor motor, IRelacionesDiferenciales relacion, ISuspension suspension) {
this.motor = motor;
this.relacion = relacion;
this.suspension = suspension;
}
public String tipoCarroOffRoad() {
System.out.println("\nCarro de Diesel");
System.out.println("Motor tipo: " + motor.tipo());
System.out.println("Relaciones diferenciales tipo: " + relacion.tipo());
System.out.println("Suspension tipo: " + suspension.tipo());
System.out.println("- - - - - - - - - - - - - - - -- - - -- - - - -- - - - -\n");
return "Carro de Diesel\n";
}
}
|
package com.project.android.app.kys.fragments;
import android.app.DialogFragment;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import com.project.android.app.kys.R;
import com.project.android.app.kys.activities.CourseActivity;
import com.project.android.app.kys.adapters.FeedbackListAdapter;
import com.project.android.app.kys.business.Course;
import com.project.android.app.kys.business.Feedback;
import com.project.android.app.kys.business.Professor;
import com.project.android.app.kys.callbacks.ResponseListener;
import com.project.android.app.kys.controller.ViewInformationController;
import com.project.android.app.kys.helper.Constants;
import com.project.android.app.kys.helper.Constants.Tag.BusinessTag;
import com.project.android.app.kys.helper.Util;
import com.project.android.app.kys.popup.AUFeedbackDialog;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class CourseFragment extends Fragment {
public RecyclerView mRecyclerView = null;
public ViewInformationController mViewInfoController;
static CourseFragment mFragment;
public FeedbackListAdapter mAdapter;
public CardView mHeaderCardView;
public TextView mHeaderCourseTitle;
public TextView mHeaderCourseIntials;
public TextView mHeaderCourseCode;
public TextView mHeaderCourseSummary;
public CardView mOverallRatingsCardView;
public RatingBar mOverallRatingBar;
public TextView mFeedbackCountView;
public CardView mUserFeedbackCardView;
public TextView mUserFeedbackUserName;
public TextView mUserFeedbackUserIntials;
public TextView mUserFeedDate;
public TextView mUserFeedbackTitle;
public TextView mUserFeedbackComment;
public TextView mUserFeedbackProfessorName;
public TextView mUserFeedbackCourseName;
public RatingBar mUserFeedbackRatingBar;
public LinearLayout mUserFeedbackLoadingView;
public RelativeLayout mUserFeedbackErrorView;
public TextView mUserFeedbackErrorText;
public CardView mAllFeedbackCardView;
public LinearLayout mAllFeedbackLoadingView;
public RelativeLayout mAllFeedbackErrorView;
public TextView mAllFeedbackErrorText;
public Spinner mSortOptinSpinner;
public Spinner mPorfNameFilterSpinner;
public String mCourseName;
public String mCourseCode;
public String mCourseInitials;
public String mCourseSummary;
public Integer mCourseID;
public Integer mUserID;
private ArrayList<Professor> mProfList;
private Feedback mUserFeedback;
public FloatingActionButton mAddFeedbackButton;
public CourseFragment() {
// Required empty public constructor
}
public static CourseFragment newInstance(Integer courseID, String courseName, String courseSummary, String courseCode, String courseInitials) {
mFragment = new CourseFragment();
Bundle args = new Bundle();
args.putInt(BusinessTag.COURSE_ID, courseID);
args.putString(BusinessTag.COURSE_NAME, courseName);
args.putString(BusinessTag.COURSE_SUMMARY, courseSummary);
args.putString(BusinessTag.COURSE_CODE, courseCode);
args.putString(BusinessTag.COURSE_INITIALS, courseInitials);
mFragment.setArguments(args);
return mFragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mCourseID = getArguments().getInt(BusinessTag.COURSE_ID);
mCourseName = getArguments().getString(BusinessTag.COURSE_NAME);
mCourseSummary = getArguments().getString(BusinessTag.COURSE_SUMMARY);
mCourseCode = getArguments().getString(BusinessTag.COURSE_CODE);
mCourseInitials = getArguments().getString(BusinessTag.COURSE_INITIALS);
}
mUserID = 100;
setTitle(mCourseName);
mViewInfoController = ViewInformationController.createInstance(getActivity());
}
private void setTitle(String deptName) {
if (deptName != null) {
((CourseActivity) getActivity()).getSupportActionBar().setTitle(deptName);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_course, null);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.d("ARJUN", "DrawerFragment() - onViewCreated()");
initViews(view);
initHeaderView();
showUserFeedbackLoadingView();
showAllFeedbackLoadingView();
mRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), mRecyclerView, new ClickListener() {
@Override
public void onClick(View view, int position) {
onListItemClicked(view, position);
}
@Override
public void onLongClick(View view, int position) {
}
}));
requesFeedbackListAdapter();
requesUserFeedbackInfo();
requestProfessorInfo();
}
private void initHeaderView() {
mHeaderCourseIntials.setText(mCourseInitials);
mHeaderCourseTitle.setText(mCourseName);
mHeaderCourseCode.setText(mCourseCode);
mHeaderCourseSummary.setText(mCourseSummary);
}
private void initViews(View view) {
mHeaderCardView = (CardView) view.findViewById(R.id.frag_course_cv_header);
mHeaderCourseTitle = (TextView) view.findViewById(R.id.fch_tv_course_title);
mHeaderCourseIntials = (TextView) view.findViewById(R.id.fch_tv_course_code);
mHeaderCourseCode = (TextView) view.findViewById(R.id.fch_tv_course_code);
mHeaderCourseSummary = (TextView) view.findViewById(R.id.fch_tv_course_summary);
mOverallRatingsCardView = (CardView) view.findViewById(R.id.frag_course_cv_overall_ratings);
mOverallRatingBar = (RatingBar) view.findViewById(R.id.fcor_ratingbar);
mFeedbackCountView = (TextView) view.findViewById(R.id.fcor_feedback_count);
mUserFeedbackCardView = (CardView) view.findViewById(R.id.frag_course_cv_user_feedback);
mUserFeedbackUserName = (TextView) view.findViewById(R.id.fcuf_tv_user_name);
mUserFeedbackUserIntials = (TextView) view.findViewById(R.id.fcuf_tv_initials);
mUserFeedDate = (TextView) view.findViewById(R.id.fcuf_tv_submit_time);
mUserFeedbackTitle = (TextView) view.findViewById(R.id.fcuf_tv_feedback_title);
mUserFeedbackComment = (TextView) view.findViewById(R.id.fcuf_tv_feedback_comment);
mUserFeedbackProfessorName = (TextView) view.findViewById(R.id.fcuf_tv_prof_name);
mUserFeedbackCourseName = (TextView) view.findViewById(R.id.fcuf_tv_course_name);
mUserFeedbackRatingBar = (RatingBar) view.findViewById(R.id.fcuf_ratingbar);
mUserFeedbackLoadingView = (LinearLayout) view.findViewById(R.id.fcuf_loading_view);
mUserFeedbackErrorView = (RelativeLayout) view.findViewById(R.id.fcuf_error_view);
mUserFeedbackErrorText = (TextView) view.findViewById(R.id.fcuf_tv_error);
mAllFeedbackCardView = (CardView) view.findViewById(R.id.frag_course_cv_all_feedback);
mRecyclerView = (RecyclerView) view.findViewById(R.id.fcaf_list_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.requestDisallowInterceptTouchEvent(true);
mAllFeedbackLoadingView = (LinearLayout) view.findViewById(R.id.fcaf_loading_view);
mAllFeedbackErrorText = (TextView) view.findViewById(R.id.fcaf_tv_error);
mAllFeedbackErrorView = (RelativeLayout) view.findViewById(R.id.fcaf_error_view);
mSortOptinSpinner = (Spinner) view.findViewById(R.id.fcaf_spinner_sort);
mPorfNameFilterSpinner = (Spinner) view.findViewById(R.id.fcaf_spinner_filter_professor);
mAddFeedbackButton = (FloatingActionButton) view.findViewById(R.id.floating_af_button);
mAddFeedbackButton.setOnClickListener(mOnAddFeedbackClickListener);
}
public View.OnClickListener mOnAddFeedbackClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
AUFeedbackDialog fragment = AUFeedbackDialog.newInstance();
fragment.setParentFragment(mFragment);
Bundle bundle = new Bundle();
bundle.putInt(BusinessTag.COURSE_ID, mCourseID);
bundle.putString(BusinessTag.COURSE_NAME, mCourseName);
fragment.setArguments(bundle);
fragment.show(getActivity().getFragmentManager(), "missiles");
}
};
private void showAddFeedbackFloatingButton() {
if (mAddFeedbackButton != null) {
mAddFeedbackButton.setVisibility(View.VISIBLE);
}
}
private void hideAddFeedbackFloatingButton() {
if (mAddFeedbackButton != null) {
mAddFeedbackButton.setVisibility(View.GONE);
}
}
private void showUserFeedbackLoadingView() {
if (mUserFeedbackLoadingView != null) {
mUserFeedbackLoadingView.setVisibility(View.VISIBLE);
}
hideUserFeedbackErrorView();
}
private void showAllFeedbackLoadingView() {
if (mAllFeedbackLoadingView != null) {
mAllFeedbackLoadingView.setVisibility(View.VISIBLE);
}
hideRecyclerView();
hideAllFeedbackErrorView();
}
private void hideUserFeedbackLoadingView() {
if (mUserFeedbackLoadingView != null) {
mUserFeedbackLoadingView.setVisibility(View.INVISIBLE);
}
}
private void hideAllFeedbackLoadingView() {
if (mAllFeedbackLoadingView != null) {
mAllFeedbackLoadingView.setVisibility(View.INVISIBLE);
}
}
private void showUserFeedbackErrorView(String errorMsg) {
if (mUserFeedbackErrorView != null && mUserFeedbackErrorText != null) {
mUserFeedbackErrorView.setVisibility(View.VISIBLE);
mUserFeedbackErrorText.setText(errorMsg);
hideUserFeedbackLoadingView();
}
}
private void showAllFeedbackErrorView(String errorMsg) {
if (mAllFeedbackErrorView != null && mAllFeedbackErrorText != null) {
mAllFeedbackErrorView.setVisibility(View.VISIBLE);
mAllFeedbackErrorText.setText(errorMsg);
hideAllFeedbackLoadingView();
hideRecyclerView();
}
}
private void hideUserFeedbackErrorView() {
if (mUserFeedbackErrorView != null) {
mUserFeedbackErrorView.setVisibility(View.INVISIBLE);
}
}
private void hideAllFeedbackErrorView() {
if (mAllFeedbackErrorView != null) {
mAllFeedbackErrorView.setVisibility(View.INVISIBLE);
}
}
private void hideUserFeedbackView() {
if(mUserFeedbackCardView != null) {
mUserFeedbackCardView.setVisibility(View.GONE);
}
}
private void showUserFeedbackView() {
if(mUserFeedbackCardView != null) {
mUserFeedbackCardView.setVisibility(View.VISIBLE);
}
}
public void showRecyclerView() {
if (mRecyclerView != null) {
mRecyclerView.setVisibility(View.VISIBLE);
}
}
public void hideRecyclerView() {
if (mRecyclerView != null) {
mRecyclerView.setVisibility(View.INVISIBLE);
}
}
private void hideNoDataView() {
hideAllFeedbackLoadingView();
hideAllFeedbackErrorView();
}
private void onListItemClicked(View view, int position) {
if (view.getTag() == null) return;
if (view.getTag() instanceof Course) {
Intent intent = new Intent(getActivity(), CourseActivity.class);
intent.putExtra(BusinessTag.COURSE_ID, ((Course) view.getTag()).getCourseId());
intent.putExtra(BusinessTag.COURSE_NAME, ((Course) view.getTag()).getCourseName());
getActivity().startActivity(intent);
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
private void requesUserFeedbackInfo() {
if (mViewInfoController != null) {
ResponseListener.getInstnace().setCourseFeedbackDataListener(mFragment);
mViewInfoController.getFeebdbacksForUser(mUserID, mCourseID);
}
}
private void requesFeedbackListAdapter() {
if (mViewInfoController != null) {
ResponseListener.getInstnace().setCourseFeedbackDataListener(mFragment);
mViewInfoController.getFeebdbacksForCourse(mCourseID);
}
}
private void requestProfessorInfo() {
if (mViewInfoController != null) {
ResponseListener.getInstnace().setCourseFeedbackDataListener(mFragment);
mViewInfoController.getProfessorForCourse(mCourseID);
}
}
public void onAllFeedbackResponse(ArrayList<Feedback> fbList, boolean isError, String error) {
Log.d("ARJUN", "DrawerFragment() - onResponse()");
// if (isError) {
// hideAllFeedbackLoadingView();
// showAllFeedbackErrorView("Failed to load data");
// } else {
// if(fbList == null || fbList.size() <= 0) {
// hideAllFeedbackLoadingView();
// showAllFeedbackErrorView("No data");
// } else {
// setAdapter(fbList);
// }
// }
setAdapter(fbList);
}
public void onUserFeedbackResponse(Feedback userFB, boolean isError, String error) {
Log.d("ARJUN", "DrawerFragment() - onResponse()");
// if (isError) {
// showUserFeedbackErrorView("No data");
// } else {
// if(userFB == null) {
// hideUserFeedbackView();
// } else {
// mUserFeedback = userFB;
// showAddFeedbackFloatingButton();
// loadUserFeebdack(mUserFeedback);
// showUserFeedbackView();
// }
// }
loadUserFeebdack(mUserFeedback);
showUserFeedbackView();
}
public void onProfessorDataResponse(ArrayList<Professor> profList, boolean isError, String error) {
if (isError) {
} else {
mProfList = profList;
loadProfFilterSpinner();
}
}
private void loadProfFilterSpinner() {
ArrayList<String> profNameArray = new ArrayList<String>();
if (mProfList != null && mProfList.size() > 0) {
for(Professor prof : mProfList) {
profNameArray.add(prof.getProfessorName());
}
}
if(mPorfNameFilterSpinner != null && profNameArray.size() > 0) {
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, profNameArray);
dataAdapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
mPorfNameFilterSpinner.setAdapter(dataAdapter);
mPorfNameFilterSpinner.setOnItemSelectedListener(new SpineerOnItemSelectedListener());
}
}
public class SpineerOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(getActivity(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
public int getProfIDAt(int position) {
return mProfList.get(position).getProfessorId();
}
private void loadUserFeebdack(Feedback feedback) {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Date date = new Date();
String currDate = dateFormat.format(date);
Feedback dummyFeedback = new Feedback();
dummyFeedback.setFeedBackId(1);
dummyFeedback.setCourseId(2);
dummyFeedback.setCourseName("Artificial Intellifence");
dummyFeedback.setProfessorId(3);
dummyFeedback.setProfessorName("Vamsi");
dummyFeedback.setUserId(4);
dummyFeedback.setUserName("Arjun Vekariya");
dummyFeedback.setDate(currDate);
dummyFeedback.setTitle("Worst profesor ever");
dummyFeedback.setComment("Always confused professor Always confused professor Always confused professor Always confused professor Always confused professor" +
"Always confused professorAlways confused professorAlways confused professorAlways confused professor Always confused professor");
dummyFeedback.setHelpfulnessCount(50);
dummyFeedback.setUnhelpfulnessCount(6);
dummyFeedback.setIsAnonymous(false);
dummyFeedback.setIsSpam(false);
dummyFeedback.setRating(1.5f);
mUserFeedbackTitle.setText(dummyFeedback.getTitle());
mUserFeedbackUserIntials.setText(Util.getInitials(dummyFeedback.getCourseName()));
mUserFeedbackComment.setText(dummyFeedback.getComment());
mUserFeedbackUserName.setText(dummyFeedback.getUserName());
mUserFeedbackRatingBar.setRating(dummyFeedback.getRating());
mUserFeedDate.setText(dummyFeedback.getDate());
mUserFeedbackCourseName.setText(dummyFeedback.getCourseName());
mUserFeedbackProfessorName.setText(dummyFeedback.getProfessorName());
hideUserFeedbackLoadingView();
}
private void setAdapter(ArrayList<Feedback> fbList) {
ArrayList<Feedback> dummyFeedbackList = new ArrayList<Feedback>();
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Date date = new Date();
String currDate = dateFormat.format(date);
Feedback dummyFeedback1 = new Feedback();
dummyFeedback1.setFeedBackId(1);
dummyFeedback1.setCourseId(2);
dummyFeedback1.setCourseName("Artificial Intellifence");
dummyFeedback1.setProfessorId(3);
dummyFeedback1.setProfessorName("Vamsi");
dummyFeedback1.setUserId(4);
dummyFeedback1.setUserName("Arjun Vekariya");
dummyFeedback1.setDate(currDate);
dummyFeedback1.setTitle("Worst profesor ever");
dummyFeedback1.setComment("Always confused professor");
dummyFeedback1.setHelpfulnessCount(50);
dummyFeedback1.setUnhelpfulnessCount(6);
dummyFeedback1.setIsAnonymous(false);
dummyFeedback1.setIsSpam(false);
dummyFeedback1.setRating(1.5f);
dummyFeedbackList.add(dummyFeedback1);
Feedback dummyFeedback2 = new Feedback();
dummyFeedback2.setFeedBackId(1);
dummyFeedback2.setCourseId(2);
dummyFeedback2.setCourseName("Artificial Intellifence");
dummyFeedback2.setProfessorId(3);
dummyFeedback2.setProfessorName("Vamsi");
dummyFeedback2.setUserId(4);
dummyFeedback2.setUserName("Arjun Vekariya");
dummyFeedback2.setDate(currDate);
dummyFeedback2.setTitle("Worst profesor ever");
dummyFeedback2.setComment("Always confused professor");
dummyFeedback2.setHelpfulnessCount(50);
dummyFeedback2.setUnhelpfulnessCount(6);
dummyFeedback2.setIsAnonymous(false);
dummyFeedback2.setIsSpam(false);
dummyFeedback2.setRating(1.5f);
dummyFeedbackList.add(dummyFeedback2);
dummyFeedbackList.add(dummyFeedback2);
dummyFeedbackList.add(dummyFeedback2);
dummyFeedbackList.add(dummyFeedback2);
dummyFeedbackList.add(dummyFeedback2);
dummyFeedbackList.add(dummyFeedback2);
dummyFeedbackList.add(dummyFeedback2);
dummyFeedbackList.add(dummyFeedback2);
dummyFeedbackList.add(dummyFeedback2);
dummyFeedbackList.add(dummyFeedback2);
dummyFeedbackList.add(dummyFeedback2);
dummyFeedbackList.add(dummyFeedback2);
dummyFeedbackList.add(dummyFeedback2);
dummyFeedbackList.add(dummyFeedback2);
dummyFeedbackList.add(dummyFeedback2);
dummyFeedbackList.add(dummyFeedback2);
dummyFeedbackList.add(dummyFeedback2);
dummyFeedbackList.add(dummyFeedback2);
dummyFeedbackList.add(dummyFeedback2);
dummyFeedbackList.add(dummyFeedback2);
dummyFeedbackList.add(dummyFeedback2);
dummyFeedbackList.add(dummyFeedback2);
dummyFeedbackList.add(dummyFeedback2);
Feedback dummyFeedback3 = new Feedback();
dummyFeedback3.setFeedBackId(1);
dummyFeedback3.setCourseId(2);
dummyFeedback3.setCourseName("Artificial Intellifence");
dummyFeedback3.setProfessorId(3);
dummyFeedback3.setProfessorName("Vamsi");
dummyFeedback3.setUserId(4);
dummyFeedback3.setUserName("Arjun Vekariya");
dummyFeedback3.setDate(currDate);
dummyFeedback3.setTitle("Worst profesor ever");
dummyFeedback3.setComment("Always confused professor");
dummyFeedback3.setHelpfulnessCount(50);
dummyFeedback3.setUnhelpfulnessCount(6);
dummyFeedback3.setIsAnonymous(false);
dummyFeedback3.setIsSpam(false);
dummyFeedback3.setRating(4.5f);
dummyFeedbackList.add(dummyFeedback3);
Feedback dummyFeedback4 = new Feedback();
dummyFeedback4.setFeedBackId(1);
dummyFeedback4.setCourseId(2);
dummyFeedback4.setCourseName("Artificial Intellifence");
dummyFeedback4.setProfessorId(3);
dummyFeedback4.setProfessorName("Vamsi");
dummyFeedback4.setUserId(4);
dummyFeedback4.setUserName("Arjun Vekariya");
dummyFeedback4.setDate(currDate);
dummyFeedback4.setTitle("Worst profesor ever");
dummyFeedback4.setComment("Always confused professor");
dummyFeedback4.setHelpfulnessCount(50);
dummyFeedback4.setUnhelpfulnessCount(6);
dummyFeedback4.setIsAnonymous(false);
dummyFeedback4.setIsSpam(false);
dummyFeedback4.setRating(3.0f);
dummyFeedbackList.add(dummyFeedback4);
Feedback dummyFeedback5 = new Feedback();
dummyFeedback5.setFeedBackId(1);
dummyFeedback5.setCourseId(2);
dummyFeedback5.setCourseName("Artificial Intellifence");
dummyFeedback5.setProfessorId(3);
dummyFeedback5.setProfessorName("Vamsi");
dummyFeedback5.setUserId(4);
dummyFeedback5.setUserName("Arjun Vekariya");
dummyFeedback5.setDate(currDate);
dummyFeedback5.setTitle("Worst profesor ever");
dummyFeedback5.setComment("Always confused professor");
dummyFeedback5.setHelpfulnessCount(50);
dummyFeedback5.setUnhelpfulnessCount(6);
dummyFeedback5.setIsAnonymous(false);
dummyFeedback5.setIsSpam(false);
dummyFeedback5.setRating(1.0f);
dummyFeedbackList.add(dummyFeedback5);
mAdapter = new FeedbackListAdapter(getActivity(), dummyFeedbackList);
if (mRecyclerView != null && mAdapter != null && mAdapter.getItemCount() > 0 && isResumed()) {
showRecyclerView();
hideNoDataView();
Log.d("ARJUN", "setAdapter() - " + mAdapter.getItemCount());
mRecyclerView.setAdapter(mAdapter);
}
}
public static interface ClickListener {
public void onClick(View view, int position);
public void onLongClick(View view, int position);
}
static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
}
}
|
package org.gatein.wcm.ui;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
public class BaseBean {
public String getLocale() {
return FacesContext.getCurrentInstance().getViewRoot().getLocale().getLanguage();
}
public void msg(String msg) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(msg));
}
}
|
package com.kingnode.gou.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
/**
* 商品目录组
*/
@Entity @Table(name="product_catalog") public class ProductCatalog extends BaseEntity{
private static final long serialVersionUID=2753416710803050072L;
private String catalogName;//目录组名称
private String catalogDesc;//目录组备注
private String catalogAttrNames;//目录组属性名称
private String catalogType;//目录组类型
private String catalogTypeName;//目录组名称
public String getCatalogName(){
return catalogName;
}
public void setCatalogName(String catalogName){
this.catalogName=catalogName;
}
@Column(length=2000) public String getCatalogDesc(){
return catalogDesc;
}
public void setCatalogDesc(String catalogDesc){
this.catalogDesc=catalogDesc;
}
@Transient public String getCatalogAttrNames(){
return catalogAttrNames;
}
public void setCatalogAttrNames(String catalogAttrNames){
this.catalogAttrNames=catalogAttrNames;
}
public String getCatalogType(){
return catalogType;
}
public void setCatalogType(String catalogType){
this.catalogType=catalogType;
}
@Transient
public String getCatalogTypeName(){
if("SHOP".equals(this.catalogType)){
return "商品属性";
}
if("SPEC".equals(this.catalogType)){
return "商品规格";
}
return catalogTypeName;
}
public void setCatalogTypeName(String catalogTypeName){
this.catalogTypeName=catalogTypeName;
}
}
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Stack;
public class Test {
private static final String NULL_NODE = "null";
private static final String LIST_SEPARATOR = ", ";
public void solution(Node root) {
if (root == null) {
return;
}
String serializedTree = serialize(root);
System.out.println(serializedTree);
Node newRoot = deserialize(serializedTree);
String reserializedTree = serialize(newRoot);
System.out.println(reserializedTree); // it should be the same as serializedTree
}
private String serialize(Node root) {
StringBuilder stringBuilder = new StringBuilder();
buildString(stringBuilder, root);
return stringBuilder.toString();
}
private void buildString(StringBuilder stringBuilder, Node node) {
if (node == null) {
stringBuilder.append(NULL_NODE).append(LIST_SEPARATOR);
} else {
stringBuilder.append(node.val).append(LIST_SEPARATOR);
buildString(stringBuilder, node.left);
buildString(stringBuilder, node.right);
}
}
public Node deserialize(String data) {
Queue<String> nodes = new LinkedList<>();
nodes.addAll(Arrays.asList(data.split(LIST_SEPARATOR)));
return buildTree(nodes);
}
private Node buildTree(Queue<String> nodes) {
String val = nodes.poll();
if (val.equals(NULL_NODE)) {
return null;
} else {
Node node = new Node(Integer.valueOf(val));
node.left = buildTree(nodes);
node.right = buildTree(nodes);
return node;
}
}
private static class Node {
int val;
Node left;
Node right;
Node(int theVal) {
val = theVal;
}
}
public static void main(String[] args) {
Node n1 = new Node(1);
Node n2 = new Node(2);
Node n3 = new Node(3);
Node n4 = new Node(4);
Node n5 = new Node(5);
Node n6 = new Node(6);
Node n7 = new Node(7);
n1.left = n2;
n1.right = n3;
n3.left = n4;
n3.right = n5;
Test test = new Test();
test.solution(n1);
}
}
|
/**
* @Author: Mahmoud Abdelrahman
* Course Service class is where the code responsible for implementing the course controller methods
* implemented.
*/
package com.easylearn.easylearn.service;
import com.easylearn.easylearn.entity.Appointment;
import com.easylearn.easylearn.entity.Course;
import com.easylearn.easylearn.entity.Student;
import com.easylearn.easylearn.mapper.CourseMapper;
import com.easylearn.easylearn.model.CourseReqDTO;
import com.easylearn.easylearn.model.CourseRespDTO;
import com.easylearn.easylearn.model.StudentRespDTO;
import com.easylearn.easylearn.repository.CourseRepository;
import com.easylearn.easylearn.validation.AppointmentValidator;
import com.easylearn.easylearn.validation.CourseValidator;
import com.easylearn.easylearn.validation.StudentValidator;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Log4j2
@Service
@Transactional
public class CourseService {
private final CourseRepository courseRepository;
private final CourseMapper courseMapper;
private final CourseValidator courseValidator;
private final AppointmentValidator appointmentValidator;
private final StudentValidator studentValidator;
@Autowired
public CourseService(CourseRepository courseRepository, CourseMapper courseMapper, CourseValidator courseValidator, AppointmentValidator appointmentValidator, StudentValidator studentValidator) {
this.courseRepository = courseRepository;
this.courseMapper = courseMapper;
this.courseValidator = courseValidator;
this.appointmentValidator = appointmentValidator;
this.studentValidator = studentValidator;
}
public ResponseEntity<CourseRespDTO> createCourse(CourseReqDTO request) {
log.info(" *** START OF SAVING COURSE *** ");
Course course = courseMapper.mapToEntity(request);
course = courseMapper.mapToEntity(request);
course = courseRepository.save(course);
CourseRespDTO response = courseMapper.mapToDTO(course);
log.info(" *** END OF SAVING COURSE *** ");
return ResponseEntity.status(HttpStatus.CREATED).body(response);
}
public CourseRespDTO findCourseById(Long courseId) {
log.info(" *** START OF FINDING COURSE BY ID *** ");
Course course = courseValidator.validateExistence(courseId);
CourseRespDTO response = courseMapper.mapToDTO(course);
log.info(" *** END OF FINDING COURSE BY ID *** ");
return response;
}
public ResponseEntity<List<CourseRespDTO>> findAllCourses(Long teacherId, Long studentId, Long parentId, Boolean ideal) {
log.info(" *** START OF FINDING ALL COURSES *** ");
Set<Course> courses;// = courseRepository.findAll(Sort.by("courseCode"));
if (teacherId != null) {
courses = courseRepository.findAllByTeacherId(teacherId, Sort.by("courseCode"));
} else if (studentId != null) {
courses = courseRepository.findAllByStudentsId(studentId, Sort.by("courseCode"));
} else if (parentId != null) {
courses = courseRepository.findAllCoursesOfParentsStudents(parentId);
} else if (ideal != null && ideal) {
courses = courseRepository.findAllByTeacherIdNull(Sort.by("courseCode"));
} else {
courses = courseRepository.findAll(Sort.by("courseCode"));
}
if (courses.isEmpty())
return ResponseEntity.noContent().build();
List<CourseRespDTO> coursesResponse = new ArrayList<>(courses.size());
courses.forEach(course -> coursesResponse.add(courseMapper.mapToDTO(course)));
log.info(" *** END OF FINDING ALL COURSES *** ");
return ResponseEntity.ok(coursesResponse);
}
public CourseRespDTO updateCourse(Long courseId, CourseReqDTO request) {
log.info(" *** START OF UPDATING COURSE BY ID *** ");
Course course = courseValidator.validateExistence(courseId);
course = courseMapper.mapToEntity(course, request);
courseRepository.save(course);
CourseRespDTO response = courseMapper.mapToDTO(course);
log.info(" *** END OF UPDATING COURSE BY ID *** ");
return response;
}
public CourseRespDTO assignAppointmentsToCourse(Long courseId, Set<Long> appointmentIds) {
log.info(" *** START OF ASSIGNING APPOINTMENTS TO COURSE BY IDS *** ");
Set<Appointment> appointments = new HashSet<>();
Course course = courseValidator.validateExistence(courseId);
appointmentIds.forEach(appointmentId -> appointments.add(appointmentValidator.validateExistence(appointmentId)));
course.addAppointments(appointments);
courseRepository.save(course);
CourseRespDTO response = courseMapper.mapToDTO(course);
log.info(" *** END OF ASSIGNING APPOINTMENTS TO COURSE BY IDS *** ");
return response;
}
public CourseRespDTO assignStudentsToCourse(Long courseId, Set<Long> studentIds) {
log.info(" *** START OF ASSIGNING STUDENTS TO COURSE BY ID *** ");
Course course = courseValidator.validateExistence(courseId);
Set<Student> students = new HashSet<>();
studentIds.forEach(studentId -> students.add(studentValidator.validateExistence(studentId)));
course.addStudents(students);
courseRepository.save(course);
CourseRespDTO response = courseMapper.mapToDTO(course);
log.info(" *** END OF ASSIGNING STUDENTS TO COURSE BY ID *** ");
return response;
}
public ResponseEntity deleteCourse(Long courseId) {
log.info(" *** START OF DELETING COURSE BY ID *** ");
Course course = courseValidator.validateExistence(courseId);
courseRepository.delete(course);
log.info(" *** END OF DELETING COURSE BY ID *** ");
return ResponseEntity.noContent().build();
}
}
|
package com.yang.Dao;
import com.yang.Beans.Dish;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class DishDao extends Connector {
public DishDao(int id, String name, String info) {
setId(id);
setInfo(info);
setName(name);
}
public DishDao(String name, String info) {
this.name = name;
this.info = info;
}
public DishDao(int id, String name) {
this.id = id;
this.name = name;
}
public DishDao(){
}
public ArrayList<Dish> AllDishs(){
ArrayList<Dish> dList = new ArrayList<Dish>();
String sql = "SELECT dish.id, dish.name, dish.info FROM dish";
List<Map<String, Object>> list=connect(sql);
for(int i=0;i<list.size();i++){
Dish d = new Dish(new Integer(list.get(i).get("id").toString()),list.get(i).get("name").toString(),list.get(i).get("info").toString());
dList.add(d);
}
return dList;
}
public boolean check(){
String sql = "SELECT id,name,info FROM dish WHERE id = '" + this.id + "\'AND name=\'"+this.name+"\'";
List<Map<String, Object>> list=connect(sql);
if(list.size()>0){
return true;
}
else{
return false;
}
}
public boolean create(){
String sql = "INSERT INTO dish VALUES ("+this.id+",\'"+this.name+"\',\'" + this.info + "\')";
int i=update(sql);
if(i!=0&&check()){
return true;
}
else{
return false;
}
}
public boolean delete(){
String sql = "DELETE FROM dish WHERE id = '"+this.id+"\'AND name=\'"+this.name+"\'";
int i=update(sql);
if(i!=0){
return true;
}
else{
return false;
}
}
public boolean update(){
String sql = "UPDATE dish SET id ="+ this.id+", name=\'"+this.name+"\', info=\'"+this.info+"\' WHERE id =" + this.id ;
int i=update(sql);
if(i!=0){
return true;
}
else{
return false;
}
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
private int id;
private String name;
private String info;
public static void main(String[] args) {
DishDao test = new DishDao(101,"test2","test.com");
System.out.println(test.create());
// DishDao test = new DishDao(101,"test2");
// System.out.println(test.delete());
// DishDao test = new DishDao(0,"test2");
//
// System.out.println(test.delete());
// DishDao test = new DishDao();
// ArrayList<Dish> rec = test.AllDishs();
//
// for(int i = 0; i <rec.size(); i++){
// System.out.print("gaga");
// System.out.println(rec.get(i).getDishName());
// System.out.print("gaga");
// }
}
}
|
package pl.dkiszka.bank.handlers;
import pl.dkiszka.bank.events.UserRegisteredEvent;
import pl.dkiszka.bank.events.UserRemovedEvent;
import pl.dkiszka.bank.events.UserUpdatedEvent;
/**
* @author Dominik Kiszka {dominikk19}
* @project bank-application
* @date 21.04.2021
*/
public interface UserEventHandler {
void on(UserRegisteredEvent event);
void on(UserUpdatedEvent event);
void on(UserRemovedEvent event);
}
|
package wyrazenia;
import java.util.HashMap;
public class Zmienna extends Wyrazenie {
int numer;
static HashMap<Integer, Zmienna> zmienne = new HashMap<>();
@Override
protected int precedence() {
return 0;
}
private Zmienna(int numer) {
this.numer = numer;
}
public static Zmienna daj(int numer) {
if (zmienne.containsKey(numer)) {
return zmienne.get(numer);
}
zmienne.put(numer, new Zmienna(numer));
return zmienne.get(numer);
}
@Override
public String toString() {
return "x" + String.valueOf(numer);
}
@Override
public boolean wartosc(boolean... wartosciowanie_zmiennych) {
return wartosciowanie_zmiennych[numer];
}
}
|
package com.company;
public interface Equipment {
public void increaseDamage(int tamadoKocka, int sebzoKocka);
public void inceaseAC(int armor);
public void chooseWarriorEquipment(Karakter karakter);
public void chooseArcherEquipment();
public String toStringEquipment(Karakter kari);
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.innovaciones.reporte.dao;
import com.innovaciones.reporte.model.DetalleReporteInstalacionNueva;
import com.innovaciones.reporte.model.DetalleReporteTemporal;
import java.io.Serializable;
import lombok.Setter;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
/**
*
* @author pisama
*/
@Repository
public class DetalleReporteTemporalDAOImpl implements DetalleReporteTemporalDAO, Serializable {
@Setter
private SessionFactory sessionFactory;
@Override
public DetalleReporteTemporal addDetalleReporteTemporal(DetalleReporteTemporal detalleReporteTemporal) {
sessionFactory.getCurrentSession().saveOrUpdate(detalleReporteTemporal);
return detalleReporteTemporal;
}
@Override
public DetalleReporteTemporal updateDetalleReporteTemporal(DetalleReporteTemporal detalleReporteTemporal) {
sessionFactory.getCurrentSession().update(detalleReporteTemporal);
return detalleReporteTemporal;
}
}
|
/*
* 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 wholesalemarket_SMP;
import jade.core.AID;
import jade.core.Agent;
import jade.lang.acl.ACLMessage;
import java.io.File;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import static javax.xml.bind.DatatypeConverter.parseFloat;
import marketpool.tools.AgentsFromExcel;
import scheduling.ProducerScheduling;
/**
*
* @author Administrator
*/
public class InputData_Agents extends javax.swing.JFrame {
private SMP_Market_Controller controller;
private ArrayList<String> agentList;
private ArrayList<AgentData> agent_offers = new ArrayList<>();
/*private ArrayList<String> sellerList;
private ArrayList<String> buyerList;
private ArrayList<AgentData> bids = new ArrayList<>();
private ArrayList<AgentData> offers = new ArrayList<>();*/
private ArrayList<Float> uploadBids_price = new ArrayList<>();
private ArrayList<Float> uploadBids_power = new ArrayList<>();
private ArrayList<double[]> uploadBids_pricefile = new ArrayList<>();
private ArrayList<double[]> uploadBids_powerfile = new ArrayList<>();
private ArrayList<double[]> uploadOffers_pricefile = new ArrayList<>();
private ArrayList<double[]> uploadOffers_powerfile = new ArrayList<>();
private ArrayList<String> uploadOffers_namefile = new ArrayList<>();
private ArrayList<String> uploadBids_namefile = new ArrayList<>();
private DefaultTableModel model;
private SMP_DynamicWindow openDynamicWindow;
private String outputfilename = "output.csv";
private String[] agentName;
private int startHour;
private Agent market;
private int endHour;
private boolean isSeller;
private String nameLabel;
private static final String SEARCH_INFO = "Search...";
/**
* Creates new form InputData_Seller
*/
public InputData_Agents(Agent Market, SMP_Market_Controller _controller, boolean _isSeller, int _startHour, int _endHour) {
controller = _controller;
agentList = new ArrayList<>();
isSeller = _isSeller;
initComponents();
defineWindow();
startHour = _startHour;
endHour = _endHour;
market = Market;
// try {
//
// uploadFile("input.xlsx", "output-sym.csv");
// } catch (Exception ex) {
// System.out.println("InputData.java / InputData function -> " + ex);
// readButton.setEnabled(false);
// }
setPanel(isSeller);
submitButton.requestFocusInWindow();
startTable();
setAgentComboBox();
}
private void defineWindow() {
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.readButton.setVisible(false);
}
private void setAgentComboBox() {
if (isSeller) {
agentName = controller.getSellerNames();
} else {
agentName = controller.getBuyerNames();
}
initComboBox();
}
public void initComboBox() {
boolean verif;
jComboBox_SelectAgent.removeAllItems();
jComboBox_SelectAgent.addItem("Select Agent");
if (agentList.isEmpty()) {
for (int i = 0; i < agentName.length; i++) {
jComboBox_SelectAgent.addItem(agentName[i]);
}
} else {
for (int i = 0; i < agentName.length; i++) {
verif = false;
for (String name : agentList) {
if (name.equalsIgnoreCase(agentName[i])) {
verif = true;
break;
}
}
if (!verif) {
jComboBox_SelectAgent.addItem(agentName[i]);
}
}
}
if (jComboBox_SelectAgent.getItemCount() == 0) {
jComboBox_SelectAgent.addItem("");
}
jComboBox_SelectAgent.setSelectedIndex(0);
}
private void setPanel(boolean _isSeller) {
String panelName;
if (_isSeller) {
this.setTitle("Generators Offers");
panelName = "Generators Data";
jLabel_selectAgent.setText("Generator:");
} else {
this.setTitle("Retailers Offers");
panelName = "Retailers Data";
jLabel_selectAgent.setText("Retailer:");
}
TitledBorder title;
title = BorderFactory.createTitledBorder(panelName);
title.setTitleJustification(TitledBorder.CENTER);
title.setTitlePosition(TitledBorder.TOP);
jPanel3.setBorder(title);
}
private void startTable() {
defineTable(agentTable, agent_offers);
}
public void defineTable(JTable table, ArrayList<AgentData> list) {
sortList(list);
model = new DefaultTableModel() {
@Override
public Class<?> getColumnClass(int Column) {
switch (Column) {
case 0:
return String.class;
case 1:
return Integer.class;
case 2:
return Boolean.class;
case 3:
return Boolean.class;
default:
return String.class;
}
}
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
table.setModel(model);
model.addColumn("Name");
model.addColumn("ID");
model.addColumn("Price");
model.addColumn("Power");
for (int i = 0; i < list.size(); i++) {
model.addRow(new Object[0]);
model.setValueAt(list.get(i).getAgent(), i, 0);
model.setValueAt(list.get(i).getId(), i, 1);
model.setValueAt(list.get(i).getStatus(), i, 2);
model.setValueAt(list.get(i).getStatus(), i, 3);
}
configTable(model, table);
}
private void sortList(ArrayList<AgentData> _list) {
for (int i = 0; i < _list.size() - 1; i++) {
for (int j = i; j < _list.size() - i - 1; j++) {
if (_list.get(j).getId() > _list.get(j + 1).getId()) {
AgentData temp = _list.get(j + 1);
_list.set(j + 1, _list.get(j));
_list.set(j, temp);
}
}
}
}
private void configTable(TableModel _tableSupplierModel, JTable _table) {
_table.setAutoscrolls(true);
_table.setShowGrid(true);
_table.setEnabled(true);
for (int i = 0; i < _tableSupplierModel.getColumnCount(); i++) {
if (i == 0) {
_table.getColumnModel().getColumn(i).setMinWidth(100);
_table.getColumnModel().getColumn(i).setPreferredWidth(100);
} else {
_table.getColumnModel().getColumn(i).setMinWidth(10);
_table.getColumnModel().getColumn(i).setPreferredWidth(10);
}
}
DefaultTableCellRenderer render = new DefaultTableCellRenderer();
render.setHorizontalAlignment(JLabel.CENTER);
_table.setDefaultRenderer(Object.class, render);
}
public void setList(String _name, int _ID, ArrayList<Float> _price, ArrayList<Float> _power, boolean _isSeller) {
int id;
id = verifID(_ID, agent_offers);
agent_offers.add(new AgentData(_name, id, roundValue(_price, 2), roundValue(_power, 2)));
defineTable(agentTable, agent_offers);
startTable();
read_usedAgents();
initComboBox();
}
private void create_uploadArray(ArrayList<Float> _price, ArrayList<Float> _power) {
double[] price = new double[_price.size()];
double[] power = new double[_power.size()];
for (int i = 0; i < _price.size(); i++) {
price[i] = _price.get(i);
power[i] = _power.get(i);
}
if (isSeller) {
uploadOffers_powerfile.add(power);
uploadOffers_pricefile.add(price);
} else {
uploadBids_powerfile.add(power);
uploadBids_pricefile.add(price);
}
}
public ArrayList<double[]> getUploadBids_pricefile() {
return uploadBids_pricefile;
}
public ArrayList<double[]> getUploadBids_powerfile() {
return uploadBids_powerfile;
}
public ArrayList<double[]> getUploadOffers_pricefile() {
return uploadOffers_pricefile;
}
public ArrayList<double[]> getUploadOffers_powerfile() {
return uploadOffers_powerfile;
}
public ArrayList<String> getUploadOffers_namefile() {
return uploadOffers_namefile;
}
public ArrayList<String> getUploadBids_namefile() {
return uploadBids_namefile;
}
private ArrayList<Float> roundValue(ArrayList<Float> _values, int roundPrecision) {
ArrayList<Float> finalValue = new ArrayList<>();
int auxValue;
for (Float value1 : _values) {
auxValue = (int) (value1 * Math.pow(10, roundPrecision));
finalValue.add((float) (auxValue / Math.pow(10, roundPrecision)));
}
return finalValue;
}
private int verifID(int _id, ArrayList<AgentData> _list) {
int id = _id;
if (id == 0) {
for (int i = 1; i < _list.size() + 2; i++) {
id = 0;
for (AgentData agent : _list) {
if (agent.getId() == i) {
id = -1;
break;
}
}
if (id == 0) {
id = i;
break;
}
}
}
return id;
}
private void deleteAgent(JTable table, ArrayList<AgentData> _list) {
model = (DefaultTableModel) table.getModel();
try {
if (table.getSelectedRow() != -1) {
int[] row = table.getSelectedRows();
for (int i = 0; i < row.length; i++) {
for (AgentData agent : _list) {
if (agent.getId() == (Integer) model.getValueAt(row[i], 1)) {
_list.remove(agent);
break;
}
}
}
} else {
if (_list.size() > 0) {
_list.remove(_list.size() - 1);
}
}
defineTable(table, _list);
sortList(_list);
read_usedAgents();
initComboBox();
} catch (Exception ex) {
JOptionPane.showMessageDialog(this,
"Table is Empty",
"Information",
JOptionPane.INFORMATION_MESSAGE);
}
}
public void setComboBox_Index() {
jComboBox_SelectAgent.setSelectedIndex(0);
}
private void updateAgentInfo(JTable table, ArrayList<AgentData> _list) {
int agentID = 0;
model = (DefaultTableModel) table.getModel();
ArrayList<double[]> price = new ArrayList<double[]>(24);
ArrayList<double[]> power = new ArrayList<double[]>(24);
double[] Price = new double[24];
double[] Power = new double[24];
try {
if (table.getSelectedRow() != -1) {
int row = table.getSelectedRow();
for (AgentData agent : _list) {
if (agent.getId() == (Integer) model.getValueAt(row, 1)) {
agentID = agent.getId();
// for (int i = 0; i < 3; i++) {
for (int j = 0; j < price.get(0).length; j++) {
Price[j] = agent.getPeriodPrice(j);
Power[j] = agent.getPeriodPower(j);
}
price.add(Price);
power.add(Power);
}
_list.remove(agent);
break;
// }
}
for (int i = 0; i < agentList.size(); i++) {
if (agentList.get(i).equalsIgnoreCase(model.getValueAt(row, 0).toString())) {
agentList.remove(i);
}
}
openDynamicWindow = new SMP_DynamicWindow(this, isSeller, startHour, endHour, price, power, model.getValueAt(row, 0).toString(), agentID, model.getValueAt(row, 0).toString());
openDynamicWindow.createWindow();
openDynamicWindow.updateValues(price, power);
sortList(_list);
}
} catch (Exception ex) {
System.out.println("InputData.java / updateAgentInfo/ " + ex);
}
}
public String uploadFile(String inputfile, String outputfile) {
String warning = "";
if (inputfile != null && !inputfile.isEmpty()) {
AgentsFromExcel agts = new AgentsFromExcel();
if (agts.readFile(inputfile)) {
ArrayList<Float> bPrices;
ArrayList<Float> bPowers;
uploadBids_price.removeAll(uploadBids_price);
uploadBids_power.removeAll(uploadBids_power);
if (isSeller) {
String[] anames = agts.getAgentsNames("Sellers");
for (int i = 1; i <= anames.length; i++) {
bPrices = agts.getAgentPrices("Sellers", anames[i - 1]);
bPowers = agts.getAgentPowers("Sellers", anames[i - 1]);
if (agts.getCellValue("Sellers", (2*i), 26)!= ""){
uploadOffers_namefile.add(agts.getCellValue("Sellers", (2*i), 26));
}else{
uploadOffers_namefile.add(anames[i - 1]);
}
create_uploadArray(bPrices, bPowers);
}
// for (int j=0;j<5;j++){
// System.out.println("\nLinha "+j+": ");
// for (int i=0;i<30;i++){
// System.out.println("Coluna "+i+": "+ agts.getCellValue("Sellers", j, i));
// }
// }
} else {
String[] anames = agts.getAgentsNames("Buyers");
for (int i = 1; i <= anames.length; i++) {
bPrices = agts.getAgentPrices("Buyers", anames[i - 1]);
bPowers = agts.getAgentPowers("Buyers", anames[i - 1]);
// uploadBids_namefile.add("Bid "+i);
if (agts.getCellValue("Buyers", (2*i), 26)!= ""){
uploadBids_namefile.add(agts.getCellValue("Buyers", (2*i), 26));
}else{
uploadBids_namefile.add(anames[i - 1]);
}
create_uploadArray(bPrices, bPowers);
}
}
} else {
warning += "Error opening the input file!\nCheck if the file is in the correct location.";
}
} else {
warning += "Invalid filename!\nCheck if the file is in the correct location.";
}
//
if (outputfile != null && !outputfile.isEmpty()) {
this.outputfilename = outputfile;
}
return warning;
}
public void readFile(String inputfile, String outputfile) {
if (inputfile != null && !inputfile.isEmpty()) {
// Get Agents From Excel file
AgentsFromExcel agts = new AgentsFromExcel();
if (agts.readFile(inputfile)) {
agent_offers.removeAll(agent_offers);
ArrayList<Float> bPrices;
ArrayList<Float> bPowers;
if (isSeller) {
String[] anames = agts.getAgentsNames("Sellers");
for (int i = 1; i <= anames.length; i++) {
bPrices = agts.getAgentPrices("Sellers", anames[i - 1]);
bPowers = agts.getAgentPowers("Sellers", anames[i - 1]);
uploadOffers_namefile.add(agts.getCellValue("Sellers", (2*i)+2, 27));
create_uploadArray(bPrices, bPowers);
setList("Seller" + i, 0, bPrices, bPowers, true);
}
} else {
String[] anames = agts.getAgentsNames("Buyers");
for (int i = 1; i <= anames.length; i++) {
bPrices = agts.getAgentPrices("Buyers", anames[i - 1]);
bPowers = agts.getAgentPowers("Buyers", anames[i - 1]);
uploadBids_namefile.add("Bid "+i);
create_uploadArray(bPrices, bPowers);
setList("Buyer" + i, 0, bPrices, bPowers, false);
}
}
defineTable(agentTable, agent_offers);
} else {
JOptionPane.showMessageDialog(null,
"Error opening the input file!\nCheck if the file is in the correct location.",
"Market Simulator",
JOptionPane.INFORMATION_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(null,
"Invalid filename!\nCheck if the file is in the correct location.",
"Market Simulator",
JOptionPane.INFORMATION_MESSAGE);
}
//
if (outputfile != null && !outputfile.isEmpty()) {
this.outputfilename = outputfile;
}
}
private void read_usedAgents() {
DefaultTableModel agent_model = (DefaultTableModel) agentTable.getModel();
agentList.removeAll(agentList);
for (int i = 0; i < agent_model.getRowCount(); i++) {
agentList.add(agentTable.getValueAt(i, 0).toString());
}
}
public ArrayList<String> getAgentList() {
return agentList;
}
public void setCaseStudydata(String Case) {
isSeller=true;
try {
// System.out.println("files\\"+jComboBox_SelectAgent.getSelectedItem()+"\\input.xlsx");
// JOptionPane.showMessageDialog(null, "Loading Data. Select when finished", "Invalid Selection", JOptionPane.INFORMATION_MESSAGE);
uploadFile("files\\"+Case+"\\input.xlsx", "output-sym.csv");
} catch (Exception ex) {
System.out.println("InputData.java / InputData function -> " + ex);
readButton.setEnabled(false);
}
// ArrayList<ArrayList<Float>> addPrice = new ArrayList<ArrayList<Float>>();
// ArrayList<ArrayList<Float>> addPower = new ArrayList<ArrayList<Float>>();
ArrayList<Float> addPrices = new ArrayList<Float>();
ArrayList<Float> addPowers = new ArrayList<Float>();
double[] Price = new double[uploadOffers_pricefile.get(0).length];
double[] Power = new double[uploadOffers_powerfile.get(0).length];
agent_offers.removeAll(agent_offers);
int ID= controller.getSellers().size()+controller.getBuyers().size()+1;
for(int i=0; i<uploadOffers_namefile.size();i++){
Price=uploadOffers_pricefile.get(i);
Power=uploadOffers_powerfile.get(i);
addPrices.removeAll(addPrices);
addPowers.removeAll(addPowers);
for(int j=0; j<uploadOffers_pricefile.get(0).length;j++){
addPrices.add(Float.parseFloat(String.valueOf(Price[j]).replace(",", ".")));
addPowers.add(Float.parseFloat(String.valueOf(Power[j]).replace(",", ".")));
}
agent_offers.add(new AgentData(uploadOffers_namefile.get(i), ID, roundValue(addPrices, 2), roundValue(addPowers, 2)));
ID++;
}
controller.addSellers(agent_offers);
isSeller=false;
try {
// System.out.println("files\\"+jComboBox_SelectAgent.getSelectedItem()+"\\input.xlsx");
// JOptionPane.showMessageDialog(null, "Loading Data. Select when finished", "Invalid Selection", JOptionPane.INFORMATION_MESSAGE);
uploadFile("files\\"+Case+"\\input.xlsx", "output-sym.csv");
} catch (Exception ex) {
System.out.println("InputData.java / InputData function -> " + ex);
readButton.setEnabled(false);
}
agent_offers.removeAll(agent_offers);
for(int i=0; i<uploadBids_namefile.size();i++){
Price=uploadBids_pricefile.get(i);
Power=uploadBids_powerfile.get(i);
addPrices.removeAll(addPrices);
addPowers.removeAll(addPowers);
for(int j=0; j<uploadBids_pricefile.get(0).length;j++){
addPrices.add(Float.parseFloat(String.valueOf(Price[j]).replace(",", ".")));
addPowers.add(Float.parseFloat(String.valueOf(Power[j]).replace(",", ".")));
}
agent_offers.add(new AgentData(uploadBids_namefile.get(i), ID, roundValue(addPrices, 2), roundValue(addPowers, 2)));
ID++;
}
// controller.addBuyers(agent_offers);
}
public void openRiskAttitude() {
// new ProducerScheduling(jComboBox_SelectAgent.getSelectedItem().toString()).setVisible(true);
// ACLMessage msg = new ACLMessage(ACLMessage.PROPOSE);
// msg.setOntology("market_ontology");
// msg.setProtocol("hello_protocol");
// msg.setContent("spot");
// msg.addReceiver(new AID(jComboBox_SelectAgent.getSelectedItem().toString(), AID.ISLOCALNAME));
// market.send(msg);
// File f = new File("files\\"+jComboBox_SelectAgent.getSelectedItem()+"\\input.xlsx");
// while(!f.exists() && !f.isDirectory()) {
// try {
// Thread.currentThread().sleep(10000); //1000 milliseconds is one second.
// } catch(InterruptedException e) {
// Thread.currentThread().interrupt();
// }
// f = new File("files\\"+jComboBox_SelectAgent.getSelectedItem()+"\\input.xlsx");
// }
// while(0==ProducerScheduling.a){
//
// }
try {
// System.out.println("files\\"+jComboBox_SelectAgent.getSelectedItem()+"\\input.xlsx");
// JOptionPane.showMessageDialog(null, "Loading Data. Select when finished", "Invalid Selection", JOptionPane.INFORMATION_MESSAGE);
uploadFile("files\\"+jComboBox_SelectAgent.getSelectedItem()+"\\input.xlsx", "output-sym.csv");
} catch (Exception ex) {
System.out.println("InputData.java / InputData function -> " + ex);
readButton.setEnabled(false);
}
openDynamicWindow = new SMP_DynamicWindow(this, isSeller, startHour, endHour, jComboBox_SelectAgent.getSelectedItem().toString());
openDynamicWindow.createWindow();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel3 = new javax.swing.JPanel();
jScrollPane3 = new javax.swing.JScrollPane();
agentTable = new javax.swing.JTable();
delButton_Seller = new javax.swing.JButton();
updtButton_Seller = new javax.swing.JButton();
jLabel_selectAgent = new javax.swing.JLabel();
jComboBox_SelectAgent = new javax.swing.JComboBox();
jPanel1 = new javax.swing.JPanel();
searchTextField = new javax.swing.JTextField();
searchButton = new javax.swing.JButton();
clearButton = new javax.swing.JButton();
readButton = new javax.swing.JButton();
submitButton = new javax.swing.JButton();
cancelButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder(null, "Seller Information", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP)));
agentTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
agentTable.setName("seller_Table"); // NOI18N
jScrollPane3.setViewportView(agentTable);
delButton_Seller.setText("Remove");
delButton_Seller.setName("delButton_Seller"); // NOI18N
delButton_Seller.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
delButton_SellerActionPerformed(evt);
}
});
updtButton_Seller.setText("Update");
updtButton_Seller.setName("updtButton_Seller"); // NOI18N
updtButton_Seller.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
updtButton_SellerActionPerformed(evt);
}
});
jLabel_selectAgent.setText("jLabel1");
jComboBox_SelectAgent.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox_SelectAgent.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
}
public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
jComboBox_SelectAgentPopupMenuWillBecomeInvisible(evt);
}
public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
}
});
jComboBox_SelectAgent.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox_SelectAgentActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 347, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel_selectAgent)
.addGap(18, 18, 18)
.addComponent(jComboBox_SelectAgent, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(delButton_Seller, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE)
.addComponent(updtButton_Seller, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addGap(0, 6, Short.MAX_VALUE)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel_selectAgent)
.addComponent(jComboBox_SelectAgent, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addComponent(updtButton_Seller, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(delButton_Seller, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(27, 27, 27))
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)))
);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
searchTextField.setText("Search...");
searchTextField.setToolTipText("");
searchTextField.setName("search_TextField"); // NOI18N
searchTextField.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
searchTextFieldFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
searchTextFieldFocusLost(evt);
}
});
searchButton.setText("Search");
searchButton.setName("search_Button"); // NOI18N
searchButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
searchButtonActionPerformed(evt);
}
});
clearButton.setText("Clear");
clearButton.setName("clear_Button"); // NOI18N
clearButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
clearButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(searchTextField)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(searchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(clearButton, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(searchTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(searchButton)
.addComponent(clearButton))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
readButton.setText("Read File");
readButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
readButtonActionPerformed(evt);
}
});
submitButton.setText("Save");
submitButton.setName("submit_Button"); // NOI18N
submitButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
submitButtonActionPerformed(evt);
}
});
cancelButton.setText("Cancel");
cancelButton.setName("cancel_Button"); // NOI18N
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(readButton, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(submitButton, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cancelButton)
.addComponent(submitButton)
.addComponent(readButton))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void delButton_SellerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_delButton_SellerActionPerformed
deleteAgent(agentTable, agent_offers);
}//GEN-LAST:event_delButton_SellerActionPerformed
private void updtButton_SellerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updtButton_SellerActionPerformed
read_usedAgents();
updateAgentInfo(agentTable, agent_offers);
}//GEN-LAST:event_updtButton_SellerActionPerformed
private void searchTextFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_searchTextFieldFocusGained
if (searchTextField.getText().compareToIgnoreCase(SEARCH_INFO) == 0) {
searchTextField.setText("");
}
}//GEN-LAST:event_searchTextFieldFocusGained
private void searchTextFieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_searchTextFieldFocusLost
if (searchTextField.getText().isEmpty()) {
searchTextField.setText(SEARCH_INFO);
}
}//GEN-LAST:event_searchTextFieldFocusLost
private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed
ArrayList<AgentData> offersAux = new ArrayList<>();
if (!searchTextField.getText().isEmpty() && searchTextField.getText().compareToIgnoreCase(SEARCH_INFO) != 0) {
for (AgentData agent : agent_offers) {
if (agent.getAgent().contains(searchTextField.getText())) {
offersAux.add(agent);
}
}
defineTable(agentTable, offersAux);
} else {
defineTable(agentTable, agent_offers);
}
}//GEN-LAST:event_searchButtonActionPerformed
private void clearButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearButtonActionPerformed
searchTextField.setText(SEARCH_INFO);
startTable();
}//GEN-LAST:event_clearButtonActionPerformed
private void readButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_readButtonActionPerformed
// TODO add your handling code here:
readFile("input.xlsx", "output-sym.csv");
}//GEN-LAST:event_readButtonActionPerformed
private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submitButtonActionPerformed
// TODO add your handling code here:
try {
if (isSeller) {
// ALTERALÕES < ---------------------------------------------------------------------------------
System.out.println("\n\n\n Vai juntar as ofertas ao agente buyer " + agentName + "\n\n\n");
// ALTERAÇÕES < ---------------------------------------------------------------------------------
controller.setSellers(agent_offers);
} else {
// ALTERALÕES < ---------------------------------------------------------------------------------
System.out.println("\n\n\n Vai juntar as ofertas ao agente seller" + agentName + "\n\n\n");
// ALTERAÇÕES < ---------------------------------------------------------------------------------
controller.setBuyers(agent_offers);
}
this.dispose();
} catch (Exception ex) {
System.out.println("Submit Button Error: " + ex);
}
}//GEN-LAST:event_submitButtonActionPerformed
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
this.dispose();
}//GEN-LAST:event_cancelButtonActionPerformed
private void jComboBox_SelectAgentPopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_jComboBox_SelectAgentPopupMenuWillBecomeInvisible
// TODO add your handling code here:
if (jComboBox_SelectAgent.getSelectedIndex() != 0) {
read_usedAgents();
if (isSeller) {
RiskAttitude riskAttitude = new RiskAttitude(market,null, this, jComboBox_SelectAgent.getSelectedItem().toString(), 2);
riskAttitude.setVisible(true);
} else {
openRiskAttitude();
}
}
}//GEN-LAST:event_jComboBox_SelectAgentPopupMenuWillBecomeInvisible
private void jComboBox_SelectAgentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox_SelectAgentActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox_SelectAgentActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTable agentTable;
private javax.swing.JButton cancelButton;
private javax.swing.JButton clearButton;
private javax.swing.JButton delButton_Seller;
private javax.swing.JComboBox jComboBox_SelectAgent;
private javax.swing.JLabel jLabel_selectAgent;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel3;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JButton readButton;
private javax.swing.JButton searchButton;
private javax.swing.JTextField searchTextField;
private javax.swing.JButton submitButton;
private javax.swing.JButton updtButton_Seller;
// End of variables declaration//GEN-END:variables
}
|
package net.MindTree.spring.boot.example.controller;
import java.util.Arrays;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;
import net.MindTree.spring.boot.example.pojo.Transaction;
/**
* @author prasa
*
*/
@RestController
public class SpringMVCController {
Logger logger = Logger.getLogger(SpringMVCController.class.getName());
static final String TRANSACTION_URL = "http://ec2-52-15-52-170.us-east-2.compute.amazonaws.com:8080/transactions/v1/transactions?productId=AnyID";
/**
* @param orderBy
* @param direction
* @param from
* @param size
* @return
*/
@RequestMapping(value = { "/transactions"}, method = RequestMethod.GET)
public ModelAndView getDetails(@RequestParam(value="orderBy", required=false, defaultValue="id") String orderBy,
@RequestParam(value="direction", required=false, defaultValue="ASC") String direction,
@RequestParam(value="from", required=false, defaultValue="0") Integer from,
@RequestParam(value="size", required=false) Integer size){
logger.info("Inside getDetails Method");
logger.info("request parameters are orderBy:"+orderBy+" direction:"+direction+" from:"+from+" size:"+size);
RestTemplate restTemplate = new RestTemplate();
Transaction[] list = restTemplate.getForObject(TRANSACTION_URL, Transaction[].class);
List<Transaction> transactionList = Arrays.asList(list);
//Sorting as per id
if(orderBy.equals("id"))
{
logger.info("Sorting by ID");
transactionList.sort((t1, t2) -> {
if(t1.getId() == t2.getId()){
return 0;
}
//Selecting the order
if(direction.equals("DESC"))
return t2.getId().compareTo(t1.getId());
else
return t1.getId().compareTo(t2.getId());
});
}
else if(orderBy.equals("amount"))
{
logger.info("Sorting by Amount");
transactionList.sort((t1, t2) -> {
if(t1.getAmount() == t2.getAmount()){
return 0;
}
//Selecting the order
if(direction.equals("DESC"))
return t2.getAmount().compareTo(t1.getAmount());
else
return t1.getAmount().compareTo(t2.getAmount());
});
}
else if(orderBy.equals("instructedAmount"))
{
logger.info("Sorting by instructedAmount");
transactionList.sort((t1, t2) -> {
if(t1.getInstructedAmount() == t2.getInstructedAmount()){
return 0;
}
//Selecting the order
if(direction.equals("DESC"))
return t2.getInstructedAmount().compareTo(t1.getInstructedAmount());
else
return t1.getInstructedAmount().compareTo(t2.getInstructedAmount());
});
}
int toSize =0;
if(from<0 || from > transactionList.size())
{
logger.info("from is either <0 or > total number of records so reseting the value to 0");
from = 0;
}
if(null == size || from+size<0)
{
logger.info("size is either null or from+size > total number of records so reseting the value to total number of records");
toSize = transactionList.size();
}
else if(from+size > transactionList.size())
{
logger.info("from + size > total number of records so reseting the value to total number of records");
toSize = transactionList.size();
}
else
{
toSize = from+size;
}
//Creating the sublist as per the from and size values
List<Transaction> pagedList = transactionList.subList(from, toSize);
ModelAndView model = new ModelAndView("index");
model.addObject("transactions", pagedList);
return model;
}
}
|
package Ex1;
public class Circulo extends Figura {
private double area;
private double perimetro;
protected double raio;
public Circulo (String nome, double raio) {
super(nome);
this.raio = raio;
this.area = (Math.PI) * (Math.pow(this.raio, 2));
this.perimetro = Math.PI * 2 * this.raio;
}
@Override
public double perimetro() {
return perimetro;
}
@Override
public double area() {
// TODO Auto-generated method stub
return area;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.davivienda.sara.dto;
import com.davivienda.sara.entitys.Zona;
/**
*
* @author jmcastel
*/
public class ZonaDTO {
public int idZonac;
private Integer idZona;
private String zona;
private String descripcionZona;
public void limpiarZonaDTO() {
this.idZonac = 0;
this.idZona = 0;
this.zona = "";
this.descripcionZona = "";
}
public ZonaDTO entidadDTO(Zona item) {
ZonaDTO respItems = new ZonaDTO();
respItems.setIdZona(item.getIdZona());
respItems.setZona(item.getZona());
respItems.setDescripcionZona(item.getDescripcionZona());
return respItems;
}
public Zona entidad() {
Zona respItems = new Zona();
respItems.setIdZona(getIdZona());
respItems.setZona(getZona());
respItems.setDescripcionZona(getDescripcionZona());
return respItems;
}
public int getIdZonac() {
return idZonac;
}
public void setIdZonac(int idZonac) {
this.idZonac = idZonac;
}
public Integer getIdZona() {
return idZona;
}
public void setIdZona(Integer idZona) {
this.idZona = idZona;
}
public String getZona() {
return zona;
}
public void setZona(String zona) {
this.zona = zona;
}
public String getDescripcionZona() {
return descripcionZona;
}
public void setDescripcionZona(String descripcionZona) {
this.descripcionZona = descripcionZona;
}
@Override
public String toString() {
return "ZonaDTO{" + "idZonac=" + idZonac + ", idZona=" + idZona + ", zona=" + zona + ", descripcionZona=" + descripcionZona + '}';
}
}
|
package Lector9.Task9_2;
import Lector9.Task9_1.Pair;
public final class PairUtil {
private PairUtil(){}
public static <K, V> Pair <V, K> swap(Pair<K, V> ob) {
return new Pair<V, K>(ob.getName(), ob.getId());
}
}
|
package io.nekohasekai.tmicro.utils;
import com.sun.lwuit.html.HTMLComponent;
import com.sun.lwuit.html.HTMLElement;
import com.sun.lwuit.html.HTMLParser;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
public class HtmlUtil {
}
|
package com.apap.igd.rest;
import java.util.ArrayList;
import java.util.List;
import com.apap.igd.model.response.ObatListResponse;
import com.apap.igd.model.rest.ObatModel;
import org.springframework.web.client.RestTemplate;
public class ObatRest {
public static List<ObatModel> getAllObat() {
RestTemplate restTemplate = new RestTemplate();
ObatListResponse response = restTemplate.getForObject(Setting.SI_FARMASI_URL + "/daftar-medical-service", ObatListResponse.class);
return response.getResult();
}
public static ObatModel getObatModelById(long id) {
ObatModel obatFix = null;
for (ObatModel obat : getAllObat()) {
if (obat.getId() == id) obatFix = obat;
}
return obatFix;
}
}
|
package com.blackflagbin.kcommondemowithjava.ui.adapter.pageradapter;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.blackflagbin.kcommondemowithjava.ui.fragment.factory.FragmentFactory;
/**
* Created by blackflagbin on 2018/3/25.
*/
public class MainPagerAdapter extends FragmentPagerAdapter {
private static String[] mTypeArray = {"all", "Android", "iOS", "休息视频", "福利", "拓展资源", "前端", "瞎推荐", "App"};
public MainPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return FragmentFactory.getFragment(position);
}
@Override
public int getCount() {
return mTypeArray.length;
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return mTypeArray[position];
}
}
|
package se.rtz.bindings.view;
import se.rtz.bindings.model.Property;
import se.rtz.bindings.model.SModel;
import se.rtz.bindings.model.SimpleProperty;
public class TestModel extends SModel {
private Property<String> textFieldModel = new SimpleProperty<String>("");
public Property<String> getTextFieldModel() {
return textFieldModel;
}
}
|
/*
* Copyright Daon.
*
* 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.daon.identityx.controller.model;
/**
* Created by Daon
*/
public class ValidateTransactionAuthResponse {
private String fidoAuthenticationResponse;
private Long fidoResponseCode;
private String fidoResponseMsg;
public String getFidoAuthenticationResponse() {
return fidoAuthenticationResponse;
}
public void setFidoAuthenticationResponse(String fidoAuthenticationResponse) {
this.fidoAuthenticationResponse = fidoAuthenticationResponse;
}
public Long getFidoResponseCode() {
return fidoResponseCode;
}
public void setFidoResponseCode(Long fidoResponseCode) {
this.fidoResponseCode = fidoResponseCode;
}
public String getFidoResponseMsg() {
return fidoResponseMsg;
}
public void setFidoResponseMsg(String fidoResponseMsg) {
this.fidoResponseMsg = fidoResponseMsg;
}
}
|
package com.github.angads25.nature.elements;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Path;
import android.graphics.Point;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import com.github.angads25.nature.model.NatureView;
/**
* <p>
* Created by Angad on 29-04-2017.
* </p>
*/
public class TreeView extends NatureView {
private Point[] lower;
private Path lowerLayer;
public TreeView(Context context) {
super(context);
}
public TreeView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void initView() {
super.initView();
lower = new Point[3];
for(int i = 0; i < 3; i++) {
lower[i] = new Point();
}
lowerLayer = new Path();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//Stem
int padding = (minDim >>> 1) / 5;
paint.setColor(Color.parseColor("#663300"));
canvas.drawRect(center - (padding >>> 1), (minDim / 1.5f), center + (padding >>> 1), minDim - padding, paint);
//Tree Layer
paint.setColor(Color.parseColor("#476A34"));
lowerLayer.moveTo(lower[0].x, lower[0].y);
lowerLayer.lineTo(lower[1].x, lower[1].y);
lowerLayer.lineTo(lower[2].x, lower[2].y);
canvas.drawPath(lowerLayer, paint);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(minDim, minDim);
lower[0].set(center - (int)(minDim / 3.5f), center + (int)(minDim / 4.5f));
lower[1].set(center + (int)(minDim / 3.5f), center + (int)(minDim / 4.5f));
lower[2].set(center, (minDim >>> 1) / 5);
}
}
|
package vnfoss2010.smartshop.serverside.services.account;
import java.util.Map;
import vnfoss2010.smartshop.serverside.Global;
import vnfoss2010.smartshop.serverside.database.AccountServiceImpl;
import vnfoss2010.smartshop.serverside.database.ServiceResult;
import vnfoss2010.smartshop.serverside.database.entity.UserInfo;
import vnfoss2010.smartshop.serverside.services.BaseRestfulService;
import vnfoss2010.smartshop.serverside.services.exception.RestfulException;
import com.google.appengine.repackaged.org.json.JSONObject;
public class RegisterService extends BaseRestfulService{
private AccountServiceImpl db = AccountServiceImpl.getInstance();
public RegisterService(String serviceName) {
super(serviceName);
}
@Override
public String process(Map<String, String[]> params, String content)
throws Exception, RestfulException {
UserInfo userInfo = Global.gsonDateWithoutHour.fromJson(content, UserInfo.class);
// JSONObject json = null;
// try {
// json = new JSONObject(content);
// } catch (Exception e) {
// }
// UserInfo userInfo = new UserInfo();
// userInfo.setUsername(getParameter("username", params, json));
// userInfo.setPassword(getParameter("password", params, json));
// userInfo.setFirst_name(getParameter("first_name", params, json));
// userInfo.setLast_name(getParameter("last_name", params, json));
// userInfo.setPhone(getParameter("phone", params, json));
// userInfo.setEmail(getParameter("email", params, json));
// userInfo.setAddress(getParameter("address", params, json));
//
// Date birthday = null;
// try {
// birthday = Global.df.parse(getParameter("birthday", params, json));
// } catch (Exception e) {
// }
// userInfo.setBirthday(birthday);
//
// double lat = 0;
// try {
// lat = Double.parseDouble(getParameter("lat", params, json));
// } catch (Exception e) {
// }
// userInfo.setLat(lat);
//
// double lng = 0;
// try {
// lng = Double.parseDouble(getParameter("lng", params, json));
// } catch (Exception e) {
// }
// userInfo.setLng(lng);
JSONObject jsonReturn = new JSONObject();
ServiceResult<Void> result = db.insertUserInfo(userInfo);
if (result.isOK()) {
jsonReturn.put("errCode", 0);
jsonReturn.put("message", result.getMessage());
} else {
jsonReturn.put("errCode", 1);
jsonReturn.put("message", result.getMessage());
}
return jsonReturn.toString();
}
}
|
package com.emg.projectsmanage.common;
/**
* 操作类型
*
* @author zsen
*
*/
public enum DatabaseType {
/**
* 0-未知
*/
UNKNOW(0, "未知"),
/**
* 1, "MySQL"
*/
MYSQL(1, "MySQL"),
/**
* 2, "PostgreSQL"
*/
POSTGRESQL(2, "PostgreSQL");
private Integer value;
private String des;
public String getDes() {
return des;
}
public void setDes(String des) {
this.des = des;
}
private DatabaseType(Integer value, String des) {
this.setValue(value);
this.des = des;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
|
package GuiLayer;
/*
import Models;
import ControllerLayer;
*/
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.util.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class MainMenuUI {
private JFrame frame;
private JButton orderButton;
private JButton order2Button;
private JButton order3Button;
private JButton usersButton;
private JButton productsButton;
public MainMenuUI() {
initializeFrame();
}
private void initializeFrame() {
frame = new JFrame("Main Menu");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1280, 720);
frame.setResizable(false);
frame.getContentPane().setLayout(null);
orderButtons();
orderButton = new JButton("New Order");
orderButton.setFont(new Font("Arial", Font.PLAIN, 25));
orderButton.setBounds(140, 260, 250, 100);
orderButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {order2Button.setVisible(true); order3Button.setVisible(true);
}
});
frame.getContentPane().add(orderButton);
usersButton = new JButton("Users");
usersButton.setFont(new Font("Arial", Font.PLAIN, 25));
usersButton.setBounds(530, 260, 250, 100);
usersButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {order2Button.setVisible(false); order3Button.setVisible(false);
}
});
frame.getContentPane().add(usersButton);
productsButton = new JButton("Products");
productsButton.setFont(new Font("Arial", Font.PLAIN, 25));
productsButton.setBounds(920, 260, 250, 100);
productsButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {order2Button.setVisible(false); order3Button.setVisible(false);
}
});
frame.getContentPane().add(productsButton);
frame.setVisible(true);
}
private void orderButtons() {
order2Button = new JButton("New Sale");
order2Button.setFont(new Font("Arial", Font.PLAIN, 25));
order2Button.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {OrderUI orderWindow = new OrderUI();
}
});
order2Button.setBounds(165, 380, 200, 80);
frame.getContentPane().add(order2Button);
order2Button.setVisible(false);
order3Button = new JButton("New Rent");
order3Button.setFont(new Font("Arial", Font.PLAIN, 25));
order3Button.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
}
});
order3Button.setBounds(165, 470, 200, 80);
frame.getContentPane().add(order3Button);
order3Button.setVisible(false);
}
}
|
package com.brainacademy.mvc;
public class Student {
private String name;
private String group;
private String school;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setGroup(String group) {
this.group = group;
}
public String getGroup() {
return group;
}
public void setSchool(String school) {
this.school = school;
}
public String getSchool() {
return school;
}
}
|
package com.Exam.Entity;
import java.util.Date;
import java.util.List;
import java.util.Set;
import javax.persistence.*;
import org.apache.lucene.analysis.core.KeywordAnalyzer;
import org.hibernate.search.annotations.*;
import org.hibernate.search.annotations.Index;
import org.hibernate.search.bridge.builtin.IntegerBridge;
@Entity
@Table(name = "orders")
@Indexed
public class Orders {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@DocumentId
int id;
String ngay;
@Field
String tenKH;
@Field(termVector = TermVector.YES)
String email;
int phone;
String diaChi;
String tenNguoiBan;
String cuaHang;
@Field
String trangThai;
int tongTien;
@OneToMany(mappedBy = "order",cascade = CascadeType.ALL,fetch = FetchType.LAZY)
@IndexedEmbedded
List<OrderItem>orderItems;
public int getTongTien() {
return tongTien;
}
public void setTongTien(int tongTien) {
this.tongTien = tongTien;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNgay() {
return ngay;
}
public void setNgay(String ngay) {
this.ngay = ngay;
}
public String getTenKH() {
return tenKH;
}
public void setTenKH(String tenKH) {
this.tenKH = tenKH;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getPhone() {
return phone;
}
public void setPhone(int phone) {
this.phone = phone;
}
public String getDiaChi() {
return diaChi;
}
public void setDiaChi(String diaChi) {
this.diaChi = diaChi;
}
public String getTenNguoiBan() {
return tenNguoiBan;
}
public void setTenNguoiBan(String tenNguoiBan) {
this.tenNguoiBan = tenNguoiBan;
}
public String getCuaHang() {
return cuaHang;
}
public void setCuaHang(String cuaHang) {
this.cuaHang = cuaHang;
}
public String getTrangThai() {
return trangThai;
}
public void setTrangThai(String trangThai) {
this.trangThai = trangThai;
}
public Orders() {
super();
}
public Orders(int id, String ngay, String tenKH, String email, int phone, String diaChi, String tenNguoiBan,
String cuaHang, String trangThai) {
super();
this.id = id;
this.ngay = ngay;
this.tenKH = tenKH;
this.email = email;
this.phone = phone;
this.diaChi = diaChi;
this.tenNguoiBan = tenNguoiBan;
this.cuaHang = cuaHang;
this.trangThai = trangThai;
}
public List<OrderItem> getOrderItems() {
return orderItems;
}
public void setOrderItems(List<OrderItem> orderItems) {
this.orderItems = orderItems;
}
}
|
/**
* @auther lzy
* 实现功能:
* 将评论内容发送至前端
*/
package com.github.web.servlet;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.domain.User;
import com.github.domain.text2;
import com.github.service.impl.TextServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/comment")
public class comment extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
HttpSession session = request.getSession();
User user = (User) session.getAttribute("usermsg");
if (user != null) {
//int textid = Integer.parseInt(request.getParameter("thistext"));
int atextid = (int) session.getAttribute("atextid");
TextServiceImpl textService = new TextServiceImpl();
text2 text = textService.findAlltext(atextid);
//传递评论集
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(response.getWriter(), text.getList());
String s = JSON.toJSONString(text.getList());
System.out.println(s);
//session.removeAttribute("atextid");
}else{
//没登录
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
|
package ovh.corail.recycler.container;
import java.util.List;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import ovh.corail.recycler.tileentity.TileEntityRecycler;
public class SlotRecycler extends Slot {
private TileEntityRecycler invent;
private int id;
public SlotRecycler(TileEntityRecycler inventory, int index, int xPos, int yPos) {
super(inventory, index, xPos, yPos);
this.id = index;
this.invent = inventory;
}
@Override
public boolean isItemValid(ItemStack stack) {
return invent.isItemValidForSlot(id, stack);
}
@Override
public void onSlotChange(ItemStack item1, ItemStack item2) {
super.onSlotChange(item1, item2);
}
@Override
public boolean canTakeStack(EntityPlayer player) {
return true;
}
@Override
public void onSlotChanged() {
super.onSlotChanged();
}
}
|
import java.sql.*;
import sun.jdbc.odbc.*;
public class access {
public static void main(String args[])
{
try{
new JdbcOdbcDriver();
Connection can =DriverManager.getConnection("jdbc:odbc:FIRST");
System.out.println("connection success");
Statement s=can.createStatement();
ResultSet r=s.executeQuery("select * from exam");
while(r.next());
{
System.out.print(r.getInt(1)+","+r.getString(2)+","+r.getInt(3));
}
}
catch(Exception e)
{
System.out.println("recordover");
}
}
}
|
package com.proyectofinal.game.objects.trops;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.proyectofinal.game.helpers.AssetManager;
import com.proyectofinal.game.objects.road.Camino;
import com.proyectofinal.game.objects.towers.Torres;
import java.util.ArrayList;
/**
* Created by ALUMNEDAM on 31/05/2017.
*/
public class AtaqueTropa {
public AtaqueTropa() {
}
/**
* Recorre todas las tropas que estan atacando le quitan vida a la torre
*
* @param torre
* @param tropas
* @param musica
*/
public void atacarTorre(Torres torre, ArrayList<Tropas> tropas, boolean musica) {
for (int danyoTorre = 0; danyoTorre < tropas.size(); danyoTorre++) {
if (!tropas.get(danyoTorre).isanimacionCaminar()) { //Si la animacion no es la de atacar...
torre.setVida(torre.getVida() - tropas.get(danyoTorre).getDanyo()); //A la vida se le resta el daño de la tropa
if (torre.getVida() <= 0) { //Cuando la vida de la torre es menor a 0
for (int i = 0; i < tropas.size(); i++) {
tropas.get(i).setEstaAtacando(false);
}
if (torre.isOrientacion() && torre.isViva()) { //Dependiendo de la orientación el rectangulo de colisiones
torre.getCollisionCircle().setY(torre.getCollisionCircle().y + 75);
}
torre.getCollisionCircle().setRadius(5); //Cambia el radio de la torre
torre.setViva(false);
torre.setOverlaps(false);
if (musica) {
AssetManager.soundTowerDead.play();
}
}
}
}
}
/**
* Ejecuta el disparo del robot
*
* @param torre
* @param robot
* @param stage
*/
public void disparoRobot(Torres torre, Tropas robot, Stage stage) {
robot.setContadorBala(robot.getContadorBala() + 1);
robot.setanimacionCaminar(false);
if (robot.getContadorBala() % 120 == 0) { //Cada 2 segundos entre cada disparo
robot.ataque(robot.getPosition(), new Vector2(torre.getCollisionCircle().x, torre.getCollisionCircle().y), stage);
}
}
/**
* Ejecuta el metodo que hace que se llegue a la torre para atacarla
*
* @param torreActual
* @param tropaActual
* @param caminoTotal
*/
public void llegarATorre(Torres torreActual, Tropas tropaActual, ArrayList<Camino> caminoTotal) {
LlegarATorre llegar = new LlegarATorre(tropaActual, torreActual, caminoTotal);
ArrayList<Camino> camino = llegar.caminarHaciaTorre();
if (!tropaActual.siguienteCasillaAtaque(camino) && !tropaActual.llegarATorre(tropaActual.getY(), torreActual.getPosicionAtaque().y, torreActual.isOrientacion())) {
tropaActual.setanimacionCaminar(false);
}
}
}
|
package com.example.acer.home;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.Uri;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import java.util.List;
import java.util.Objects;
/**
* This class contain the code for side navigation bar
* @author Manasa, Sarmad, Jesse, Abi, Seth
* @version 4.0
* @updated 2 December, 2018
*/
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, SensorEventListener {
CurrentFragmentEnum currentFragment;
private SensorManager sensorManager;
private SharedPreferences sharedPref;
private SharedPreferences.Editor editor;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected( MenuItem item) {
Fragment selectedFragment = null;
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
switch (item.getItemId()) {
case R.id.groceries:
selectedFragment = GroceriesFragment.newInstance();
navigationView.setCheckedItem(R.id.groceries);
break;
case R.id.recipes:
selectedFragment = RecipesFragment.newInstance();
navigationView.setCheckedItem(R.id.recipes);
break;
case R.id.Activity:
selectedFragment = FitnessFragment.newInstance();
navigationView.setCheckedItem(R.id.Activity);
break;
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, selectedFragment);
transaction.commit();
return true;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//make initial screen groceries
Fragment selectedFragment = GroceriesFragment.newInstance();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, selectedFragment);
transaction.commit();
sharedPref = getPreferences(Context.MODE_PRIVATE);
editor = sharedPref.edit();
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Sensor stepSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
sensorManager.registerListener(this, stepSensor, SensorManager.SENSOR_DELAY_NORMAL);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setItemIconTintList(null);
navigationView.setNavigationItemSelectedListener(this);
navigationView.setCheckedItem(R.id.groceries);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//setTitle(currentFragment);
if (Objects.equals(currentFragment,CurrentFragmentEnum.Groceries))
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
}
else {
//Reference URL: https://stackoverflow.com/questions/10692755/how-do-i-hide-a-menu-item-in-the-actionbar
for (int i=0; i < menu.size();i++)
{
menu.getItem(i).setVisible(false);
}
//return false;
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
try {
// Handle navigation view item clicks here.
Intent i;
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
switch(item.getItemId())
{
case R.id.help :
Intent helpIntent =new Intent(this,HelpActivity.class);
startActivity(helpIntent);
break;
case R.id.call:
Intent dialIntent = new Intent(Intent.ACTION_DIAL);
dialIntent.setData(Uri.parse("tel:" + "9027896475"));
startActivity(dialIntent);
break;
case R.id.recipes:
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container,new RecipesFragment()).commit();
invalidateOptionsMenu();// now onCreateOptionsMenu(...) is called again
currentFragment = CurrentFragmentEnum.Recipes;
navigation.setSelectedItemId(R.id.recipes);
break;
case R.id.groceries :
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container,new GroceriesFragment()).commit();
invalidateOptionsMenu();// now onCreateOptionsMenu(...) is called again
currentFragment = CurrentFragmentEnum.Groceries;
navigation.setSelectedItemId(R.id.groceries);
break;
case R.id.Activity :
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container,new FitnessFragment()).commit();
invalidateOptionsMenu(); // now onCreateOptionsMenu(...) is called again
currentFragment = CurrentFragmentEnum.Activity;
navigation.setSelectedItemId(R.id.Activity);
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
catch (Exception ex)
{
}
return true;
}
@Override
public void onSensorChanged(SensorEvent event) {
editor.putInt(getString(R.string.savedSteps), (int) event.values[0]);
editor.commit();
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
return;
}
public enum CurrentFragmentEnum
{
Groceries,
Recipes,
Activity
}
}
|
package github.tornaco.android.thanos.dashboard;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
import github.tornaco.android.thanos.databinding.ItemFeatureDashboardBinding;
public class DashboardAdapter extends RecyclerView.Adapter<DashboardAdapter.TileHolder> {
private final List<Tile> tiles = new ArrayList<>();
// Global.
@NonNull
private OnTileClickListener onClickListener;
@NonNull
private OnTileLongClickListener onLongClickListener;
@Nullable
private OnTileSwitchChangeListener onSwitchChangeListener;
public DashboardAdapter(@NonNull OnTileClickListener onClickListener,
@NonNull OnTileLongClickListener onLongClickListener,
@Nullable OnTileSwitchChangeListener onSwitchChangeListener) {
this.onClickListener = onClickListener;
this.onLongClickListener = onLongClickListener;
this.onSwitchChangeListener = onSwitchChangeListener;
}
public void replaceData(List<Tile> tiles) {
this.tiles.clear();
this.tiles.addAll(tiles);
notifyDataSetChanged();
}
@NonNull
@Override
public TileHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new TileHolder(ItemFeatureDashboardBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false));
}
@Override
public void onBindViewHolder(@NonNull TileHolder holder, int position) {
Tile tile = tiles.get(position);
holder.binding.setTile(tile);
holder.binding.setIsLastOne(position == getItemCount() - 1);
holder.binding.tileRoot.setOnLongClickListener(v -> {
onLongClickListener.onLongClick(tile, v);
return true;
});
holder.binding.tileRoot.setOnClickListener(v -> onClickListener.onClick(tile));
holder.binding.setCheckable(tile.isCheckable());
if (onSwitchChangeListener != null) {
holder.binding.tileSwitch.setOnClickListener(v -> {
boolean checked = holder.binding.tileSwitch.isChecked();
tile.setChecked(checked);
onSwitchChangeListener.onSwitchChange(tile, checked);
});
}
holder.binding.executePendingBindings();
}
@Override
public int getItemCount() {
return tiles.size();
}
static final class TileHolder extends RecyclerView.ViewHolder {
private ItemFeatureDashboardBinding binding;
TileHolder(@NonNull ItemFeatureDashboardBinding binding) {
super(binding.getRoot());
this.binding = binding;
}
}
public interface OnTileSwitchChangeListener {
void onSwitchChange(@NonNull Tile tile, boolean checked);
}
}
|
public class TestArrayClass {
public static void main(String[] args){
//int[] intArray = new int[10];
int[] intArray = new int[]{1,2,3,4,5,6,7,8,9,10};
intArray[0] = 1;
intArray[1] = 5;
intArray[2] = 7;
for(int i = 0; i < intArray.length; i++){
intArray[i] = i;
}
}
public static int[] squareThhree(int num1, int num2, int num3){
int[] squares = new int[3];
squares[0] = num1 * num1;
squares[1] = num2 * num2;
squares[2] = num3 * num3;
return squares;
}
public static void bubbleSort(int[] inputArray){
boolean swapped = true;
int temp;
while (swapped){
swapped = false;
for(int i = 0; i < inputArray.length - 1; i++){
if(inputArray[i] > inputArray[i + 1]){
temp = inputArray[i];
inputArray[i] = inputArray[i+1];
inputArray[i + 1] = temp;
swapped = true;
}
}
}
}
public static void selectionSort(int[] inputArray){
for(int i = 0; i < inputArray.length - 1; i++){
int pos = 0; //the position to swap to, always start at index 0
for(int j = i + 1; j < inputArray.length; j++){
if(inputArray[j] < inputArray[i]){
pos = j;
}
}
int temp = inputArray[pos];
inputArray[pos] = inputArray[i];
inputArray[i] = temp;
}
}
}
|
package de.aoe.musicworld.base.adapter;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import de.aoe.musicworld.utils.BaseFileUtils;
/**
* This class implements an concrete Adapter which can be processed by any Task.
*
* @author DavidJanicki
*
*/
public class FileAdapter extends AbstractAdapter {
private static final Log LOG = LogFactory.getLog(FileAdapter.class);
/** The outputStream to put in file. */
private OutputStream outputStream;
/** The outgoingWorkDir to place file in. */
private String outgoingWorkDir;
/** The outgoingFilePrefix to prefixing filename. */
private String outgoingFilePrefix;
/** The outgoingFileExtension to set extension to filename. */
private String outgoingFileExtension;
/** The properties to read global parameters of the task. */
private Properties properties;
/*
* (non-Javadoc)
* @see de.aoe.musicworld.base.adapter.AbstractAdapter#postProcess()
*/
public void postProcess() {
String TaskId = properties.getProperty("taskId");
final String TASKID = "Task #" + TaskId + " - ";
LOG.debug(TASKID + "Process FileAdapter ... ");
/* generates unique FileName */
String uniqueFileName = BaseFileUtils.generateUniqueFileName(outgoingFilePrefix, outgoingFileExtension);
File outputFile = new File(outgoingWorkDir.concat(uniqueFileName));
/* writes file with content of the outputStream
* on Exception return - the file will be polled again
*/
try {
BaseFileUtils.outputStreamToFile(outputStream, outputFile);
} catch (IOException e) {
LOG.error(TASKID + e.getMessage(), e);
return;
}
LOG.debug(TASKID + "Written file to " + outputFile.getAbsolutePath());
/* if file is written, the inputfile will be removed
*/
String inputFileName = properties.getProperty("inputFileName");
if (inputFileName != null) {
File inputFile = new File(inputFileName);
if (inputFile.canRead() && !inputFile.delete()) {
LOG.error(TASKID + "Error on delete file " + inputFileName);
return;
}
}
LOG.debug(TASKID + "Removed file from " + inputFileName);
}
@Override
protected AbstractAdapter createAdapter() {
return new FileAdapter();
}
@Override
public void setOutputStream(OutputStream outputStream) {
this.outputStream = outputStream;
}
@Override
public OutputStream getOutputStream() {
return outputStream;
}
public String getOutgoingWorkDir() {
return outgoingWorkDir;
}
public void setOutgoingWorkDir(String outgoingWorkDir) {
this.outgoingWorkDir = outgoingWorkDir;
}
public String getOutgoingFilePrefix() {
return outgoingFilePrefix;
}
public void setOutgoingFilePrefix(String outgoingFilePrefix) {
this.outgoingFilePrefix = outgoingFilePrefix;
}
public String getOutgoingFileExtension() {
return outgoingFileExtension;
}
public void setOutgoingFileExtension(String outgoingFileExtension) {
this.outgoingFileExtension = outgoingFileExtension;
}
@Override
public void setProperties(Properties properties) {
this.properties = properties;
}
@Override
public Properties getProperties() {
return properties;
}
}
|
package com.nfschina.aiot.entity;
import com.nfschina.aiot.constant.Constant;
/**
* 湿度实体
*
* @author xu
*
*/
public class HumidityEntity extends EnvironmentParameterEntity {
// 湿度实体的属性
private float mData;
private String mTime;
public HumidityEntity(float mData, String time) {
this.mData = mData;
mTime = time;
setKind(Constant.HUMIDITY);
}
public float getData() {
return mData;
}
public String getTime() {
return mTime;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.fastHotel.modeloTabla;
/**
*
* @author rudolf
*/
public class F_RegistroHuesped {
private String nombreCompleto;
private String tipoDocumento;
private String numeroDocumento;
private String caducidadDocumento;
private String fechaNacimiento;
private int edad;
private String nacionalidad;
private String telefono;
private String email;
private boolean seleccionar;
public F_RegistroHuesped(String nombreCompleto, String tipoDocumento, String numeroDocumento, String caducidadDocumento, String fechaNacimiento, int edad, String nacionalidad, String telefono, String email, boolean seleccionar){
this.nombreCompleto = nombreCompleto;
this.tipoDocumento = tipoDocumento;
this.numeroDocumento = numeroDocumento;
this.caducidadDocumento = caducidadDocumento;
this.fechaNacimiento = fechaNacimiento;
this.edad = edad;
this.nacionalidad = nacionalidad;
this.telefono = telefono;
this.email = email;
this.seleccionar = seleccionar;
}
public String getNombreCompleto() {
return nombreCompleto;
}
public void setNombreCompleto(String nombreCompleto) {
this.nombreCompleto = nombreCompleto;
}
public String getTipoDocumento() {
return tipoDocumento;
}
public void setTipoDocumento(String tipoDocumento) {
this.tipoDocumento = tipoDocumento;
}
public String getNumeroDocumento() {
return numeroDocumento;
}
public void setNumeroDocumento(String numeroDocumento) {
this.numeroDocumento = numeroDocumento;
}
public String getCaducidadDocumento() {
return caducidadDocumento;
}
public void setCaducidadDocumento(String caducidadDocumento) {
this.caducidadDocumento = caducidadDocumento;
}
public String getFechaNacimiento() {
return fechaNacimiento;
}
public void setFechaNacimiento(String fechaNacimiento) {
this.fechaNacimiento = fechaNacimiento;
}
public int getEdad() {
return edad;
}
public void setEdad(int edad) {
this.edad = edad;
}
public String getNacionalidad() {
return nacionalidad;
}
public void setNacionalidad(String nacionalidad) {
this.nacionalidad = nacionalidad;
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isSeleccionar() {
return seleccionar;
}
public void setSeleccionar(boolean seleccionar) {
this.seleccionar = seleccionar;
}
}
|
package com.edasaki.rpg.regions;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import com.edasaki.core.utils.RScheduler;
import com.edasaki.core.utils.RTicks;
import com.edasaki.rpg.AbstractManagerRPG;
import com.edasaki.rpg.PlayerDataRPG;
import com.edasaki.rpg.SakiRPG;
import com.edasaki.rpg.regions.areas.TriggerArea;
import com.edasaki.rpg.regions.areas.TriggerAreaAction;
import com.edasaki.rpg.regions.areas.actions.TriggerAreaActionDelay;
import com.edasaki.rpg.worldboss.WorldBossManager;
public class RegionManager extends AbstractManagerRPG {
protected static final String GENERAL_NAME = "The Zentrelan Continent";
protected static final RegionPoint MIN_POINT = new RegionPoint(-1000000, -1000000, -1000000);
protected static final RegionPoint MAX_POINT = new RegionPoint(1000000, 1000000, 1000000);
private static ArrayList<Region> regions;
private static ArrayList<TriggerArea> areas;
public RegionManager(SakiRPG plugin) {
super(plugin);
}
@Override
public void initialize() {
regions = new ArrayList<Region>();
areas = new ArrayList<TriggerArea>();
reload();
}
public static void reload() {
regions.clear();
for (World w : plugin.getServer().getWorlds()) {
Region r = new Region(GENERAL_NAME, 1, 2, w, Arrays.asList(MIN_POINT, MAX_POINT));
regions.add(r);
}
File dir = new File(plugin.getDataFolder(), "regions");
if (!dir.exists())
dir.mkdirs();
for (File f : dir.listFiles()) {
if (f.getName().endsWith(".txt")) {
readRegion(f);
}
}
System.out.println("Loaded " + regions.size() + " regions.");
dir = new File(plugin.getDataFolder(), "areas");
if (!dir.exists())
dir.mkdirs();
for (File f : dir.listFiles()) {
if (f.getName().endsWith(".txt")) {
readArea(f);
}
}
System.out.println("Loaded " + areas.size() + " trigger areas.");
}
public static void readArea(File f) {
try (Scanner scan = new Scanner(f)) {
World w = plugin.getServer().getWorld(scan.nextLine().trim());
if (w == null)
throw new Exception("Invalid world");
ArrayList<RegionPoint> points = new ArrayList<RegionPoint>();
String s = null;
while (scan.hasNextLine()) {
s = scan.nextLine();
if (s.startsWith("###"))
break;
String[] data = s.trim().split(" ");
if (data.length != 3)
break;
points.add(new RegionPoint(Integer.parseInt(data[0]), Integer.parseInt(data[1]), Integer.parseInt(data[2])));
}
if (s == null) {
throw new Exception("Error reading area " + f.getName());
}
ArrayList<TriggerAreaAction> actions = new ArrayList<TriggerAreaAction>();
long delay = 0;
while (scan.hasNextLine()) {
s = scan.nextLine();
TriggerAreaAction taa = TriggerAreaAction.parse(s);
if (taa == null)
continue;
if (taa instanceof TriggerAreaActionDelay) {
delay = ((TriggerAreaActionDelay) taa).delay;
continue;
}
actions.add(taa);
}
String regionName = f.getName().substring(0, f.getName().indexOf(".txt"));
if (regionName.contains("."))
regionName = regionName.substring(0, regionName.lastIndexOf("."));
TriggerArea ta = new TriggerArea(regionName, w, delay, points, actions);
areas.add(ta);
} catch (Exception e) {
System.out.println("Error reading area " + f);
e.printStackTrace();
}
}
public static void readRegion(File f) {
try (Scanner scan = new Scanner(f)) {
ArrayList<RegionPoint> points = new ArrayList<RegionPoint>();
String s = null;
while (scan.hasNextLine()) {
s = scan.nextLine();
String[] data = s.trim().split(" ");
if (data.length != 3)
break;
points.add(new RegionPoint(Integer.parseInt(data[0]), Integer.parseInt(data[1]), Integer.parseInt(data[2])));
}
if (s == null) {
throw new Exception("Error reading region " + f.getName());
}
int recLv = Integer.parseInt(s.trim()); // use s because s is read in from last thing
int dangerLv = Integer.parseInt(scan.nextLine().trim());
World w = plugin.getServer().getWorld(scan.nextLine().trim());
String[] c = scan.nextLine().trim().split(" ");
if (w == null)
return;
String regionName = f.getName().substring(0, f.getName().indexOf(".txt"));
if (regionName.contains("."))
regionName = regionName.substring(0, regionName.lastIndexOf("."));
Region r = new Region(regionName, recLv, dangerLv, w, points);
r.startTime = Long.parseLong(c[0]);
r.endTime = Long.parseLong(c[1]);
r.timeDiff = r.endTime - r.startTime;
r.cycleLengthSeconds = Integer.parseInt(c[2]);
regions.add(r);
} catch (Exception e) {
e.printStackTrace();
}
}
@EventHandler
public void onPlayerMove(PlayerMoveEvent event) {
if (event.getFrom().getBlock().equals(event.getTo().getBlock()))
return;
initiateCheck(event.getPlayer());
}
@EventHandler
public void onPlayerTeleport(PlayerTeleportEvent event) {
RScheduler.schedule(plugin, () -> {
initiateCheck(event.getPlayer());
}, RTicks.seconds(1));
}
private void initiateCheck(Player p) {
if (p == null)
return;
final PlayerDataRPG pd = plugin.getPD(p);
if (pd != null && pd.isValid()) {
try {
checkRegion(p, pd);
checkArea(p, pd);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void checkArea(Player p, PlayerDataRPG pd) {
if (!pd.loadedSQL)
return;
if (System.currentTimeMillis() - pd.lastAreaCheck > 200) {
WorldBossManager.checkLocation(p);
pd.lastAreaCheck = System.currentTimeMillis();
TriggerArea ta = getArea(p);
if (ta != null) {
// only run triggerarea action once a second after the first time
// longer cooldown must be implemented manually in TriggerArea implementations
if (ta != pd.lastArea) { // last area has changed, force trigger immediately
pd.lastArea = ta;
pd.lastAreaTriggered = System.currentTimeMillis();
ta.runActions(p, pd);
} else { // area hasn't changed (ta == last)
if (System.currentTimeMillis() - pd.lastAreaTriggered > 1000) { // has it been 1 sec? if so then trigger
pd.lastAreaTriggered = System.currentTimeMillis();
ta.runActions(p, pd);
}
}
}
}
}
public static void checkRegion(Player p, PlayerDataRPG pd) {
if (!pd.loadedSQL)
return;
boolean changedRegion = false;
if (System.currentTimeMillis() - pd.lastRegionCheck > 200) {
pd.lastRegionCheck = System.currentTimeMillis();
Region r = getRegion(p);
if (pd.region == null || pd.region != r) {
Region last = pd.region;
pd.region = r;
r.sendWelcome(p, last);
changedRegion = true;
pd.lastRegionChange = System.currentTimeMillis();
}
}
long delay = System.currentTimeMillis() - pd.lastRegionChange < 10000 ? 100 : 1000;
if (changedRegion || System.currentTimeMillis() - pd.lastRegionTimeUpdate > delay) {
updateTime(p, pd);
}
}
public static void updateTime(Player p, PlayerDataRPG pd) {
if (pd.region != null) {
pd.lastRegionTimeUpdate = System.currentTimeMillis();
// PacketManager.registerTime(p, pd.region.getTime());
}
}
public static TriggerArea getArea(Player p) {
return getArea(p.getLocation());
}
public static TriggerArea getArea(Location loc) {
TriggerArea curr = null;
for (TriggerArea a : areas) {
if (a.isWithin(loc)) {
if (curr == null || a.size < curr.size)
curr = a;
}
}
return curr;
}
public static Region getRegion(Player p) {
return getRegion(p.getLocation());
}
public static Region getRegion(Location loc) {
Region curr = null;
for (Region r : regions) {
if (r.isWithin(loc)) {
if (curr == null || r.size < curr.size)
curr = r;
}
}
if (curr == null) {
// This should only happen if a world is loaded manually after regions have loaded
Region r = new Region(GENERAL_NAME, 1, 2, loc.getWorld(), Arrays.asList(MIN_POINT, MAX_POINT));
regions.add(r);
return r;
}
return curr;
}
}
|
package com.gen.serve;
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
@WebServlet(name="GenServlet",urlPatterns={"/GenServlet"})
public class GenServlet extends GenericServlet {
@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = res.getWriter();
ServletConfig sc = getServletConfig();
String name = sc.getInitParameter("Name");
out.println("Welcome ");
ServletContext context = sc.getServletContext();
String channel = context.getInitParameter("channelName");
out.println("Channelname is" +channel);
out.close();
}
}
|
package pokergame;
/**
* 创建两名玩家 属性:ID,姓名,手牌(扑克牌的集合)
*/
import java.util.ArrayList;
import java.util.List;
public class Player {
private int id;
private String name;
public List<Poker> playerPockers;
public List<Poker> getPlayerPockers() {
return playerPockers;
}
public void setPlayerPockers(List<Poker> playerPockers) {
this.playerPockers = playerPockers;
}
public Player(int id,String name){
this.id=id;
this.name=name;
playerPockers=new ArrayList<Poker>();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
package com.romens.yjkgrab.table;
/**
* Created by myq on 15-12-12.
*/
public class RuntimeGrabingTable extends BaseTable {
public static final String RuntimeGrabing = "RuntimeGrabing";
public static final String grabdate = "grabdate";
public static final String installationId = "installationId";
public static final String order = "order";
}
|
package heylichen.alg.graph.structure;
public interface Graph {
int getVertexCount();
int getEdgeCount();
void addEdge(int v, int w);
Iterable<Integer> getAdjacentVertices(int vertex);
}
|
package com.mitobit.camel.component.nexmo;
import org.apache.camel.Exchange;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.util.ObjectHelper;
import com.nexmo.messaging.sdk.messages.BinaryMessage;
import com.nexmo.messaging.sdk.messages.Message;
import com.nexmo.messaging.sdk.messages.TextMessage;
public class SmsBinding {
public Message createSmsMessage(NexmoEndpoint endpoint, Exchange exchange) {
String from = exchange.getIn().getHeader(NexmoConstants.NEXMO_FROM, endpoint.getFrom(), String.class);
String to = exchange.getIn().getHeader(NexmoConstants.NEXMO_TO, endpoint.getTo(), String.class);
if (ObjectHelper.isEmpty(from)) {
from = NexmoConstants.NEXMO_DEFAULT_FROM;
}
if (ObjectHelper.isEmpty(to)) {
throw new RuntimeCamelException("Missing 'to' param");
}
final Object messageBody = exchange.getIn().getBody();
if (messageBody instanceof String) {
return new TextMessage(from, to, (String) messageBody);
} else if (messageBody instanceof byte[]) {
return new BinaryMessage(from, to, (byte[]) messageBody, null);
}
throw new RuntimeCamelException("Cannot create a Nexmo message by this message body " + messageBody);
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
class rectarea{
int l,b;
rectarea(int x,int y){
l=x;
b=y;
}
int area() {
return l*b;
}
}
class rectvolume extends rectarea {
int h;
rectvolume(int x,int y,int z){
super(x,y);
h=z;
}
int volume(){
return l*b*h;
}
}
public class singleinheritance {
public static void main(String[] args) {
// TODO code application logic here
rectvolume obj1=new rectvolume(5,5,5);
int area1 = obj1.area();
int vol= obj1.volume();
System.out.println("area =" +area1);
System.out.println("volume =" +vol);
}
}
|
package domen;
import java.io.Serializable;
import java.lang.reflect.Constructor;
/**
* Predstavlja proizvod koji se prodaje u prodavnici. Objekte je moguce cuvati u
* fajlovima. {@link Serializable}
*
* @author Milos Cvetkovic
*
*/
@SuppressWarnings("serial")
public class Proizvod implements Serializable {
/**
* Jedinstvena sifra proizvoda.
*
* @author Milos Cvetkovic
*/
private String sifra;
/**
* Naziv proizvoda.
*
* @author Milos Cvetkovic
*/
private String naziv;
/**
* Cena proizvoda.
*
* @author Milos Cvetkovic
*/
private double cena;
/**
* {@link Constructor} koji kreira novi proizvod.
*
* @param sifra
* String
* @param naziv
* String
* @param cena
* double
* @author Milos Cvetkovic
*/
public Proizvod(String sifra, String naziv, double cena) {
setSifra(sifra);
setNaziv(naziv);
setCena(cena);
}
/**
* Vraca sifru proizvoda.
*
* @return {@link String}
* @author Milos Cvetkovic
*/
public String getSifra() {
return sifra;
}
/**
* Postavlja sifru proizvoda.
*
* @param sifra
* String
* @author Milos Cvetkovic
*/
public void setSifra(String sifra) {
if (sifra == null || sifra.isEmpty()) {
throw new RuntimeException("");
} else {
this.sifra = sifra;
}
}
/**
* Vraca naziv proizvoda.
*
* @return {@link String}
* @author Milos Cvetkovic
*/
public String getNaziv() {
return naziv;
}
/**
* Postavlja naziv proizvoda.
*
* @param naziv
* String
* @author Milos Cvetkovic
*/
public void setNaziv(String naziv) {
if (naziv == null || naziv.isEmpty()) {
throw new RuntimeException("");
} else {
this.naziv = naziv;
}
}
/**
* Vraca cenu proizvoda.
*
* @return double
* @author Milos Cvetkovic
*/
public double getCena() {
return cena;
}
/**
* Postavlja cenu proizvoda.
*
* @param cena
* double
* @author Milos Cvetkovic
*/
public void setCena(double cena) {
if (cena < 0) {
throw new RuntimeException("");
} else {
this.cena = cena;
}
}
/**
* Redefinisana hashCode() metoda klase {@link Object} prema parametru
* sifra.
*
* @return int
* @author Milos Cvetkovic
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((sifra == null) ? 0 : sifra.hashCode());
return result;
}
/**
* Redefinisana equals() metoda klase {@link Object} prema parametru sifra.
* Vraca true ako je parametar sifra isti kao kod zadatog proizvoda.
*
* @return boolean
* @author Milos Cvetkovic
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Proizvod other = (Proizvod) obj;
if (sifra == null) {
if (other.sifra != null)
return false;
} else if (!sifra.equals(other.sifra))
return false;
return true;
}
/**
* Vraca sve podatke o proizvodu.
*
* @return {@link String}
* @author Milos Cvetkovic
*/
@Override
public String toString() {
return "Proizvod [sifra=" + sifra + ", naziv=" + naziv + ", cena=" + cena + "]";
}
}
|
package zhuoxin.com.viewpagerdemo.activity;
import android.content.Intent;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import zhuoxin.com.viewpagerdemo.R;
import zhuoxin.com.viewpagerdemo.activity.base.BaseActivity;
import zhuoxin.com.viewpagerdemo.interfaces.DeleteInterface;
import zhuoxin.com.viewpagerdemo.myview.FlowAddLayout;
import zhuoxin.com.viewpagerdemo.myview.FlowLayout;
import zhuoxin.com.viewpagerdemo.utils.sharedpres;
public class TitleActivity extends BaseActivity{
private Toolbar toolbar;
private TextView btn_add;
private FlowLayout flowLayout;
private FlowAddLayout flow_add;
private boolean flag = false;
public void setContentLayout() {
setContentView(R.layout.activity_title);
}
public void initView() {
toolbar=(Toolbar)findViewById(R.id.title_tool_bar);
toolbar.setNavigationIcon(R.drawable.btn_return);
toolbar.setTitle("");
toolbar.setTitleTextColor(getResources().getColor(R.color.colorWhite));
setSupportActionBar(toolbar);
flowLayout=(FlowLayout)findViewById(R.id.title_flow_layout);
flow_add=(FlowAddLayout)findViewById(R.id.title_flow_add);
btn_add=(TextView) findViewById(R.id.activity_title_add);
}
public void initListener() {
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
finish();
}
});
btn_add.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent();
intent.putExtra("flag",flag);
setResult(101,intent);
finish();
}
});
}
public void initData() {
flowLayout.getSetData(sharedpres.getSets(this));
flowLayout.setDeleteInterface(new DeleteInterface() {
public void deleteData() {
flowLayout.getSetData(sharedpres.getSets(TitleActivity.this));
flow_add.getSetData(sharedpres.getSetAll(TitleActivity.this));
flag=true;
}
});
flow_add.getSetData(sharedpres.getSetAll(this));
flow_add.setDeleteInterface(new DeleteInterface() {
public void deleteData() {
flowLayout.getSetData(sharedpres.getSets(TitleActivity.this));
flow_add.getSetData(sharedpres.getSetAll(TitleActivity.this));
flag=true;
}
});
}
}
|
package com.zantong.mobilecttx.utils.popwindow;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import com.zantong.mobilecttx.R;
import com.zantong.mobilecttx.utils.Tools;
/**
* 作者:王海洋
* 时间:2016/6/7 09:39
*/
public class IOSpopwindow extends PopupWindow{
public IOSpopwindow(final Context mContext, View parent) {
View view = View
.inflate(mContext, R.layout.item_popupwindows, null);
view.startAnimation(AnimationUtils.loadAnimation(mContext,
R.anim.fade_ins));
LinearLayout ll_popup = (LinearLayout) view
.findViewById(R.id.ll_popup);
ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
R.anim.push_bottom_in_2));
setWidth(ViewGroup.LayoutParams.FILL_PARENT);
setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
setBackgroundDrawable(new BitmapDrawable());
setFocusable(true);
setOutsideTouchable(true);
setContentView(view);
showAtLocation(parent, Gravity.BOTTOM, 0, 0);
update();
TextView line_bg = (TextView) view
.findViewById(R.id.line_bg);
Button bt1 = (Button) view
.findViewById(R.id.item_popupwindows_camera);
Button bt2 = (Button) view
.findViewById(R.id.item_popupwindows_Photo);
Button bt3 = (Button) view
.findViewById(R.id.item_popupwindows_cancel);
line_bg.setBackgroundColor(mContext.getResources().getColor(R.color.appmain));
bt3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dismiss();
}
});
}
public IOSpopwindow(final Context mContext, View parent, final View.OnClickListener btn1, final View.OnClickListener btn2) {
final View view = View
.inflate(mContext, R.layout.item_popupwindows, null);
view.startAnimation(AnimationUtils.loadAnimation(mContext,
R.anim.fade_ins));
final LinearLayout ll_popup = (LinearLayout) view
.findViewById(R.id.ll_popup);
ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
R.anim.push_bottom_in_2));
setWidth(ViewGroup.LayoutParams.FILL_PARENT);
setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
setBackgroundDrawable(new BitmapDrawable());
setFocusable(true);
setOutsideTouchable(true);
setContentView(view);
showAtLocation(parent, Gravity.BOTTOM, 0, 0);
update();
TextView line_bg = (TextView) view
.findViewById(R.id.line_bg);
Button bt1 = (Button) view
.findViewById(R.id.item_popupwindows_camera);
Button bt2 = (Button) view
.findViewById(R.id.item_popupwindows_Photo);
Button bt3 = (Button) view
.findViewById(R.id.item_popupwindows_cancel);
line_bg.setBackgroundColor(mContext.getResources().getColor(R.color.appmain));
bt1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
btn1.onClick(v);
dismiss();
}
});
bt2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
btn2.onClick(v);
dismiss();
}
});
bt3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dismiss();
}
});
view.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int height = ll_popup.getTop();
int y=(int) event.getY();
if(event.getAction()==MotionEvent.ACTION_UP){
if(y<height){
dismiss();
}
}
return true;
}
});
}
public IOSpopwindow(final Context mContext, View parent, String btnText1, String btnText2, final View.OnClickListener btn1, final View.OnClickListener btn2) {
final View view = View
.inflate(mContext, R.layout.item_popupwindows, null);
view.startAnimation(AnimationUtils.loadAnimation(mContext,
R.anim.fade_ins));
final LinearLayout ll_popup = (LinearLayout) view
.findViewById(R.id.ll_popup);
ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
R.anim.push_bottom_in_2));
setWidth(ViewGroup.LayoutParams.FILL_PARENT);
setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
setBackgroundDrawable(new BitmapDrawable());
setFocusable(true);
setOutsideTouchable(true);
setContentView(view);
showAtLocation(parent, Gravity.BOTTOM, 0, 0);
update();
TextView line_bg = (TextView) view
.findViewById(R.id.line_bg);
Button bt1 = (Button) view
.findViewById(R.id.item_popupwindows_camera);
Button bt2 = (Button) view
.findViewById(R.id.item_popupwindows_Photo);
Button bt3 = (Button) view
.findViewById(R.id.item_popupwindows_cancel);
LinearLayout btll1 = (LinearLayout) view
.findViewById(R.id.item_popupwindows_camera_ll);
LinearLayout btll2 = (LinearLayout) view
.findViewById(R.id.item_popupwindows_Photo_ll);
line_bg.setBackgroundColor(mContext.getResources().getColor(R.color.appmain));
bt1.setText(btnText1);
bt2.setText(btnText2);
if(btn2 == null){
btll2.setVisibility(View.GONE);
}
if(btn1 == null){
btll1.setVisibility(View.GONE);
}
bt1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
btn1.onClick(v);
dismiss();
}
});
bt2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
btn2.onClick(v);
dismiss();
}
});
bt3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dismiss();
}
});
view.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int height = ll_popup.getTop();
int y=(int) event.getY();
if(event.getAction()==MotionEvent.ACTION_UP){
if(y<height){
dismiss();
}
}
return true;
}
});
}
public IOSpopwindow(final Context mContext, View parent, String btnText1, String btnText2, final View.OnClickListener btn1, final View.OnClickListener btn2, String notice) {
final View view = View
.inflate(mContext, R.layout.item_popupwindows, null);
view.startAnimation(AnimationUtils.loadAnimation(mContext,
R.anim.fade_ins));
final LinearLayout ll_popup = (LinearLayout) view
.findViewById(R.id.ll_popup);
ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
R.anim.push_bottom_in_2));
setWidth(ViewGroup.LayoutParams.FILL_PARENT);
setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
setBackgroundDrawable(new BitmapDrawable());
setFocusable(true);
setOutsideTouchable(true);
setContentView(view);
showAtLocation(parent, Gravity.BOTTOM, 0, 0);
update();
TextView line_bg = (TextView) view
.findViewById(R.id.line_bg);
Button bt1 = (Button) view
.findViewById(R.id.item_popupwindows_camera);
Button bt2 = (Button) view
.findViewById(R.id.item_popupwindows_Photo);
Button bt3 = (Button) view
.findViewById(R.id.item_popupwindows_notice);
Button bt4 = (Button) view
.findViewById(R.id.item_popupwindows_cancel);
LinearLayout btll1 = (LinearLayout) view
.findViewById(R.id.item_popupwindows_camera_ll);
LinearLayout btll2 = (LinearLayout) view
.findViewById(R.id.item_popupwindows_Photo_ll);
LinearLayout noticell = (LinearLayout) view
.findViewById(R.id.item_popupwindows_notice_ll);
line_bg.setBackgroundColor(mContext.getResources().getColor(R.color.appmain));
bt1.setText(btnText1);
bt2.setText(btnText2);
if(btn2 == null){
btll2.setVisibility(View.GONE);
}
if(!Tools.isStrEmpty(notice)){
bt3.setText(notice);
noticell.setVisibility(View.VISIBLE);
}else{
noticell.setVisibility(View.GONE);
}
bt1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
btn1.onClick(v);
dismiss();
}
});
bt2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
btn2.onClick(v);
dismiss();
}
});
bt4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dismiss();
}
});
view.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int height = ll_popup.getTop();
int y=(int) event.getY();
if(event.getAction()==MotionEvent.ACTION_UP){
if(y<height){
dismiss();
}
}
return true;
}
});
}
public IOSpopwindow(final Context mContext, View parent, final View.OnClickListener btn1) {
final View view = View
.inflate(mContext, R.layout.item_nomal_popupwindows, null);
view.startAnimation(AnimationUtils.loadAnimation(mContext,
R.anim.fade_ins));
final LinearLayout ll_popup = (LinearLayout) view
.findViewById(R.id.ll_popup);
ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
R.anim.push_bottom_in_2));
setWidth(ViewGroup.LayoutParams.FILL_PARENT);
setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
setBackgroundDrawable(new BitmapDrawable());
setFocusable(true);
setOutsideTouchable(true);
setContentView(view);
showAtLocation(parent, Gravity.BOTTOM, 0, 0);
update();
TextView line_bg = (TextView) view
.findViewById(R.id.line_bg);
Button bt1 = (Button) view
.findViewById(R.id.item_popupwindows_camera);
Button bt2 = (Button) view
.findViewById(R.id.item_popupwindows_cancel);
line_bg.setBackgroundColor(mContext.getResources().getColor(R.color.appmain));
bt1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
btn1.onClick(v);
dismiss();
}
});
bt2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dismiss();
}
});
view.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int height = ll_popup.getTop();
int y=(int) event.getY();
if(event.getAction()==MotionEvent.ACTION_UP){
if(y<height){
dismiss();
}
}
return true;
}
});
}
}
|
package com.test.array;
import com.test.base.ArrayGraph;
import com.test.base.ArraySolution;
/**
* DFS:递归方式
* .指定点开始搜索
* @author YLine
*
* 2019年2月22日 下午3:52:51
*/
public class SolutionDFS implements ArraySolution
{
private int startIndex = 0;
@Override
public Object[] traverse(ArrayGraph graph)
{
int size = graph.getSize();
Object[] objArray = new Object[size];
dfs(graph, objArray, startIndex, 0);
return objArray;
}
public void setStartIndex(int startIndex)
{
if (startIndex >= 0)
{
this.startIndex = startIndex;
}
}
/**
* @param index 开始位置
* @param deep 遍历深度
*/
private void dfs(ArrayGraph graphs, Object[] objArray, int index, int deep)
{
if (graphs.isVisited(index))
{
return;
}
Object obj = graphs.getValue(index);
objArray[deep] = obj;
deep++;
for (int next : graphs.getNextArray(index))
{
dfs(graphs, objArray, next, deep);
}
}
}
|
package BinaryTrees;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;
public class BottomViewOfBT {
static HashMap<Node, Integer > node_distance = new HashMap<>();
public void topView(Node root) {
if(root == null)
return ;
node_distance.put(root,0);
traverse(root,0);
/* <distance(encountered for the first time), data> */
HashMap<Integer, Integer> level_firstview = new HashMap<>();
level_firstview.put(root.data, 0);
Queue<Node> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()) {
Node temp = queue.poll();
if(temp.left != null) {
int dist = node_distance.get(temp.left);
// if(level_firstview.get(dist) == null) {
level_firstview.put(dist, temp.left.data);
queue.add(temp.left);
// }
}
if(temp.right != null) {
int dist = node_distance.get(temp.right);
// if(level_firstview.get(dist) == null) {
level_firstview.put(dist, temp.right.data);
queue.add(temp.right);
// }
}
}
for(Node temp: node_distance.keySet())
System.out.println(node_distance.get(temp)+ " "+temp.data);
System.out.println("-------------------------------------");
for(int dist : level_firstview.keySet())
System.out.println("dist "+ dist +" value "+ level_firstview.get(dist));
}
public static void traverse(Node root, int level) {
if(root == null)
return ;
if(root.left != null) {
node_distance.put(root.left, level-1);
traverse(root.left, level-1);
}
if(root.right != null) {
node_distance.put(root.right, level+1);
traverse(root.right, level+1);
}
}
public static void main(String[] args) {
BottomViewOfBT obj = new BottomViewOfBT();
Node root = new Node();
root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.right = new Node(4);
root.left.right.right = new Node(5);
root.left.right.right.right = new Node(6);
System.out.println("Following are nodes in top view of Binary Tree");
obj.topView(root);
}
}
|
package com.misa.pool.dom;
import java.io.Serializable;
public class BaseForm implements Serializable
{
/**
*
*/
private static final long serialVersionUID = -6356809034255559137L;
}
|
package escolasis.modelo.xml;
import java.util.List;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.ParameterStyle;
import javax.jws.soap.SOAPBinding.Style;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import escolasis.modelo.PapelPessoa;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class ListaPapelPessoa {
@XmlElement(name = "papel")
List<PapelPessoa> papeis;
public ListaPapelPessoa() {
}
public ListaPapelPessoa(List<PapelPessoa> lista) {
this.papeis = lista;
}
public List<PapelPessoa> getPapeis() {
return papeis;
}
public void setPapeis(List<PapelPessoa> papeis) {
this.papeis = papeis;
}
@Override
public String toString() {
return "ListaPapelPessoa [papeis=" + papeis + "]";
}
}
|
/* HibernateSessionContextListener.java
Purpose:
Description:
History:
Tue Sep 11 12:55:11 2006, Created by henrichen
Copyright (C) 2006 Potix Corporation. All Rights Reserved.
{{IS_RIGHT
This program is distributed under LGPL Version 2.1 in the hope that
it will be useful, but WITHOUT ANY WARRANTY.
}}IS_RIGHT
*/
package org.zkoss.zkplus.hibernate;
import org.zkoss.zkplus.util.ThreadLocals;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.UiException;
import org.zkoss.zk.ui.Execution;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.WebApp;
import org.zkoss.zk.ui.util.Configuration;
import org.zkoss.zk.ui.util.ExecutionInit;
import org.zkoss.zk.ui.util.ExecutionCleanup;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventThreadInit;
import org.zkoss.zk.ui.event.EventThreadResume;
import org.zkoss.lang.Classes;
import org.zkoss.util.logging.Log;
import java.util.Map;
import java.util.HashMap;
import java.lang.reflect.Field;
import java.util.List;
/**
* <p>Listener to make sure each ZK thread got the same hibernat session context;
* used with Hibernate's "thread" session context (org.hibernate.context.ThreadLocalSessionContext).
* </p>
* <p>
* This listener is used with Hibernate's (version 3.1+) "thread" session context.
* That is, when you specify </p>
* <pre><code>
* hibernate.current_session_context_class = thread
* </code></pre>
*
* <p>then you have to add following lines in application's WEB-INF/zk.xml:</p>
* <pre><code>
* <listener>
* <description>Hibernate thread session context management</description>
* <listener-class>org.zkoss.zkplus.hibernate.HibernateSessionContextListener</listener-class>
* </listener>
* </code></pre>
* <p>Applicable to Hibernate version 3.2.ga or later</p>
* @author henrichen
*/
public class HibernateSessionContextListener implements ExecutionInit, ExecutionCleanup, EventThreadInit, EventThreadResume {
private static final Log log = Log.lookup(HibernateSessionContextListener.class);
private static final String HIBERNATE_SESSION_MAP = "org.zkoss.zkplus.hibernate.SessionMap";
private static final Object SOMETHING = new Object();
private final boolean _enabled; //whether event thread enabled
public HibernateSessionContextListener() {
final WebApp app = Executions.getCurrent().getDesktop().getWebApp();
_enabled = app.getConfiguration().isEventThreadEnabled();
}
//-- ExecutionInit --//
public void init(Execution exec, Execution parent) {
if (_enabled) {
if (parent == null) { //root execution
//always prepare a ThreadLocal SessionMap in Execution attribute
Map map = getSessionMap();
if (map == null) {
map = new HashMap();
setSessionMap(map); //copy to servlet thread's ThreadLocal
}
exec.setAttribute(HIBERNATE_SESSION_MAP, map); // store in Execution attribute
//20060912, henrichen: tricky. Stuff something into session map to
//prevent the map from being removed from context ThreadLocal by the
//ThreadLocalSessionContext#unbind() when it is empty.
map.put(SOMETHING, null);
}
}
}
//-- ExecutionCleanup --//
public void cleanup(Execution exec, Execution parent, List errs) {
if (_enabled) {
if (parent == null) { //root execution
Map map = getSessionMap();
if (map != null) {
//20060912, henrichen: tricky. Remove the previously stuffed
//something (when ExecutuionInit#init() is called) from
//session map to make the map possible to be removed by the
//ThreadLocalSessionContext#unbind() when it is empty.
map.remove(SOMETHING);
}
exec.removeAttribute(HIBERNATE_SESSION_MAP);
}
}
}
//-- EventThreadInit --//
public void prepare(Component comp, Event evt) {
//do nothing
}
public boolean init(Component comp, Event evt) {
if (_enabled) {
//Copy SessionMap stored in Execution attribute into event's ThreadLocal
Map map = (Map) Executions.getCurrent().getAttribute(HIBERNATE_SESSION_MAP);
setSessionMap(map); //copy to event thread's ThreadLocal
}
return true;
}
//-- EventThreadResume --//
public void beforeResume(Component comp, Event evt) {
//do nothing
}
public void afterResume(Component comp, Event evt) {
if (_enabled) {
//always keep the prepared SessionMap in event's ThreadLocal
Map map = (Map) Executions.getCurrent().getAttribute(HIBERNATE_SESSION_MAP);
setSessionMap(map); //copy to event thread's ThreadLocal
}
}
public void abortResume(Component comp, Event evt){
//do nothing
}
//-- utilities --//
private void setSessionMap(Map map) {
getContextThreadLocal().set(map);
}
private Map getSessionMap() {
return (Map) getContextThreadLocal().get();
}
private ThreadLocal getContextThreadLocal() {
return ThreadLocals.getThreadLocal("org.hibernate.context.ThreadLocalSessionContext", "context");
}
}
|
package Practice;
import java.util.Scanner;
public class NestedPractice {
public static String BMI() {
Scanner scanner = new Scanner(System.in);
System.out.println("身高(m):");
double height = scanner.nextDouble();
System.out.println("体重(kg):");
double weight = scanner.nextDouble();
double BMI = weight / (height * height);
if (BMI < 18.5)
return "过轻";
else if (18.5 <= BMI && BMI < 24)
return "正常";
else if (24 <= BMI && BMI < 27)
return "过重";
else if (27 <= BMI && BMI < 30)
return "轻肥";
else if (30 <= BMI && BMI < 35)
return "中肥";
else
return "重肥";
}
public static String LeapYear(){
Scanner scanner = new Scanner(System.in);
System.out.println("年份:");
int year = scanner.nextInt();
if ((year%4 == 0 && year%100 != 0) || year%400 == 0)
return "闰年";
else
return "非闰年";
}
public static String Season() {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入月份");
int month = scanner.nextInt();
return switch (month) {
case 1, 2, 3 -> "spring";
case 4, 5, 6 -> "summer";
case 7, 8, 9 -> "fall";
case 10,11,12 -> "winter";
default -> "invalid";
};
}
public static int factorial() { //阶乘
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个整数");
int i = scanner.nextInt();
int sum = 1;
while (i>0) {
sum = sum * i;
i--;
}
/* do {
sum = sum * i;
i--;
} while (i>0); */
return sum;
}
public static int Begging() { // 0 1 2 4 8 16,等比数列求和
int income = 0;
int total = 0;
for (int i=0; i<=10; i++) {
if (i<=1)
income = i;
else
income = income*2;
total = total + income;
}
int sum = 0;
for (int i = 0; i<= 10; i++) {
if (i>=1)
sum = sum*2 + 1; // S(n) = 2S(n-1)+1
System.out.println("第"+i+"天要了"+sum+"块钱");
}
return sum;
}
public static void ContinueAndBreak() {
for (int i=0; i<=100; i++) {
if (i%3 == 0 || i%5 == 0)
continue;
System.out.println(i);
}
boolean breakout = false; //是否终止外部循环的标记
for (int i = 0; i < 10; i++) {
for (int j = 1; j < 10; j++) {
System.out.println(i+":"+j);
if (j%2 == 0) {
breakout = true;
break;
}
}
if (breakout) //判断是否终止外部循环
break;
}
outLoop: //使用标签结束外部循环
for (int i = 0; i < 10; i++) {
for (int j = 1; j < 10; j++) {
System.out.println(i+":"+j);
if (0==j%2)
break outLoop; //如果是双数,结束当前循环
}
}
}
public static void GoldenRatio() {
double temp, min = 1;
int m = 0, n = 0;
for (int i = 1; i <= 20; i++) {
for (int j = 1; j <=20; j++) {
if (i%2 == 0 && j%2 == 0)
continue;
if (i >= j)
continue;
temp = Math.abs((double) i/j - 0.618);
if (temp < min) {
min = temp;
m = i;
n = j;
System.out.printf("%d, %d, %f %n", m, n, (double)m/n);
}
}
}
System.out.printf("离黄金分割点最近的两个数是:%d / %d = %f", m, n, (double)m/n);
}
public static void Narcissistic() {
for (int i = 100; i < 1000; i++) {
String num = String.valueOf(i); //int转String
//String num = Integer.toString(i);
int first = Integer.parseInt(Character.toString(num.charAt(0))); //char转int
int second = Integer.parseInt(String.valueOf(num.charAt(1)));
int third = Character.getNumericValue(num.charAt(2));
int number = first*first*first + second*second*second + third*third*third;
if (number == i)
System.out.println(i);
}
}
public static void Primary() {
Start:
for (int a = 0; a < 8; a ++) {
for (int b = 0; b < 8; b++) {
for (int c = 0; c < 14; c++) {
for (int d = 0; d < 10; d++) {
if (a + b == 8 && a + c == 14 && b + d == 10 && c - d == 6) {
System.out.println("a = " + a + "\nb = " + b + "\nc = " + c + "\nd = " + d);
break Start;
}
}
}
}
}
}
public static void main(String[] args) {
//while (true) { System.out.println(BMI()); }
//while (true) { System.out.println(LeapYear()); }
//System.out.println(Season());
//System.out.println(factorial());
//System.out.println(Begging());
//Nested.ContinueAndBreak();
//Nested.GoldenRatio();
//Nested.Narcissistic();
NestedPractice.Primary();
}
}
|
package com.asm.persistance.node.client;
import com.asm.entities.Automobile;
import com.asm.entities.MockData;
import com.asm.entities.client.Client;
import com.asm.interactors.ClientPersistence;
import com.fasterxml.jackson.databind.*;
import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class ClientNodePersistence implements ClientPersistence {
ObjectMapper mapper;
public ClientNodePersistence() {
this.mapper = new ObjectMapper();
}
@Override
public void save(Client c) throws IOException {
String json = mapper.writeValueAsString(c);
String response = NodePersistence.sendPostRequest(json, "http://localhost:8080/clients/new");
System.out.println(json);
}
@Override
public Client read(String id) throws IOException {
String response = NodePersistence.setRequest("http://localhost:8080/clients/" + id,"GET");
return mapper.readValue(response, Client.class);
}
@Override
public List<Client> readAll() throws IOException {
List<Client> clientsList = new ArrayList<>();
String response = NodePersistence.setRequest("http://localhost:8080/clients/","GET");
System.out.println("response = " + response);
JsonNode rootNode = new ObjectMapper().readTree(new StringReader(response));
JsonNode clientsNode = rootNode.get("clients");
for (int i = 0; i < clientsNode.size(); i++) {
JsonNode clientJson = clientsNode.get(i);
JsonNode clientCars = clientJson.get("cars");
List<Automobile> carsList = new ArrayList<>();
if (clientCars.size() != 0) {
for (final JsonNode carNode : clientCars) {
//carsList.add(mapper.readValue(carNode.toString(), Automobile.class));
}
}
Client client = new Client();
client.setId(clientJson.get("_id").textValue());
client.setName(clientJson.get("name").textValue());
client.setSurnames(clientJson.get("surnames").textValue());
client.setPhone(clientJson.get("phone").textValue());
client.setEmail(clientJson.get("email").textValue());
client.setAddress(clientJson.get("address").textValue());
client.setCars(MockData.createMockAutomobileList());
clientsList.add(client);
}
return clientsList;
}
@Override
public void update(Client c) throws IOException {
String json = mapper.writeValueAsString(c);
String response = NodePersistence.sendPostRequest(json, "http://localhost:8080/client/update");
}
@Override
public void delete(String id) throws IOException {
String response = NodePersistence.setRequest("http://localhost:8080/clients/" + id,"DELETE");
}
}
|
package com.Hackerrank.algos.implementation;
import java.util.Scanner;
public class BiggerIsGreater {
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 t=sc.nextInt();
String[] input=new String[t];
char[] ch=null;
for(int i=0;i<t;i++){
input[i]=sc.next();
}
for(int i=0;i<t;i++){
ch=input[i].toCharArray();
char firstChar=' ';
char celing=' ';
int firstCharPos=0;
int celingPos=0;
int flag=0;
for(int j=ch.length-1;j>0;j--){
if(ch[j-1] < ch[j]){
firstChar=ch[j-1];
firstCharPos=j-1;
celing = ch [j];
celingPos=j;
flag=1;
break;
}
}
if(flag==0){
System.out.println("no answer");
}else{
for(int k=firstCharPos+1;k<ch.length;k++){
if(ch[k] < celing && ch[k] > firstChar){
celing = ch[k];
celingPos=k;
}
}
//swapping celing and first Char
if(celing != ' ' && firstChar != ' ' ){
ch[firstCharPos]=celing;
ch[celingPos]=firstChar;
}
char temp;
for(int j=firstCharPos+1;j<ch.length;j++){
for(int k=firstCharPos+2;k<ch.length-j+firstCharPos+1;k++){
if(ch[k-1]>ch[k]){
temp=ch[k-1];
ch[k-1]=ch[k];
ch[k]=temp;
}
}
}
System.out.println(String.valueOf(ch));
}
}
sc.close();
}
}
|
/**
* 湖北安式软件有限公司
* Hubei Anssy Software Co., Ltd.
* FILENAME : DatadictEntity.java
* PACKAGE : com.anssy.venturebar.base.entity
* CREATE DATE : 2016-8-13
* AUTHOR : make it
* MODIFIED BY :
* DESCRIPTION :
*/
package com.anssy.venturebar.base.entity;
import com.anssy.webcore.core.entity.IdEntity;
/**
* @author make it
* @version SVN #V1# #2016-8-13#
* 基础_数据字典
*/
public class DatadictEntity extends IdEntity {
private static final long serialVersionUID = -6593114801733153454L;
/**
* 类别
*/
private String category;
/**
* 顺序
*/
private int showIndex;
/**
* 常量
*/
private Long literal;
/**
* 描述
*/
private String dictDesc;
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public int getShowIndex() {
return showIndex;
}
public void setShowIndex(int showIndex) {
this.showIndex = showIndex;
}
public Long getLiteral() {
return literal;
}
public void setLiteral(Long literal) {
this.literal = literal;
}
public String getDictDesc() {
return dictDesc;
}
public void setDictDesc(String dictDesc) {
this.dictDesc = dictDesc;
}
}
|
package br.com.webstore.repository;
import br.com.webstore.model.OrderProduct;
import br.com.webstore.model.OrderProductPK;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
* @project: api-webstore
* @author: Lucas Kanô de Oliveira (lucaskano)
* @since: 23/04/2020
*/
public interface OrderProductRepository extends PagingAndSortingRepository<OrderProduct, OrderProductPK> {
}
|
package ru.bookstore.domain;
import javax.persistence.*;
@Entity
@Table(name = "Address")
public class AddressEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
private Integer id;
@Column(name = "city", nullable = false)
private String city;
@Column(name = "street", nullable = false)
private String street;
@Column(name = "build", nullable = false)
private String build;
@Column(name = "room", nullable = false)
private int room;
public AddressEntity(String city, String street, String build, int room) {
this.city = city;
this.street = street;
this.build = build;
this.room = room;
}
public AddressEntity() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getBuild() {
return build;
}
public void setBuild(String build) {
this.build = build;
}
public int getRoom() {
return room;
}
public void setRoom(int room) {
this.room = room;
}
}
|
public class Main {
public static void main(String[] args) {
// write your code here
SplayRecordTree<String, String> srt = new SplayRecordTree<>();
srt.insert("www.youkneetee.com", "192.168.303.202");
srt.insert("www.sknapchap.com", "192.168.303.202");
srt.insert("www.instantgrammy.com", "192.168.303.202");
srt.insert("www.armbook.com", "192.168.303.202");
srt.insert("www.notgoogle.com", "192.168.303.202");
srt.insert("www.nodejstakesover.com", "192.168.303.202");
srt.insert("www.djangorocks.com", "192.168.303.202");
srt.insert("www.htmlishard.com", "192.168.303.202");
srt.insert("www.whatisreact.com", "192.168.303.202");
System.out.println(srt);
System.out.println(srt);
System.out.println(srt);
System.out.println(srt);
System.out.println(srt);
System.out.println(srt);
System.out.println(srt);
System.out.println(srt);
System.out.println(srt);
}
}
|
package ru.job4j.crud.models;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* @author Sir-Hedgehog (mailto:quaresma_08@mail.ru)
* @version 1.0
* @since 18.02.2020
*/
public interface Store {
boolean add(User user);
boolean update(int id, User recent);
boolean delete(int id);
CopyOnWriteArrayList<User> findAll();
User findById(int id);
}
|
import static org.junit.Assert.assertArrayEquals;
import model.Filter;
import org.junit.Test;
/**
* Testing class for the filter enumeration.
*/
public class FilterTest {
//tests that the getMatrix returns the correct matrix for the filter enumeration
@Test
public void testGetMatrix() {
double [][] matrix = Filter.BLUR.getMatrix();
double [][] expectedMatrix = {{0.0625,0.125,0.0625},{0.125,0.25,0.125},{0.0625,0.125,0.0625}};
assertArrayEquals(expectedMatrix, matrix);
}
}
|
package com.test.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.test.id.ProductIdGenerator;
import com.test.model.Product;
import com.test.service.ProductService;
@RestController
@RequestMapping("/product")
public class ProductController {
@Autowired
private ProductService productService;
@Autowired
private ProductIdGenerator productIdGenerator;
@RequestMapping(path="/{productName}", method={RequestMethod.POST})
public String createProduct(@PathVariable("productName") String productName) {
Product product = new Product();
product.setProductId(productIdGenerator.generateId().intValue());
product.setProductName(productName);
productService.createProduct(product);
return "success";
}
}
|
package lego.mapper;
import java.util.List;
import lego.pojo.Sales;
public interface SalesMapper {
public List<Sales> findAllSales();
}
|
package org.sayesaman.app4;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
import org.sayesaman.R;
import org.sayesaman.database.model.SalePath;
import java.util.ArrayList;
/**
* Created with IntelliJ IDEA.
* User: ameysami
* Android: How to bind spinner to custom object list?
* http://stackoverflow.com/questions/1625249/android-how-to-bind-spinner-to-custom-object-list
*/
public class SalePathAdapter extends ArrayAdapter<SalePath> {
private final ArrayList<SalePath> items;
private final Context context;
public SalePathAdapter(Context context, int textViewResourceId, ArrayList<SalePath> items) {
super(context, textViewResourceId, items);
this.items = items;
this.context = context;
}
@Override
public int getCount() {
return items.size();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//convertView = inflater.sakhtemankala(R.layout.app4_row_salepath, null);
View rowView = inflater.inflate(R.layout.app4_row_salepath, parent, false);
TextView label = (TextView) super.getView(position, convertView, parent);
label.setTextColor(Color.BLACK);
label.setText(this.getItem(position).getName());
return label;
/*
SalePath o = items.get(position);
if (o != null) {
TextView tvSalePathName = (TextView) rowView.findViewById(R.id.tvSalePathName);
if (tvSalePathName != null) {
tvSalePathName.setText(o.getName());
}
}
*/
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
TextView label = (TextView) super.getView(position, convertView, parent);
label.setTextColor(Color.BLACK);
label.setText(this.getItem(position).getName());
return label;
}
}
|
package cn.gxh.faceattach.base;
import android.app.Application;
import com.bulong.rudeness.RudenessScreenHelper;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import java.util.concurrent.TimeUnit;
import cn.gxh.faceattach.bean.LoginInfo;
import cn.gxh.faceattach.util.SharePrefUtil;
import okhttp3.OkHttpClient;
public class MyApp extends Application {
//设计图标注的宽度
public static int designWidth = 720;
public static LoginInfo loginInfo;
@Override
public void onCreate() {
super.onCreate();
//初始化适配类
new RudenessScreenHelper(this, designWidth).activate();
Global.init(this);
SharePrefUtil.getInstance().initSP(this);
loginInfo= (LoginInfo) SharePrefUtil.getInstance().getObj("login");
initOkGo();
}
private void initOkGo() {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
//全局的读取超时时间
builder.readTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
//全局的写入超时时间
builder.writeTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
//全局的连接超时时间
builder.connectTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
// HttpsUtils.SSLParams sslParams1 = HttpsUtils.getSslSocketFactory();
// builder.sslSocketFactory(sslParams1.sSLSocketFactory, sslParams1.trustManager);
//配置https的域名匹配规则,详细看demo的初始化介绍,不需要就不要加入,使用不当会导致https握手失败
//builder.hostnameVerifier(new SafeHostnameVerifier());
// HttpHeaders headers = new HttpHeaders();
// HttpParams params = new HttpParams();
OkGo.getInstance().init(this) //必须调用初始化
.setOkHttpClient(builder.build()) //建议设置OkHttpClient,不设置将使用默认的
.setCacheMode(CacheMode.NO_CACHE)//全局统一缓存模式,默认不使用缓存,可以不传
//.setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE) //全局统一缓存时间,默认永不过期,可以不传
.setRetryCount(3); //全局统一超时重连次数,默认为三次,那么最差的情况会请求4次(一次原始请求,三次重连请求),不需要可以设置为0
//.addCommonHeaders(headers) //全局公共头
//.addCommonParams(params); //全局公共参数
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.service.annotation;
import java.util.ArrayList;
import java.util.List;
import org.springframework.aop.framework.AopProxyUtils;
import org.springframework.aot.generate.GenerationContext;
import org.springframework.aot.hint.ProxyHints;
import org.springframework.beans.factory.aot.BeanRegistrationAotContribution;
import org.springframework.beans.factory.aot.BeanRegistrationAotProcessor;
import org.springframework.beans.factory.aot.BeanRegistrationCode;
import org.springframework.beans.factory.support.RegisteredBean;
import org.springframework.core.annotation.MergedAnnotations;
import org.springframework.core.annotation.MergedAnnotations.Search;
import org.springframework.lang.Nullable;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;
import static org.springframework.core.annotation.MergedAnnotations.SearchStrategy.TYPE_HIERARCHY;
/**
* AOT {@code BeanRegistrationAotProcessor} that detects the presence of
* {@link HttpExchange @HttpExchange} on methods and creates the required proxy
* hints.
*
* @author Sebastien Deleuze
* @since 6.0
*/
class HttpExchangeBeanRegistrationAotProcessor implements BeanRegistrationAotProcessor {
@Nullable
@Override
public BeanRegistrationAotContribution processAheadOfTime(RegisteredBean registeredBean) {
Class<?> beanClass = registeredBean.getBeanClass();
List<Class<?>> exchangeInterfaces = new ArrayList<>();
Search search = MergedAnnotations.search(TYPE_HIERARCHY);
for (Class<?> interfaceClass : ClassUtils.getAllInterfacesForClass(beanClass)) {
ReflectionUtils.doWithMethods(interfaceClass, method -> {
if (!exchangeInterfaces.contains(interfaceClass) &&
search.from(method).isPresent(HttpExchange.class)) {
exchangeInterfaces.add(interfaceClass);
}
});
}
if (!exchangeInterfaces.isEmpty()) {
return new HttpExchangeBeanRegistrationAotContribution(exchangeInterfaces);
}
return null;
}
private static class HttpExchangeBeanRegistrationAotContribution implements BeanRegistrationAotContribution {
private final List<Class<?>> httpExchangeInterfaces;
public HttpExchangeBeanRegistrationAotContribution(List<Class<?>> httpExchangeInterfaces) {
this.httpExchangeInterfaces = httpExchangeInterfaces;
}
@Override
public void applyTo(GenerationContext generationContext, BeanRegistrationCode beanRegistrationCode) {
ProxyHints proxyHints = generationContext.getRuntimeHints().proxies();
for (Class<?> httpExchangeInterface : this.httpExchangeInterfaces) {
proxyHints.registerJdkProxy(AopProxyUtils.completeJdkProxyInterfaces(httpExchangeInterface));
}
}
}
}
|
package main.java.com.javacore.io_nio.task3.view;
import static main.java.com.javacore.io_nio.task3.utils.ConsoleUtils.parseStringForId;
import static main.java.com.javacore.io_nio.task3.utils.ConsoleUtils.printSuccessMessage;
import static main.java.com.javacore.io_nio.task3.utils.ConsoleUtils.processDeleteRequest;
import static main.java.com.javacore.io_nio.task3.view.OperationType.CREATE;
import static main.java.com.javacore.io_nio.task3.view.OperationType.DELETE;
import static main.java.com.javacore.io_nio.task3.view.OperationType.READ;
import static main.java.com.javacore.io_nio.task3.view.OperationType.UPDATE;
import java.io.IOException;
import java.util.List;
import java.util.Scanner;
import main.java.com.javacore.io_nio.task3.controller.DeveloperController;
import main.java.com.javacore.io_nio.task3.controller.dto.AccountDto;
import main.java.com.javacore.io_nio.task3.controller.dto.BaseDto;
import main.java.com.javacore.io_nio.task3.controller.dto.DeveloperDto;
import main.java.com.javacore.io_nio.task3.controller.dto.ProjectDto;
public class DeveloperView extends CommonView {
private final DeveloperController developerController;
public DeveloperView() {
this.developerController = new DeveloperController();
}
public static void main(String[] args) {
new DeveloperView().developerViewExecutor();
}
private void developerViewExecutor() {
OperationType operationType;
boolean isTerminated = false;
Scanner scanner = new Scanner(System.in);
while (!isTerminated) {
System.out.println("Выберите тип операции: " + String
.join(", ", OperationType.getAllDescTypes()));
String type = scanner.nextLine();
operationType = OperationType.getByDesc(type);
try {
if (operationType == null) {
System.out.println("Данная операция не поддерживается");
} else if (operationType.equals(READ)) {
System.out.println("Введите ID разработчика или отображение всех записей");
Integer id = parseStringForId(scanner.nextLine());
read(id);
} else if (operationType.equals(CREATE)) {
ProjectDto projectDto = createProjectDto(scanner, operationType);
printSuccessMessage(create(projectDto));
} else if (operationType.equals(UPDATE)) {
DeveloperDto developerDto = createDeveloperDto(scanner);
printSuccessMessage(update(developerDto));
} else if (operationType.equals(DELETE)) {
System.out.println("Введите ID разработчика или удалите все записи");
Integer id = parseStringForId(scanner.nextLine());
delete(id);
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.print("Продолжить работу с консолью? Y/N: ");
String continueChoice = scanner.nextLine();
if (continueChoice.equalsIgnoreCase("N")) {
isTerminated = true;
}
}
}
private void read(Integer id) throws IOException {
List<? extends BaseDto> dtos = developerController.read(id);
System.out.println(dtos);
}
private boolean create(ProjectDto projectDto) throws IOException {
boolean result = developerController.create(projectDto);
read(null);
return result;
}
private void delete(Integer id) throws IOException {
String result = developerController.delete(id);
read(null);
processDeleteRequest(result);
}
private boolean update(DeveloperDto developerDto) throws IOException {
boolean result = developerController.update(developerDto);
read(null);
return result;
}
private DeveloperDto createDeveloperDto(Scanner scanner) {
DeveloperDto developerDto = new DeveloperDto();
AccountDto accountDto = new AccountDto();
System.out.println("Выберите ID разработчика для апдейта");
Integer id = parseStringForId(scanner.nextLine());
developerDto.setId(id);
System.out.println("Выберите DATA для счета:");
accountDto.setData(scanner.nextLine());
developerDto.setAccount(accountDto);
return developerDto;
}
}
|
package net.kemitix.dependency.digraph.maven.plugin;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayDeque;
import java.util.Deque;
/**
* Manager for the creation and cleanup of temporary directories.
*
* @author pcampbell
*
* @deprecated see {@link org.junit.rules.TemporaryFolder}
*/
@Deprecated
public class TemporaryFileManager {
private final Deque<File> createdFiles = new ArrayDeque<>();
/**
* Delete all the created files.
*/
public void cleanUp() {
createdFiles.forEach(File::delete);
}
/**
* Creates a temporary directory.
*
* @return the created directory
*
* @throws IOException if error creating directory
*/
public File createTempDirectory() throws IOException {
File dir = Files.createTempDirectory("")
.toFile();
createdFiles.push(dir);
return dir;
}
/**
* Creates a temporary file.
*
* @return the created file
*
* @throws IOException if error creating file
*/
public File createTempFile() throws IOException {
File file = Files.createTempFile("", "")
.toFile();
createdFiles.push(file);
return file;
}
}
|
package com.esum.wp.as2.pkistore.dao;
import java.util.List;
import com.esum.appframework.dao.IBaseDAO;
import com.esum.appframework.exception.ApplicationException;
public interface IPkiStoreDAO extends IBaseDAO {
List searchPkiAlias(Object object) throws ApplicationException;
List selectPkiStoreList(Object object) throws ApplicationException;
List checkPkiStoreDuplicate(Object object) throws ApplicationException;
List selectXMLDsigInfoFK(Object object) throws ApplicationException;
List selectXMLEncInfoFK(Object object) throws ApplicationException;
List selectHTTPAuthInfoFK(Object object) throws ApplicationException;
Object selectPkiNodeList(Object object) throws ApplicationException ;
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.tfar.beans;
/**
*
* @author hatem
*/
import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
import javax.faces.context.ExternalContext;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
@ManagedBean
public class FileUploadView implements Serializable{
private UploadedFile uploadedFile;
//Primitives
private static final int BUFFER_SIZE = 6124;
public byte[] buffer;
public UploadedFile getUploadedFile() {
return uploadedFile;
}
public void setUploadedFile(UploadedFile uploadedFile) {
this.uploadedFile = uploadedFile;
}
public void upload(FileUploadEvent event) {
UploadedFile uploadedFile = event.getFile();
String fileName = uploadedFile.getFileName();
String contentType = uploadedFile.getContentType();
this.buffer = uploadedFile.getContents();
if(uploadedFile != null) {
FacesMessage message = new FacesMessage("Succesful", uploadedFile.getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, message);
}
}
public void handleFileUpload(FileUploadEvent event) {
ExternalContext extContext =
FacesContext.getCurrentInstance().getExternalContext();
// File result = new File("/Users/hatem/NetBeansProjects/TFAR/target/TFAR-2.0/files/" + event.getFile().getFileName());
File result = new File("/Users/hatem/NetBeansProjects/TFAR/target/TFAR-2.0/files/temp.png");
System.out.println(extContext.getRealPath
("/Users/hatem/NetBeansProjects/TFAR/target/TFAR-2.0/files/" + event.getFile().getFileName()));
try {
FileOutputStream fileOutputStream = new FileOutputStream(result);
buffer = new byte[BUFFER_SIZE];
int bulk;
InputStream inputStream = event.getFile().getInputstream();
while (true) {
bulk = inputStream.read(buffer);
if (bulk < 0) {
break;
}
fileOutputStream.write(buffer, 0, bulk);
fileOutputStream.flush();
}
fileOutputStream.close();
inputStream.close();
FacesMessage msg =
new FacesMessage("File Description", "file name: " +
event.getFile().getFileName() + "<br/>file size: " +
event.getFile().getSize() / 1024 +
" Kb<br/>content type: " +
event.getFile().getContentType() +
"<br/><br/>The file was uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
} catch (IOException e) {
e.printStackTrace();
FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR,
"The files were not uploaded!", "");
FacesContext.getCurrentInstance().addMessage(null, error);
}
}
}
|
package global.dao;
import global.model.Major;
import global.model.View_major;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class Viewmajoraccess {
public static ArrayList<View_major> getMajor(String o_id) {
// 生成查找“Major”表的select查询语句
String sql = "SELECT * FROM View_major";
// 如果传入的科室编号不为空,则SQL语句添加查找条件为根据科室编号查找“Major”视图数据
if (!(o_id == null || o_id.equals(""))) {
sql += " WHERE o_id='" + o_id + "'";
}
// 初始化“Major”类的数组列表对象
ArrayList<View_major> majorlist = new ArrayList<View_major>();
// 取得数据库的连接
Connection con=null;
ResultSet rs = null;
try {
con = Databaseconnection.getconnection();
// 如果数据库的连接为空,则返回空
if (con == null)
return null;
// 生成数据库声明对象
Statement st = con.createStatement();
// 声明对象执行SQL语句,返回满足条件的结果集
rs = st.executeQuery(sql);
// 如果结果集有数据
while (rs.next()) {
// 取出结果集对应字段数据
String d_id=rs.getString("d_id");
String d_name=rs.getString("d_name");
o_id = rs.getString("o_id");
String o_name=rs.getString("o_name");
String m_id = rs.getString("m_id");
String m_name = rs.getString("m_name");
// 根据结果集的数据生成“Major”类对象
View_major m = new View_major(d_id, d_name, o_id, o_name, m_id, m_name);
// 将“Major”类对象添加到“Major”类的数组列表对象中
majorlist.add(m);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
rs.close();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 返回“View_teacher”类的数组列表对象
return majorlist;
}
}
|
package app.web.choi.vo;
public class BoardVO {
private String boardId;
private String title;
public String getBoardId() {
return boardId;
}
public void setBoardId(String boardId) {
this.boardId = boardId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
|
package com.worldchip.bbp.bbpawmanager.cn.json;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.AssetManager;
import com.worldchip.bbp.bbpawmanager.cn.model.Information;
public class InformationJsonParse {
@SuppressLint("SimpleDateFormat")
public static List<Information> doParseJsonToBean(String json) {
List<Information> list = new ArrayList<Information>();
try {
JSONObject person = new JSONObject(json);
int count = person.getInt("count");
if (count <= 0) {
return null;
}
JSONArray groupArray = person.getJSONArray("group");
for(int i = 0; i < groupArray.length(); i++) {
Information info = new Information();
info.setMainType(Integer.valueOf((person.getString("maintype"))));
JSONObject jsonObject = groupArray.getJSONObject(i);
info.setMsgId(Integer.valueOf(jsonObject.getString("id")));
info.setType(Integer.valueOf(jsonObject.getString("type")));
info.setDate(jsonObject.getString("update_time"));
info.setMsgType(jsonObject.getInt("order_type"));
info.setIcon(jsonObject.getString("mini_image"));
info.setMsgImage(jsonObject.getString("large_image"));
info.setActivitiesUrl(jsonObject.getString("activities_url"));
info.setDownloadUrl(jsonObject.getString("url"));
info.setTitle(jsonObject.getString("title"));
info.setDescription(jsonObject.getString("description"));
info.setContent(jsonObject.getString("content"));
info.setRead(false);
list.add(info);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
public static String getDefaultJson(Context context, String fileName) {
StringBuilder stringBuilder = new StringBuilder();
try {
AssetManager assetManager = context.getAssets();
BufferedReader bf = new BufferedReader(new InputStreamReader(
assetManager.open(fileName),"UTF-8"));
String line;
while ((line = bf.readLine()) != null) {
stringBuilder.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
}
|
/*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2011 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: proactive@ow2.org or contact@activeeon.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package org.ow2.proactive.scheduler.policy;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
import org.apache.log4j.Logger;
import org.objectweb.proactive.annotation.PublicAPI;
import org.objectweb.proactive.core.util.log.ProActiveLogger;
import org.ow2.proactive.resourcemanager.common.RMState;
import org.ow2.proactive.scheduler.common.Scheduler;
import org.ow2.proactive.scheduler.common.SchedulerCoreMethods;
import org.ow2.proactive.scheduler.common.util.SchedulerLoggers;
import org.ow2.proactive.scheduler.core.SchedulerCore;
import org.ow2.proactive.scheduler.core.properties.PASchedulerProperties;
import org.ow2.proactive.scheduler.descriptor.EligibleTaskDescriptor;
import org.ow2.proactive.scheduler.descriptor.JobDescriptor;
/**
* Policy interface for the scheduler.
* Must be implemented in order to be used as a policy in the scheduler core.
*
* @author The ProActive Team
* @since ProActive Scheduling 0.9
*/
@PublicAPI
public abstract class Policy implements Serializable {
/** */
private static final long serialVersionUID = 31L;
protected static final Logger logger = ProActiveLogger.getLogger(SchedulerLoggers.POLICY);
/**
* Resources manager state. Can be used in an inherit policy to be aware
* of resources informations like total nodes number, used nodes, etc.
* Can be null the first time the {@link #getOrderedTasks(List)} method is called.
*/
protected RMState RMState = null;
/** Scheduler core link */
protected SchedulerCoreMethods core = null;
/** Config properties */
protected Properties configProperties = null;
/**
* Create a new instance of Policy. (must be public)
* Called by class.forname when instantiating the policy.
*<br/><br/>
* The {@link #reloadConfig()} method is called by the scheduler after the creation of this policy instance
* This empty constructor remains mandatory to enable the core to instantiate the policy but SchedulerCore
* does not wait for any special or mandatory behavior inside.
* <br/><br/>
* This constructor can/should be empty.
*/
public Policy() {
//reloadConfig();
}
/**
* Return the tasks that have to be scheduled.
* The tasks must be in the desired scheduling order.
* The first task to be schedule must be the first in the returned Vector.
*
* @param jobs the list of pending or running job descriptors.
* @return a vector of every tasks that are ready to be schedule.
*/
public abstract Vector<EligibleTaskDescriptor> getOrderedTasks(List<JobDescriptor> jobs);
/**
* Set the core
*
* @param core
*/
public final void setCore(SchedulerCore core) {
this.core = core;
}
/**
* Set the RM state
*
* @param RM state
*/
public final void setRMState(RMState state) {
this.RMState = state;
}
/**
* Return the configuration as properties (key->value) read in the policy config file.
* The returned value can be null or empty if no property has been loaded.
*
* @return the configuration read in the policy config file.
*/
protected final Properties getConfigurationProperties() {
return configProperties;
}
/**
* Return the value of the given property key.
* The returned value can be null if property does not exist.
*
* @return the value of the given property key or null if not found.
*/
protected final String getProperty(final String name) {
if (configProperties == null) {
return null;
}
return configProperties.getProperty(name);
}
/**
* Reload the configuration file of the corresponding policy.<br/>
* This method is called each time a reload action is performed for the policy
* (ie. {@link Scheduler#reloadPolicyConfiguration()} method is called from client side)<br/>
* <br/>
* This method just call {@link #getConfigFile()} method and then, load the content of the returned file
* in this policy properties.<br/>
* <br/>
* Override this method to have a fully custom reload, override only the {@link #getConfigFile()} method to
* change the properties file location.
* <br/>
* This method will reload the whole content of the properties. Every old properties will be erased and new one from file
* will be set.
* <br/>
* <br/>
* Note : this method is also called once at Scheduler startup.
*
* @return true if the configuration has been successfully reload, false otherwise.
*
* @see Properties#load(java.io.InputStream) Properties.load(java.io.InputStream) for more details
* about the structure and content of property file
*/
public boolean reloadConfig() {
configProperties = new Properties();
try {
FileInputStream fis = new FileInputStream(getConfigFile());
configProperties.load(fis);
fis.close();
return true;
} catch (IOException ioe) {
logger.warn("Cannot read policy configuration file", ioe);
return false;
}
}
/**
* Return the configuration file for this policy.<br/>
* Default configuration file is config/policy/[SimpleClassName].conf.<br/>
* <br/>
* In the default behavior, this method is called by {@link #reloadConfig()} method each time a policy reload is performed.<br/>
* <br/>
* Override this method to change the default path where to find the configuration file.
*/
protected File getConfigFile() {
String relPath = "config/scheduler/policy/" + getClass().getSimpleName() + ".conf";
return new File(PASchedulerProperties.getAbsolutePath(relPath));
}
}
|
/** #kmp */
import java.util.Scanner;
class FileRecoverTesting {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
int k = sc.nextInt();
String s = sc.next();
if (k == -1 && s.equals("*")) break;
int result = 0;
int n = s.length();
if (k >= n) {
// build prefix array
int[] prefix = new int[n];
calculatePrefix(s, prefix);
int cnt = prefix[n - 1];
if (cnt == 0) {
result = k / n;
} else {
result = 1 + (k - n) / (n - cnt);
}
}
System.out.println(result);
}
}
public static void calculatePrefix(String p, int[] prefix) {
prefix[0] = 0;
int m = p.length();
int j = 0, i = 1;
while (i < m) {
if (p.charAt(i) == p.charAt(j)) {
j++;
prefix[i] = j;
i++;
} else {
if (j != 0) {
j = prefix[j - 1];
} else {
prefix[i] = 0;
i++;
}
}
}
}
}
|
package ru.spb.itolia.redmine.ui;
import android.app.Activity;
public class IssueActivity extends Activity {
}
|
package ejercicio16;
import java.util.ArrayList;
import java.util.Scanner;
/**
*
* @author Javier
*/
public class Ejercicio16 {
// funciona hasta el 63
public static long factorial(long numero) {
long resultado = numero;
for (long i = numero-1; i > 1; i--) {
resultado = resultado * i;
}
return resultado;
}
public static void main(String[] args) {
Scanner entrada = new Scanner(System.in);
ArrayList <Long> numeros = new ArrayList <>();
System.out.println("Introduce primero la cantidad de numeros a comprobar"
+ "\nDespués introduzca los numeros: ");
int cantidad = entrada.nextInt();
for (int i = 0; i < cantidad; i++) {
numeros.add(entrada.nextLong());
}
System.out.println("\nResultados: ");
for (int i = 0; i < numeros.size(); i++) {
System.out.println(factorial(numeros.get(i)));
}
}
}
|
package com.ridvankabak.flickrgallery.Adapter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import com.like.LikeButton;
import com.like.OnLikeListener;
import com.ridvankabak.flickrgallery.Data.Images;
import com.ridvankabak.flickrgallery.R;
import com.ridvankabak.flickrgallery.ui.FavoriteActivity.FavoriteActivity;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.CardViewTasarimTutucu>{
FavoriteActivity favoriteActivity;
List<Images> imageList;
public ImageAdapter(FavoriteActivity favoriteActivity,List<Images> imageList){
this.favoriteActivity = favoriteActivity;
this.imageList = imageList;
}
@NonNull
@Override
public CardViewTasarimTutucu onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_design_fav,parent,false);
return new ImageAdapter.CardViewTasarimTutucu(v);
}
@Override
public void onBindViewHolder(@NonNull CardViewTasarimTutucu holder, int position) {
Images image = imageList.get(position);
loadImage(image.imageNo,holder);
holder.satirYazi.setText(image.title);
holder.satirLike.setOnLikeListener(new OnLikeListener() {
@Override
public void liked(LikeButton likeButton) {
}
@Override
public void unLiked(LikeButton likeButton) {
FavoriteActivity.deleteImageData(image);
}
});
}
private void loadImage(String imageNo, CardViewTasarimTutucu holder) {
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
String myDir = root + "/flickr_saved_images";
try {
File f=new File(myDir, "Image-"+imageNo+".jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
holder.satirImage.setImageBitmap(b);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
@Override
public int getItemCount() {
return imageList.size();
}
public class CardViewTasarimTutucu extends RecyclerView.ViewHolder{
public TextView satirYazi;
public ImageView satirImage;
public CardView satirCard;
public LikeButton satirLike;
public CardViewTasarimTutucu (View view){
super(view);
satirYazi = view.findViewById(R.id.textViewTitleFavv);
satirImage = view.findViewById(R.id.imageViewGelPicFav);
satirCard = view.findViewById(R.id.foto_card_fav);
satirLike = view.findViewById(R.id.heart_button_fav);
}
}
}
|
package com.dbsys.rs.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dbsys.rs.lib.DateUtil;
import com.dbsys.rs.lib.Kelas;
import com.dbsys.rs.lib.entity.Pasien;
import com.dbsys.rs.lib.entity.Pasien.StatusPasien;
import com.dbsys.rs.lib.entity.Pasien.Type;
import com.dbsys.rs.repository.PasienRepository;
import com.dbsys.rs.service.PasienService;
@Service
@Transactional
public class PasienServiceImpl implements PasienService {
@Autowired
private PasienRepository pasienRepository;
@Override
public Pasien daftar(Pasien pasien) {
pasien.setTanggalMasuk(DateUtil.getDate());
pasien.setStatus(StatusPasien.OPEN);
pasien.setTipe(Type.RAWAT_JALAN);
pasien.generateKode();
return pasienRepository.save(pasien);
}
@Override
public Pasien convert(Pasien pasien, Kelas kelas) {
pasien.setTipe(Type.RAWAT_INAP);
pasien.setKelas(kelas);
return pasienRepository.save(pasien);
}
@Override
public Pasien get(Long id) {
return pasienRepository.findOne(id);
}
}
|
package pro.likada.service;
import pro.likada.model.TransportationHiredVehicleType;
import java.util.List;
/**
* Created by Yusupov on 3/17/2017.
*/
public interface TransportationHiredVehicleTypeService {
List<TransportationHiredVehicleType> getAllTransportationHiredVehicleTypes();
}
|
package org.typhon.client.service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.modelmapper.ModelMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.MediaTypes;
import org.springframework.hateoas.PagedResources;
import org.springframework.hateoas.hal.Jackson2HalModule;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import org.typhon.client.model.Customer;
import org.typhon.client.model.dto.CustomerDTO;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
public class CustomerService {
private static final Logger logger = LoggerFactory.getLogger(CustomerService.class);
private String baseUrl;
ModelMapper modelMapper;
private RestTemplate restTemplate;
public CustomerService(String baseUrl) {
this.baseUrl = baseUrl;
restTemplate = restTemplate();
modelMapper = new ModelMapper();
}
RestTemplate restTemplate() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new Jackson2HalModule());
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
messageConverter.setObjectMapper(objectMapper);
messageConverter.setSupportedMediaTypes(Arrays.asList(MediaTypes.HAL_JSON));
return new RestTemplate(Arrays.asList(messageConverter));
}
public Customer findById(int
id) {
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(baseUrl + "/customer/" + id);
String uriBuilder = builder.build().encode().toUriString();
CustomerDTO customerDTO = restTemplate
.exchange(uriBuilder, HttpMethod.GET, null, new ParameterizedTypeReference<CustomerDTO>() {
}).getBody();
Customer customer = modelMapper.map(customerDTO, Customer.class);
return customer;
}
public void delete(Customer objToDelete) {
try {
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(baseUrl + "/customer/" + objToDelete.getId());
String uriBuilder = builder.build().encode().toUriString();
restTemplate.delete(uriBuilder);
}
catch(HttpClientErrorException e) {
logger.error(e.getMessage());
}
}
public PagedResources<Customer> findAll(int page, int size, String order) {
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(baseUrl + "/customer").queryParam("page", page)
.queryParam("size", size).queryParam("order", order);
String uriBuilder = builder.build().encode().toUriString();
PagedResources<CustomerDTO> queryResult = restTemplate.exchange(uriBuilder, HttpMethod.GET, null,
new ParameterizedTypeReference<PagedResources<CustomerDTO>>() {
}).getBody();
List<Customer> objList = new ArrayList<Customer>();
queryResult.forEach(z -> objList.add(modelMapper.map(z, Customer.class)));
PagedResources<Customer> result = new PagedResources<Customer>(objList, queryResult.getMetadata(),
new ArrayList<Link>());
return result;
}
public Customer create(Customer objToCreate) {
CustomerDTO p = modelMapper.map(objToCreate, CustomerDTO.class);
HttpEntity<CustomerDTO> request = new HttpEntity<>(p);
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(baseUrl + "/customer");
String uriBuilder = builder.build().encode().toUriString();
ResponseEntity<CustomerDTO> response = restTemplate.exchange(uriBuilder, HttpMethod.POST, request, CustomerDTO.class);
CustomerDTO foo = response.getBody();
objToCreate = modelMapper.map(foo, Customer.class);
return objToCreate;
}
public Customer update(Customer objToUpdate) {
CustomerDTO p = modelMapper.map(objToUpdate, CustomerDTO.class);
HttpEntity<CustomerDTO> request = new HttpEntity<>(p);
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(baseUrl + "/customer/" + objToUpdate.getId());
String uriBuilder = builder.build().encode().toUriString();
ResponseEntity<CustomerDTO> response = restTemplate.exchange(uriBuilder, HttpMethod.PUT, request, CustomerDTO.class);
CustomerDTO foo = response.getBody();
objToUpdate = modelMapper.map(foo, Customer.class);
return objToUpdate;
}
}
|
/*
* Copyright 2011 Cedric Priscal
*
* 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.serialportapp.sample;
import java.io.IOException;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import com.serialportapp.R;
import android_serialport_api.Converter;
public class SendingActivity extends SerialPortActivity {
private TextView text;
private Button send;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sending);
text = (TextView) findViewById(R.id.textView1);
text.setMovementMethod(ScrollingMovementMethod.getInstance());
send = (Button) findViewById(R.id.start);
send.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mSerialPort != null) {
toSend = !toSend;
if (toSend) {
sendThread.start();
}
}
}
});
}
@Override
protected void onDestroy() {
toSend = false;
super.onDestroy();
}
@Override
protected void onDataReceived(final byte[] buffer, final int size) {
runOnUiThread(new Runnable() {
public void run() {
String hexString = Converter.bytesToHexString(buffer, size);
if (hexString.endsWith("0b0d")) {
hexString = hexString + "\n";
}
try {
Thread.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
text.append(hexString);
int offset = text.getLineCount() * text.getLineHeight();
if (offset > text.getHeight()) {
text.scrollTo(0, offset - text.getHeight());
}
}
});
}
byte[] sendByte = new byte[] { (byte) 0xA5, 0x00, 0x0D, 0x01, 0x52,
(byte) 0xD7, 0x0B, 0x0D };
boolean toSend = false;
private Thread sendThread = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while (toSend) {
try {
Thread.sleep(200);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (mOutputStream != null) {
try {
mOutputStream.write(sendByte);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
});
}
|
package io.quarkuscoffeeshop.domain;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
public abstract class WebUpdate {
public String orderId;
public String itemId;
public String name;
public Item item;
public OrderStatus status;
public WebUpdate() {
super();
}
public WebUpdate(String orderId, String itemId, String name, Item item, OrderStatus status) {
this.orderId = orderId;
this.itemId = itemId;
this.name = name;
this.item = item;
this.status = status;
}
}
|
package de.mvbonline.tools.restapidoc.model;
public class ApiBodyObjectDoc {
private String object;
public ApiBodyObjectDoc(String object) {
super();
this.object = object;
}
public String getObject() {
return object;
}
}
|
package model;
public class Plato {
private int Id;
private double precio;
private String decripcion;
/**
* @return the id
*/
public int getId() {
return Id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
Id = id;
}
/**
* @return the precio
*/
public double getPrecio() {
return precio;
}
/**
* @param precio the precio to set
*/
public void setPrecio(double precio) {
this.precio = precio;
}
/**
* @return the decripcion
*/
public String getDecripcion() {
return decripcion;
}
/**
* @param decripcion the decripcion to set
*/
public void setDecripcion(String decripcion) {
this.decripcion = decripcion;
}
}
|
package cn.itcast.core.service;
import cn.itcast.core.pojo.entity.PageResult;
import cn.itcast.core.pojo.seller.Seller;
public interface SellerService {
public void add(Seller seller);
public PageResult findPage(Seller seller, Integer page, Integer rows);
public Seller findOne(String id);
public void updateStatus(String sellerId, String status);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.