text stringlengths 10 2.72M |
|---|
package com.example.mac.swinedu.Models;
import java.util.HashMap;
/**
* Created by mac on 11/7/17.
*/
public class ChatMembers
{
private HashMap<String, Boolean> members = new HashMap<>();
public ChatMembers()
{
}
public HashMap<String, Boolean> getMembers()
{
return members;
}
public void addMember(String member)
{
members.put(member, true);
}
public void setMembers(HashMap<String, Boolean> members)
{
this.members = members;
}
}
|
/*
* 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 gob.igm.ec.servicios;
import gob.igm.ec.TcontrolIva;
import java.math.BigDecimal;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.apache.log4j.Logger;
/**
*
* @author TOAPANTA_JUAN
*/
@Stateless
public class TcontrolIvaFacade extends AbstractFacade<TcontrolIva> {
private static Logger localLogger;
@PersistenceContext(unitName = "gob.igm.ec_sistemaProformasOnlineIGMv1-ejb_ejb_1.0-SNAPSHOTPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public BigDecimal recuperaIva(){
BigDecimal iva = null;
String condicion="'A'";
try{
Query query=em.createQuery("SELECT o.valor FROM TcontrolIva o WHERE o.control ="
+ condicion);
iva=new BigDecimal(query.getSingleResult().toString());
}catch(Exception ex){
localLogger.error(ex);
}
return iva;
}
public TcontrolIvaFacade() {
super(TcontrolIva.class);
}
}
|
package com.kh.efp.codeFactory.model.vo;
public class ExecuteResult implements java.io.Serializable{
private String output;
private String statusCode;
private String memory;
private String cpuTime;
public ExecuteResult() {}
public ExecuteResult(String output, String statusCode, String memory, String cpuTime) {
this.output = output;
this.statusCode = statusCode;
this.memory = memory;
this.cpuTime = cpuTime;
}
public String getOutput() {
return output;
}
public void setOutput(String output) {
this.output = output;
}
public String getStatusCode() {
return statusCode;
}
public void setStatusCode(String statusCode) {
this.statusCode = statusCode;
}
public String getMemory() {
return memory;
}
public void setMemory(String memory) {
this.memory = memory;
}
public String getCpuTime() {
return cpuTime;
}
public void setCpuTime(String cpuTime) {
this.cpuTime = cpuTime;
}
@Override
public String toString() {
return "ExecuteResult [output=" + output + ", statusCode=" + statusCode + ", memory=" + memory + ", cpuTime="
+ cpuTime + "]";
}
}
|
package com.fanbo.kai.zhihu_funny.presenter;
import com.fanbo.kai.zhihu_funny.model.Section;
import com.fanbo.kai.zhihu_funny.presenter.base.BasePresenter;
import com.fanbo.kai.zhihu_funny.presenter.contract.ContentContract;
import com.fanbo.kai.zhihu_funny.presenter.contract.ContentContract.Presenter;
import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
/**
* Created by HK on 2017/1/25.
* Email: kaihu1989@gmail.com.
*/
public class ContentPresenter extends BasePresenter<ContentContract.View> implements Presenter {
private List<Integer> storyIds = new ArrayList<>();
@Inject
public ContentPresenter() {
}
@Override
public void initContentData(int sectionId) {
httpRequest(funnyApi.getSectionById(sectionId), response -> {
storyIds.addAll(Lists.transform(response.getStories(), Section.Story::getId));
fetchContentBody();
});
}
private void fetchContentBody() {
httpRequestWithLoading(funnyApi.getNewsById(storyIds.get(0)), response -> mView.showContent(response.getBody()));
}
}
|
package com.geekparkhub.core.hbase.api.producehub;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import java.io.IOException;
/**
* Geek International Park | 极客国际公园
* GeekParkHub | 极客实验室
* Website | https://www.geekparkhub.com/
* Description | Open开放 · Creation创想 | OpenSource开放成就梦想 GeekParkHub共建前所未见
* HackerParkHub | 黑客公园枢纽
* Website | https://www.hackerparkhub.com/
* Description | 以无所畏惧的探索精神 开创未知技术与对技术的崇拜
* GeekDeveloper : JEEP-711
*
* @author system
* <p>
* HbaseHub
* <p>
*/
public class HbaseHub {
/**
* Public Configuration information
* 公共配置信息
*/
private static Admin admin = null;
private static Connection connection = null;
private static Configuration configuration;
static {
/**
* HBase ConfigurationFile
* HBase 配置文件
*/
configuration = HBaseConfiguration.create();
configuration.set("hbase.zookeeper.quorum", "172.16.168.130");
configuration.set("hbase.zookeeper.property.clientPort", "2181");
try {
/**
* Get Connected
* 获取连接
*/
connection = ConnectionFactory.createConnection(configuration);
/**
* Get HBase Administrator Object
* 获取HBase管理员对象
*/
admin = connection.getAdmin();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Close Resource
* 关闭资源
*
* @param conf
* @param admin
*/
private static void close(Connection conf, Admin admin) {
if (conf != null) {
try {
conf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (admin != null) {
try {
admin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Determine if DataTable Exists
* 判断数据表是否存在
*
* @param tableName
*/
public static boolean isTableExist(String tableName) throws IOException {
/**
* Execution Method
* 执行方法
*/
boolean tableExists = admin.tableExists(TableName.valueOf(tableName));
return tableExists;
}
/**
* Create DataTable
* 创建数据表
*
* @param tableName
* @param columnFamily
* @throws IOException
*/
public static void createTable(String tableName, String... columnFamily) throws IOException {
/**
* Verify that the DataTable Exists Before Creating the DataTable
* 创建数据表前,验证数据表是否存在
*/
if (isTableExist(tableName)) {
System.out.printf(tableName + " Data table creation failed , " + tableName + " Data table already exists!" + "\n");
return;
}
/**
* Instantiation Table Description information
* 实例化 表描述信息
*/
HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf(tableName));
/**
* Add Multiple Column Families
* 添加多个列族
*/
for (String cn : columnFamily) {
/**
* Instantiation Column Name Description information
* 实例化 列名描述信息
*/
HColumnDescriptor columnDescriptor = new HColumnDescriptor(String.valueOf(cn));
tableDescriptor.addFamily(columnDescriptor);
}
/**
* Execution Method
* 执行方法
*/
admin.createTable(tableDescriptor);
/**
* Logger INFO
*/
System.out.printf(tableName + " Data Sheet Was Created Successfully!" + "\n");
}
/**
* Delete Data Table
* 删除数据表
*
* @param tableName
* @throws IOException
*/
public static void deleteTable(String tableName) throws IOException {
/**
* Before Deleting the Data Table, Verify that the Data Table Exists.
*/
if (!isTableExist(tableName)) {
System.out.println("Data Table Deletion Failed , Reason : The Data Table Does Not Exist !");
return;
}
/**
* Data Table Offline
* 数据表下线
*/
admin.disableTable(TableName.valueOf(tableName));
/**
* Delete Data Table
* 删除数据表
*/
admin.deleteTable(TableName.valueOf(tableName));
/**
* Logger INFO
*/
System.out.println("Data Table Has Been Deleted Successfully!");
}
/**
* Adding Data
* 添加数据
*
* @param tableName
* @param rowKey
* @param columnFamily
* @param columnName
* @param value
* @throws IOException
*/
public static void addData(String tableName, String rowKey, String columnFamily, String columnName, String value) throws IOException {
/**
* Instantiated Table Object
* 实例化 表对象
*/
Table table = connection.getTable(TableName.valueOf(tableName));
/**
* Verify that the data table exists before adding data
* 添加数据前,验证数据表是否存在
*/
if (!isTableExist(String.valueOf(TableName.valueOf(tableName)))) {
System.out.println("Adding Data Failed, Reason: " + table + "DataTable Does Not Exist !");
return;
}
/**
* Instantiate Put Object
* 实例化 Put对象
*
* Convert String type primary key ID to byte data
* 将String类型主键ID转换字节数据
*/
Put put = new Put(Bytes.toBytes(rowKey));
/**
* Add data (column family/column name/numeric) and convert the String type to a byte array
* 添加数据 (列族/ 列名 / 数值)并将String类型转换为字节数组
*/
put.addColumn(Bytes.toBytes(columnFamily), Bytes.toBytes(columnName), Bytes.toBytes(value));
/**
* Execution method
* 执行方法
*/
table.put(put);
System.out.println(table.toString() + " Data added Successfully !");
/**
* Close resource
* 关闭资源
*/
table.close();
}
/**
* Change Data
* 修改数据
*
* @param tableName
* @param rowKey
* @param columnFamily
* @param columnName
* @param value
*/
public static void changeData(String tableName, String rowKey, String columnFamily, String columnName, String value) throws IOException {
/**
* Instantiated Table Object
* 实例化 表对象
*/
Table table = connection.getTable(TableName.valueOf(tableName));
/**
* Verify that the data table exists before modifying the data
* 修改数据前,验证数据表是否存在
*/
if (!isTableExist(String.valueOf(TableName.valueOf(tableName)))) {
System.out.println("Change Data Failed, Reason: " + table + "DataTable Does Not Exist !");
return;
}
/**
* Instantiate Put Object
* 实例化 Put对象
*
* Convert String type primary key ID to byte data
* 将String类型主键ID转换字节数据
*/
Put put = new Put(Bytes.toBytes(rowKey));
/**
* Change data (column family/column name/numeric) and convert the String type to a byte array
* 修改数据 (列族/ 列名 / 数值)并将String类型转换为字节数组
*/
put.addColumn(Bytes.toBytes(columnFamily), Bytes.toBytes(columnName), Bytes.toBytes(value));
/**
* Execution method
* 执行方法
*/
table.put(put);
System.out.println(table.toString() + " Data Change Successfully !");
/**
* Close resource
* 关闭资源
*/
table.close();
}
/**
* Full Table Scan - Query Data
* 全表扫描 - 查询数据
*
* @param tableName
*/
public static void scanTable(String tableName) throws IOException {
/**
* Instantiated Table Object
* 实例化 表对象
*/
Table table = connection.getTable(TableName.valueOf(tableName));
/**
* Verify that the data table exists before modifying the data
* 查询数据前,验证数据表是否存在
*/
if (!isTableExist(String.valueOf(TableName.valueOf(tableName)))) {
System.out.println("Inquire Data Failed, Reason: " + table + "DataTable Does Not Exist !");
return;
}
/**
* Instantiation Scanner
* 实例化 扫描器
*/
Scan scan = new Scan();
/**
* Execution Method
* 执行方法
*/
ResultScanner results = table.getScanner(scan);
/**
* Traversing RowKey data
* 遍历RowKey数据
*/
for (Result result : results) {
Cell[] cells = result.rawCells();
/**
* Traversing the Row Key collection data
* 遍历RowKey集合数据
*/
for (Cell cell : cells) {
System.out.println("RowKey is = " + Bytes.toString(CellUtil.cloneRow(cell))
+ " & " + "ColumnFamily is = " + Bytes.toString(CellUtil.cloneFamily(cell))
+ " & " + "ColumnName is = " + Bytes.toString(CellUtil.cloneQualifier(cell))
+ " & " + "Value is = " + Bytes.toString(CellUtil.cloneValue(cell))
+ "\n" + ("===========================================================================")
);
}
}
/**
* Logger INFO
*/
System.out.println("FullTable Data Query Success !");
/**
* Close resource
* 关闭资源
*/
table.close();
}
/**
* Specified Parameter - Query Data
* 指定参数 - 查询数据
*
* @param tableName
* @param rowKey
* @param columnFamily
* @param columnName
* @throws IOException
*/
public static void getData(String tableName, String rowKey, String columnFamily, String columnName) throws IOException {
/**
* Instantiated Table Object
* 实例化 表对象
*/
Table table = connection.getTable(TableName.valueOf(tableName));
/**
* Verify that the data table exists before modifying the data
* 查询数据前,验证数据表是否存在
*/
if (!isTableExist(String.valueOf(TableName.valueOf(tableName)))) {
System.out.println("Inquire Data Failed, Reason: " + table + "DataTable Does Not Exist !");
return;
}
/**
* Instantiate the Get object
* 实例化Get对象
*/
Get get = new Get(Bytes.toBytes(rowKey));
/**
* Specify column family & column name
* 指定列族&列名
*/
get.addColumn(Bytes.toBytes(columnFamily), Bytes.toBytes(columnName));
/**
* Execution method
* 执行方法
*/
Result result = table.get(get);
Cell[] cells = result.rawCells();
/**
* Traversing the Row Key collection data
* 遍历RowKey集合数据
*/
for (Cell cell : cells) {
System.out.println("RowKey is = " + Bytes.toString(CellUtil.cloneRow(cell))
+ " & " + "ColumnFamily is = " + Bytes.toString(CellUtil.cloneFamily(cell))
+ " & " + "ColumnName is = " + Bytes.toString(CellUtil.cloneQualifier(cell))
+ " & " + "Value is = " + Bytes.toString(CellUtil.cloneValue(cell))
+ "\n" + ("===========================================================================")
);
}
/**
* Logger INFO
*/
System.out.println("Specified Parameter Data Query Success !");
/**
* Close resource
* 关闭资源
*/
table.close();
}
/**
* Delete Data
* 删除数据
*
* @param tableName
* @param rowKey
* @param columnFamily
* @param columnName
* @throws IOException
*/
public static void deleteData(String tableName, String rowKey, String columnFamily, String columnName) throws IOException {
/**
* Instantiated Table Object
* 实例化 表对象
*/
Table table = connection.getTable(TableName.valueOf(tableName));
/**
* Verify that the data table exists before modifying the data
* 删除数据前,验证数据表是否存在
*/
if (!isTableExist(String.valueOf(TableName.valueOf(tableName)))) {
System.out.println("Delete Data Failed, Reason: " + table + "DataTable Does Not Exist !");
return;
}
/**
* Instantiate the delete object
* 实例化 delete对象
*/
Delete delete = new Delete(Bytes.toBytes(rowKey));
/**
* 删除指定数据
*/
delete.addColumns(Bytes.toBytes(columnFamily), Bytes.toBytes(columnName));
/**
* Execution method
* 执行方法
*/
table.delete(delete);
/**
* Logger INFO
*/
System.out.println("Data Deletion is Successful!");
/**
* Close resource
* 关闭资源
*/
table.close();
}
public static void main(String[] args) throws IOException {
/**
* isTableExist Result
*/
System.out.printf("test isTableExist Result is = " + String.valueOf(isTableExist("test")) + "\n");
System.out.printf("test001 isTableExist Result is = " + String.valueOf(isTableExist("test001")) + "\n");
System.out.printf("test002 isTableExist Result is = " + String.valueOf(isTableExist("test002")) + "\n");
System.out.printf("test003 isTableExist Result is = " + String.valueOf(isTableExist("test003")) + "\n");
/**
* CreateTable Result
*/
createTable("test001", "info");
createTable("test_factory", "factorymode", "factoryinfo");
System.out.printf("factory TableExist Result is = " + String.valueOf(isTableExist("factory")) + "\n");
System.out.printf("test_factory TableExist Result is = " + String.valueOf(isTableExist("test_factory")) + "\n");
/**
* Delete Data Table
*/
deleteTable("test_factory");
/**
* Adding Data
*/
addData("test001", "0003", "info", "name", "testUser003");
/**
* Change Data
*/
changeData("test001", "0003", "info", "name", "testUser004");
/**
* Delete Data
*/
deleteData("test001", "0003", "name", "testUser004");
/**
* Full Table Scan - Query Data
*/
scanTable("test");
/**
* Specified Parameter - Query Data
*/
getData("test", "0001", "info", "name");
/**
* Close Resource
* 关闭资源
*/
close(connection, admin);
}
}
|
package com.root.mssm.ui.specification.moreinfo;
import androidx.lifecycle.ViewModel;
public class MoreInfoViewModel extends ViewModel {
// TODO: Implement the ViewModel
} |
package com.smxknife.java.ex3;
public interface Animal {
}
|
package com.lizikj.tracker.pojo;
import static zipkin.internal.Util.equal;
import java.io.Serializable;
import com.github.kristofa.brave.internal.Nullable;
/**
*
* @auth zone
* @date 2017-10-18
*/
public class Annotation implements Serializable {
static final long serialVersionUID = 1L;
public static Annotation create(long timestamp, String value, @Nullable Endpoint endpoint) {
return new Annotation(timestamp, value, endpoint);
}
/**
* Microseconds from epoch.
*
* This value should use the most precise value possible. For example,
* gettimeofday or syncing nanoTime against a tick of currentTimeMillis.
*/
public final long timestamp; // required
public final String value; // required
/**
* Always the host that recorded the event. By specifying the host you allow
* rollup of all events (such as client requests to a service) by IP address.
*/
public final Endpoint host; // optional
Annotation(long timestamp, String value, Endpoint host) {
this.timestamp = timestamp;
this.value = value;
this.host = host;
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o instanceof Annotation) {
Annotation that = (Annotation) o;
return (this.timestamp == that.timestamp) && (this.value.equals(that.value)) && equal(this.host, that.host);
}
return false;
}
@Override
public int hashCode() {
int h = 1;
h *= 1000003;
h ^= (timestamp >>> 32) ^ timestamp;
h *= 1000003;
h ^= value.hashCode();
h *= 1000003;
h ^= (host == null) ? 0 : host.hashCode();
return h;
}
}
|
package example.nz.org.take.compiler.userv.spec;
/**
* Class generated by the take compiler.
* This class represents the external fact store DP_00x
* for the predicate specialLocation
* @version Sun Oct 21 23:25:20 NZDT 2007
*/
public interface ExternalFactStore4specialLocation {
// Get all instances of this type from the fact store.
public nz.org.take.rt.ResourceIterator<example.nz.org.take.compiler.userv.spec.specialLocation> fetch(
example.nz.org.take.compiler.userv.domainmodel.Driver slot1);
}
|
import java.util.*;
import java.io.*;
public class ACM {
public static void main(String[] args) throws IOException {
Scanner nya = new Scanner(System.in);
HashSet<Character> right = new HashSet<>();
HashMap<String, Integer> value = new HashMap<>();
while(true){
String[] stuff = nya.nextLine().split(" ");
if(stuff[0].equals("-1"))
break;
if(stuff[2].equals("right"))
right.add(stuff[1].charAt(0));
if(!value.containsKey(stuff[1]))
if(stuff[2].equals("right"))
value.put(stuff[1], Integer.parseInt(stuff[0]));
else
value.put(stuff[1], 20);
else
if(stuff[2].equals("right"))
value.put(stuff[1], value.get(stuff[1]) + Integer.parseInt(stuff[0]));
else
value.put(stuff[1], value.get(stuff[1]) + 20);
}
int sum = 0;
for(char x: right)
sum += value.get(Character.toString(x));
System.out.printf("%d %d",right.size(),sum);
}
}
|
package com.infotec.registro;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("det")
public class DetalleResource {
DetalleRepo repo = new DetalleRepo();
@GET
@Produces({MediaType.APPLICATION_JSON})
@Path("detalles/{idProceso}/{idUsuario}/{status}/{fecha_ini}/{asunto}/{folio}")
public List<Detalle> getDetalles(@PathParam("idProceso") int idProceso,@PathParam("idUsuario") int idUsuario, @PathParam("status") String status, @PathParam("fecha_ini") String fecha_ini, @PathParam("asunto") String asunto, @PathParam("folio") String folio ) {
System.out.println("Si corre!");
return repo.getDetalles(idProceso, idUsuario, status, fecha_ini, asunto,folio);
}
@GET
@Produces({MediaType.APPLICATION_JSON})
@Path("detalle/{idProceso}/{idEvento}")
public Detalle getDetalle(@PathParam("idProceso") int idProceso,@PathParam("idEvento") int idEvento) {
System.out.println("Si corre!");
return repo.getDetalle(idProceso, idEvento);
}
@POST
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
@Path("cdetalle")
public Detalle createDetalle(Detalle detalle) {
repo.create(detalle);
System.out.println(detalle);
return detalle;
}
@PUT
@Path("mdetalle")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Detalle updateDetalle(Detalle detalle) {
String fechaIni="";
String fechaFin=" ";
String errorMsg=" ";
int tarea=detalle.getIdTarea();
Metrica meta = new Metrica();
Metrica metb = new Metrica();
MetricaResource metRes = new MetricaResource();
repo.update(detalle);
System.out.println(detalle);
fechaFin+=detalle.getFecha_fin();
errorMsg+=detalle.geterrorMsg();
/* Si ya se asignó el destino, cambia de estado y se crea nueva tarea */
if (detalle.getIdUsrd()>0 && errorMsg.length()<5 && fechaFin.length()>5 ) { // Si existe fecha final entonces terminó la etapa.
if (tarea!=3) {
tarea++;
detalle.setIdTarea(tarea);
fechaIni=detalle.getFecha_fin();
detalle.setFecha_ini(fechaIni);
repo.create(detalle);
if (tarea==3) {
meta.setAtendido(1);
meta.setAsignado(-1);
meta.setIdUsuario(detalle.getIdUsro());
metRes.updateMetricas(meta);
metb.setAtendido(1);
metb.setAsignado(-1);
metb.setIdUsuario(detalle.getIdUsrd());
metRes.updateMetricas(metb);
}
}
else { // se tiene que hacer el cierre del proceso.
Evento ev = new Evento();
EventoRepo repoev = new EventoRepo();
ev.setFechaFin(detalle.getFecha_fin());
ev.setIdEvento(detalle.getIdEvento());
ev.setStatus("Terminado");
ev.setIdProceso(1);
repoev.update(ev);
meta.setAtendido(-1);
meta.setTerminado(1);
meta.setIdUsuario(detalle.getIdUsro());
metRes.updateMetricas(meta);
metb.setAtendido(-1);
metb.setTerminado(1);
metb.setIdUsuario(detalle.getIdUsrd());
metRes.updateMetricas(metb);
}
}
return detalle;
}
}
|
package edu.byu.cs.tweeter.view.main;
import android.content.Context;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import edu.byu.cs.tweeter.R;
import edu.byu.cs.tweeter.model.domain.AuthToken;
import edu.byu.cs.tweeter.model.domain.User;
import edu.byu.cs.tweeter.view.main.follower.FollowerFragment;
import edu.byu.cs.tweeter.view.main.following.FollowingFragment;
import edu.byu.cs.tweeter.view.main.story.StoryFragment;
public class OtherPagerAdapter extends FragmentPagerAdapter {
private static final int FOLLOWING_FRAGMENT_POSITION = 1;
private static final int FOLLOWER_FRAGMENT_POSITION = 2;
private static final int STORY_FRAGMENT_POSITION = 0;
@StringRes
private static final int[] TAB_TITLES = new int[]{R.string.storyTabTitle, R.string.followingTabTitle, R.string.followersTabTitle};
private final Context mContext;
private final User user;
private final AuthToken authToken;
//private final Status status;
public OtherPagerAdapter(Context context, FragmentManager fm, User user, AuthToken authToken) { //, Status status) {
super(fm);
mContext = context;
this.user = user;
this.authToken = authToken;
//this.status = new Status("FJLKDJSL", user, "Nonyah 10:00");
}
@Override
public Fragment getItem(int position) {
if (position == FOLLOWING_FRAGMENT_POSITION) {
return FollowingFragment.newInstance(user, authToken);
}
else if (position == FOLLOWER_FRAGMENT_POSITION) {
return FollowerFragment.newInstance(user, authToken);
}
else if (position == STORY_FRAGMENT_POSITION) {
return StoryFragment.newInstance(user, authToken);//User
}
else {
return PlaceholderFragment.newInstance(position + 1);
}
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return mContext.getResources().getString(TAB_TITLES[position]);
}
@Override
public int getCount() {
// Show 4 total pages.
return 3;
}
}
|
package com.jlgproject.adapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.jlgproject.R;
import com.jlgproject.activity.Pic_Text_Details;
import com.jlgproject.model.Answer_Tu_Model;
import java.util.List;
/**
* Created by sunbeibei on 2017/8/4.
*/
public class The_Answer_Tu_Search_Adapter extends BaseAdapter {
private Context context;
private List<Answer_Tu_Model.DataBean.ItemsBean> items;
public The_Answer_Tu_Search_Adapter(Context context,List<Answer_Tu_Model.DataBean.ItemsBean> items) {
this.context = context;
this.items=items;
}
public void setItems(List<Answer_Tu_Model.DataBean.ItemsBean> items) {
this.items = items;
}
@Override
public int getCount() {
return items.size();
}
@Override
public Object getItem(int position) {
return items.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
VierHolder_Answer_Tu answer_tu ;
if (convertView==null){
convertView= LayoutInflater.from(context).inflate(R.layout.the_answer_tu_item,null);
answer_tu= new VierHolder_Answer_Tu();
answer_tu.buju_tu= (LinearLayout) convertView.findViewById(R.id.buju_tu);
answer_tu.the_answwer_tu = (TextView) convertView.findViewById(R.id.the_answers_tu);
convertView.setTag(answer_tu);
}else{
answer_tu= (VierHolder_Answer_Tu) convertView.getTag();
}
answer_tu.the_answwer_tu.setText(items.get(position).getSubtitle());
answer_tu.buju_tu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
context.startActivity(new Intent(context, Pic_Text_Details.class).putExtra("url",items.get(position).getUrl()));
}
});
return convertView;
}
public class VierHolder_Answer_Tu{
private LinearLayout buju_tu;
private TextView the_answwer_tu;
}
}
|
package com.example.bratwurst.service;
import com.amazonaws.services.sns.AmazonSNS;
import com.amazonaws.services.sns.model.*;
import com.example.bratwurst.model.FriendsViewModel;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import com.example.bratwurst.model.User;
import com.example.bratwurst.repo.UserRepo;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Service
// @EnableAutoConfiguration
public class UserServiceImpl implements UserService {
Logger log = Logger.getLogger(UserServiceImpl.class.getName());
@Autowired
UserRepo userRepo;
@Autowired
AmazonSNS amazonSNS;
private int authCode;
private String topicArn = "arn:aws:sns:eu-west-1:966879952819:bratwurst-two-factor-auth";
@Override
public boolean validateAuthCode(int inputCode) {
if (inputCode == this.authCode){
return true;
}else {
return false;
}
}
@Override
public void publishMessage(String email) throws JSONException {
Random rand = new Random();
int authCodeInt = rand.nextInt(100000);
this.authCode = authCodeInt;
PublishRequest publishRequest = new PublishRequest(topicArn, "your code is: " + authCode, "Auth code");
Map<String, MessageAttributeValue> messageAttributeValueMap = new HashMap<>();
messageAttributeValueMap.put("email", new MessageAttributeValue().withDataType("String").withStringValue(email.toLowerCase()));
publishRequest.withMessageAttributes(messageAttributeValueMap);
amazonSNS.publish(publishRequest);
}
@Override
public void subscribeToTopic(String email) throws JSONException {
SubscribeRequest subscribeRequest = new SubscribeRequest(topicArn, "email", email.toLowerCase());
amazonSNS.subscribe(subscribeRequest);
// setPolicyFilter(email);
}
@Override
public void setPolicyFilter(String email) throws JSONException {
String[] s = {email.toLowerCase()};
JSONObject jo = new JSONObject();
jo.put("email", s);
String filterP = jo.toString();
ListSubscriptionsByTopicRequest listSubscriptionsByTopicRequest = new ListSubscriptionsByTopicRequest(topicArn);
ListSubscriptionsByTopicResult list = amazonSNS.listSubscriptionsByTopic(listSubscriptionsByTopicRequest);
List<Subscription> subArnList = list.getSubscriptions();
for (int i = 0; i < subArnList.size(); i++){
Subscription subArn = subArnList.get(i);
if (subArn.getEndpoint().equals(email.toLowerCase())){
String subArnValue = subArn.getSubscriptionArn();
SetSubscriptionAttributesRequest request = new SetSubscriptionAttributesRequest(subArnValue, "FilterPolicy", jo.toString());
amazonSNS.setSubscriptionAttributes(request);
break;
}
}
}
@Override
public User getLogin(String username, String password) {
User user = userRepo.getLogin(username, password);
if (user == null){
return null;
}
else{
return user;
}
}
public List<FriendsViewModel> getUsers(int id) {
return userRepo.getUsers(id);
}
@Override
public User addUser(User user, String confirm_password) {
User matching_user = userRepo.findLogin(user.getUsername(), user.getEmail());
String current_pass = user.getPassword();
boolean strongPassword = passwordStrong(user.getPassword());
if (strongPassword != true){
return null;
}
// if the two passwords match
if (current_pass.equals(confirm_password)){
if (matching_user == null){
return userRepo.addUser(user);
}
// if there is a match on email
if (user.getEmail().equals(matching_user.getEmail())){
matching_user.setUsername(null);
return matching_user;
// if there is a match on username
} else if(user.getUsername().toLowerCase().equals(matching_user.getUsername().toLowerCase())) {
matching_user.setEmail(null);
return matching_user;
}
return null;
} else{
return null;
}
}
@Override
public boolean passwordStrong(String password) {
boolean haveUpper = false;
boolean haveLower = false;
boolean length = false;
boolean specialCharacter = false;
// Checks for lowercase and upercase
for( int i = 0; i< password.length(); i++){
char ch = password.charAt(i);
if (Character.isUpperCase(ch)){
haveUpper = true;
}else if(Character.isLowerCase(ch)){
haveLower = true;
}
}
// Checks for length
if (password.length() > 7) {
length = true;
}
// Checks for special character
Pattern p = Pattern.compile("[A-Za-z0-9]");
Matcher m = p.matcher(password);
boolean b = m.find();
if (b){
specialCharacter = true;
}
if (haveUpper && haveLower && length && specialCharacter){
return true;
}else{
return false;
}
}
public User getUserById(int id) {
return userRepo.getUserById(id);
}
public void friendRequest(int userId, int receiverId){
userRepo.friendRequest(userId, receiverId);
}
public List<User> notifications(int id){
return userRepo.notifications(id);
}
public void acceptRequest(int receiverId, int userId) {
userRepo.acceptRequest(receiverId, userId);
}
@Override
public boolean isAdmin(User user){
if (user.getEmail().equals("tobias.ku22@gmail.com")){
return true;
}else {
return false;
}
}
@Override
public void deleteById(int id) {
userRepo.deleteById(id);
}
}
|
package com.selesgames.weave.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public class UserInfo {
@JsonProperty("UserId")
private String userId;
public String getUserId() {
return userId;
}
}
|
package com.yougou.merchant.api.help.vo;
import java.io.Serializable;
import java.util.Date;
/**
* 商家帮助中心图片实体
*
* @author huang.tao
*
*/
public class HelpCenterImg implements Serializable {
private static final long serialVersionUID = 4223630121266688780L;
private String id;
/** 图片名称 */
private String picName;
private Date created;
private Date updated;
public HelpCenterImg() {}
public HelpCenterImg(String picName, Date created,
Date updated) {
this.picName = picName;
this.created = created;
this.updated = updated;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPicName() {
return picName;
}
public void setPicName(String picName) {
this.picName = picName;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
}
|
package org.usfirst.frc.team1155.robot;
import edu.wpi.first.wpilibj.I2C;
public class RioDuinoController {
private I2C i2cBus;
private String rioDuinoDrive;
RioDuinoController() {
i2cBus = new I2C(I2C.Port.kMXP, 4);
}
public void SendStateChange(char state) {
i2cBus.write(0x02, state);
//causes color to update
}
public String getRioDuinoDrive() {
return rioDuinoDrive;
}
public void setRioDuinoDrive(String set) {
rioDuinoDrive = set;
}
public void SendString(String writeStr) {
byte[] toSend = new byte[1];
switch (writeStr) {
case ("autoBlue"):
toSend[0] = 0;
break;
case ("autoRed"):
toSend[0] = 1;
break;
case ("tankRed"):
toSend[0] = 3;
break;
case ("mechBlue"):
toSend[0] = 4;
break;
case ("mechRed"):
toSend[0] = 5;
break;
case ("disableInit"):
toSend[0] = 6;
break;
case ("depositingGear"):
toSend[0] = 7;
break;
case ("shooting"):
toSend[0] = 8;
break;
case ("climbing"):
toSend[0] = 9;
break;
case ("red"):
toSend[0] = 10;
break;
case ("yellow"):
toSend[0] = 11;
break;
case ("green"):
toSend[0] = 12;
break;
case ("blue"):
toSend[0] = 13;
break;
case ("purple"):
toSend[0] = 14;
break;
}
//i2cBus.transaction(toSend, toSend.length, null, 0);
//sends it to RioDuino
}
} |
package co.nos.noswallet.di.analytics;
import android.content.Context;
import co.nos.noswallet.analytics.AnalyticsService;
import co.nos.noswallet.bus.Logout;
import co.nos.noswallet.bus.RxBus;
import co.nos.noswallet.db.Migration;
import co.nos.noswallet.di.activity.ActivityScope;
import co.nos.noswallet.di.application.ApplicationScope;
import co.nos.noswallet.di.persistence.PersistenceModule;
import co.nos.noswallet.util.SharedPreferencesUtil;
import co.nos.noswallet.util.Vault;
import dagger.Module;
import dagger.Provides;
import io.realm.Realm;
@Module(includes = PersistenceModule.class)
public class AnalyticsModule {
@Provides
@ApplicationScope
AnalyticsService providesAnalyticsService(Context context, Realm realm) {
return new AnalyticsService(context.getApplicationContext(), realm);
}
}
|
package jc.sugar.JiaHui.jmeter.configtestelement;
import jc.sugar.JiaHui.jmeter.*;
import org.apache.jmeter.protocol.http.control.CacheManager;
import java.util.HashMap;
import java.util.Map;
import static org.apache.jorphan.util.Converter.getBoolean;
import static org.apache.jorphan.util.Converter.getInt;
@JMeterElementMapperFor(value = JMeterElementType.CacheManager, testGuiClass = JMeterElement.CacheManager)
public class CacheManagerMapper extends AbstractJMeterElementMapper<CacheManager> {
public static final String WEB_CLEAR_EACH_ITERATION = "clearEachIteration";
public static final String WEB_CONTROLLED_BY_THREAD = "controlledByThread";
public static final String WEB_USE_EXPIRES = "useExpires";
public static final String WEB_MAX_SIZE = "maxSize";
private CacheManagerMapper(CacheManager element, Map<String, Object> attributes) {
super(element, attributes);
}
public CacheManagerMapper(Map<String, Object> attributes){
this(new CacheManager(), attributes);
}
public CacheManagerMapper(CacheManager element){
this(element, new HashMap<>());
}
@Override
public CacheManager fromAttributes() {
element.setClearEachIteration(getBoolean(attributes.get(WEB_CLEAR_EACH_ITERATION)));
element.setControlledByThread(getBoolean(attributes.get(WEB_CONTROLLED_BY_THREAD)));
element.setUseExpires(getBoolean(attributes.get(WEB_USE_EXPIRES)));
element.setMaxSize(getInt(attributes.get(WEB_MAX_SIZE)));
return element;
}
@Override
public Map<String, Object> toAttributes() {
attributes.put(WEB_CATEGORY, JMeterElementCategory.ConfigElement);
attributes.put(WEB_TYPE, JMeterElementType.CacheManager);
attributes.put(WEB_CLEAR_EACH_ITERATION, element.getClearEachIteration());
attributes.put(WEB_CONTROLLED_BY_THREAD, element.getControlledByThread());
attributes.put(WEB_USE_EXPIRES, element.getUseExpires());
attributes.put(WEB_MAX_SIZE, element.getMaxSize());
return attributes;
}
}
|
package dto.jang.hs;
public class detail2 {
private String VAN_ADR;
private String NEW_ADR;
private String TEL;
private String POLL_DIV_CD;
private String OS_NM;
private String LPG_YN;
private String MAINT_YN;
private String CAR_WASH_YN;
private String KPETRO_YN;
private String CVS_YN;
private long B034_PRICE;
private long B027_PRICE;
private long D047_PRICE;
private long K015_PRICE;
public long getB034_PRICE() {
return B034_PRICE;
}
public void setB034_PRICE(long b034_PRICE) {
B034_PRICE = b034_PRICE;
}
public long getB027_PRICE() {
return B027_PRICE;
}
public void setB027_PRICE(long b027_PRICE) {
B027_PRICE = b027_PRICE;
}
public long getD047_PRICE() {
return D047_PRICE;
}
public void setD047_PRICE(long d047_PRICE) {
D047_PRICE = d047_PRICE;
}
public long getK015_PRICE() {
return K015_PRICE;
}
public void setK015_PRICE(long k015_PRICE) {
K015_PRICE = k015_PRICE;
}
public String getPOLL_DIV_CD() {
return POLL_DIV_CD;
}
public void setPOLL_DIV_CD(String pOLL_DIV_CD) {
if(pOLL_DIV_CD.equals("SKE")) { POLL_DIV_CD="SK에너지";}
else if(pOLL_DIV_CD.equals("GSC")) { POLL_DIV_CD="GS칼텍스";}
else if(pOLL_DIV_CD.equals("HDO")) { POLL_DIV_CD="현대오일뱅크";}
else if(pOLL_DIV_CD.equals("SOL")) { POLL_DIV_CD="S-OIL";}
else if(pOLL_DIV_CD.equals("RTO")) { POLL_DIV_CD="자영알뜰";}
else if(pOLL_DIV_CD.equals("RTX")) { POLL_DIV_CD="고속도로 알뜰";}
else if(pOLL_DIV_CD.equals("NHO")) { POLL_DIV_CD="농협 알뜰";}
else if(pOLL_DIV_CD.equals("ETC")) { POLL_DIV_CD="자가상표";}
else if(pOLL_DIV_CD.equals("E1G")) { POLL_DIV_CD="E1";}
else if(pOLL_DIV_CD.equals("SKG")) { POLL_DIV_CD="SK가스";}
else {
POLL_DIV_CD=pOLL_DIV_CD;
}
}
public String getOS_NM() {
return OS_NM;
}
public void setOS_NM(String oS_NM) {
OS_NM = oS_NM;
}
public String getLPG_YN() {
return LPG_YN;
}
public void setLPG_YN(String lPG_YN) {
//LPG_YN = lPG_YN;
if(lPG_YN.equals("N")) { this.LPG_YN="일반 주유소";}
else if(lPG_YN.equals("Y")) {this.LPG_YN="자동차 충전소";}
else if(lPG_YN.equals("C")) {this.LPG_YN="주유소 충전소 겸업";}
}
public String getMAINT_YN() {
return MAINT_YN;
}
public void setMAINT_YN(String mAINT_YN) {
MAINT_YN = mAINT_YN;
}
public String getCAR_WASH_YN() {
return CAR_WASH_YN;
}
public void setCAR_WASH_YN(String cAR_WASH_YN) {
CAR_WASH_YN = cAR_WASH_YN;
}
public String getKPETRO_YN() {
return KPETRO_YN;
}
public void setKPETRO_YN(String kPETRO_YN) {
KPETRO_YN = kPETRO_YN;
}
public String getCVS_YN() {
return CVS_YN;
}
public void setCVS_YN(String cVS_YN) {
CVS_YN = cVS_YN;
}
public String getVAN_ADR() {
return VAN_ADR;
}
public void setVAN_ADR(String vAN_ADR) {
VAN_ADR = vAN_ADR;
}
public String getNEW_ADR() {
return NEW_ADR;
}
public void setNEW_ADR(String nEW_ADR) {
NEW_ADR = nEW_ADR;
}
public String getTEL() {
return TEL;
}
public void setTEL(String tEL) {
TEL = tEL;
}
}
|
package com.example.journey_datn.Model;
import androidx.room.Ignore;
import androidx.room.PrimaryKey;
public class Diary {
private String id;
private String date, title, contain;
private boolean checkRdb = false;
public Diary() {
}
public Diary(String id, String date, String title, String contain) {
this.id = id;
this.date = date;
this.title = title;
this.contain = contain;
}
public Diary(String date, String title, String contain) {
this.date = date;
this.title = title;
this.contain = contain;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContain() {
return contain;
}
public void setContain(String contain) {
this.contain = contain;
}
public boolean isCheckRdb() {
return checkRdb;
}
public void setCheckRdb(boolean checkRdb) {
this.checkRdb = checkRdb;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package legaltime;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
/**
*
* @author bmartin
*/
public class TextUtils {
public static String frontZeroFill(Object value_, int charCount_){
StringBuffer value = new StringBuffer(value_.toString());
for(int ndx =value.length();ndx<charCount_; ndx ++){
value.insert(0, "0");
}
return value.toString();
}
public static String getStackTrace(Throwable aThrowable) {
final Writer result = new StringWriter();
final PrintWriter printWriter = new PrintWriter(result);
aThrowable.printStackTrace(printWriter);
return result.toString();
}
public static String prepareFileName(String fileName_){
fileName_ = fileName_.replaceAll("\\\\","" );
fileName_ = fileName_.replaceAll("<","" );
fileName_ = fileName_.replaceAll(">","" );
fileName_ = fileName_.replaceAll(":","" );
fileName_ = fileName_.replaceAll("\"","" );
fileName_ = fileName_.replaceAll("/","" );
fileName_ = fileName_.replaceAll("|","" );
return fileName_;
}
}
|
package com.esri.alejo.ramapa;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.LayerList;
import java.io.Serializable;
/**
* Created by alejo on 2/02/2018.
*/
public class mapaCarga implements Serializable {
public ArcGISMap mapa;
public LayerList layers;
public mapaCarga(String urlMapa){
mapa = new ArcGISMap(urlMapa);
layers = mapa.getOperationalLayers();
}
public ArcGISMap getMap(){
return mapa;
}
public LayerList getLayers(){
return layers;
}
}
|
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.staticUIExtensions;
import jetbrains.buildServer.BaseTestCase;
import jetbrains.buildServer.staticUIExtensions.config.ConfigurationReader;
import jetbrains.buildServer.staticUIExtensions.model.Rule;
import jetbrains.buildServer.util.FileUtil;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
/**
* @author Eugene Petrenko (eugene.petrenko@gmail.com)
* Date: 17.11.11 18:56
*/
public class ConfigurationListenerTest extends BaseTestCase {
private Mockery m;
private PagePlacesInitializer myInitializer;
private ConfigurationReader myReader;
private ConfigurationListener myListener;
private Configuration myConfig;
private File myConfigXml;
@BeforeMethod
@Override
protected void setUp() throws Exception {
super.setUp();
m = new Mockery();
myConfigXml = createTempFile();
myInitializer = m.mock(PagePlacesInitializer.class);
myReader = m.mock(ConfigurationReader.class);
myConfig = m.mock(Configuration.class);
m.checking(new Expectations(){{
allowing(myConfig).getConfigurationXml(); will(returnValue(myConfigXml));
}});
myListener = new ConfigurationListener(
myReader,
myInitializer,
myConfig
);
}
@Test
public void testLoadIfNoConfig() {
FileUtil.delete(myConfigXml);
m.checking(new Expectations(){{
oneOf(myInitializer).registerPagePlaces(with(equal(Collections.<Rule>emptyList())));
}});
myListener.configurationChanged();
m.assertIsSatisfied();
}
@Test
public void testLoadIfConfig() throws ConfigurationException {
FileUtil.writeFile(myConfigXml, "complicated config");
final Collection<Rule> rulez = new ArrayList<Rule>();
m.checking(new Expectations(){{
oneOf(myReader).parseConfiguration(myConfigXml); will(returnValue(rulez));
oneOf(myInitializer).registerPagePlaces(with(equal(rulez)));
}});
myListener.configurationChanged();
m.assertIsSatisfied();
}
@Test
public void testLoadIfConfigError() throws ConfigurationException {
FileUtil.writeFile(myConfigXml, "complicated config");
m.checking(new Expectations(){{
oneOf(myReader).parseConfiguration(myConfigXml); will(throwException(new ConfigurationException("oopsy")));
oneOf(myInitializer).registerPagePlaces(with(equal(Collections.<Rule>emptyList())));
}});
myListener.configurationChanged();
m.assertIsSatisfied();
}
}
|
package course;
import java.util.List;
public class Invoice {
public List<Part> parts;
public int number;
public Invoice(List<Part> parts, int number) {
super();
this.parts = parts;
this.number = number;
}
public Invoice(String string, List<Part> thirdPack) {
}
public List<Part> getParts() {
return parts;
}
public void setParts(List<Part> parts) {
this.parts = parts;
}
public int getNumber() {
return number;
}
public void setNumber(int Number) {
this.number = number;
}
}
|
package fr.tungnguyen.hibernate.batch.modelb;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "Person")
public class PersonB {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(unique = true, nullable = false, insertable = true, updatable = true)
private Long id;
@Column(unique = false, nullable = true, insertable = true, updatable = true, length = 40)
private String firstName;
/**
* Constructeur
*/
public PersonB() {
super();
}
/**
* Getter pour id
* @return la valeur du champ id
*/
public Long getId() {
return id;
}
/**
* Setter pour id
* @param id La nouvelle valeur du champ id
*/
public void setId(final Long id) {
this.id = id;
}
/**
* Getter pour firstName
* @return la valeur du champ firstName
*/
public String getFirstName() {
return firstName;
}
/**
* Setter pour firstName
* @param firstName La nouvelle valeur du champ firstName
*/
public void setFirstName(final String firstName) {
this.firstName = firstName;
}
}
|
package cn.yhd.base;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author master
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
public @interface NotEmpty {
String name() default "";
} |
package com.pointburst.jsmusic.player;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.widget.RemoteViews;
import com.pointburst.jsmusic.listener.PMediaPlayerListener;
import com.pointburst.jsmusic.model.Media;
import com.pointburst.jsmusic.ui.MainActivity;
import com.pointburst.jsmusic.utils.Logger;
/**
* Created by FARHAN on 1/22/2015.
*/
public class PMediaPlayerService extends Service implements MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnInfoListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener {
private PMediaPlayer mMediaPlayer = new PMediaPlayer();
private final Binder mBinder = new MediaPlayerBinder();
private PMediaPlayerListener mClient;
public class MediaPlayerBinder extends Binder {
public PMediaPlayerService getService() {
return PMediaPlayerService.this;
}
}
public PMediaPlayer getMediaPlayer() {
return mMediaPlayer;
}
public void initializePlayer(Media media) {
mClient.onInitializePlayerStart("Connecting...");
mMediaPlayer = new PMediaPlayer(media);
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnInfoListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.prepareAsync();
}
/**
* Initializes a StatefulMediaPlayer for streaming playback of the provided stream url
* @param streamUrl The URL of the stream to play.
*/
public void initializePlayer(String streamUrl) {
mMediaPlayer = new PMediaPlayer();
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mMediaPlayer.setDataSource(streamUrl);
}
catch (Exception e) {
Logger.print("error setting data source");
mMediaPlayer.setState(PMediaPlayer.MPStates.ERROR);
}
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnInfoListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.prepareAsync();
}
@Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
@Override
public void onBufferingUpdate(MediaPlayer player, int percent) {
}
@Override
public boolean onError(MediaPlayer player, int what, int extra) {
mMediaPlayer.reset();
mClient.onError();
return true;
}
@Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
return false;
}
@Override
public void onPrepared(MediaPlayer player) {
mClient.onInitializePlayerSuccess();
startMediaPlayer();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
public void pauseMediaPlayer() {
Logger.print("pauseMediaPlayer() called");
mMediaPlayer.pause();
stopForeground(true);
}
public void setClient(PMediaPlayerListener client) {
this.mClient = client;
}
/**
* Starts the contained StatefulMediaPlayer and foregrounds the service to support
* persisted background playback.
*/
public void startMediaPlayer() {
Context context = getApplicationContext();
//set to foreground
Notification notification = new Notification(android.R.drawable.ic_media_play, "MediaPlayerService",
System.currentTimeMillis());
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
CharSequence contentTitle = "MediaPlayerService Is Playing";
CharSequence contentText = mMediaPlayer.getMedia().getTitle();
notification.setLatestEventInfo(context, contentTitle,
contentText, pendingIntent);
startForeground(1, notification);
Logger.print("startMediaPlayer() called");
mMediaPlayer.start();
}
/**
* Stops the contained StatefulMediaPlayer.
*/
public void stopMediaPlayer() {
stopForeground(true);
mMediaPlayer.stop();
mMediaPlayer.release();
}
public void resetMediaPlayer() {
stopForeground(true);
mMediaPlayer.reset();
}
}
|
package com.vilio.bps.commonMapper.pojo;
import java.io.Serializable;
/**
* @实体名称 询价请求与计算结果关联表
* @数表名称 BPS_INQUIRY_RESULT_RELATION
* @开发日期 2017-06-12
* @技术服务 www.fwjava.com
*/
public class BpsInquiryResultRelation implements Serializable {
/**
* (必填项)(主键ID)
*/
private Integer id = null;
/**
* bps_user_inquiry表中serial_no
*/
private String serialNo = null;
/**
* bps_house_assessment_result中code
*/
private String resultCode = null;
/**
* 排序
*/
private String orderBy = null;
/*
*--------------------------------------------------
* Getter方法区
*--------------------------------------------------
*/
/**
* (必填项)(主键ID)
*/
public Integer getId() {
return id;
}
/**
* bps_user_inquiry表中serial_no
*/
public String getSerialNo() {
return trim(serialNo);
}
/**
* bps_house_assessment_result中code
*/
public String getResultCode() {
return trim(resultCode);
}
/**
* 排序
*/
public String getOrderBy() {
return trim(orderBy);
}
/*
*--------------------------------------------------
* Setter方法区
*--------------------------------------------------
*/
/**
* (必填项)(主键ID)
*/
public void setId(Integer id) {
this.id = id;
}
/**
* bps_user_inquiry表中serial_no
*/
public void setSerialNo(String serialNo) {
this.serialNo = serialNo;
}
/**
* bps_house_assessment_result中code
*/
public void setResultCode(String resultCode) {
this.resultCode = resultCode;
}
/**
* 排序
*/
public void setOrderBy(String orderBy) {
this.orderBy = orderBy;
}
/*
*--------------------------------------------------
* 常用自定义字段
*--------------------------------------------------
*/
/*
*--------------------------------------------------
* 应用小方法
*--------------------------------------------------
*/
/**
* serialVersionUID
*/
private static final long serialVersionUID = 1L;
public String trim(String input)
{
return input==null?null:input.trim();
}
}
/**
------------------------------------------------------
Copy专用区
------------------------------------------------------
------------------------------------------------------------------------------------------------------------
Setter方法
------------------------------------------------------------------------------------------------------------
// 询价请求与计算结果关联表
BpsInquiryResultRelation bpsInquiryResultRelation = new BpsInquiryResultRelation();
// (必填项)(主键ID)
bpsInquiryResultRelation.setId( );
// bps_user_inquiry表中serial_no
bpsInquiryResultRelation.setSerialNo( );
// bps_house_assessment_result中code
bpsInquiryResultRelation.setResultCode( );
//------ 自定义部分 ------
------------------------------------------------------------------------------------------------------------
Getter方法
------------------------------------------------------------------------------------------------------------
// 询价请求与计算结果关联表
BpsInquiryResultRelation bpsInquiryResultRelation = new BpsInquiryResultRelation();
// (必填项)(主键ID)
bpsInquiryResultRelation.getId();
// bps_user_inquiry表中serial_no
bpsInquiryResultRelation.getSerialNo();
// bps_house_assessment_result中code
bpsInquiryResultRelation.getResultCode();
//------ 自定义部分 ------
------------------------------------------------------------------------------------------------------------
Getter Setter方法
------------------------------------------------------------------------------------------------------------
// 询价请求与计算结果关联表
BpsInquiryResultRelation bpsInquiryResultRelation = new BpsInquiryResultRelation();
// (必填项)(主键ID)
bpsInquiryResultRelation.setId( bpsInquiryResultRelation2.getId() );
// bps_user_inquiry表中serial_no
bpsInquiryResultRelation.setSerialNo( bpsInquiryResultRelation2.getSerialNo() );
// bps_house_assessment_result中code
bpsInquiryResultRelation.setResultCode( bpsInquiryResultRelation2.getResultCode() );
//------ 自定义部分 ------
------------------------------------------------------------------------------------------------------------
HTML标签区
------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------
属性区
------------------------------------------------------------------------------------------------------------
<!-- -->
<input name="id" value="" type="text" maxlength="11"/>
<!-- bps_user_inquiry表中serial_no -->
<input name="serialNo" value="" type="text" maxlength="36"/>
<!-- bps_house_assessment_result中code -->
<input name="resultCode" value="" type="text" maxlength="36"/>
------------------------------------------------------------------------------------------------------------
表名 + 属性区
------------------------------------------------------------------------------------------------------------
<!-- -->
<input name="bpsInquiryResultRelation.id" value="" type="text" maxlength="11"/>
<!-- bps_user_inquiry表中serial_no -->
<input name="bpsInquiryResultRelation.serialNo" value="" type="text" maxlength="36"/>
<!-- bps_house_assessment_result中code -->
<input name="bpsInquiryResultRelation.resultCode" value="" type="text" maxlength="36"/>
------------------------------------------------------------------------------------------------------------
ID + 属性区
------------------------------------------------------------------------------------------------------------
<!-- -->
<input id="BIRR_ID" name="id" value="" type="text" maxlength="11"/>
<!-- bps_user_inquiry表中serial_no -->
<input id="BIRR_SERIAL_NO" name="serialNo" value="" type="text" maxlength="36"/>
<!-- bps_house_assessment_result中code -->
<input id="BIRR_RESULT_CODE" name="resultCode" value="" type="text" maxlength="36"/>
------------------------------------------------------------------------------------------------------------
ID + 表名 + 属性区
------------------------------------------------------------------------------------------------------------
<!-- -->
<input id="BIRR_ID" name="bpsInquiryResultRelation.id" value="" type="text" maxlength="11"/>
<!-- bps_user_inquiry表中serial_no -->
<input id="BIRR_SERIAL_NO" name="bpsInquiryResultRelation.serialNo" value="" type="text" maxlength="36"/>
<!-- bps_house_assessment_result中code -->
<input id="BIRR_RESULT_CODE" name="bpsInquiryResultRelation.resultCode" value="" type="text" maxlength="36"/>
--------------------------------------------------------
*/
|
package com.etar.purifier.modules.firmware.service.impl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import com.etar.purifier.modules.firmware.service.FirmwareService;
import entity.firmware.Firmware;
import entity.firmware.QueryFirmware;
import com.etar.purifier.modules.firmware.jpa.FirmwareRepository;
import javax.persistence.criteria.Predicate;
import java.io.File;
import java.util.List;
import java.util.Optional;
/**
* <p>
* Firmware服务类
* </p>
*
* @author hzh
* @since 2019-07-01
*/
@Service
public class FirmwareServiceImpl implements FirmwareService {
@Autowired
private FirmwareRepository firmwareRepository;
/**
* 保存对象
*
* @param firmware 对象
* 持久对象,或者对象集合
*/
@Override
public Firmware save(Firmware firmware) {
return firmwareRepository.save(firmware);
}
/**
* 删除对象
*
* @param firmware 对象
*/
@Override
public void delete(Firmware firmware) {
firmwareRepository.delete(firmware);
}
@Override
public void deleteById(Integer id) {
firmwareRepository.deleteById(id);
}
@Override
public void deleteAll(List<Firmware> list) {
firmwareRepository.deleteAll(list);
}
/**
* 通过id判断是否存在
*
* @param id 主键
*/
@Override
public boolean existsById(Integer id) {
return firmwareRepository.existsById(id);
}
/**
* 返回可用实体的数量
*/
@Override
public long count() {
return firmwareRepository.count();
}
/**
* 通过id查询
*
* @param id id
* @return Firmware对象
*/
@Override
public Firmware findById(Integer id) {
Optional<Firmware> optional = firmwareRepository.findById(id);
boolean present = optional.isPresent();
return present ? optional.get() : null;
}
/**
* 分页查询
* id处字符串为需要排序的字段,可以传多个,比如 "id","createTime",...
*
* @param page 页面
* @param pageSize 页面大小
* @return Page<Firmware>对象
*/
@Override
public Page<Firmware> findAll(int page, int pageSize) {
Pageable pageable = PageRequest.of(page, pageSize, Sort.Direction.DESC, "id");
return firmwareRepository.findAll(pageable);
}
@Override
public List<Firmware> findList() {
return firmwareRepository.findAll();
}
@Override
public Page<Firmware> findAll(int page, int pageSize, QueryFirmware queryFirmware) {
Pageable pageable = PageRequest.of(page, pageSize, Sort.Direction.DESC, "id");
//查询条件构造
Specification<Firmware> spec = (Specification<Firmware>) (root, query, cb) -> {
Predicate predicate = cb.conjunction();
if (StringUtils.isNotBlank(queryFirmware.getName())) {
predicate.getExpressions().add(cb.like(root.get("name").as(String.class), "%" + queryFirmware.getName() + "%"));
}
return predicate;
};
return firmwareRepository.findAll(spec, pageable);
}
/**
* 根据Id查询list
*
* @param ids id集合
* @return list
*/
@Override
public List<Firmware> findAllById(List<Integer> ids) {
return firmwareRepository.findAllById(ids);
}
@Override
public boolean existsByName(String name) {
return firmwareRepository.existsByName(name);
}
@SuppressWarnings("ResultOfMethodCallIgnored")
@Override
public void delBatch(List<Integer> ids) {
List<Firmware> byIds = firmwareRepository.findAllById(ids);
if (!byIds.isEmpty()) {
for (Firmware byId : byIds) {
String bin = StringUtils.split(byId.getOssUrl(), "/", 4)[3];
//删除对应上传的固件
File file1 = new File("/var/firmware/" + bin);
if (file1.exists()) {
file1.delete();
}
}
firmwareRepository.deleteInBatch(byIds);
}
}
public static void main(String[] args) {
final String[] split = StringUtils.split("http://iotsvr.he-live.com/firmware/firmware-1562826832739.bin", "/");
for (String aSplit : split) {
System.out.println(aSplit);
}
}
}
|
package digitalInnovation.javaBasico;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;
public class Aula_13_StreamAPI {
public static void main(String[] args) {
List<String> estudantes = new ArrayList<>(); //define uma lista do tipo string
estudantes.add("Brenda"); //adiciona elementos na lista
estudantes.add("Braian");
estudantes.add("Victor");
estudantes.add("Leonardo");
estudantes.add("Lavinia");
estudantes.add("Ana");
estudantes.add("Vinicus");
estudantes.add("Nicomar");
estudantes.add("Rafael");
System.out.println("Qtd de elementos da lista: " + estudantes.stream().count()); //retorna a qtd de elementos da lista
System.out.println("Maior elemento da lista: " + estudantes.stream().max(Comparator.comparingInt(String::length))); //retorna o maior elemento
System.out.println("Menor elemento da lista: " + estudantes.stream().min(Comparator.comparing(String::length))); //retorna o menor elemento
System.out.println("Elementos da lista que contenha a letra C: " +
estudantes.stream().filter((estudante) -> estudante.toLowerCase().contains("c")).collect(Collectors.toList())); //realiza filtro
System.out.println("Nova colecao com qtd de letras: " +
estudantes.stream().map(estudante -> estudante.concat(" - ").concat(String.valueOf(estudante.length()))).collect(Collectors.toList()));
System.out.println("Tres primeiros elementos da lista: " + estudantes.stream().limit(3).collect(Collectors.toList())); //retorna apenas uma determinada qtd de elementos
System.out.println("Mesmos elementos - peek(): " + estudantes.stream().peek(System.out::println).collect(Collectors.toList())); //retorna os mesmos elementos da lista
System.out.println("Mesmos elementos - forEach(): ");
estudantes.stream().forEach(System.out::println); //retorna os mesmos elemento da lista
System.out.println("Verifica se tem J na lista: " + estudantes.stream().allMatch((elemento) -> elemento.contains("j"))); //verifica se todos os elementos da lista contem a letra
System.out.println("Verifica se ao menos um elemento da lista possui s: " + estudantes.stream().anyMatch((estudante) -> estudante.contains("s"))); //verifica se ao menos um elemento da lista com a letra
System.out.println("Verifica se não contém W na lista: " + estudantes.stream().noneMatch((estudante) -> estudante.contains("w"))); //verifica se não contem a letra na lista
System.out.println("Primeiro elemento da lista: ");
estudantes.stream().findFirst().ifPresent(System.out::println); //retorna o primeiro elemento da lista
//Operacao encadeada
System.out.println("Operacao encadeada:");
System.out.println(estudantes.stream()
.peek(System.out::println)
.map(estudante -> estudante.concat(" - ").concat(String.valueOf(estudante.length())))
.peek(System.out::println)
.filter((estudante) -> estudante.toLowerCase().contains("r"))
// .collect(Collectors.toList())
// .collect(Collectors.joining(", "))
// .collect(Collectors.toSet())
.collect(Collectors.groupingBy(estudante -> estudante.substring(estudante.indexOf("-") + 1)))
);
}
}
|
package com.zoupeng.community;
import com.zoupeng.community.dao.AlphaDao;
import com.zoupeng.community.service.AlphaService;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.test.context.ContextConfiguration;
import java.text.SimpleDateFormat;
import java.util.Date;
@Slf4j
@SpringBootTest
@ContextConfiguration(classes = CommunityApplication.class)
class CommunityApplicationTests implements ApplicationContextAware {//想获取容器需要实现ApplicationContextAware
private ApplicationContext applicationContext;//用来记录容器
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;//记录
}
@Test
void testSpringContext() {
System.out.println(applicationContext);
AlphaDao alphaDao = applicationContext.getBean(AlphaDao.class);
System.out.println(alphaDao);
AlphaDao alphaDao2 = applicationContext.getBean("aaaa", AlphaDao.class);
System.out.println(alphaDao2);
log.info("test");
log.warn("test");
log.error("test");
}
@Test
public void testBeanManagement() {
AlphaService bean = applicationContext.getBean(AlphaService.class);
AlphaService bean1 = applicationContext.getBean(AlphaService.class);
System.out.println(bean);
System.out.println(bean1);
}
@Test
public void testBeanConfig() {
SimpleDateFormat simpleDateFormat = applicationContext.getBean(SimpleDateFormat.class);
System.out.println(simpleDateFormat.format(new Date()));
}
@Autowired //自动注入
private AlphaDao alphaDao;
@Autowired
private SimpleDateFormat simpleDateFormat;
@Autowired
@Qualifier("aaaa")//当有多个Alpha的实现类在容器中时,可通过@Qualifier筛选
private AlphaDao alphaDao1;
@Test
public void testDI(){//测试依赖注入
System.out.println(alphaDao);
System.out.println(alphaDao1);
System.out.println(simpleDateFormat);
}
}
|
/**
*/
package ConceptMapDSL.impl;
import ConceptMapDSL.*;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.impl.EFactoryImpl;
import org.eclipse.emf.ecore.plugin.EcorePlugin;
/**
* <!-- begin-user-doc -->
* An implementation of the model <b>Factory</b>.
* <!-- end-user-doc -->
* @generated
*/
public class ConceptMapDSLFactoryImpl extends EFactoryImpl implements ConceptMapDSLFactory {
/**
* Creates the default factory implementation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static ConceptMapDSLFactory init() {
try {
ConceptMapDSLFactory theConceptMapDSLFactory = (ConceptMapDSLFactory)EPackage.Registry.INSTANCE.getEFactory("http://spray.eclipselabs.org/examples/Conceptmap");
if (theConceptMapDSLFactory != null) {
return theConceptMapDSLFactory;
}
}
catch (Exception exception) {
EcorePlugin.INSTANCE.log(exception);
}
return new ConceptMapDSLFactoryImpl();
}
/**
* Creates an instance of the factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ConceptMapDSLFactoryImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public EObject create(EClass eClass) {
switch (eClass.getClassifierID()) {
case ConceptMapDSLPackage.NAMED_ELEMENT: return createNamedElement();
case ConceptMapDSLPackage.CONCEPT_MAP: return createConceptMap();
case ConceptMapDSLPackage.MAP_ELEMENTS: return createMapElements();
case ConceptMapDSLPackage.ELEMENT: return createElement();
case ConceptMapDSLPackage.ARROW_CONNECTION: return createArrowConnection();
case ConceptMapDSLPackage.DOUBLE_ARROW_CONNECTION: return createDoubleArrowConnection();
case ConceptMapDSLPackage.DEFAULT_CONNECTION: return createDefaultConnection();
default:
throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NamedElement createNamedElement() {
NamedElementImpl namedElement = new NamedElementImpl();
return namedElement;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ConceptMap createConceptMap() {
ConceptMapImpl conceptMap = new ConceptMapImpl();
return conceptMap;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MapElements createMapElements() {
MapElementsImpl mapElements = new MapElementsImpl();
return mapElements;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Element createElement() {
ElementImpl element = new ElementImpl();
return element;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ArrowConnection createArrowConnection() {
ArrowConnectionImpl arrowConnection = new ArrowConnectionImpl();
return arrowConnection;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DoubleArrowConnection createDoubleArrowConnection() {
DoubleArrowConnectionImpl doubleArrowConnection = new DoubleArrowConnectionImpl();
return doubleArrowConnection;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DefaultConnection createDefaultConnection() {
DefaultConnectionImpl defaultConnection = new DefaultConnectionImpl();
return defaultConnection;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ConceptMapDSLPackage getConceptMapDSLPackage() {
return (ConceptMapDSLPackage)getEPackage();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @deprecated
* @generated
*/
@Deprecated
public static ConceptMapDSLPackage getPackage() {
return ConceptMapDSLPackage.eINSTANCE;
}
} //ConceptMapDSLFactoryImpl
|
package single;
public class SingleMain {
private ActionFactory factory;
private CustomerAction customerAction;
private HistoryAction historyAction;
public SingleMain() {
factory = new ActionFactory();
customerAction = factory.getCustomerAction();
historyAction = factory.getHistoryAction();
}
public static void main(String[] args) {
SingleMain main = new SingleMain();
main.execute();
}
private void execute() {
Customer customer = customerAction.get(1);
System.out.println("Customer name: " + customer.getName());
factory.close();
}
}
|
package treerecursion3;
public class Solution {
public int maxPathSum(TreeNode root) {
// Write your solution here.
int[] max = new int[]{Integer.MIN_VALUE};
helper(root,max);
return max[0];
}
private int helper(TreeNode root, int [] max){
//base case
if(root == null){
return 0;
}
int left = helper(root.left,max);
int right = helper(root.right,max);
left = left > 0 ? left : 0;
right = right > 0 ? right : 0;
max[0] = Math.max(max[0], right + left + root.key);
return Math.max(right, left) + root.key;
}
}
|
package com.example.d;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
/**
* Wrapper activity demonstrating the use of {@link GLSurfaceView} to
* display translucent 3D graphics.
*/
public class TranslucentSurface extends Activity {
private final float TOUCH_SCALE_FACTOR = 180.0f / 320;
private final float TRACKBALL_SCALE_FACTOR = 36.0f;
private CubeRenderer mRenderer;
private float mPreviousX;
private float mPreviousY;
private ScaleGestureDetector mScaleDetector;
private float mScaleFactor = 1.f;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// Create our Preview view and set it as the content of our
// Activity
mGLSurfaceView = new TouchSurfaceView(this);
// We want an 8888 pixel format because that's required for
// a translucent window.
// And we want a depth buffer.
// mGLSurfaceView.setEGLConfigChooser(8, 8, 8, 8, 16, 0);
// Tell the cube renderer that we want to render a translucent version
// of the cube:
// mGLSurfaceView.setRenderer(new CubeRenderer(true));
// Use a surface format with an Alpha channel:
mGLSurfaceView.getHolder().setFormat(PixelFormat.TRANSLUCENT);
mGLSurfaceView.setZOrderOnTop(true);
setContentView(mGLSurfaceView);
mScaleDetector = new ScaleGestureDetector(this, new ScaleListener());
mGLSurfaceView.requestFocus();
mGLSurfaceView.setFocusableInTouchMode(true);
}
@Override
protected void onResume() {
super.onResume();
mGLSurfaceView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mGLSurfaceView.onPause();
}
private TouchSurfaceView mGLSurfaceView;
class TouchSurfaceView extends GLSurfaceView {
public TouchSurfaceView(Context context) {
super(context);
mRenderer = new CubeRenderer(true);
setRenderer(mRenderer);
// setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
}
@Override public boolean onTrackballEvent(MotionEvent e) {
mRenderer.mAngleX += e.getX() * TRACKBALL_SCALE_FACTOR;
mRenderer.mAngleY += e.getY() * TRACKBALL_SCALE_FACTOR;
requestRender();
return true;
}
@Override public boolean onTouchEvent(MotionEvent e) {
mScaleDetector.onTouchEvent(e);
float x = e.getX();
float y = e.getY();
switch (e.getAction()) {
case MotionEvent.ACTION_MOVE:
float dx = x - mPreviousX;
float dy = y - mPreviousY;
mRenderer.mAngleX += dx * TOUCH_SCALE_FACTOR;
mRenderer.mAngleY += dy * TOUCH_SCALE_FACTOR;
requestRender();
}
mPreviousX = x;
mPreviousY = y;
return true;
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.save();
canvas.scale(mScaleFactor, mScaleFactor);
//...
//Your onDraw() code
//...
canvas.restore();
}
}
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScale(ScaleGestureDetector detector) {
mScaleFactor *= detector.getScaleFactor();
// Don't let the object get too small or too large.
mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 4.0f));
System.out.println(mScaleFactor);
mRenderer.scale = mScaleFactor;
return true;
}
}
}
|
package com.tencent.mm.plugin.wenote.ui.nativenote.b;
import com.tencent.mm.plugin.wenote.model.a.h;
import com.tencent.mm.pluginsdk.ui.d.j;
import com.tencent.mm.sdk.platformtools.ah;
class k$2 implements Runnable {
final /* synthetic */ k qvL;
final /* synthetic */ h qvN;
k$2(k kVar, h hVar) {
this.qvL = kVar;
this.qvN = hVar;
}
public final void run() {
k.a(this.qvL).setRichTextEditing(this.qvN.content);
k.a(this.qvL).cab();
k.a(this.qvL).cad();
j.g(k.a(this.qvL));
k.a(this.qvL).cae();
k.a(this.qvL).cac();
if (this.qvN.qoH) {
if (this.qvN.qoJ == -1 || this.qvN.qoJ >= k.a(this.qvL).getText().toString().length()) {
k.a(this.qvL).setSelection(k.a(this.qvL).getText().toString().length());
} else {
k.a(this.qvL).setSelection(this.qvN.qoJ);
}
k.a(this.qvL).requestFocus();
ah.i(new 1(this), 500);
} else if (k.a(this.qvL).hasFocus()) {
k.a(this.qvL).clearFocus();
}
if (this.qvN.qoP) {
this.qvN.qoP = false;
k.a(this.qvL).qoP = true;
k.a(this.qvL).onTextContextMenuItem(16908322);
}
}
}
|
package com.tencent.mm.ui.chatting.b.b;
import com.tencent.mm.storage.bd;
import com.tencent.mm.ui.chatting.b.u;
public interface i extends u {
void aV(bd bdVar);
void aW(bd bdVar);
void aX(bd bdVar);
}
|
package MTv1;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
public class M3U8DOWNLOADER {
public M3U8DOWNLOADER(String m3u8_url, String DOWNLOAD_PATH) throws IOException, InterruptedException {
// String m3u8_og ="https://streaming.azure.queensu.ca/ensemble/_definst_/smil:JamesStewartstewartjqueensu.ca/GHOolt_gRUSwDFLssR7F4A.smil/playlist.m3u8";
ArrayList<String> ts_fregmetns_list = new SECONDLAYER_URL().SECONDLAYER_URL(m3u8_url);
//下载地址
// String DOWNLOAD_PATH = "C:\\Users\\STEVO\\Desktop\\java_project\\Blob\\t5\\";
//thread
//设置时间格式
SimpleDateFormat Current_date = new SimpleDateFormat("MMddHHmmSS");
//下载路径
String Org_Download_Path = DOWNLOAD_PATH;
DOWNLOAD_PATH += "\\download"+Current_date.format(new Date());
File DOWNLOAD_PATH_FILE = new File(DOWNLOAD_PATH);
if (!DOWNLOAD_PATH_FILE.exists()){
DOWNLOAD_PATH_FILE.mkdirs();
}
List<MultiThread> Thread_List = new ArrayList<MultiThread>();
//
MultiThread
thread1 = null, thread2=null, thread3=null, thread4=null, thread5=null, thread6=null, thread7=null, thread8=null;
int Thread_num = 4;
int total_task_num=ts_fregmetns_list.size();
int task_per_t=total_task_num/Thread_num;
int task_res = total_task_num % Thread_num;
//建立线程vector
Vector<Thread> threadVector = new Vector<Thread>();
threadVector.add(thread1);
threadVector.add(thread2);
threadVector.add(thread3);
threadVector.add(thread4);
threadVector.add(thread5);
threadVector.add(thread6);
threadVector.add(thread7);
threadVector.add(thread8);
//count down latch
// final CountDownLatch latch1 = new CountDownLatch(4);
//通用 file task per t
if (Thread_num == 4) {
thread1 = new MultiThread("thread1", (ArrayList) ts_fregmetns_list, DOWNLOAD_PATH_FILE, "thread1", task_per_t, task_per_t * 0);
thread1.start();
//
thread2 = new MultiThread("thread2", (ArrayList) ts_fregmetns_list, DOWNLOAD_PATH_FILE, "thread2", task_per_t, task_per_t * 1);
thread2.start();
//
thread3 = new MultiThread("thread3", (ArrayList) ts_fregmetns_list, DOWNLOAD_PATH_FILE, "thread3", task_per_t, task_per_t * 2);
thread3.start();
//
thread4 = new MultiThread("thread4", (ArrayList) ts_fregmetns_list, DOWNLOAD_PATH_FILE, "thread4", task_per_t + task_res, task_per_t * 3);
thread4.start();
thread1.join();
thread2.join();
thread3.join();
thread4.join();
}
if (Thread_num == 6) {
thread1 = new MultiThread("thread1", (ArrayList) ts_fregmetns_list, DOWNLOAD_PATH_FILE, "thread1", task_per_t, task_per_t * 0);
thread1.start();
thread2 = new MultiThread("thread2", (ArrayList) ts_fregmetns_list, DOWNLOAD_PATH_FILE, "thread1", task_per_t, task_per_t * 1);
thread2.start();
thread3 = new MultiThread("thread3", (ArrayList) ts_fregmetns_list, DOWNLOAD_PATH_FILE, "thread1", task_per_t, task_per_t * 2);
thread3.start();
thread4 = new MultiThread("thread4", (ArrayList) ts_fregmetns_list, DOWNLOAD_PATH_FILE, "thread1", task_per_t , task_per_t * 3);
thread4.start();
thread4 = new MultiThread("thread5", (ArrayList) ts_fregmetns_list, DOWNLOAD_PATH_FILE, "thread1", task_per_t , task_per_t * 4);
thread4.start();
thread4 = new MultiThread("thread6", (ArrayList) ts_fregmetns_list, DOWNLOAD_PATH_FILE, "thread1", task_per_t + task_res, task_per_t * 5);
thread4.start();
}
// for (Thread sub_thread : threadVector){
// sub_thread.join();
// }
String this_video_name = ts_fregmetns_list.get(0);
this_video_name=this_video_name.substring(this_video_name.lastIndexOf("/")+1,this_video_name.lastIndexOf("."));
System.out.println("##########\n******All Threads tasks finished! ");
new MERGE_FILE(DOWNLOAD_PATH_FILE, Org_Download_Path, this_video_name);
System.out.println("##########\n******File Merged succeed! ");
System.out.printf("******************\n Task finished finished \n Download Path: "+ DOWNLOAD_PATH);
System.out.println("\n ***************");
// if(thread1.getState() == Thread.State.TERMINATED){
// System.out.println("13123");
//
// }
}
}
|
package com.coder4.lmsia.thrift.client;
import com.coder4.lmsia.thrift.client.func.ThriftCallFunc;
import com.coder4.lmsia.thrift.client.func.ThriftExecFunc;
import com.coder4.lmsia.thrift.client.pool.TTransportPool;
import com.coder4.lmsia.thrift.client.pool.TTransportPoolFactory;
import org.apache.thrift.TServiceClient;
import org.apache.thrift.transport.TTransport;
/**
* @author coder4
*/
public class K8ServiceThriftClient<TCLIENT extends TServiceClient>
extends AbstractThriftClient<TCLIENT> {
private K8ServiceKey k8ServiceKey;
private TTransportPool connPool;
@Override
public void init() {
super.init();
// check
if (k8ServiceKey == null) {
throw new RuntimeException("invalid k8ServiceName or k8Serviceport");
}
// init pool
connPool = new TTransportPool(new TTransportPoolFactory());
}
@Override
public <TRET> TRET call(ThriftCallFunc<TCLIENT, TRET> tcall) {
// Step 1: get TTransport
TTransport tpt = null;
K8ServiceKey key = getConnBorrowKey();
try {
tpt = connPool.borrowObject(key);
} catch (Exception e) {
throw new RuntimeException(e);
}
// Step 2: get client & call
try {
TCLIENT tcli = createClient(tpt);
TRET ret = tcall.call(tcli);
returnTransport(key, tpt);
return ret;
} catch (Exception e) {
returnBrokenTransport(key, tpt);
throw new RuntimeException(e);
}
}
@Override
public void exec(ThriftExecFunc<TCLIENT> texec) {
// Step 1: get TTransport
TTransport tpt = null;
K8ServiceKey key = getConnBorrowKey();
try {
// borrow transport
tpt = connPool.borrowObject(key);
} catch (Exception e) {
throw new RuntimeException(e);
}
// Step 2: get client & exec
try {
TCLIENT tcli = createClient(tpt);
texec.exec(tcli);
returnTransport(key, tpt);
} catch (Exception e) {
returnBrokenTransport(key, tpt);
throw new RuntimeException(e);
}
}
private K8ServiceKey getConnBorrowKey() {
return k8ServiceKey;
}
private void returnTransport(K8ServiceKey key, TTransport transport) {
connPool.returnObject(key, transport);
}
private void returnBrokenTransport(K8ServiceKey key, TTransport transport) {
connPool.returnBrokenObject(key, transport);
}
public K8ServiceKey getK8ServiceKey() {
return k8ServiceKey;
}
public void setK8ServiceKey(K8ServiceKey k8ServiceKey) {
this.k8ServiceKey = k8ServiceKey;
}
} |
package api.domain;
import api.AbstractRestService;
import api.Identity;
import api.domain.model.AdvancedTypeConverter;
import api.domain.model.oauth.AuthorizationRequest;
import api.domain.model.oauth.AuthorizationResponse;
import exceptions.RestServiceException;
import org.apache.cxf.common.util.Base64Utility;
import org.apache.cxf.jaxrs.client.Client;
import org.apache.cxf.jaxrs.client.ClientConfiguration;
import org.apache.cxf.jaxrs.client.JAXRSClientFactory;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
import org.apache.cxf.jaxrs.provider.json.JSONProvider;
import org.apache.cxf.rs.security.oauth2.client.OAuthClientUtils;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import java.util.Arrays;
public class OpenApiV3ServiceImpl extends AbstractRestService implements OpenApiV3Service {
private static final String consumerId = "Auto_client";
private static final String consumerKey = "Auto_client";
private static final boolean CHUNKING_DEFAULT_VALUE = false;
//@CCProperty("open.api.rest.v3")
private String openApiV3BaseUrl;
private OpenApiV3RestClient proxyClient;
private AuthorizationResponse authorizationResponse;
private JSONProvider jsonProvider;
private OAuthClientUtils.Consumer consumer;
private String basicKey;
private String httpAuthorizationBasic;
public OpenApiV3ServiceImpl() throws RestServiceException {
}
public void setOpenApiV3BaseUrl(String openApiV3BaseUrl) {
this.openApiV3BaseUrl = openApiV3BaseUrl;
}
@Override
public void setup() {
ClientConfiguration clientConfiguration;
HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
HTTPConduit httpConduit;
WebClient webClient;
consumer = new OAuthClientUtils.Consumer(consumerId, consumerKey);
basicKey = consumer.getKey() + ":" + consumer.getSecret();
httpAuthorizationBasic = "Basic " + Base64Utility.encode(basicKey.getBytes());
proxyClient = JAXRSClientFactory.create(openApiV3BaseUrl, OpenApiV3RestClient.class, Arrays.asList(getJSONProvider()));
clientConfiguration = WebClient.getConfig(proxyClient);
httpConduit = (HTTPConduit) clientConfiguration.getConduit();
httpClientPolicy.setAllowChunking(CHUNKING_DEFAULT_VALUE);
httpConduit.setClient(httpClientPolicy);
webClient = WebClient.fromClient(WebClient.client(proxyClient));
webClient.header(HttpHeaders.AUTHORIZATION, httpAuthorizationBasic);
proxyClient = JAXRSClientFactory.fromClient(webClient, OpenApiV3RestClient.class, true);
}
public JSONProvider getJSONProvider() {
jsonProvider = new JSONProvider();
jsonProvider.setSupportUnwrapped(true);
jsonProvider.setDropRootElement(true);
jsonProvider.setDropCollectionWrapperElement(true);
jsonProvider.setIgnoreNamespaces(true);
jsonProvider.setTypeConverter(new AdvancedTypeConverter());
// jsonProvider.setSerializeAsArray(true); TODO: near future realization
// jsonProvider.setArrayKeys(Arrays.asList("circuits", "sets", "exercises", "components"));
return jsonProvider;
}
@Override
public void doAuthorize() throws RestServiceException {
WebClient webClient = null;
Client client;
AuthorizationRequest authorizationRequest = new AuthorizationRequest();
authorizationRequest.setEmail(sessionOwner.getEmail());
authorizationRequest.setPassword(sessionOwner.getPassword());
webClient = WebClient.fromClient(WebClient.client(proxyClient));
webClient.header(HttpHeaders.AUTHORIZATION, httpAuthorizationBasic);
proxyClient = JAXRSClientFactory.fromClient(webClient, OpenApiV3RestClient.class, true);
Response response = proxyClient.OAuth2Authorize(authorizationRequest);
checkResponseStatus(response);
//authorizationResponse = response.readEntity(AuthorizationResponse.class);
client = WebClient.client(proxyClient);
webClient = WebClient.fromClient(client);
webClient.replaceHeader(HttpHeaders.AUTHORIZATION, "Bearer " + authorizationResponse.getAccessToken());
proxyClient = JAXRSClientFactory.fromClient(webClient, OpenApiV3RestClient.class, true);
}
@Override
public Identity getIdentity() {
return sessionOwner;
}
public void checkResponseStatus(Response response) throws RestServiceException{
if (response.getStatus() != 200) {
// ErrorResponse error = response.readEntity(ErrorResponse.class);
//throw new RestServiceException(error.getError().getKey());
}
}
@Override
public void loginToOpenApi(String email, String password) throws RestServiceException {
sessionOwner = new Identity();
sessionOwner.setEmail(email);
sessionOwner.setPassword(password);
doAuthorize();
}
@Override
public Response getAchievementsStats(int userId) {
return null;
}
}
|
package com.dnomaid.iot;
import java.security.acl.Group;
import java.util.ArrayList;
import java.util.stream.Collectors;
import com.dnomaid.iot.mqtt.Mqtt;
import com.dnomaid.iot.mqtt.device.Device;
import com.dnomaid.iot.mqtt.device.DeviceConfig;
import com.dnomaid.iot.mqtt.device.Devices;
import com.dnomaid.iot.mqtt.global.Constants.GroupList;
import com.dnomaid.iot.mqtt.global.Constants.TypeDevice;
import com.dnomaid.iot.mqtt.topic.ActionTopic.TypeTopic;
public class App implements Runnable {
public static void main(String[] args) {
App app= new App();
Devices.getInst().newDevice(TypeDevice.SonoffS20, "1");
Devices.getInst().newDevice(TypeDevice.SonoffS20, "2");
Devices.getInst().newDevice(TypeDevice.SonoffS20, "3");
Devices.getInst().newDevice(TypeDevice.SonoffS20, "4");
Devices.getInst().newDevice(TypeDevice.SonoffS20, "5");
Devices.getInst().newDevice(TypeDevice.SonoffSNZB02, "1");
Devices.getInst().newDevice(TypeDevice.AqaraTemp, "1");
Devices.getInst().newDevice(TypeDevice.TuyaZigBeeSensor, "1");
Devices.getInst().newDevice(TypeDevice.XiaomiZNCZ04LM, "1");
Mqtt m = new Mqtt();
m.connection();
m.subscribe();
//m.publish(Devices.getInst().getPublishTopicRelay(2), "ON");
//m.publish(Devices.getInst().getRelays().get(5).getTopics().get(1).getName(),"ON");
//Devices.getInst().getRelay().stream().forEach(a->{m.publish(a.getTopics().get(1).getName(), "ON");});
//m.unsubscribe();
//m.disconnection();
//qui
while(true){app.run();}
}
@Override
public void run() {
try {
Thread.sleep(1 * 5000);
Devices.getInst().getRelays().stream().forEach(a->{
System.out.println(a.getDevice()+" "+a.getGroupList()+": "
+a.getTopics().get(0).getValueTopic(TypeTopic.Power) +": "+TypeTopic.Power);
});
Devices.getInst().getSensorsClimate().stream().forEach(a->{
System.out.println(a.getDevice()+" "+a.getGroupList()+": "
+a.getTopics().get(0).getValueTopic(TypeTopic.Temperature)+": "+TypeTopic.Temperature);
System.out.println(a.getDevice()+" "+a.getGroupList()+": "
+a.getTopics().get(0).getValueTopic(TypeTopic.Humidity)+": "+TypeTopic.Humidity);
});
/*
Devices.getInst().getDevices().stream().forEach(a->{
a.getTopics().stream().forEach(b->{
System.out.println("Topic::>"+b.getName());
});
});
ArrayList<Device> Relayss = (ArrayList<Device>) Devices.getInst().getDevices().stream()
.filter(c -> c.getGroupList().equals(GroupList.Relay))
.collect(Collectors.toList());
Relayss.stream().forEach(a->{
System.out.println(a.getDevice()+" "+a.getGroupList()+":::::::::::::::: "
+a.getTopics().get(0).getValueTopic(TypeTopic.Power) +": "+TypeTopic.Power);
});
*/
// Devices.getInst().deleteDevice(new DeviceConfig(TypeDevice.SonoffS20, "3"));
// System.out.println("Relay1: "+Devices.getInst().getRelays().get(0).getTopics().get(0).getValueTopic(TypeTopic.Power));
// System.out.println("Relay2: "+Devices.getInst().getRelays().get(1).getTopics().get(0).getValueTopic(TypeTopic.Power));
// System.out.println("Relay3: "+Devices.getInst().getRelays().get(2).getTopics().get(0).getValueTopic(TypeTopic.Power));
// System.out.println("Relay4: "+Devices.getInst().getRelays().get(3).getTopics().get(0).getValueTopic(TypeTopic.Power));
// System.out.println("Relay5: "+Devices.getInst().getRelays().get(4).getTopics().get(0).getValueTopic(TypeTopic.Power));
// System.out.println("Relay6: "+Devices.getInst().getRelays().get(5).getTopics().get(0).getValueTopic(TypeTopic.Power));
// System.out.println("SensorTemp1: "+Devices.getInst().getSensors().get(0).getTopics().get(0).getValueTopic(TypeTopic.Temperature));
// System.out.println("SensorHum2: "+Devices.getInst().getSensors().get(0).getTopics().get(0).getValueTopic(TypeTopic.Humidity));
// System.out.println("SensorTemp3: "+Devices.getInst().getSensors().get(1).getTopics().get(0).getValueTopic(TypeTopic.Temperature));
// System.out.println("SensorHum4: "+Devices.getInst().getSensors().get(1).getTopics().get(0).getValueTopic(TypeTopic.Humidity));
// System.out.println("SensorTemp5: "+Devices.getInst().getSensors().get(2).getTopics().get(0).getValueTopic(TypeTopic.Temperature));
// System.out.println("SensorHum6: "+Devices.getInst().getSensors().get(2).getTopics().get(0).getValueTopic(TypeTopic.Humidity));
// System.out.println("SensorTemp7: "+Devices.getInst().getSensors().get(3).getTopics().get(0).getValueTopic(TypeTopic.Temperature));
Devices.getInst().deleteDevice(new DeviceConfig(TypeDevice.SonoffS20, "3"));
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
|
package com.zhonghuilv.shouyin.service.impl;
import com.zhonghuilv.shouyin.mapper.OrderBackDetailsMapper;
import com.zhonghuilv.shouyin.mapper.OrderBackMapper;
import com.zhonghuilv.shouyin.mapper.StockMapper;
import com.zhonghuilv.shouyin.pojo.OrderBack;
import com.zhonghuilv.shouyin.pojo.OrderBackDetails;
import com.zhonghuilv.shouyin.pojo.Stock;
import com.zhonghuilv.shouyin.requestForm.OrderBackForm;
import com.zhonghuilv.shouyin.service.OrderBackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* Created by mengfanguang on 2018-07-04 17:13:47
*/
@Service
public class OrderBackServiceImpl implements OrderBackService {
@Autowired
private OrderBackMapper orderBackMapper;
@Autowired
private StockMapper stockMapper;
@Autowired
private OrderBackDetailsMapper orderBackDetailsMapper;
/**
* 退款
* @param model
* @return
*/
@Override
@Transactional(rollbackFor = Exception.class)
public OrderBack orderback(OrderBackForm model){
//生成orderbackUUID并将orderBack插入数据库。
OrderBack orderBack = model.getOrderBack();
String orderBackUUID=getOrderUUId();
orderBack.setOrderbackuuid(orderBackUUID);
orderBackMapper.insertUseGeneratedKeys(orderBack);
//循环orderBackDetailsList 并插入到表,每一个orderBackDetails对应的orderBackUUID都是之前生成的
List<OrderBackDetails> orderBackDetails = model.getOrderBackDetailsList();
for(OrderBackDetails orderBackDetail: orderBackDetails){
orderBackDetail.setOrderbackuuid(orderBackUUID);
orderBackDetailsMapper.insertUseGeneratedKeys(orderBackDetail);
//获取商品条码,销售数量,在库存表中对应减去销售的数量
String articleCode = orderBackDetail.getArticleBarcode();
Integer num = orderBackDetail.getNum();
Stock stock=stockMapper.selectByArticleCode(articleCode);
stock.setNum(stock.getNum()+num);
stockMapper.updateStock(stock);
}
return orderBack;
}
/**
* 根据时间生成订单号
* @return
*/
public static String getOrderUUId(){
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMddHHmmss");
Date date=new Date();
String nowStr=simpleDateFormat.format(date);
return nowStr;
}
}
|
package com.ibtsic.android.model;
/*
* Author: Joshi Dnyanesh Madhav
* */
public class Announcement
{
public int id;
public String name;
public String description;
public String startInstant;
public String validity;
public int node1Id;
public int node2Id;
public Announcement(int id, String name, String description, String startInstant,
String validity, int node1Id, int node2Id)
{
this.id=id;
this.name=name;
this.description=description;
this.startInstant=startInstant;
this.validity=validity;
this.node1Id=node1Id;
this.node2Id=node2Id;
}
} |
package com.shopify.shop;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.shopify.mapper.ShopMapper;
@Controller
public class ShopController {
@Autowired private ShopMapper shopMapper;
@Autowired private ShopService shopService;
private Logger LOGGER = LoggerFactory.getLogger(ShopController.class);
public boolean shopInsert(ShopData shop) {
boolean retYN = false;
shopMapper.insertShop(shop);
ShopData list = shopMapper.selectOneShop(shop);
if(list.getAccessToken() != null) retYN = true;
/*
* for(int i=0; i<list.size(); i++){ System.out.println("name : " +
* list.get(i).getUserId()); System.out.println("team : " +
* list.get(i).getUserName()); }
*/
return retYN;
}
@GetMapping("/shopList")
public String shopList(Model model, @RequestParam(value = "currentPage", required = false, defaultValue = "1") int currentPage) {
Map<String, Object> map = shopService.shopList(currentPage);
model.addAttribute("shopList", map.get("list"));
model.addAttribute("currentPage", map.get("currentPage"));
model.addAttribute("lastPage", map.get("lastPage"));
model.addAttribute("startPageNum", map.get("startPageNum"));
model.addAttribute("lastPageNum", map.get("lastPageNum"));
return "shop/shopList";
}
} |
package April;
import java. util.*;
public class Repl_Split {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String email = input.nextLine();
//Write your code below
String[] email2 = email.split("@");
System.out.println(Arrays.toString(email2));
for(String each : email2){
if (!each.contains("@") && each.contains("@@")){
System.out.println("Invalid email ");
}else{
}
}
System.out.println("Email id: "+email2[0] +"\nEmail domain: "+email2[1]);
}
}
|
/*
* Copyright 2016 Johns Hopkins University
*
* 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 org.dataconservancy.cos.osf.client.model;
import static org.dataconservancy.cos.osf.client.support.JodaSupport.DATE_TIME_FORMATTER_ALT;
import java.net.URI;
import java.util.Map;
import com.github.jasminb.jsonapi.RelType;
import com.github.jasminb.jsonapi.ResolutionStrategy;
import com.github.jasminb.jsonapi.annotations.Relationship;
import org.dataconservancy.cos.osf.client.support.DateTimeTransform;
import org.dataconservancy.cos.osf.client.support.JodaSupport;
import org.dataconservancy.cos.rdf.annotations.IndividualUri;
import org.dataconservancy.cos.rdf.annotations.OwlIndividual;
import org.dataconservancy.cos.rdf.annotations.OwlProperty;
import org.dataconservancy.cos.rdf.support.OwlClasses;
import org.dataconservancy.cos.rdf.support.OwlProperties;
import org.joda.time.DateTime;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.jasminb.jsonapi.annotations.Id;
import com.github.jasminb.jsonapi.annotations.Links;
import com.github.jasminb.jsonapi.annotations.Type;
/**
* Comment model for OSF
*
* @author khanson
* @author esm
*/
@Type("comments")
@OwlIndividual(OwlClasses.OSF_COMMENT)
public class Comment {
/**
* Unique OSF id for comment
*/
@Id
@IndividualUri
private String id;
/**
* content of the comment
*/
@OwlProperty(OwlProperties.OSF_HAS_CONTENT)
private String content;
/**
* timestamp that the comment was created
*/
@OwlProperty(value = OwlProperties.OSF_HAS_DATECREATED, transform = DateTimeTransform.class)
private DateTime date_created;
/**
* timestamp when the comment was last updated
*/
@OwlProperty(value = OwlProperties.OSF_HAS_DATEMODIFIED, transform = DateTimeTransform.class)
private DateTime date_modified;
/**
* has this comment been edited?
*/
private boolean isModified;
/**
* is this comment deleted?
*/
private boolean isDeleted;
/**
* has this comment been marked as abuse?
*/
private boolean is_abuse;
/**
* has this comment been reported?
*/
private boolean has_report;
/**
* does this comment have replies?
*/
private boolean has_children;
/**
* can the current user edit this comment?
*/
private boolean can_edit;
/**
* Gets other links found in data.links:{} section of JSON
**/
@Links
Map<String, ?> links;
/**
* pagination links for multiple records
*/
private PageLinks pageLinks;
/**
* the node this comment belongs to (distinct from the target)
*/
@Relationship(value = "node", resolve = true, relType = RelType.RELATED, strategy = ResolutionStrategy.OBJECT)
@OwlProperty(OwlProperties.OSF_HAS_NODE)
private Node node;
/**
* API url to replies to this comment
*/
@Relationship(value = "replies", resolve = true, relType = RelType.RELATED, strategy = ResolutionStrategy.REF)
private String replies;
/**
* API url to the target of this comment (i.e. the entity that the comment was placed on)
*/
@Relationship(value = "target", resolve = true, relType = RelType.RELATED, strategy = ResolutionStrategy.REF)
private String target;
/**
* API url to the target of this comment (i.e. the entity that the comment was placed on), typed as a URI
*/
@OwlProperty(OwlProperties.OSF_IN_REPLY_TO)
private URI targetUri;
/**
* The user that authored the comment
*/
@Relationship(value = "user", resolve = true, relType = RelType.RELATED, strategy = ResolutionStrategy.OBJECT)
@OwlProperty(OwlProperties.OSF_HAS_USER)
private User user;
@Relationship(value = "reports", resolve = true, relType = RelType.RELATED, strategy = ResolutionStrategy.REF)
private String reports;
/**
* whether or not this comment is ham
*/
private boolean is_ham;
/**
* The "type" of thing being commented on (e.g. "page", "wiki")
*/
private String page;
/**
* String identifying this comment.
*
* @return the identifier
*/
public String getId() {
return id;
}
/**
* String identifying this comment.
*
* @param id the string identifying this comment
*/
public void setId(final String id) {
this.id = id;
}
/**
* The textual content of the comment.
*
* @return the content
*/
public String getContent() {
return content;
}
/**
* The textual content of the comment.
*
* @param content the content
*/
public void setContent(final String content) {
this.content = content;
}
/**
* The date the comment was created, may be {@code null}. The date will be formatted according to the format
* string {@code yyyy-MM-dd'T'HH:mm:ss.SSS'Z'}, and be in the UTC time zone. See also
* {@link JodaSupport#DATE_TIME_FORMATTER}.
*
* @return the date the comment was created
*/
public String getDate_created() {
if (this.date_created != null) {
return this.date_created.toString(DATE_TIME_FORMATTER_ALT);
}
return null;
}
/**
* The date the comment was created. A variety of date time format strings are supported.
*
* @param date_created the date creation string
* @throws RuntimeException if the supplied {@code date_created} is not recognized as a dateTime
*/
public void setDate_created(final String date_created) {
if (date_created != null) {
this.date_created = JodaSupport.parseDateTime(date_created);
}
}
/**
* The date the comment was modified, may be {@code null}. The date will be formatted according to the format
* string {@code yyyy-MM-dd'T'HH:mm:ss.SSS'Z'}, and be in the UTC time zone. See also
* {@link JodaSupport#DATE_TIME_FORMATTER}.
*
* @return the date the comment was modified
*/
public String getDate_modified() {
if (this.date_modified != null) {
return this.date_modified.toString(DATE_TIME_FORMATTER_ALT);
}
return null;
}
/**
* The date the comment was created, may be {@code null}. The date will be formatted according to the format
* string {@code yyyy-MM-dd'T'HH:mm:ss.SSSSSS}, and be in the UTC time zone. See also
* {@link JodaSupport#DATE_TIME_FORMATTER}.
*
* @param date_modified the date creation string
* @throws RuntimeException if the supplied {@code date_modified} is not recognized as a dateTime
*/
public void setDate_modified(final String date_modified) {
if (date_modified != null) {
this.date_modified = JodaSupport.parseDateTime(date_modified);
}
}
/**
* If the comment has been edited
*
* @return true if the content was modified
*/
public boolean isModified() {
return isModified;
}
/**
* If the comment has been edited
*
* @param isModified if the content was modified
*/
public void setModified(final Boolean isModified) {
this.isModified = isModified;
}
/**
* If the comment has been deleted
*
* @return true if the comment was deleted
*/
public boolean isDeleted() {
return isDeleted;
}
/**
* If the comment has been deleted
*
* @param isDeleted if the comment was deleted
*/
public void setDeleted(final Boolean isDeleted) {
this.isDeleted = isDeleted;
}
/**
* If the comment is abuse
*
* @return true if the comment is abuse
*/
public boolean isIs_abuse() {
return is_abuse;
}
/**
* If the comment is abuse
*
* @param is_abuse if the comment is abuse
*/
public void setIs_abuse(final Boolean is_abuse) {
this.is_abuse = is_abuse;
}
/**
* If there are child comments
*
* @return true if this comment has child comments
*/
public boolean isHas_children() {
return has_children;
}
/**
* If there are child comments
*
* @param has_children if this comment has child comments
*/
public void setHas_children(final Boolean has_children) {
this.has_children = has_children;
}
/**
* If this comment can be edited
*
* @return true if the comment can be edited
*/
public boolean isCan_edit() {
return can_edit;
}
/**
* If this comment can be edited
*
* @param can_edit if the comment can be edited
*/
public void setCan_edit(final Boolean can_edit) {
this.can_edit = can_edit;
}
/**
*
* @return
*/
public PageLinks getPageLinks() {
return pageLinks;
}
/**
*
* @param pageLinks
*/
@JsonProperty("links")
public void setPageLinks(final PageLinks pageLinks) {
this.pageLinks = pageLinks;
}
/**
*
* @return
*/
public Map<String, ?> getLinks() {
return links;
}
/**
*
* @param links
*/
public void setLinks(final Map<String, ?> links) {
this.links = links;
}
/**
*
* @return
*/
public Node getNode() {
return node;
}
/**
*
* @param node
*/
public void setNode(final Node node) {
this.node = node;
}
/**
*
* @return
*/
public String getReplies() {
return replies;
}
/**
*
* @param replies
*/
public void setReplies(final String replies) {
this.replies = replies;
}
/**
*
* @return
*/
public String getTarget() {
return target;
}
/**
* Sets the target of this comment, which is the URI (typed as a {@code String}) of the thing being commented on.
* <p>
* <em>N.B.</em> this method calls {@link #setTargetUri(URI)} to provide a type-safe way of obtaining the URI.
* </p>
*
* @param target the URI of the thing being commented on
*/
public void setTarget(final String target) {
this.target = target;
setTargetUri(URI.create(target));
}
/**
*
* @return
*/
public URI getTargetUri() {
return targetUri;
}
/**
* Sets the target of this comment, which is the URI (typed as a {@code URI}) of the thing being commented on.
* <p>
* <em>N.B.</em> this method is invoked by {@link #setTarget(String)} to provide a type-safe way of obtaining the
* URI.
* </p>
*
* @param targetUri the URI of the thing being commented on
*/
public void setTargetUri(final URI targetUri) {
this.targetUri = targetUri;
}
/**
*
* @return
*/
public User getUser() {
return user;
}
/**
*
* @param user
*/
public void setUser(final User user) {
this.user = user;
}
/**
*
* @return
*/
public boolean is_ham() {
return is_ham;
}
/**
*
* @param is_ham
*/
public void setIs_ham(final boolean is_ham) {
this.is_ham = is_ham;
}
/**
*
* @return
*/
public boolean isHas_report() {
return has_report;
}
/**
*
* @param has_report
*/
public void setHas_report(final boolean has_report) {
this.has_report = has_report;
}
/**
*
* @return
*/
public String getPage() {
return page;
}
/**
*
* @param page
*/
public void setPage(final String page) {
this.page = page;
}
/**
*
* @return
*/
public String getReports() {
return reports;
}
/**
*
* @param reports
*/
public void setReports(final String reports) {
this.reports = reports;
}
}
|
package org.buckeram.jobscraper.domain;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.net.URL;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
/**
* This class represents the one page of job search results.
* A search results page consists of:
* <ul>
* <li>a collection of links to job descriptions</li>
* <li>a link to the next page of results (if one exists)</li>
* </ul>
*/
@Data
@NoArgsConstructor
public class SearchResults
{
private Set<URL> jobLinks = new HashSet<URL>();
private Optional<URL> nextPage = Optional.empty();
public void setNextPage(final URL nextPage)
{
this.nextPage = Optional.of(nextPage);
}
public void addJobLink(final URL link)
{
this.jobLinks.add(link);
}
}
|
package com.tencent.mm.plugin.wallet.bind.ui;
import android.view.View;
import android.view.View.OnClickListener;
import com.tencent.mm.g.a.qu;
import com.tencent.mm.plugin.wallet_core.model.f;
import com.tencent.mm.sdk.b.a;
import com.tencent.mm.sdk.platformtools.bi;
class WalletBankcardManageUI$7 implements OnClickListener {
final /* synthetic */ WalletBankcardManageUI pdm;
final /* synthetic */ f pdo;
WalletBankcardManageUI$7(WalletBankcardManageUI walletBankcardManageUI, f fVar) {
this.pdm = walletBankcardManageUI;
this.pdo = fVar;
}
public final void onClick(View view) {
qu quVar = new qu();
quVar.cbq.userName = this.pdo.pmw;
quVar.cbq.cbs = bi.aG(this.pdo.pmx, "");
quVar.cbq.scene = 1071;
quVar.cbq.cbt = 0;
a.sFg.m(quVar);
}
}
|
import java.util.Scanner;
/**
*
* @author 141638
*/
public class CheckInput {
Scanner sc = new Scanner(System.in);
int CheckInput(int a,int min,int max){
String Numtext;
do{
Numtext = sc.nextLine();
try{
if(a==0){
if(Numtext.matches("[0-9]+")){
a = Integer.parseInt(Numtext);
if(a>=min && a<= max)
break;
}
}
else if(a==1){
if(Numtext.matches("[-]?[0-9]+")){
a = Integer.parseInt(Numtext);
break;
}
}
else{
if(Numtext.matches("[1-9]+[0-9]*")){
a = Integer.parseInt(Numtext);
break;
}
}
}
catch(ArithmeticException e){}System.err.println("Error!!");
}
while(true);
return a;
}
}
|
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JTextPane;
import javax.swing.JLabel;
import java.awt.TextField;
import java.awt.Panel;
public class AutoScore extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AutoScore frame = new AutoScore();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void btnNew_ActionPerformed(java.awt.event.ActionEvent event){
a = (int)(Math.random()*9+1);
b = (int)(Math.random()*9+1);
int c = (int)(Math.random()*4);
switch ( c ) {
case 0:
op = "+";
result = a+b;
break;
case 1:
op = "-";
result = a-b;
break;
case 3:
op = "*";
result = a*b;
break;
case 4:
op = "/";
result = a/b;
break;
}
}
int a=0,b =0;
String op ;
double result = 0;
/**
* Create the frame.
*/
public AutoScore() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton button = new JButton("\u51FA\u9898");
button.setBounds(10, 85, 93, 23);
contentPane.add(button);
JButton button_1 = new JButton("\u5224\u5206");
button_1.setBounds(320, 85, 93, 23);
contentPane.add(button_1);
JList listDisp = new JList();
listDisp.setBackground(Color.white);
listDisp.setBounds(10, 251, 391, -130);
contentPane.add(listDisp);
JLabel lblA = new JLabel("");
lblA.setBounds(20, 30, 54, 15);
contentPane.add(lblA);
JLabel lblOp = new JLabel("");
lblOp.setBounds(108, 30, 54, 15);
contentPane.add(lblOp);
JLabel lblB = new JLabel("");
lblB.setBounds(198, 30, 54, 15);
contentPane.add(lblB);
TextField txtAnswer = new TextField();
txtAnswer.setBounds(320, 30, 93, 23);
contentPane.add(txtAnswer);
}
public void btnJudge_ActionPerformed(java.awt.event.ActionEvent event){
// String str = txtAnswer.getText();
// double d = Double.parseDouble(str);
// String disp = "" + a + op + b + "=" + str + " ";
// if(d == result){
// disp = "ΆΤΑΛ";
// }
// else{
// disp = "΄νΑΛ";
// }
}
}
|
package ru.learn2code.yrank.service;
import java.util.Date;
import java.util.List;
import ru.learn2code.yrank.model.Serp;
public interface SerpService {
List<Serp> findByProjectIdAndCreated(Long id, Date date);
}
|
package org.jon.lv.scheduled;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import org.jon.lv.date.DateUtils;
/**
* @Package org.jon.lv.scheduled.SingleExecuteJob
* @Description: 只执行一次
* @Copyright: Copyright (c) 2016
* Author lv bin
* @date 2017/7/18 14:40
* version V1.0.0
*/
public class SingleExecuteJob implements SimpleJob {
@Override
public void execute(ShardingContext shardingContext) {
System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$:" + DateUtils.getCurrentTime());
}
}
|
package org.usfirst.frc.team3223.robot;
public enum TurningState {
Start,
Calculate,
Drive,
End,
}
|
package com.swqs.schooltrade.fragment;
import java.io.IOException;
import java.util.List;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.swqs.schooltrade.R;
import com.swqs.schooltrade.activity.SellOrderDetailsActivity;
import com.swqs.schooltrade.app.TradeApplication;
import com.swqs.schooltrade.entity.Identify;
import com.swqs.schooltrade.util.Server;
import com.swqs.schooltrade.util.Util;
import android.annotation.SuppressLint;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class SellDetailsFragment extends Fragment {
View view;
ListView listView;
List<Identify> data;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (view == null) {
view = inflater.inflate(R.layout.fragment_buy_details, null);
listView = (ListView) view.findViewById(R.id.list);
TextView tvTitle = (TextView) view.findViewById(R.id.tvTitle);
tvTitle.setText("我卖出的");
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
onItemClicked(position);
}
});
}
getData();
return view;
}
private void getData() {
OkHttpClient client = Server.getSharedClient();
FormBody body=new FormBody.Builder().add("uid", TradeApplication.uid).build();
Request request = Server.requestBuilderWithApi("mysell/goodslist").post(body).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Call arg0, Response arg1) throws IOException {
String jsonString = arg1.body().string();
ObjectMapper mapper = new ObjectMapper();
List<Identify> goodsList = mapper.readValue(jsonString, new TypeReference<List<Identify>>() {
});
data = goodsList;
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
listAdapter.notifyDataSetChanged();
}
});
}
@Override
public void onFailure(Call arg0, IOException arg1) {
}
});
}
BaseAdapter listAdapter = new BaseAdapter() {
@SuppressLint("InflateParams")
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
convertView = inflater.inflate(R.layout.widget_sell_item, null);
holder = new ViewHolder();
holder.ivImg = (ImageView) convertView.findViewById(R.id.ivImg);
holder.tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
holder.tvMoney = (TextView) convertView.findViewById(R.id.tvMoney);
holder.tvState = (TextView) convertView.findViewById(R.id.tvState);
// holder.btnCommunicate = (Button) convertView.findViewById(R.id.btnCommunicate);
// holder.btnComment = (Button) convertView.findViewById(R.id.btnComment);
// holder.btnComment.setOnClickListener(new OnClickListener() {
//
// @Override
// public void onClick(View v) {
// Intent intent = new Intent(getActivity(), SellEvaluationDetailsActivity.class);
// startActivity(intent);
// }
// });
// holder.btnCommunicate.setOnClickListener(new OnClickListener() {
//
// @Override
// public void onClick(View v) {
//
// }
// });
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Identify identify = data.get(position);
holder.tvTitle.setText(identify.getGoods().getTitle());
holder.tvMoney.setText("¥" + identify.getGoods().getCurPrice());
Util.loadImage(getActivity(), identify.getGoods().getListImage().get(0).getPictureUrl(), holder.ivImg);
int state=identify.getTradeState();
String strState="";
if(state==1){
strState="未发货";
}else if(state==2){
strState="已发货";
}else if(state==3){
strState="买家已收货";
}else{
strState="买家已评价";
}
holder.tvState.setText(strState);
return convertView;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public Object getItem(int position) {
return data == null ? null : data.get(position);
}
@Override
public int getCount() {
return data == null ? 0 : data.size();
}
class ViewHolder {
ImageView ivImg;
TextView tvTitle;
TextView tvMoney;
TextView tvState;
// Button btnCommunicate;
// Button btnComment;
}
};
void onItemClicked(int position) {
Intent itnt = new Intent(getActivity(), SellOrderDetailsActivity.class);
itnt.putExtra("data", data.get(position).getGoods());
startActivity(itnt);
}
}
|
package com.tencent.mm.plugin.scanner.util;
import com.tencent.mm.g.a.oo;
import com.tencent.mm.plugin.scanner.util.ScanCameraLightDetector.1;
import com.tencent.mm.sdk.b.a;
class ScanCameraLightDetector$1$2 implements Runnable {
final /* synthetic */ 1 mND;
ScanCameraLightDetector$1$2(1 1) {
this.mND = 1;
}
public final void run() {
oo ooVar = new oo();
ooVar.bZv.bZw = false;
a.sFg.m(ooVar);
}
}
|
package com.batiaev.java3.lesson7;
import lombok.Data;
import java.util.Currency;
@Data
@Table("gb_account")
public class Account {
@PrimaryKey
private final int id;
private String name;
private String amount;
@Field("curr")
private Currency currency;
}
|
/*
* Copyright 2008 University of California at Berkeley
*
* 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 org.rebioma.client;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.rebioma.client.SearchFieldSuggestion.TermSelectionListener;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.RadioButton;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.HTMLTable.Cell;
import com.google.gwt.user.client.ui.HTMLTable.CellFormatter;
/**
* A view to enable advance search with a suggestion box to search in specific
* fields.
*
* Each time search criteria(s) is/are added add a new history token which
* contains the current search queries in the url.
*
* The history token url for the advance search is.
* view=Advance&asearch=searchQuery&asearch=searchQuery&...
*
* Search query format: database field name + space + operator + space + search
* value.
*
* When history is changed by either refresh, back, or forward button, search
* queries queue is restore and display.
*
* @author Tri
*
*/
public class AdvanceSearchView extends ComponentView implements
TermSelectionListener, ClickHandler, MouseOutHandler, MouseOverHandler,
KeyUpHandler, BlurHandler {
/**
* Encodes an advance search field type: {@link ValueType}, database field
* name, client human readable name, and fixedValues if any.
*
* @author Tri
*
*/
public static class ASearchType {
/**
* The {@link ValueType} for a {@link SearchField}
*/
private final ValueType type;
/**
* The database field name presentation of a search field that associated
* with the {@link #clientName}.
*/
private final String databaseField;
/**
* The human readable name of a search field which associated with
* {@link #databaseField}.
*/
private final String clientName;
/**
* The possible search values for a {@link ValueType#FIXED} of a search
* field. These values are not used if {@link ValueType} is not FIXED.
*/
private final String fixedValues[];
private final String link;
/**
* Construct a ASearchType with a {@link ValueType}, a human readable name,
* its database representation, and its fixed values if ValueType is FIXED.
*
* @param type the {@link ValueType} for this search type.
* @param clientName the human readable name for its database field.
* @param databaseField the database representation of the client name.
* @param fixedValues the possiable search values if {@link ValueType} is
* FIXED.
*/
public ASearchType(ValueType type, String clientName, String databaseField,
String fixedValues[], String link) {
this.type = type;
this.databaseField = databaseField;
this.fixedValues = fixedValues;
this.clientName = clientName;
this.link = link;
}
/**
* Gets the human readable name of {@link databaseField} for this
* {@link ASearchType}.
*
* @return the human readable name as {@link String}
*/
public String getClientName() {
return clientName;
}
/**
* Gets the database representation of {@link #clientName} for this
* {@link ASearchType}.
*
* @return the database representation as {@link String}
*/
public String getDatabaseField() {
return databaseField;
}
/**
* Gets the possible search values for this {@link ASearchType}.
*
* Note: these values are only used if the {@link #type} is
* {@link ValueType#FIXED}.
*
* @return the possible search values as an array of {@link String}
*/
public String[] getFixedValues() {
return fixedValues;
}
public String getLink() {
return link;
}
/**
* Gets the {@link ValueType} for this {@link ASearchType}.
*
* @return the {@link ValueType}.
*/
public ValueType getType() {
return type;
}
}
/**
* A value type for a {@link SearchField}. There are 3 possible values: FIXED,
* TEXT, and DATE. Base on which ValueType is used the SearchField will
* display a propriated user interface for it.
*
* @author Tri
*
*/
public enum ValueType {
/**
* If FIXED type is used then the {@link SearchField} should only allows
* user to selected from a list of possible search values.
*/
FIXED,
/**
* If TEXT type is used then the {@link SearchField} can be any thing so a
* {@link TextBox} should be used for accepted search input.
*/
TEXT,
/**
* If DATE type is used then the {@link SearchField} should only accept date
* time value.
*/
DATE,
/**
* If NUMBER type is user then the {@link SearchField} would be a range of
* numbers.
*/
NUMBER;
}
/**
* A SearchArea contains 2 opposite {@link SearchField}. If
* {@link SearchField#type} is {@link ValueType#FIXED} or
* {@link ValueType#TEXT} then the first field is using = or like operator and
* the second field is != or !like operator. If it is {@link ValueType#DATE}
* then the first field is before field which using >= operator, and the
* second field is after which is using <= operator.
*
* Note: !like operator is not a real SQL operator. In the server !like is
* convert to propriated SQL operator.
*
* @author tri
*
*/
private class SearchArea extends Composite {
/**
* The name label for this SearchArea (i.e "Search in Darwin Core").
*/
private final HTML searchLabel;
/**
* The first {@link SearchField} from the left.
*/
private final SearchField normalField;
/**
* The opposite {@link SearchField} of {@link normalField}.
*/
private SearchField negateField = null;
/**
* The {@link ASearchType} of this search area contains information to
* communicated with the server.
*/
private final ASearchType type;
/**
* Construct a SearchArea with a {@link ASearchType}.
*
* @param type {@link ASearchType} for constructing this SearchArea.
*/
public SearchArea(ASearchType type) {
String clientName = type.getClientName();
String databaseName = type.getDatabaseField();
this.type = type;
HorizontalPanel labelHp = new HorizontalPanel();
if (!type.getLink().equals("")) {
searchLabel = new HTML(constants.SearchIn());
searchLabel.setStyleName("SearchLabel");
HTML clientLink = new HTML("<a href='" + type.getLink()
+ "' target='_blank'>" + clientName + "</a>");
clientLink.setStyleName("link");
clientLink.addStyleName("SearchLabel");
labelHp.add(searchLabel);
labelHp.add(clientLink);
} else {
searchLabel = new HTML(constants.SearchIn() + " " + clientName);
searchLabel.setStyleName("SearchLabel");
labelHp.add(searchLabel);
}
labelHp.setSpacing(5);
normalField = new SearchField(type, clientName, databaseName, false);
HorizontalPanel mainHp = new HorizontalPanel();
mainHp.add(normalField);
if (type.getType() != ValueType.NUMBER
&& type.getType() != ValueType.DATE) {
negateField = new SearchField(type, clientName, databaseName, true);
mainHp.add(negateField);
}
mainHp.setSpacing(5);
VerticalPanel areaVp = new VerticalPanel();
areaVp.add(labelHp);
areaVp.add(mainHp);
areaVp.setStyleName("SearchArea");
initWidget(areaVp);
}
/**
* Gets database field representation of this {@link SearchArea}.
*
* @return database field representation as String.
*/
public String getDatabaseField() {
return type.getDatabaseField();
}
/**
* Gets the operator of the second {@link SearchField} from the left.
*
* @return the operator of the second SearchField as String.
*/
public String getNegateOp() {
if (negateField == null) {
return "";
} else {
return negateField.getOperator();
}
}
/**
* Gets the query of the second {@link SearchField} from the left.
*
* @return empty if {@link #negateField} is empty, return databaseField +
* space + operator + space + searchValue otherwise.
*/
public String getNegateQuery() {
String searchValue = negateField.getSearchValue();
if (!negateField.getOperator().equals("!empty")
&& searchValue.trim().equals("")) {
return "";
}
return type.getDatabaseField() + " " + negateField.getOperator() + " "
+ searchValue;
}
/**
* Gets the search value of the second {@link SearchField} from the left.
*
* @return the search value of the second SearchField
*/
public String getNegateSearch() {
if (negateField == null) {
return "";
} else {
return negateField.getSearchValue();
}
}
/**
* Gets the operator of the first {@link SearchField} from the left.
*
* @return the operator of the first SearchField as String.
*/
public String getNormalOp() {
return normalField.getOperator();
}
/**
* Gets the query of the first {@link SearchField} from the left.
*
* @return empty if {@link #normalField} is empty, return databaseField +
* space + operator + space + searchValue otherwise.
*/
public String getNormalQuery() {
String searchValue = normalField.getSearchValue();
if (!normalField.getOperator().equals("empty")
&& searchValue.trim().equals("")) {
return "";
}
return type.getDatabaseField() + " " + normalField.getOperator() + " "
+ searchValue;
}
/**
* Gets the search value of the first {@link SearchField} from the left.
*
* @return the search value of the first SearchField
*/
public String getNormalSearch() {
return normalField.getSearchValue();
}
/**
* Gets the {@link ASearchType} is used to construct this SearchArea.
*
* @return this {@link ASearchType}
*/
public ASearchType getType() {
return type;
}
/**
* Sets the focus of this SearchArea to be the first {@link SearchField}.
*
* @param focus true if focused.
*/
public void setFocus(boolean focus) {
normalField.setFocus(focus);
}
}
/**
* A SearchField is a dynamic search interface base on {@link ValueType}. If
* the {@link #type} is {@link ValueType#FIXED} then the search input area is
* a {@link ListBox} of all its possible values with the operator is =. If it
* is {@link ValueType#TEXT} then the search input area is a TextBox with the
* operator is whether =, like, !like, or !=. If it is {@link ValueType#DATE}
* then the search input area is a {@link TextBox} with the operator is
* whether >= or <=.
*
* @author Tri
*
*/
private class SearchField extends Composite {
/**
* The search input box for {@link ValueType#TEXT} and
* {@link ValueType#DATE}.
*/
private TextBox searchTextBox;
/**
* The search input box for {@link ValueType#FIXED}.
*/
private ListBox searchListBox;
private String radioButtonGroup;
private RadioButton startsWith;
private RadioButton exact;
private RadioButton contains;
private RadioButton in;
private RadioButton empty;
private RadioButton equals;
private RadioButton notEquals;
private RadioButton lessThan;
private RadioButton moreThan;
private RadioButton lessThanOrEquals;
private RadioButton moreThanOrEquals;
/**
* True to use "!" operator or <= operator if {@link ValueType#DATE}.
*/
private final boolean notOperator;
/**
* The {@link ValueType} for this SearchField.
*/
private final ValueType type;
/**
* Construct a SearchField with a {@link ASearchType}, a human readable name
* for this field and its database representation, and a boolean is
* determine whether the operator should be; between != or =, !like or like,
* and >= or <=.
*
* @param type {@link ASearchType} for this field.
* @param clientName human readable name.
* @param databaseField the database representation of the clientName.
* @param notOperator true if ! or <= is used.
*/
public SearchField(ASearchType type, String clientName,
String databaseField, boolean notOperator) {
HorizontalPanel mainHp = new HorizontalPanel();
HTML fieldLabel = new HTML();
HTML tipLabel = new HTML();
tipLabel.setStyleName("Tip");
fieldLabel.setWidth("60px");
fieldLabel.setStyleName("Label");
mainHp.add(fieldLabel);
initWidget(mainHp);
mainHp.setSpacing(2);
mainHp.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
setStyleName("SearchField");
this.type = type.getType();
this.notOperator = notOperator;
switch (type.getType()) {
case FIXED:
searchListBox = new ListBox();
searchListBox.setStyleName("ListBox");
searchListBox.addItem(constants.Select() + " " + clientName + "...",
databaseField);
searchTextBox = null;
empty = null;
for (String value : type.getFixedValues()) {
searchListBox.addItem(value);
}
if (notOperator) {
fieldLabel.setHTML((constants.Exclude()));
} else {
fieldLabel.setHTML((constants.Include()));
}
mainHp.add(searchListBox);
break;
case TEXT:
VerticalPanel vp = new VerticalPanel();
searchTextBox = new TextBox();
HorizontalPanel radioHp = new HorizontalPanel();
radioButtonGroup = System.currentTimeMillis() + "";
startsWith = new RadioButton(radioButtonGroup, constants.StartsWith());
startsWith.setFormValue("sw");
startsWith.setValue(true);
exact = new RadioButton(radioButtonGroup, constants.ExactMatch());
exact.setFormValue("=");
contains = new RadioButton(radioButtonGroup, constants.Contains());
in = new RadioButton(radioButtonGroup, "in");
empty = new RadioButton(radioButtonGroup, constants.Empty());
empty.setFormValue("empty");
in.setFormValue("in");
contains.setFormValue("like");
// radioHp.add(new Label(constants.StartsWith()));
radioHp.add(startsWith);
// radioHp.add(new Label(constants.ExactMatch()));
radioHp.add(exact);
// radioHp.add(new Label(constants.Contains()));
radioHp.add(contains);
radioHp.add(in);
radioHp.add(empty);
searchListBox = null;
searchTextBox.setStyleName("Search-Text");
if (notOperator) {
fieldLabel.setHTML((constants.Exclude()));
} else {
fieldLabel.setHTML((constants.Include()));
}
vp.add(searchTextBox);
vp.add(radioHp);
mainHp.add(vp);
// mainHp.add(exactCheckBox);
break;
case DATE:
HorizontalPanel radioDateHp = new HorizontalPanel();
radioButtonGroup = System.currentTimeMillis() + "";
equals = new RadioButton(radioButtonGroup, "=");
equals.setFormValue("=");
notEquals = new RadioButton(radioButtonGroup, "!=");
notEquals.setFormValue("!=");
lessThan = new RadioButton(radioButtonGroup, "<");
lessThan.setFormValue("<");
moreThan = new RadioButton(radioButtonGroup, ">");
moreThan.setFormValue(">");
lessThanOrEquals = new RadioButton(radioButtonGroup, "<=");
lessThanOrEquals.setFormValue("<=");
moreThanOrEquals = new RadioButton(radioButtonGroup, ">=");
moreThanOrEquals.setFormValue(">=");
in = new RadioButton(radioButtonGroup, "in");
in.setFormValue("in");
empty = new RadioButton(radioButtonGroup, constants.Empty());
empty.setFormValue("empty");
radioDateHp.add(equals);
radioDateHp.add(notEquals);
radioDateHp.add(lessThan);
radioDateHp.add(moreThan);
radioDateHp.add(lessThanOrEquals);
radioDateHp.add(moreThanOrEquals);
radioDateHp.add(in);
radioDateHp.add(empty);
equals.setValue(true);
searchTextBox = new TextBox();
tipLabel.setText("YYYY-MM-DD [HH:MM:SS]");
searchTextBox.setStyleName("Search-Text");
searchListBox = null;
fieldLabel.setHTML("");
VerticalPanel searchPanel = new VerticalPanel();
searchPanel.add(searchTextBox);
searchPanel.add(tipLabel);
searchPanel.add(radioDateHp);
mainHp.add(searchPanel);
break;
case NUMBER:
HorizontalPanel radioNumHp = new HorizontalPanel();
radioButtonGroup = System.currentTimeMillis() + "";
equals = new RadioButton(radioButtonGroup, "=");
equals.setFormValue("=");
notEquals = new RadioButton(radioButtonGroup, "!=");
notEquals.setFormValue("!=");
lessThan = new RadioButton(radioButtonGroup, "<");
lessThan.setFormValue("<");
moreThan = new RadioButton(radioButtonGroup, ">");
moreThan.setFormValue(">");
lessThanOrEquals = new RadioButton(radioButtonGroup, "<=");
lessThanOrEquals.setFormValue("<=");
moreThanOrEquals = new RadioButton(radioButtonGroup, ">=");
moreThanOrEquals.setFormValue(">=");
in = new RadioButton(radioButtonGroup, "in");
in.setFormValue("in");
radioNumHp.add(equals);
radioNumHp.add(notEquals);
radioNumHp.add(lessThan);
radioNumHp.add(moreThan);
radioNumHp.add(lessThanOrEquals);
radioNumHp.add(moreThanOrEquals);
radioNumHp.add(in);
equals.setValue(true);
searchTextBox = new TextBox();
searchListBox = null;
searchTextBox.setStyleName("Search-Text");
fieldLabel.setHTML("");
VerticalPanel numVp = new VerticalPanel();
numVp.add(searchTextBox);
numVp.add(radioNumHp);
mainHp.add(numVp);
break;
}
}
/**
* Gets this SearchField operator.
*
* If {@link #notOperator} is true:<br>
* != is returned for {@link ValueType#FIXED} and {@link ValueType#TEXT} if
* exactChecBox is checked. <br>
* !like is return for {@link ValueType#TEXT} if {@link #exactCheckBox} is
* unchecked. <br>
* >= is returned for {@link ValueType#DATE}.
* <p>
*
* if {@link #notOperator} is false: <br>
* = is returned for {@link ValueType#FIXED} and {@link ValueType#TEXT} if
* exactChecBox is checked. <br>
* like is return for {@link ValueType#TEXT} if {@link #exactCheckBox} is
* unchecked. <br>
* <= is returned for {@link ValueType#DATE}.
*
*
* @return proriated operator of this field base on the given type.
*/
public String getOperator() {
switch (type) {
case FIXED:
return notOperator ? "!=" : "=";
case TEXT:
String op = "";
if (startsWith.getValue()) {
op = startsWith.getFormValue();
} else if (exact.getValue()) {
op = exact.getFormValue();
} else if (contains.getValue()) {
op = contains.getFormValue();
} else if (in.getValue()) {
op = in.getFormValue();
} else if (empty.getValue()) {
op = empty.getFormValue();
} else {
return "";
}
return notOperator ? ("!" + op) : op;
case DATE:
if (equals.getValue()) {
return equals.getFormValue();
} else if (notEquals.getValue()) {
return notEquals.getFormValue();
} else if (lessThan.getValue()) {
return lessThan.getFormValue();
} else if (lessThanOrEquals.getValue()) {
return lessThanOrEquals.getFormValue();
} else if (moreThan.getValue()) {
return moreThan.getFormValue();
} else if (moreThanOrEquals.getValue()) {
return moreThanOrEquals.getFormValue();
} else if (in.getValue()) {
return in.getFormValue();
} else if (empty.getValue()) {
return empty.getFormValue();
} else {
return "";
}
case NUMBER:
if (equals.getValue()) {
return equals.getFormValue();
} else if (notEquals.getValue()) {
return notEquals.getFormValue();
} else if (lessThan.getValue()) {
return lessThan.getFormValue();
} else if (lessThanOrEquals.getValue()) {
return lessThanOrEquals.getFormValue();
} else if (moreThan.getValue()) {
return moreThan.getFormValue();
} else if (moreThanOrEquals.getValue()) {
return moreThanOrEquals.getFormValue();
} else if (in.getValue()) {
return in.getFormValue();
} else {
return "";
}
}
return null;
}
/**
* Gets the proriated search value from whether the {@link #searchTextBox}
* or {@link #searchListBox} base on {@link #type}.
*
* @return the search value as String
*/
public String getSearchValue() {
switch (type) {
case FIXED:
int selectedIndex = searchListBox.getSelectedIndex();
if (selectedIndex <= 0) {
return "";
}
return searchListBox.getItemText(searchListBox.getSelectedIndex());
case TEXT:
case DATE:
case NUMBER:
return searchTextBox.getText();
}
return "";
}
/**
* Restores {@link #exactCheckBox} state from the given operator.
*
* @param operator
*/
public void restoreCheckedFromOperator(String operator) {
if (operator.equalsIgnoreCase(startsWith.getFormValue())) {
startsWith.setValue(true);
} else if (operator.equalsIgnoreCase(exact.getFormValue())) {
exact.setValue(true);
} else if (operator.equals(contains.getFormValue())) {
contains.setValue(true);
}
}
/**
* Sets to this SearchField if focused is true.
*
* @param focused true if the SearchField should be focused.
*/
public void setFocus(boolean focused) {
switch (type) {
case FIXED:
searchListBox.setFocus(focused);
break;
case TEXT:
case DATE:
case NUMBER:
searchTextBox.setFocus(focused);
break;
}
}
/**
* Sets value on the propriated search input box base on {@link #type}.
*
* @param value
*/
public void setValue(String value) {
switch (type) {
case FIXED:
for (int i = 0; i < searchListBox.getItemCount(); i++) {
if (searchListBox.getItemText(i).equalsIgnoreCase(value)) {
searchListBox.setSelectedIndex(i);
return;
}
}
searchListBox.setSelectedIndex(0);
break;
case TEXT:
case DATE:
case NUMBER:
searchTextBox.setValue(value);
break;
}
}
}
/**
* The column index for counter column in the {@link #queriesTable}.
*/
private static final int COUNTER_COL = 0;
/**
* The column index for human readable search field column in the
* {@link #queriesTable}
*/
private static final int CLIENT_NAME_COL = 1;
/**
* The column index for operator column in the {@link #queriesTable}
*/
private static final int OPERATOR_COL = 2;
/**
* The column index for search value column in the {@link #queriesTable}
*/
private static final int SEARCH_VALUE_COL = 3;
/**
* The column index for remove img column in the {@link #queriesTable}
*/
private static final int REMOVE_COL = 4;
private static final int START_SEARCH_FIELD_INDEX = 2;
/**
* Initialize AdvanceSearchView if it not already initialized and return its
* instance.
*
* @param parent the parent {@link View} of the {@link AdvanceSearchView}
* @param clickable TODO
* @return the View instance represent the AdvanceSearchView
*/
public static ViewInfo init(final View parent, final Clickable clickable) {
return new ViewInfo() {
protected View constructView() {
return new AdvanceSearchView(parent, clickable);
}
protected String getHisTokenName() {
return ADVANCE;
}
protected String getName() {
return ADVANCE;
}
};
}
/**
* A previous view name that because switch to this view.
*/
private String previousViewName;
/**
* A {@link VeritcalPanel} contains all {@link SearchArea}.
*/
private final VerticalPanel searchAreasVp = new VerticalPanel();
/**
* A {@link ScrollPanel} for this view to control where scroll bar should
* appear.
*/
private final ScrollPanel mainSp = new ScrollPanel();
/**
* A {@link TextBox} to edit search value in {@link #queriesTable}.
*/
private final TextBox editTextBox = new TextBox();
private final HistoryState historyState = new HistoryState() {
public Object getHistoryParameters(UrlParam param) {
switch (param) {
case VIEW:
return stringValue(param);
case ASEARCH:
return listValue(param);
}
return "";
}
};
/**
* The {@link SearchFieldSuggestion} to suggest and control user selected
* SearchArea input.
*/
private final SearchFieldSuggestion searchFieldSuggestionBox = new SearchFieldSuggestion();
/**
* The {@link Button} to to add current search criteria into
* {@link #queriesTable}.
*/
private final Button addSearchCriteriaButton = new Button(constants
.AddSearchCriteria());
/**
* A {@link Grid} table contains all current search criteria when search
* button is clicked.
*/
private final Grid queriesTable = new Grid(0, 6);
/**
* The {@link Button} for clear the {@link #queriesTable}.
*/
private final Button clearQueriesButton = new Button(constants
.ClearCriteria());
private final Button searchButton = new Button(constants.Search());
/**
* A {@link Map} from field search to its {@link ASearchType}.
*/
private final Map<String, ASearchType> fieldSearchTypesMap = new HashMap<String, ASearchType>();
/**
* The reference to currently editing search value row.
*/
private HTML editingSearchValue = null;
private List<String> defaultSuggestionList = null;
private final HTML tableLabel = new HTML(constants.SearchQueries());
private final Clickable clickable;
/**
* Construct a {@link AdvanceSearchView} with given parent {@link View}.
*
* @param parent the View display this View.
* @param query TODO
*/
private AdvanceSearchView(View parent, Clickable clickable) {
super(parent, false);
this.clickable = clickable;
HorizontalPanel mainHp = new HorizontalPanel();
VerticalPanel vp = new VerticalPanel();
tableLabel.setStyleName("Label");
vp.add(tableLabel);
vp.add(queriesTable);
HorizontalPanel buttonHp = new HorizontalPanel();
buttonHp.setSpacing(5);
buttonHp.add(searchButton);
buttonHp.add(clearQueriesButton);
vp.add(buttonHp);
vp.setCellHorizontalAlignment(tableLabel,
HasHorizontalAlignment.ALIGN_CENTER);
queriesTable.setStyleName("QueriesTable");
mainSp.setWidget(mainHp);
initWidget(mainSp);
mainHp.add(searchAreasVp);
mainHp.add(vp);
mainHp.setStyleName("AdvanceSearch");
queriesTable.setCellPadding(2);
queriesTable.setCellSpacing(0);
queriesTable.setBorderWidth(0);
clearQueriesButton.setVisible(false);
searchButton.setVisible(false);
tableLabel.setVisible(false);
clearQueriesButton.addClickHandler(this);
searchButton.addClickHandler(this);
HorizontalPanel hp = new HorizontalPanel();
HTML groupLb = new HTML(constants.AddSearchField());
groupLb.setStyleName("Label");
hp.add(groupLb);
hp.add(searchFieldSuggestionBox);
hp.setSpacing(5);
HTML instructionLb = new HTML(constants.AdvanceSearchInstruction());
instructionLb.setStyleName("Label");
searchAreasVp.add(instructionLb);
searchAreasVp.add(hp);
searchAreasVp.add(addSearchCriteriaButton);
searchAreasVp.setWidth("500px");
searchAreasVp.setSpacing(10);
searchFieldSuggestionBox.addTermSelectionListener(this);
addSearchCriteriaButton.setVisible(false);
addSearchCriteriaButton.addClickHandler(this);
addSearchCriteriaButton.addStyleName("AddButton");
queriesTable.addClickHandler(this);
editTextBox.addKeyUpHandler(this);
editTextBox.setStyleName("EditBox");
editTextBox.addBlurHandler(this);
// DOM.sinkEvents(queriesTable.getElement(), Event.MOUSEEVENTS);
// DOM.setEventListener(queriesTable.getElement(), this);
historyState.setHistoryToken(History.getToken());
}
/**
* Adds all the search {@link ASearchType#clientName} and padding its search
* group in the front to the {@link #searchFieldSuggestionBox}.
*
* @param searchGroup the search group for the given asearchType
* @param asearchTypes the list of {@link ASearchType} for the given search
* group.
* @param isDefault true to show the default suggestion if nothing is type.
*/
public void addSearchFields(String searchGroup,
List<ASearchType> asearchTypes, boolean isDefault) {
if (isDefault) {
defaultSuggestionList = new ArrayList<String>();
}
String displayMsg = constants.SearchBy();
if (searchGroup == null) {
displayMsg += "...";
} else {
displayMsg += " " + searchGroup;
}
for (ASearchType asearchType : asearchTypes) {
String clientName = asearchType.getClientName();
String term = searchGroup + " - " + clientName;
if (isDefault) {
defaultSuggestionList.add(term);
}
searchFieldSuggestionBox.addSearchTerm(term);
fieldSearchTypesMap.put(term.toLowerCase(), asearchType);
fieldSearchTypesMap.put(clientName.toLowerCase(), asearchType);
fieldSearchTypesMap.put(asearchType.getDatabaseField().toLowerCase(),
asearchType);
}
if (isDefault) {
searchFieldSuggestionBox.setDeafaultSuggestions(defaultSuggestionList);
}
}
/**
* Clears the {@link #queriesTable}.
*/
public void clearSearch() {
clearQueriesButton.setVisible(false);
searchButton.setVisible(false);
tableLabel.setVisible(false);
queriesTable.clear();
queriesTable.resizeRows(0);
}
/**
* Gets the previous view name which this view switch from.
*
* @return previous view name as String
*/
public String getPreviousViewName() {
return previousViewName;
}
/**
* Gets a {@link Set} of String represents search filters for this advance
* search. Each filter is in the following format:<br>
* database field name + space + operator + space + search value.
*
* @return {@link Set} of String filter.
*/
public Set<String> getSearchFilters() {
Set<String> searchFilters = new HashSet<String>();
for (int row = 0; row < queriesTable.getRowCount(); row++) {
searchFilters.add(getRowFilter(row));
}
return searchFilters;
}
/**
* Gets this view history token in the following format:<br>
* asearch=searchQuery&asearch=searchQuery&...<br>
* searchQuery=database field name + space + operator + space + search value.
*
* @see org.rebioma.client.ComponentView#historyToken()
*/
public String historyToken() {
StringBuilder tokensBuilder = new StringBuilder();
String asearchParam = UrlParam.ASEARCH.lower() + "=";
for (int i = 0; i < queriesTable.getRowCount(); i++) {
String clientName = queriesTable.getText(i, CLIENT_NAME_COL)
.toLowerCase();
String operator = queriesTable.getText(i, OPERATOR_COL);
String searchValue = queriesTable.getText(i, SEARCH_VALUE_COL);
String databaseField = fieldSearchTypesMap.get(clientName)
.getDatabaseField();
tokensBuilder.append("&" + asearchParam + databaseField + " " + operator
+ " " + searchValue);
}
return tokensBuilder.toString();
}
/**
* When the {@link editTextBox} save the currently edit search value in
* {@link #queriesTable}.
*/
public void onBlur(BlurEvent event) {
Object source = event.getSource();
if (source == editTextBox) {
saveCurrentEditingValue();
}
}
public void onClick(ClickEvent event) {
Object source = event.getSource();
if (source == addSearchCriteriaButton) {
Set<SearchArea> searchAreasToRemove = new HashSet<SearchArea>();
for (int i = START_SEARCH_FIELD_INDEX; i < searchAreasVp
.getWidgetIndex(addSearchCriteriaButton); i++) {
SearchArea searchArea = (SearchArea) searchAreasVp.getWidget(i);
searchAreasToRemove.add(searchArea);
String normalSearch = searchArea.getNormalSearch();
String negateSearch = searchArea.getNegateSearch();
ASearchType searchType = searchArea.getType();
if (searchArea.getNormalOp().equals("empty")
|| !normalSearch.equals("")) {
addCriteria(searchType.getClientName(), searchArea.getNormalOp(),
normalSearch);
}
if (searchArea.getNegateOp().equals("!empty")
|| !negateSearch.equals("")) {
addCriteria(searchType.getClientName(), searchArea.getNegateOp(),
negateSearch);
}
}
addSearchCriteriaButton.setVisible(false);
for (SearchArea searchArea : searchAreasToRemove) {
searchAreasVp.remove(searchArea);
}
addHistoryItem(false);
} else if (source == clearQueriesButton) {
clearSearch();
addHistoryItem(false);
} else if (source == searchButton) {
clickable.click();
} else if (source == queriesTable) {
Cell cell = queriesTable.getCellForEvent(event);
if (cell == null) {
return;
}
int row = cell.getRowIndex();
int col = cell.getCellIndex();
if (col == SEARCH_VALUE_COL) {
// saveCurrentEditingValue();
setEditSearchValue(row);
} else if (col == REMOVE_COL) {
removeCriteria(row);
addHistoryItem(false);
}
}
}
public void onKeyUp(KeyUpEvent event) {
Object source = event.getSource();
int keyCode = event.getNativeKeyCode();
if (source == editTextBox) {
if (keyCode == KeyCodes.KEY_ENTER) {
saveCurrentEditingValue();
}
}
}
public void onMouseOut(MouseOutEvent event) {
Object source = event.getSource();
Widget widget = (Widget) source;
widget.removeStyleName("hover");
widget.addStyleName("out");
}
public void onMouseOver(MouseOverEvent event) {
Object source = event.getSource();
Widget widget = (Widget) source;
widget.removeStyleName("out");
widget.addStyleName("hover");
}
public void onTermSelected(String term) {
addSearchArea(fieldSearchTypesMap.get(term.toLowerCase()));
}
public void setPreviousViewName(String previousViewName) {
this.previousViewName = previousViewName;
}
protected void handleOnValueChange(String historyToken) {
restoreFromHisToken(historyToken);
}
protected boolean isMyView(String value) {
historyState.setHistoryToken(value);
String view = historyState.getHistoryParameters(UrlParam.VIEW) + "";
return view.equalsIgnoreCase(ADVANCE);
}
protected void resetToDefaultState() {
restoreFromHisToken(History.getToken());
}
protected void resize(int width, int height) {
height = height - mainSp.getAbsoluteTop();
if (height < 0) {
height = 1;
}
mainSp.setPixelSize(width, height);
}
/**
* Adds a search query to the {@link #queriesTable}.
*
* @param clientName
* @param op
* @param searchValue
*/
private void addCriteria(String clientName, String op, String searchValue) {
if (searchValue.equals("")) {
searchValue = " ";
}
for (int i = 0; i < queriesTable.getRowCount(); i++) {
String clientNameCol = queriesTable.getText(i, CLIENT_NAME_COL);
String opCol = queriesTable.getText(i, OPERATOR_COL);
if (clientNameCol.equals(clientName) && opCol.equals(op)) {
HTML searchValueHTML = (HTML) queriesTable.getWidget(i,
SEARCH_VALUE_COL);
searchValueHTML.setHTML(searchValue);
return;
}
}
int newRowIndex = queriesTable.getRowCount();
queriesTable.insertRow(newRowIndex);
queriesTable.setText(newRowIndex, COUNTER_COL, newRowIndex + 1 + ".");
queriesTable.setText(newRowIndex, CLIENT_NAME_COL, clientName);
queriesTable.setText(newRowIndex, OPERATOR_COL, op);
HTML searchValueHTML = new HTML(searchValue);
searchValueHTML.addStyleName("out");
searchValueHTML.addMouseOutHandler(this);
searchValueHTML.addMouseOverHandler(this);
queriesTable.setWidget(newRowIndex, SEARCH_VALUE_COL, searchValueHTML);
queriesTable.setHTML(newRowIndex, REMOVE_COL, "<img src='"
+ "images/redX.png" + "'/>");
CellFormatter cellFormatter = queriesTable.getCellFormatter();
cellFormatter.setVerticalAlignment(newRowIndex, REMOVE_COL,
HasVerticalAlignment.ALIGN_MIDDLE);
cellFormatter.setStyleName(newRowIndex, COUNTER_COL, "cell");
cellFormatter.setStyleName(newRowIndex, CLIENT_NAME_COL, "cell");
cellFormatter.setStyleName(newRowIndex, OPERATOR_COL, "cell");
cellFormatter.setStyleName(newRowIndex, SEARCH_VALUE_COL, "cell");
cellFormatter.setStyleName(newRowIndex, REMOVE_COL, "link cell");
clearQueriesButton.setVisible(true);
searchButton.setVisible(true);
tableLabel.setVisible(true);
}
private void addSearchArea(ASearchType searchType) {
searchAreasVp.insert(new SearchArea(searchType), searchAreasVp
.getWidgetIndex(addSearchCriteriaButton));
addSearchCriteriaButton.setVisible(true);
}
private String getRowFilter(int row) {
String clientName = queriesTable.getText(row, CLIENT_NAME_COL)
.toLowerCase();
String operator = queriesTable.getText(row, OPERATOR_COL);
String searchValue = queriesTable.getText(row, SEARCH_VALUE_COL);
String databaseField = fieldSearchTypesMap.get(clientName)
.getDatabaseField();
return databaseField + " " + operator + " " + searchValue;
}
private int getSearchValueRow(Widget searchField) {
for (int row = 0; row < queriesTable.getRowCount(); row++) {
if (queriesTable.getWidget(row, SEARCH_VALUE_COL) == searchField) {
return row;
}
}
return -1;
}
private void removeCriteria(int rowIndex) {
queriesTable.removeRow(rowIndex);
for (int i = 0; i < queriesTable.getRowCount(); i++) {
queriesTable.setText(i, 0, (i + 1) + ".");
}
if (queriesTable.getRowCount() == 0) {
clearQueriesButton.setVisible(false);
tableLabel.setVisible(false);
}
}
@SuppressWarnings("unchecked")
private void restoreFromHisToken(String token) {
historyState.setHistoryToken(token);
List<String> asearchValues = (List<String>) historyState
.getHistoryParameters(UrlParam.ASEARCH);
clearSearch();
if (asearchValues == null || asearchValues.isEmpty()) {
return;
}
for (String asearchValue : asearchValues) {
String fieldValues[] = asearchValue.split(" ");
int fieldIndex = 0;
int fieldValuesLen = fieldValues.length;
if (fieldValuesLen < 2) {
continue;
}
String databaseName = "";
String operator = "";
String searchValue = "";
while (fieldIndex != fieldValuesLen) {
databaseName = fieldValues[fieldIndex];
fieldIndex++;
if (!databaseName.equals(" ")) {
break;
}
}
if (fieldIndex == fieldValuesLen) {
continue;
}
while (fieldIndex != fieldValuesLen) {
operator = fieldValues[fieldIndex];
fieldIndex++;
if (!operator.equals(" ")) {
break;
}
}
if (fieldIndex == fieldValuesLen && !operator.equalsIgnoreCase("empty")
&& !operator.equalsIgnoreCase("!empty")) {
continue;
}
while (fieldIndex != fieldValuesLen) {
searchValue += fieldValues[fieldIndex] + " ";
fieldIndex++;
}
ASearchType selectedType = fieldSearchTypesMap.get(databaseName
.toLowerCase());
String clientName = selectedType.getClientName();
addCriteria(clientName, operator, searchValue.trim());
}
}
private void saveCurrentEditingValue() {
if (editingSearchValue != null) {
String newSearchValue = editTextBox.getText();
int editingRow = getSearchValueRow(editTextBox);
String operator = queriesTable.getHTML(editingRow, OPERATOR_COL);
if (!operator.equalsIgnoreCase("empty")
&& !operator.equalsIgnoreCase("!empty")
&& newSearchValue.trim().equals("")) {
removeCriteria(editingRow);
addHistoryItem(false);
} else {
boolean isNew = !editingSearchValue.equals(newSearchValue);
editingSearchValue.setText(newSearchValue);
editingSearchValue.removeStyleName("hover");
editingSearchValue.addStyleName("out");
queriesTable
.setWidget(editingRow, SEARCH_VALUE_COL, editingSearchValue);
editingSearchValue = null;
if (isNew) {
addHistoryItem(false);
}
}
}
}
private void setEditSearchValue(int row) {
Widget widget = queriesTable.getWidget(row, SEARCH_VALUE_COL);
if (widget != editTextBox) {
editingSearchValue = (HTML) widget;
editTextBox.setText(editingSearchValue.getText());
queriesTable.setWidget(row, SEARCH_VALUE_COL, editTextBox);
editTextBox.setFocus(true);
editTextBox.selectAll();
}
}
} |
package com.fillikenesucn.petcare.activities;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.fillikenesucn.petcare.R;
import com.fillikenesucn.petcare.models.Acontecimiento;
import com.fillikenesucn.petcare.adapters.DataHelper;
import com.fillikenesucn.petcare.utils.IOHelper;
import java.util.Calendar;
/**
* Esta clase representa a la actividad que se registrará una nueva mascota, cuando ya se tiene el epc en memoria
* @author: Marcelo Lazo Chavez
* @version: 02/04/2020
*/
public class AddEventOldPetFragmentActivity extends FragmentActivity {
// VARIABLES
private Button btnFechaNacimiento;
private EditText et_fechaNacimiento;
private static final int DATE_ID = 0;
private int nYearIni, nMonthIni, nDayIni, sYearIni, sMonthIni, sDayIni;
private Calendar calendar = Calendar.getInstance();
private TextView txtEPC;
private EditText txtTittle;
private EditText txtDescripcion;
private Button btnAddAcontecimiento;
/**
* Constructor de la actividad
* @param savedInstanceState
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_event_old_pet_fragment);
this.sMonthIni = this.calendar.get(Calendar.MONTH);
this.sYearIni = this.calendar.get(Calendar.YEAR);
this.sDayIni = this.calendar.get(Calendar.DAY_OF_MONTH);
LoadInputs();
LoadPetExtraEpc();
btnFechaNacimiento.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
DatePickerDialog dpd = new DatePickerDialog(AddEventOldPetFragmentActivity.this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
et_fechaNacimiento.setText(i2 + "/" + (i1+1) + "/" + i);
}
}, sYearIni, sMonthIni, sDayIni);
dpd.show();
}
});
btnAddAcontecimiento.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Acontecimiento acontecimiento = new Acontecimiento(txtTittle.getText().toString(), et_fechaNacimiento.getText().toString(),txtDescripcion.getText().toString());
// Revisamos que la información sea válida
if(DataHelper.VerificarAcontecimientoValido(AddEventOldPetFragmentActivity.this, acontecimiento, txtEPC.getText().toString())){
// Si puede agregar el evento cierra la actividad
if (IOHelper.AddEvent(AddEventOldPetFragmentActivity.this,acontecimiento,txtEPC.getText().toString())) {
Toast.makeText(AddEventOldPetFragmentActivity.this, "INGRESO EXITOSO", Toast.LENGTH_SHORT).show();
finish();
}
}
}
});
}
/**
* Método que se encarga de obtener el epc que se envia por EXTRA
*/
private void LoadPetExtraEpc(){
Bundle extras = getIntent().getExtras();
txtEPC.setText(extras.getString("EPC"));
}
/**
* Método que carga los inputs del Layout
*/
private void LoadInputs(){
txtEPC = (TextView) findViewById(R.id.txtEPC);
et_fechaNacimiento = (EditText)findViewById(R.id.fechaAcontecimiento);
btnFechaNacimiento = (Button)findViewById(R.id.btnFechaNacimiento);
txtTittle = (EditText) findViewById(R.id.txtTittle);
txtDescripcion = (EditText) findViewById(R.id.txtDescripcionAcontecimiento);
btnAddAcontecimiento = (Button) findViewById(R.id.btnAddAcontecimiento);
}
}
|
package ru.itis.javalab.repositories;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import ru.itis.javalab.models.User;
import ru.itis.javalab.models.UserCookie;
import java.util.List;
import java.util.Optional;
/**
* created: 21-02-2021 - 15:24
* project: SemesterWork
*
* @author dinar
* @version v0.1
*/
@Repository
public class CookieRepositoryJdbcTemplateImpl implements CrudCookieRepository {
// language=SQL
private static final String SQL_INSERT_USER_COOKIE =
"insert into cookie(user_id, session_id) " +
"values (?, ?)";
// language=SQL
private static final String SQL_SELECT_BY_SESSION_ID =
"select *" +
"from cookie " +
"where session_id = ?";
private final RowMapper<UserCookie> mapper = (resultSet, i) -> UserCookie
.builder()
.user((User) resultSet.getObject("user_id"))
.sessionId(resultSet.getString("session_id"))
.build();
private final JdbcTemplate jdbcTemplate;
public CookieRepositoryJdbcTemplateImpl(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public Optional<UserCookie> getBySessionId(String sessionId) {
UserCookie userCookie;
try {
userCookie = jdbcTemplate.queryForObject(SQL_SELECT_BY_SESSION_ID, mapper, sessionId);
} catch (EmptyResultDataAccessException e) {
return Optional.empty();
}
return Optional.ofNullable(userCookie);
}
@Override
public Long save(UserCookie entity) {
jdbcTemplate.update(SQL_INSERT_USER_COOKIE, entity.getUser(), entity.getSessionId());
return entity.getUser().getId();
}
@Override
public List<UserCookie> findAll() {
return null;
}
@Override
public void update(UserCookie entity) {
}
@Override
public void delete(UserCookie entity) {
}
}
|
package com.jim.multipos.core;
import java.util.Calendar;
public interface BaseTableReportView extends BaseView {
void updateDateIntervalUi(Calendar fromDate, Calendar toDate);
void openDateInterval(Calendar fromDate, Calendar toDate);
void setSingleTitle(String titleReport);
void setChoiserPanel(String[] titles);
void showExportPanel();
}
|
package management.client.model;
import org.hibernate.validator.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
public class Client {
private int id;
@NotNull(message = "Nome é obrigatório")
@NotBlank(message = "Nome é obrigatório")
@Pattern(regexp = "[a-z-A-Z]*", message = "O nome contem caracteres inválidos")
private String name;
@Pattern(regexp="(^$|[0-9]{9})", message = "NIF tem que ter 9 numeros")
private String nif;
private String adress;
@Pattern(regexp="(^$|[0-9]{9})", message = "Numero de telefone tem que ter 9 numeros")
private String phone;
public Client() {
}
public Client(int id, String name, String nif, String adress, String phone) {
this.id = id;
this.name = name;
this.nif = nif;
this.adress = adress;
this.phone = phone;
}
public Client(String name, String nif, String adress, String phone) {
this.name = name;
this.nif = nif;
this.adress = adress;
this.phone = phone;
}
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 getNif() {
return nif;
}
public void setNif(String nif) {
this.nif = nif;
}
public String getAdress() {
return adress;
}
public void setAdress(String adress) {
this.adress = adress;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return "Client{" +
"name='" + name + '\'' +
", nif=" + nif +
", adress='" + adress + '\'' +
", phone=" + phone +
'}';
}
}
|
package org.denevell.natch.jsp.post.move_to_thread;
import org.denevell.natch.io.posts.PostResource;
import org.denevell.natch.utils.simpletags.NatchTagSupport.PojoWithError;
public class MoveToThreadJspOutput extends PostResource implements PojoWithError {
private String error;
public MoveToThreadJspOutput(PostResource post) {
super(post);
}
public void setError(String error) {
this.error = error;
}
public String getError() {
return error;
}
}
|
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
/**
* In Self-Testing, the code should be tested against three different types, normal cases, boundary cases, and illegal cases.
* <p>
* However, since the current program does not perform the legality detection of the parameters and the description of the abnormalities, this test only performs simple routine tests.
* <p>
* This class contains 5 tests to test the toString, the setter and getter of the class Film.
* @author Zetian Qin zxq876
* @version 2019-10-19 11:43:07
*/
public class FilmTests {
private Date date;
private Film detectiveConan;
@BeforeEach
public void init(TestInfo testInfo) {
System.out.println("Start..." + testInfo.getDisplayName());
date = new Date(18, "October", 2019);
detectiveConan = new Film("Detective Conan", date, 123);
}
@Test
@DisplayName("Getter of Date Test")
public void test1() {
int expectedDay = 18;
int actualDay = detectiveConan.getReleaseDate().getDay();
assertEquals(expectedDay, actualDay, "failure in test1: " + " expected day does not equal the actual day");
String expectedMonth = "October";
String actualMonth = detectiveConan.getReleaseDate().getMonth();
assertEquals(expectedMonth, actualMonth, "failure in test1: " + " expected month does not equal the actual month");
int expectedYear = 2019;
int actualYear = detectiveConan.getReleaseDate().getYear();
assertEquals(expectedYear, actualYear, "failure in test1: " + " expected year does not equal the actual year");
}
@Test
@DisplayName("Getter of Title Test")
public void test2() {
String expectedTitle = "Detective Conan";
String actualTitle = detectiveConan.getTitle();
assertEquals(expectedTitle, actualTitle, "failure in test2: " + " expected title does not equal the actual title");
}
@Test
@DisplayName("Getter of Length Test")
public void test3() {
int expectedLength = 123;
int actualLength = detectiveConan.getLength();
assertEquals(expectedLength, actualLength,
"failure in test3: " + " expected length does not equal the actual length");
}
@Test
@DisplayName("Setter of Date Test")
public void test4() {
Date updatedReleaseDate = new Date(03, "October", 2020);
detectiveConan.setReleaseDate(updatedReleaseDate);
String expectedDate = "3 October 2020";
String actualDate = detectiveConan.getReleaseDate().toString();
assertEquals(expectedDate, actualDate, "failure in test4: " + " expected date does not equal the actual date");
}
@Test
@DisplayName("Comprehensive Test")
public void test5() {
Date updatedReleaseDate = new Date(01, "January", 2022);
Film joker = new Film("Joker", updatedReleaseDate, 122);
joker.setReleaseDate(new Date(04, "October", 2019));
boolean expected = false;
boolean actual = detectiveConan.getReleaseDate() == updatedReleaseDate;
assertEquals(expected, actual, "failure in test5: " + " expected value date does not equal the actual value");
assertFalse(joker.getTitle().equals(detectiveConan.getTitle()), "failure in test5: " + " titles of the two films should not be the same");
assertTrue(!joker.getTitle().equals(detectiveConan.getTitle()), "failure in test5: " + " titles of the two films should not be the same");
assertTrue(joker.getReleaseDate().getDay() != detectiveConan.getReleaseDate().getDay(), "failure in test5: " + " Days of the two films should not be equal to each other");
assertTrue(joker.getReleaseDate().getYear() == detectiveConan.getReleaseDate().getYear(), "failure in test5: " + " Years of the two films should be equal to each other");
}
@Test
@AfterEach
public void tearDown(TestInfo testInfo) {
System.out.println("Finished..." + testInfo.getDisplayName());
}
}
|
/*
* 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 pe.gob.onpe.adan.model.admin;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
*
* @author bvaldez
*/
@Entity
@Table(name = "tab_usuario")
public class Usuario {
@Id
@Column(name = "n_usuario_pk")
private Integer id;
@Column(name = "c_usuario")
private String usuario;
@Column(name = "c_apellido_paterno")
private String apellidoPaterno;
@Column(name = "c_apellido_materno")
private String apellidoMaterno;
@Column(name = "c_nombre")
private String nombre;
@Column(name = "c_clave")
private String clave;
@Column(name = "n_estado")
private int estado;
@Column(name = "n_conexion")
private int conexion;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "n_perfil")
private Perfil perfil;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsuario() {
return usuario;
}
public void setUsuario(String usuario) {
this.usuario = usuario;
}
public String getApellidoPaterno() {
return apellidoPaterno;
}
public void setApellidoPaterno(String apellidoPaterno) {
this.apellidoPaterno = apellidoPaterno;
}
public String getApellidoMaterno() {
return apellidoMaterno;
}
public void setApellidoMaterno(String apellidoMaterno) {
this.apellidoMaterno = apellidoMaterno;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getClave() {
return clave;
}
public void setClave(String clave) {
this.clave = clave;
}
public int getEstado() {
return estado;
}
public void setEstado(int estado) {
this.estado = estado;
}
public Perfil getPerfil() {
return perfil;
}
public void setPerfil(Perfil perfil) {
this.perfil = perfil;
}
public int getConexion() {
return conexion;
}
public void setConexion(int conexion) {
this.conexion = conexion;
}
}
|
package java63.servlets.test04.dao;
import java.util.HashMap;
import java.util.List;
import java63.servlets.test04.domain.Member;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class MemberDao {
@Autowired
SqlSessionFactory sqlSessionFactory;
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
this.sqlSessionFactory = sqlSessionFactory;
}
public MemberDao() {}
public Member selectOne(String id) {
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
return sqlSession.selectOne(
"test04.MemberDao.selectOne",
id /* new Integer(no) */);
} finally {
sqlSession.close();
}
}
public void update(Member member) {
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
sqlSession.update(
"test04.MemberDao.update", member);
sqlSession.commit();
} finally {
sqlSession.close();
}
}
public void delete(String id) {
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
sqlSession.delete(
"test04.MemberDao.delete", id);
sqlSession.commit();
} finally {
sqlSession.close();
}
}
public List<Member> selectList(int pageNo, int pageSize) {
SqlSession sqlSession = sqlSessionFactory.openSession();
HashMap<String,Object> paramMap = new HashMap<>();
paramMap.put("startIndex", ((pageNo - 1) * pageSize));
paramMap.put("pageSize", pageSize);
try {
return sqlSession.selectList(
// 네임스페이스 + SQL문 아이디
"test04.MemberDao.selectList",
paramMap /* SQL문을 실행할 때 필요한 값 전달 */);
} finally {
sqlSession.close();
}
}
public void insert(Member member) {
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
sqlSession.insert(
"test04.MemberDao.insert", member);
sqlSession.commit();
} finally {
sqlSession.close();
}
}
public Member checkIn(String id , String pwd) {
SqlSession sqlSession = sqlSessionFactory.openSession();
HashMap<String,String> paramMap = new HashMap<>();
paramMap.put("id", id);
paramMap.put("pwd", pwd);
// System.out.println(paramMap.get("id") + "daoId");
try {
return sqlSession.selectOne(
"test04.MemberDao.checkIn01", paramMap);
} finally {
sqlSession.close();
}
}
}
|
/*
* 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.nam.vn.pro.shell.gui;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListSelectionModel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.table.DefaultTableModel;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaSparkContext;
/**
*
* @author loda
*/
public class view extends javax.swing.JFrame {
private String columnName[] = {"name", "isDirectory"};
private String root = "/";
private String dic = "/";
private List<FileStatus> data;
private Map<String, String> servers;
private FileSystem fs;
private int rowRightClickSelect = 0;
private JavaSparkContext sc;
/**
* Creates new form view
*/
public view() throws FileNotFoundException, IOException {
initComponents();
initSize();
initTable();
serverConfig();
fileSystemConfig("localhost");
System.out.println(command("ls", root));
initData();
initContext();
this.pack();
}
/***
* NEW
*/
private void initContext(){
SparkConf conf = new SparkConf();
conf.setAppName("Shell");
conf.setMaster("local[*]");
sc = new JavaSparkContext(conf);
}
private void initSize() {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double swidth = screenSize.getWidth();
double sheight = screenSize.getHeight();
int width = (int) (swidth / 2);
int height = (int) sheight;
this.setSize(width, height - 100);
}
private void initTable() {
table.setModel(new DefaultTableModel(null, columnName) {
public boolean isCellEditable(int row, int column) {
return false;//This causes all cells to be not editable
}
});
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent event) {
try {
// do some actions here, for example
// print first column value from selected row
if (event.getValueIsAdjusting() || table.getSelectedRow() == -1) {
return;
}
System.out.println(table.getSelectedRow());
changeFolder(table.getSelectedRow());
} catch (IOException ex) {
Logger.getLogger(view.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
final JPopupMenu popupMenu = new JPopupMenu();
JMenuItem deleteItem = new JMenuItem("Delete");
deleteItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (rowRightClickSelect > 0) {
System.out.println("DELETE " + rowRightClickSelect);
}
}
});
popupMenu.add(deleteItem);
popupMenu.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
rowRightClickSelect = table.rowAtPoint(SwingUtilities.convertPoint(popupMenu, new Point(0, 0), table));
if (rowRightClickSelect > -1) {
// table.setRowSelectionInterval(rowAtPoint, rowAtPoint);
System.out.println(rowRightClickSelect);
}
}
});
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
// TODO Auto-generated method stub
}
@Override
public void popupMenuCanceled(PopupMenuEvent e) {
// TODO Auto-generated method stub
}
});
table.setComponentPopupMenu(popupMenu);
}
private void initData() throws IOException {
if (fs == null) {
fileSystemConfig("localhost");
}
loadData();
}
private void loadData() throws IOException {
try{
FileStatus[] files = fs.listStatus(new Path(dic));
data = Arrays.asList(files);
String vec[][] = new String[files.length + 1][2];
vec[0][0] = "..";
for (int i = 0; i < files.length; i++) {
vec[i + 1][0] = files[i].getPath().getName();
vec[i + 1][1] = String.valueOf(files[i].isDirectory());
}
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setDataVector(vec, columnName);
model.fireTableDataChanged();
}catch(Exception e){
dic = dic.substring(0,dic.lastIndexOf("/"));
if(dic.equals("")) dic = "/";
e.printStackTrace();
}
}
/***
* NEW
*/
private void loadFile(String path){
List<String> list = sc.textFile(path)
.take(10);
updateConsole(list);
updateConsole("gaga","fafe");
}
private void updateConsole(List<String> arg){
for(String s: arg){
console.append(s+"\n");
}
}
private void updateConsole(String... arg){
for(String s: arg){
console.append(s+"\n");
}
}
private void changeFolder(int index) throws IOException {
if (index != 0) {
FileStatus file = data.get(index - 1);
if (file.isDirectory()) {
if (!dic.equals(root)) {
dic += "/" + file.getPath().getName();
}else{
dic += file.getPath().getName();
}
loadData();
} else {
txt_input.setText(file.getPath().toString());
loadFile(file.getPath().toString());
}
} else {
if (!dic.equals(root)) {
dic = dic.substring(0, dic.lastIndexOf("/"));
if(dic.equals("")){
dic = "/";
}
loadData();
}
}
}
private void serverConfig() throws FileNotFoundException {
Scanner sc = new Scanner(new File("server.con"));
if (servers == null) {
servers = new HashMap<String, String>();
}
while (sc.hasNextLine()) {
String tokens[] = sc.nextLine().split(":");
servers.put(tokens[0].trim(), tokens[1].trim());
}
}
private void fileSystemConfig(String serverName) throws IOException {
Configuration conf = new Configuration();
if (!serverName.equals("localhost")) {
conf.set("fs.defaultFS", servers.get(serverName));
}
fs = FileSystem.newInstance(conf);
System.out.println("Root: " + root);
}
public static List<String> command(final String cmdline,
final String directory) {
try {
Process process
= new ProcessBuilder(new String[]{"bash", "-c", cmdline})
.redirectErrorStream(true)
.directory(new File(directory))
.start();
List<String> output = new ArrayList<String>();
BufferedReader br = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line = null;
while ((line = br.readLine()) != null) {
output.add(line);
}
//There should really be a timeout here.
if (0 != process.waitFor()) {
return null;
}
return output;
} catch (Exception e) {
//Warning: doing this is no good in high quality applications.
//Instead, present appropriate error messages to the user.
//But it's perfectly fine for prototyping.
return null;
}
}
/**
* 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() {
txt_input = new javax.swing.JTextField();
console = new java.awt.TextArea();
jScrollPane1 = new javax.swing.JScrollPane();
table = new javax.swing.JTable();
txt_folder = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jComboBox1 = new javax.swing.JComboBox<>();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
console.setBackground(new java.awt.Color(0, 43, 54));
console.setForeground(new java.awt.Color(131, 148, 150));
table.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"
}
));
jScrollPane1.setViewportView(table);
jButton1.setText("Go");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("jButton2");
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(console, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 686, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txt_folder)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1))
.addGroup(layout.createSequentialGroup()
.addComponent(txt_input)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton2))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txt_folder, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 296, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txt_input, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(console, javax.swing.GroupLayout.PREFERRED_SIZE, 258, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
try {
String folder = txt_folder.getText();
if (folder != null && !folder.equals("")) {
Path path = new Path(folder);
dic = path.toString();
if (dic.charAt(0) != '/') {
dic = "/" + dic;
}
if(dic.equals("")){
dic = "/";
}
txt_folder.setText(dic);
}
loadData();
// TODO add your handling code here:
} catch (IOException ex) {
Logger.getLogger(view.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton1ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(view.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(view.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(view.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(view.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new view().setVisible(true);
} catch (Exception ex) {
Logger.getLogger(view.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private java.awt.TextArea console;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JComboBox<String> jComboBox1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable table;
private javax.swing.JTextField txt_folder;
private javax.swing.JTextField txt_input;
// End of variables declaration//GEN-END:variables
}
|
package com.tencent.mm.plugin.sns.storage.AdLandingPagesStorage;
import java.io.Serializable;
public class a$b implements Serializable {
public String fxE;
public String nyk;
public a$b(String str, String str2) {
this.nyk = str;
this.fxE = str2;
}
}
|
package com.gmail.cwramirezg.task.features.task;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.gmail.cwramirezg.task.R;
import com.gmail.cwramirezg.task.data.models.Task;
import com.gmail.cwramirezg.task.features.main.MainNavigationActivity;
import com.gmail.cwramirezg.task.features.shared.BaseFragment;
import com.gmail.cwramirezg.task.utils.SimpleDividerItemDecoration;
import com.gmail.cwramirezg.task.utils.UtilMethods;
import com.gmail.cwramirezg.task.utils.dialogs.CustomDialog;
import com.gmail.cwramirezg.task.utils.dialogs.ProgressDialog;
import java.util.List;
import java.util.Objects;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
public class TaskFragment extends BaseFragment implements TaskFragmentContract.View, TaskAdapter.ISelection {
@BindView(R.id.rv_data)
RecyclerView rvData;
@Inject
TaskFragmentPresenter presenter;
Unbinder unbinder;
public TaskFragment() {
}
public static TaskFragment newInstance() {
return new TaskFragment();
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
getActivityComponent().inject(this);
presenter.attachView(this);
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle avedInstanceState) {
setHasOptionsMenu(true);
View view = inflater.inflate(R.layout.fragment_task, container, false);
unbinder = ButterKnife.bind(this, view);
return view;
}
@Override
protected void setupViews(View view) {
presenter.showTasks();
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
presenter.detachView();
}
@Override
public void showTasks(List<Task> tasks) {
ProgressDialog.dismiss();
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
rvData.setLayoutManager(layoutManager);
rvData.addItemDecoration(new SimpleDividerItemDecoration(getContext(), R.drawable.line_divider_white));
TaskAdapter adapter = new TaskAdapter(tasks, this);
rvData.setAdapter(adapter);
}
@Override
public void showMessage(String message) {
UtilMethods.showToast(message);
}
@Override
public void showError(String message) {
new CustomDialog.Builder(getContext())
.setMessage(message)
.setTheme(R.style.AppTheme_Dialog_Error)
.setIcon(R.drawable.ic_close)
.setPositiveButtonLabel(getString(R.string.label_ok))
.build().show();
}
@Override
public void onClick(Task task) {
if ("1".equalsIgnoreCase(task.getStatus())) {
showMessage(getString(R.string.task_complete));
} else {
new CustomDialog.Builder(getContext())
.setMessage(getString(R.string.task_success))
.setTheme(R.style.AppTheme_Dialog)
.setIcon(R.drawable.ic_close)
.setPositiveButtonLabel(getString(R.string.label_yes))
.setNegativeButtonLabel(getString(R.string.label_no))
.setPositiveButtonlistener(() -> presenter.completeTask(task))
.build().show();
}
}
@Override
public void onClickLong(Task task) {
new CustomDialog.Builder(getContext())
.setMessage(getString(R.string.task_delete))
.setTheme(R.style.AppTheme_Dialog)
.setIcon(R.drawable.ic_close)
.setPositiveButtonLabel(getString(R.string.label_yes))
.setNegativeButtonLabel(getString(R.string.label_no))
.setPositiveButtonlistener(() -> presenter.deleteTask(task))
.build().show();
}
@OnClick(R.id.fa_add)
public void onViewClicked() {
((MainNavigationActivity) Objects.requireNonNull(getActivity())).navigateTo(R.id.nav_add);
}
} |
package Peer;
import BlockchainUtil.Block;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import proto.BlockchainGrpc;
import proto.BlockchainService;
import java.util.concurrent.TimeUnit;
public class Client {
private final ManagedChannel channel;
private final BlockchainGrpc.BlockchainBlockingStub blockingStub;
public Client(String host, int port) {
this(ManagedChannelBuilder.forAddress(host, port)
.usePlaintext()
.build());
}
Client(ManagedChannel channel) {
this.channel = channel;
blockingStub = BlockchainGrpc.newBlockingStub(channel);
}
public void sendBlock(Block b, int fromId) {
BlockchainService.Block blockMsg = BlockchainService.Block.newBuilder()
.setCreatedBy(fromId)
.setId(b.getId())
.addAllTransactions(b.getTransactionList())
.build();
blockingStub.onBlockReceive(blockMsg);
}
public void shutdown() throws InterruptedException {
channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
}
}
|
/*
* Copyright 2013 JBoss Inc
*
* 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 org.overlord.rtgov.ui.client.model;
import org.jboss.errai.common.client.api.annotations.Portable;
import org.jboss.errai.databinding.client.api.Bindable;
/**
* A simple data bean for returning information about bindings.
*
*/
@Portable
@Bindable
public class BindingBean {
private String type;
private String state;
/**
* Constructor.
*/
public BindingBean() {
}
/**
* @return the type
*/
public String getType() {
return type;
}
/**
* @param type
* the type to set
* @return
*/
public BindingBean setType(String type) {
this.type = type;
return this;
}
/**
* @return the state
*/
public String getState() {
return state;
}
public boolean isActive() {
return "STARTED".equals(state);
}
/**
* @param state
* the state to set
* @return
*/
public BindingBean setState(String state) {
this.state = state;
return this;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((state == null) ? 0 : state.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BindingBean other = (BindingBean) obj;
if (state == null) {
if (other.state != null)
return false;
} else if (!state.equals(other.state))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
}
|
package CreatingGUIs;
import java.awt.*;
import javax.swing.*;
public class main {
public static void main(String[] args) throws InterruptedException {
JFrame window = new JFrame();
window.setTitle("HELLO!");
window.setSize(new Dimension(500, 600));
window.setVisible(true);
double incr = 0;
double scaleFactor = 0.5;
while (true) {
incr += 0.01;
double sin = (scaleFactor) + Math.sin(incr) * (scaleFactor);
double width = 1920 * ((scaleFactor) + Math.sin(incr) * (scaleFactor));
window.setLocation((int) (1920 / 2 - sin * 1920 / 2), (int) (1080 / 2 - sin * 1080 / 2));
window.setSize(new Dimension((int) (sin * 1920), (int) (sin * 1080)));
Thread.sleep(20);
}
}
}
|
package com.redhat.manuela.sensor;
import com.redhat.manuela.model.Measure;
public interface Sensor {
public void initAndReset();
public int getFrequency();
public boolean isEnabled();
public Measure calculateCurrentMeasure(Measure measure);
}
|
package Transport;
import java.io.IOException;
import transport.IDelivery;
import transport.IExporter;
import java.io.FileWriter;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import transport.IItemPacked;
import transport.IVehicle;
/*
* Nome: <Samuel Luciano Correia da Cunha>
* Número: <8160526>
*/
public class Exporter implements IExporter {
/**
* The exporter delivery.
*/
private IDelivery delivery;
/**
* Exporter path to a file were the delivery info will be stored.
*/
private String GUIpath;
/**
* Constructor of Exporter.
*
* @param delivery The exporter delivery
* @param GUIpath The
*/
public Exporter(IDelivery delivery, String GUIpath) {
this.delivery = delivery;
this.GUIpath = GUIpath;
}
/**
* Getter for the exporter delivery.
*
* @return The exporter delivery.
*/
public IDelivery getDelivery() {
return delivery;
}
/**
* Setter for the exporter delivery.
*
* @param delivery The Delivery.
*/
public void setDelivery(IDelivery delivery) {
this.delivery = delivery;
}
/**
* Getter for the path file were delivery info will be stored
* @return
*/
public String getGUIpath() {
return GUIpath;
}
/**
* Setter for Gui path.
*
* @param GUIpath The GUI path.
*/
public void setGUIpath(String GUIpath) {
this.GUIpath = GUIpath;
}
/**
* Serialize an object to a specific format that can be stored.
*
* @param string The file system location in which the data will be stored.
* @throws IOException
*/
@Override
public void export(String string) throws IOException {
try (FileWriter file = new FileWriter(this.GUIpath)) {
file.write(serializeDeliveryGUI().toJSONString());
}
}
/**
* Serializes an Delivery acording to render method.
*
* @return an JSONObject that can be written to a file
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
*/
private JSONObject serializeDeliveryGUI() throws IOException {
JSONObject obj = new JSONObject();
JSONObject item;
JSONArray items = new JSONArray();
Delivery deliver = (Delivery) delivery;
IVehicle vcl = deliver.getVehicle();
Box box = (Box) vcl.getCargoBox();
obj.put("depth", box.getDepth());
obj.put("color", box.getColor().toString());
obj.put("length", box.getLength());
IItemPacked[] temp = deliver.getPackedItems();
for (int i = 0; i < temp.length; i++) {
item = new JSONObject();
item.put("depth", temp[i].getItem().getDepth());
Item tmpItem = (Item) temp[i].getItem();
item.put("color", tmpItem.getColor().toString());
item.put("x", temp[i].getPosition().getX());
item.put("length", temp[i].getItem().getLength());
item.put("y", temp[i].getPosition().getY());
item.put("z", temp[i].getPosition().getZ());
item.put("height", temp[i].getItem().getHeight());
items.add(item);
}
obj.put("items", items);
obj.put("height", box.getHeight());
return obj;
}
} |
package pl.superjaba.model;
/**
* Created by RENT on 2017-03-01.
*/
public class Users {
//pobawic sie, filtrowanie, itp
}
|
/*
* Copyright: 2020 forchange Inc. All rights reserved.
*/
package com.research.hadoop.mr.parititioner;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import java.io.IOException;
/**
* @fileName: ParititionerReducer.java
* @description: ParititionerReducer.java类说明
* @author: by echo huang
* @date: 2020-02-11 17:56
*/
public class ParititionerReducer extends Reducer<Text, LongWritable, Text, LongWritable> {
@Override
protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
int sum = 0;
for (LongWritable value : values) {
sum += value.get();
}
context.write(key, new LongWritable(sum));
}
}
|
package com.smxknife.spring.ignoredependency;
import com.smxknife.spring.ignoredependency.inter.InterfaceTest;
import com.smxknife.spring.ignoredependency.type.TypeTest;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author smxknife
* 2020/2/5
*/
public class XmlTypeBoot {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
context.addBeanFactoryPostProcessor(new IgnoreAutowiringTypeProcessor());
InterfaceTest it = context.getBean(InterfaceTest.class);
TypeTest type = context.getBean(TypeTest.class);
it.test();
type.test();
}
}
|
package api.domain.model.oauth;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class DeautorizationRequest {
private String refreshToken;
public String getRefreshToken() {
return refreshToken;
}
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
}
|
package com.mx.profuturo.bolsa.model.recruitment.vo;
import com.mx.profuturo.bolsa.model.recruitment.dto.InterviewDTO;
public class InterviewVO extends InterviewDTO {
private String nombreSede;
private String nombreEntrevistador;
public String getNombreSede() {
return nombreSede;
}
public void setNombreSede(String nombreSede) {
this.nombreSede = nombreSede;
}
public String getNombreEntrevistador() {
return nombreEntrevistador;
}
public void setNombreEntrevistador(String nombreEntrevistador) {
this.nombreEntrevistador = nombreEntrevistador;
}
} |
package leecode.other;
public class 替换后的最长重复字符_424 {
//https://leetcode-cn.com/problems/longest-repeating-character-replacement/solution/tong-guo-ci-ti-liao-jie-yi-xia-shi-yao-shi-hua-don/
public int characterReplacement(String s, int k) {
int[]map=new int[26];
if(s==null){
return 0;
}
char[]chars=s.toCharArray();
int left=0;
int right=0;
int historyCharMax = 0;
while (right<chars.length){
int index=chars[right]-'A';
map[index]++;
historyCharMax=Math.max(historyCharMax,map[index]);//当前窗口内的最多字符的个数
if(right-left+1-historyCharMax>k){////需要替换的字符个数就是当前窗口的大小减去窗口中数量最多的字符的数量
map[chars[left]-'A']--;
left++;
}
right++;
}
return chars.length-left;
}
}
|
/* PharmacyFactoryTest.java
Entity for the PharmacyFactoryTest
Author: Zuko Fukula (217299911)
Date: 6 June 2021
*/
package za.ac.cput.Factory;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import za.ac.cput.Entity.Pharmacy;
import static org.junit.jupiter.api.Assertions.*;
class PharmacyFactoryTest {
@Timeout(5)
@Test
//Valid input test
public void PharmacyItem(){
Pharmacy ph = PharmacyFactory.createPharmacyItem(2,59.00);
assertNull(ph.getMedicineID());
}
@Test
//Price equals system price test
public void PharmacyItemPrice(){
Pharmacy ph = PharmacyFactory.createPharmacyItem(2,59.00);
System.out.println("Price: "+ph.getPrice());
assertEquals(59.00,ph.getPrice());
}
//Disable Test
@Disabled("Test Disabled")
@Test
public void PharmacyPrice(){
Pharmacy ph = PharmacyFactory.createPharmacyItem(2, 59.00);
assertSame(59,ph.getPrice());
}
}
|
package prog11황인호;
/**
* 배열을 반환하는 메소드를 이용하는 문제
* 지정된 크기의 배열을 반환하는 메소드를 호출한 후
* 반환된 배열의 내용을 출력하는 작업을 반혹한다.
* 메소드가 얼마나 큰 배열을 만들게 할지는
* 메소드를 호출할 때 인수를 통해 지정해 준다.
* @author 황인호
*
*/
public class ArrayReturn2
{
public static void main(String[] args)
{
int[] array;
// makeArray 메소드를 호출하면 배열을 가리키는 참조가 반환된다.
// 그 참조를 참조변수 array에 저장한다.
// 그렇게 하고 나면 참조변수 array를 이용하여 배열에 접근할 수 있다.
array = makeArray();
// 배열을 출력한다.
printArray(array, 10);
for (int i = 0; i<10; i++)
{
for(int j = 0; j<i+1; j++)
{
System.out.print(array[j] + " ");
}
System.out.println();
}
}
/**
* 크기가 10인 int 배열을 구성한 후
* 0번 방에는 0*0을,
* 1번 방에는 1*1을
* ...
* 9번 방에는 9*9를 저장하고
* 배열을 반환한다.
* 배열을 반환한다는 것은 곧 배열을 가리키는 참조(reference)를 반환한다는 말이다.
*/
public static int[] makeArray()
{
int [] a= new int[10];
for(int i = 0; i<10; i++)
{
a[i] = i*i;
}
return a;
}
/**
* 크기가 n인 int 배열을 구성한 후
* 0번 방에는 0*0을,
* 1번 방에는 1*1을
* ...
* n-1번 방에는 (n-1)*(n-1)을 저장하고
* 배열을 반환한다.
* 배열을 반환한다는 것은 곧 배열을 가리키는 참조(reference)를 반환한다는 말이다.
* @param n 배열의 크기
* @return 배열을 가리키는 참조
*/
public static int[] makeArray(int n)
{
int [] a= new int[n];
for(int i = 0; i<n; i++)
{
a[i] = i*i;
}
return a;
}
/**
* 주어진 배열의 원소를 주어진 수만큼 출력한다.
* @param a 출력할 배열.
* @param n 배열의 원소를 몇 개 출력할 것인가?
*/
public static void printArray(int[] a, int n)
{
// 배열 a의 앞 부분의 n개의 방에 있는 값들을 차례로 출력한다.
for(int i = 0; i<n; i++)
{
System.out.print(a[i] + " ");
}
System.out.println();
}
} |
package org.newdawn.slick.tests;
import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.BasicGame;
import org.newdawn.slick.Game;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Music;
import org.newdawn.slick.MusicListener;
import org.newdawn.slick.SlickException;
public class MusicListenerTest extends BasicGame implements MusicListener {
private boolean musicEnded = false;
private boolean musicSwapped = false;
private Music music;
private Music stream;
public MusicListenerTest() {
super("Music Listener Test");
}
public void init(GameContainer container) throws SlickException {
this.music = new Music("testdata/restart.ogg", false);
this.stream = new Music("testdata/restart.ogg", false);
this.music.addListener(this);
this.stream.addListener(this);
}
public void update(GameContainer container, int delta) throws SlickException {}
public void musicEnded(Music music) {
this.musicEnded = true;
}
public void musicSwapped(Music music, Music newMusic) {
this.musicSwapped = true;
}
public void render(GameContainer container, Graphics g) throws SlickException {
g.drawString("Press M to play music", 100.0F, 100.0F);
g.drawString("Press S to stream music", 100.0F, 150.0F);
if (this.musicEnded)
g.drawString("Music Ended", 100.0F, 200.0F);
if (this.musicSwapped)
g.drawString("Music Swapped", 100.0F, 250.0F);
}
public void keyPressed(int key, char c) {
if (key == 50) {
this.musicEnded = false;
this.musicSwapped = false;
this.music.play();
}
if (key == 31) {
this.musicEnded = false;
this.musicSwapped = false;
this.stream.play();
}
}
public static void main(String[] argv) {
try {
AppGameContainer container = new AppGameContainer((Game)new MusicListenerTest());
container.setDisplayMode(800, 600, false);
container.start();
} catch (SlickException e) {
e.printStackTrace();
}
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\org\newdawn\slick\tests\MusicListenerTest.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ |
package com.example.recyclerview.data;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
public class TopicDAO {
public static final String FAMILY = "FAMILY";
public static final String ANIMAL = "ANIMAL";
public static final String CLOTHES = "CLOTHES";
public static final String COLOR = "COLOR";
public static final String FRUIT = "FRUIT";
public static final String COOKING = "COOKING";
public static final String MUSIC = "MUSIC";
public static final String NUMBER = "NUMBER";
public static final String SCHOOL = "SCHOOL";
public static final String SPORT = "SPORT";
public static final String TRAFFIC = "TRAFFIC";
public static final String VEGETABLE = "VEGETABLE";
public static final String WEATHER = "WEATHER";
public static final String HOSPITAL = "HOSPITAL";
public static final String RESTAURANT = "RESTAURANT";
public static final String ADJECTIVE = "ADJECTIVE";
public static final String ACTION = "ACTION";
public static final String CLASS1 = "CLASS1";
public static final String CLASS2 = "CLASS2";
public static final String CLASS3 = "CLASS3";
public static final String CLASS4 = "CLASS4";
public static final String CLASS5 = "CLASS5";
public static final String CLASS6 = "CLASS6";
public static final String CLASS7 = "CLASS7";
public static final String CLASS8 = "CLASS8";
public static final String CLASS9 = "CLASS9";
public static final String CLASS10 = "CLASS10";
public static final String CLASS11 = "CLASS11";
public static final String CLASS12 = "CLASS12";
public static final String POSITION = "POSITION";
public static final String DEPARTMENT = "DEPARTMENT";
public static final String SUPPLY = "SUPPLY";
public static final String BENEFIT = "BENEFIT";
public static final String CONFERENCE = "CONFERENCE";
public static final String MACHINES = "MACHINES";
public static final String COMMON = "COMMON";
public static final String STRUCTURE = "STRUCTURE";
public static final String JOBS = "JOBS";
public static final String PERIPHERALS = "PERIPHERALS";
public static final String MEETING = "MEETING";
public static final String EQUIPMENT = "EQUIPMENT";
public static final String TECHNOLOGY = "TECHNOLOGY";
public static final String TOUR_GUIDE = "TOUR_GUIDE";
public static final String AGENCY = "AGENCY";
public static final String HOTEL = "HOTEL";
public static final String SEA = "SEA";
public static final String PLANE = "PLANE";
public static final String OVERVIEW = "OVERVIEW";
public static final String LISTENING = "LISTENING";
public static final String SPEAKING = "SPEAKING";
public static final String READING = "READING";
public static final String WRITING = "WRITING";
public static final String CONTRACTS = "CONTRACTS";
public static final String SHOPPING = "SHOPPING";
public static final String MARKETING = "MARKETING";
public static final String ACCOUNTING = "ACCOUNTING";
public static final String MOVIES = "MOVIES";
public static final String TABLE_NAME = "topic";
public static final String ID = "id";
public static final String NAME = "name";
public static final String COURSE_ID = "course_id";
private final DatabaseHelper databaseHelper;
public static TopicDAO fromContext(Context context) {
DatabaseHelper databaseHelper = new DatabaseHelper(context);
return new TopicDAO(databaseHelper);
}
public TopicDAO(DatabaseHelper databaseHelper) {
this.databaseHelper = databaseHelper;
}
public ContentValues getContentValues(Topic topic) {
ContentValues values = new ContentValues();
values.put(ID, topic.getId());
values.put(COURSE_ID, topic.getCourseId());
values.put(NAME, topic.getName());
return values;
}
private void addTopic(Topic topic, SQLiteDatabase db) {
ContentValues values = getContentValues(topic);
db.insert(TABLE_NAME, null, values);
}
public void addTopics(ArrayList<Topic> topics) {
SQLiteDatabase db = this.databaseHelper.getWritableDatabase();
for (Topic topic : topics) {
addTopic(topic, db);
}
db.close();
}
public ArrayList<Topic> getTopicsByCourseId(int courseId) {
ArrayList<Topic> topics = new ArrayList<>();
String selectQuery = "SELECT * FROM " + TABLE_NAME + " where " + COURSE_ID + "=" + courseId;
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
topics.add(new Topic(
cursor.getInt(0),
cursor.getInt(1),
cursor.getString(2)
));
} while (cursor.moveToNext());
}
cursor.close();
return topics;
}
}
|
package com.sojay.testfunction.card.card2;
import java.io.Serializable;
public class BookBean implements Serializable {
private String name;
private String cover;
public BookBean() {
}
public BookBean(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String getCover() {
return cover;
}
public void setCover(String cover) {
this.cover = cover;
}
}
|
package com.hcl.dmu.demand.skill.dao;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import org.dozer.Mapper;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.hcl.dmu.demand.entity.DemandDetailsEntity;
import com.hcl.dmu.demand.entity.PrimarySkillEntity;
import com.hcl.dmu.demand.entity.SecondarySkillEntity;
import com.hcl.dmu.demand.entity.SkillsEntity;
import com.hcl.dmu.demand.vo.DemandTrakerVo;
import com.hcl.dmu.demand.vo.PrimarySkillVo;
import com.hcl.dmu.demand.vo.SecondarySkillVo;
import com.hcl.dmu.demand.vo.SkillVo;
import com.hcl.dmu.reg.dao.AbstractDAO;
@Repository
public class SkillDaoImpl extends AbstractDAO implements SkillDao {
private static final Logger log = LoggerFactory.getLogger(SkillDaoImpl.class);
@Autowired
private Mapper mapper;
@Override
public List<DemandTrakerVo> getSkillDemandDetails() {
Session session = null;
List<DemandTrakerVo> listDemandTrakerVo = null;
try {
session = getSession();
Query<DemandDetailsEntity> createQuery = session.createQuery("from DemandDetailsEntity");
List<DemandDetailsEntity> resultList = createQuery.getResultList();
if (resultList != null && resultList.size() > 0) {
listDemandTrakerVo = new ArrayList<DemandTrakerVo>();
}
} catch (Exception e) {
log.error(e.getMessage());
e.printStackTrace();
}
log.info(listDemandTrakerVo.toString());
return listDemandTrakerVo;
}
@Override
public List<SkillVo> getAllSkillDetails() {
Session session = null;
List<SkillVo> listSkillSetVo = null;
try {
session = getSession();
Query<SkillsEntity> createQuery = session.createQuery("from SkillsEntity e ");
List<SkillsEntity> resultList = createQuery.getResultList();
if (resultList != null && resultList.size() > 0) {
listSkillSetVo = new ArrayList<SkillVo>();
for (SkillsEntity skillsEntity : resultList) {
SkillVo skillVo = new SkillVo();
mapper.map(skillsEntity, skillVo);
listSkillSetVo.add(skillVo);
}
}
} catch (Exception e) {
log.error(e.getMessage());
e.printStackTrace();
}
log.info(listSkillSetVo.toString());
return listSkillSetVo;
}
@Override
public SkillsEntity findById(Long id) {
SkillsEntity skillEntity = null;
try {
skillEntity = getSession().get(SkillsEntity.class, id);
} catch (Exception e) {
log.error(e.getMessage());
e.printStackTrace();
}
log.info(skillEntity.toString());
return skillEntity;
}
@Override
public List<PrimarySkillVo> getPrimarySkills() {
Session session = null;
List<PrimarySkillVo> primarySkillVos = null;
CriteriaQuery<PrimarySkillEntity> criteriaQuery = null;
try {
session = getSession();
CriteriaBuilder cb = session.getCriteriaBuilder();
criteriaQuery = cb.createQuery(PrimarySkillEntity.class);
criteriaQuery.from(PrimarySkillEntity.class);
List<PrimarySkillEntity> resultList = session.createQuery(criteriaQuery).getResultList();
if (resultList != null && resultList.size() > 0) {
primarySkillVos = new ArrayList<PrimarySkillVo>();
for (PrimarySkillEntity primarySkillEntity : resultList) {
PrimarySkillVo primarySkillVo = new PrimarySkillVo();
mapper.map(primarySkillEntity, primarySkillVo);
primarySkillVos.add(primarySkillVo);
}
}
} catch (Exception e) {
log.error(e.getMessage());
e.printStackTrace();
}
return primarySkillVos;
}
@Override
public List<SecondarySkillVo> getSecondarySkills(String skillName) {
Session session = null;
List<SecondarySkillVo> secondarySkillVos = null;
try {
session = getSession();
@SuppressWarnings("unchecked")
Query<SecondarySkillEntity> createQuery = session.createQuery("From SecondarySkillEntity where primarySkillEntity.primarySkillName=:skillName");
createQuery.setParameter("skillName", skillName);
List<SecondarySkillEntity> resultList = createQuery.getResultList();
if (resultList != null && resultList.size() > 0) {
secondarySkillVos = new ArrayList<SecondarySkillVo>();
for (SecondarySkillEntity secondarySkillEntity : resultList) {
SecondarySkillVo secondarySkillVo = new SecondarySkillVo();
mapper.map(secondarySkillEntity, secondarySkillVo);
secondarySkillVos.add(secondarySkillVo);
}
}
} catch (Exception e) {
log.error(e.getMessage());
e.printStackTrace();
}
return secondarySkillVos;
}
}
|
package beanfactory;
import com.sun.istack.internal.Nullable;
/***
*
*@Author ChenjunWang
*@Description: 后置处理器 在实例化前后
*@Date: Created in 22:56 2020/3/6`
*@Modified By:
*
*/
public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {
@Nullable
default Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) {
return null;
}
default boolean postProcessAfterInstantiation(Object bean, String beanName) {
return true;
}
}
|
package code;
/**
* Created by likz on 2023/4/23
*
* @author likz
*/
public class TrappingRainWater {
public int trap(int[] height) {
if (height == null || height.length == 0){
return 0;
}
int len = height.length;
// leftMax
int[] leftMax = new int[len + 1];
int max = height[0];
leftMax[1] = height[0];
for (int i = 1; i < len; i++){
max = Math.max(max, height[i]);
leftMax[i + 1] = max;
}
// rightMax
int[] rightMax = new int[len + 1];
max = height[len - 1];
for (int j = len - 1; j >= 1; j--){
max = Math.max(max, height[j]);
rightMax[j - 1] = max;
}
int sum = 0;
for (int index = 0; index < len; index ++){
int boundary = Math.min(rightMax[index], leftMax[index]);
sum += boundary > height[index] ? boundary - height[index] : 0;
}
return sum;
}
}
|
package polydungeons.mixin;
import it.unimi.dsi.fastutil.objects.ObjectList;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.model.ModelPart;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
@Mixin(ModelPart.class)
@Environment(EnvType.CLIENT)
public interface ModelPartAccessor {
@Accessor
ObjectList<ModelPart.Cuboid> getCuboids();
}
|
package principal.control;
public class GestorControles {
public final static Teclado teclado = new Teclado();
//public final static Mouse mouse = new Mouse();
}
|
/*
* 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 radix;
import java.util.Scanner;
/**
*
* @author ADMIN
*/
public class Radix {
private static Integer elementos[];
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
llenarLista();//lee 10 elementos
System.out.println("Elementos Ingresados:");
imprimirLista(elementos);//imprimo la lista ingresada por el usuario sin ordenar
radix(elementos);
System.out.println("Elementos Ordenados:");
imprimirLista(elementos);//imprimo en consola los numero ya ordenados
}
/**
*Ordena los elementos de manera acendente incluyendo los negativos
* @param arr el Arreglo de numeros que se quiere ordenar
*/
public static void radix(Integer[] arr) {
Integer[] arr1 = new Integer[arr.length];//declaro un areglo auxiliar
int longMax = 0;//esta variable
//este bloque de codigo es usado para determinar cuantos digitos de requiere ordenar
for (Integer num : arr) {
for (int j = 0;; j++) {//se genera un ciclo infinito que se rompera cuando se sobrepase la cantidad de digitos del numero
if (Math.abs(num / Math.pow(10, j)) < 1) {//si la parte entera de la divicion en base 10 es menor que 1 se encuenta la cantidad maxima de digitos
if (longMax < j) {
longMax = j;//se asigna la cantidad maxima de digitos
}
break;
}
}
}
int cont;//contador para moverse por el nuevo arreglo
for (int k = 0; k <= longMax; k++) {//sirve para comparar digito por digito hasta el mas grande que se encuentre
cont = 0;//reset contador
for (int i = -9; i <= 9; i++) {//revisa desde los digitos negativos hasta los digitos positivos
for (Integer arr2 : arr) {
if (((int) (arr2 / Math.pow(10, k)) % 10) == i) {//compara si el numero pertenece al digito que se esta comparando
arr1[cont++] = arr2;//agrego el numero al arreglo parcialmente ordenado
}
}
}
System.arraycopy(arr1, 0, arr, 0, arr.length);//clono el arreglo auxiliar en el arreglo principal
}
}
/**
* llena la lista con los elementos del usuario
*/
public static void llenarLista() {
boolean noSalir = true;//me indica si se seguira leyendo elementos del teclado
Scanner teclado;//declaro un Scanner para la consola
do {
teclado = new Scanner(System.in);//refresco el scanner por problemas con el ciclo
try {
System.out.println("METODO DE RADIX SORT");
System.out.print("Ingrese la cantidad de items de la lista: ");
elementos = new Integer[teclado.nextInt()];//intento optener un numero entero
noSalir = false;//indica que se salda del ciclo
} catch (java.util.InputMismatchException | java.lang.NegativeArraySizeException e) {//controlo cuando no se ingresa un numero entero
System.err.println("El valor ingresado no es valido.");
}
} while (noSalir);
do {
teclado = new Scanner(System.in);//refresco el scanner por problemas con el ciclo
try {
System.out.println(" C-Ingresar datos por consola");
System.out.println(" R-Generar Numeros Random");
switch (teclado.next()) {
case "C":
case "c": {
leerPorConsola(elementos.length);
break;
}
case "R":
case "r": {
for (int i = 0; i < elementos.length; i++) {
elementos[i] = ((int) Math.floor(Math.random() * 1000));//genera un numero random
}
break;
}
default: {
noSalir = true;
continue;
}
}
noSalir = false;//indica que se salda del ciclo
} catch (java.util.InputMismatchException e) {//controlo cuando no se ingresa un numero entero
System.err.println("El valor ingresado no es valido.");
}
} while (noSalir);
System.out.println("");
}
/**
*
* @param items
*/
public static void leerPorConsola(int items) {
Scanner teclado;//declaro un Scanner para la consola
int i = 0;
System.out.println("Ingrese " + items + " numeros que desee ordenar");
do {
teclado = new Scanner(System.in);//refresco el scanner por problemas con el ciclo
try {
System.out.print("Ingrese un numero: ");
elementos[i] = teclado.nextInt();//intento optener un numero entero
i++;
} catch (java.util.InputMismatchException e) {//controlo cuando no se ingresa un numero entero
System.err.println("El valor ingresado no es valido.");
}
} while (i < elementos.length);
}
/**
*
* @param entrada
*/
public static void imprimirLista(Integer[] entrada) {
for (Integer i : entrada) {//itero la lista
System.out.print("{" + i + "}");//imprimo el valor
}
System.out.println("");
}
}
|
package sevenkyu.peopleonbus;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
class PeopleOnBusTest {
PeopleOnBus peopleOnBus;
@BeforeEach
void init() {
peopleOnBus = new PeopleOnBus();
}
@Test
void givenEmptyInput_countPassenger_shouldReturnWithZero() {
// given
List<int[]> input = List.of();
int expected = 0;
// when
int output = peopleOnBus.countPassengers(input);
// then
assertThat(output).isEqualTo(expected);
}
@Test
void givenOneArrayInput_countPassenger_shouldReturnWithFirstElement() {
// given
List<int[]> input = List.of(new int[]{10, 0});
int expected = 10;
// when
int output = peopleOnBus.countPassengers(input);
// then
assertThat(output).isEqualTo(expected);
}
@Test
void givenTwoArrayInput_countPassenger_shouldReturnFirstElementSumMinusSecondElementSum() {
// given
List<int[]> input = List.of(new int[]{10, 0}, new int[]{3, 5});
int expected = 8;
// when
int output = peopleOnBus.countPassengers(input);
// then
assertThat(output).isEqualTo(expected);
}
@Test
void givenMultiArrayInput_countPassenger_shouldReturnFirstElementSumMinusSecondElementSum() {
// given
List<int[]> input = List.of(new int[]{10, 0}, new int[]{3, 5}, new int[]{2, 5});
int expected = 5;
// when
int output = peopleOnBus.countPassengers(input);
// then
assertThat(output).isEqualTo(expected);
}
} |
package org.icabanas.jee.api.integracion.manager.exceptions;
public class PaginacionException extends RuntimeException {
private static final long serialVersionUID = 1L;
public PaginacionException() {
super();
// TODO Auto-generated constructor stub
}
public PaginacionException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public PaginacionException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
}
|
package com.nikogalla.tripbook.utils;
import android.util.Log;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
/**
* Created by Nicola on 2017-01-29.
*/
public class DateUtils {
final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm",Locale.getDefault());
public static String getHumanReadableDateString(String date){
final String TAG = DateUtils.class.getSimpleName();
String formattedDate = null;
try{
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date d = sdf.parse(date);
DateFormat f = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.getDefault());
formattedDate = f.format(d);
} catch (Exception e){
Log.d(TAG,e.getMessage());
}
return formattedDate;
}
public static String getUTCDateStringFromdate(Date date){
final String TAG = DateUtils.class.getSimpleName();
String formattedDate = null;
try{
formattedDate = sdf.format(date);
} catch (Exception e){
Log.d(TAG,e.getMessage());
}
return formattedDate;
}
}
|
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
@SuppressWarnings("serial")
public class Game implements Serializable {
int sizeX;
int sizeY;
int numberOfColors;
//Bubble a[][] = new Bubble[size][size];
Bubble a[][] = null;
Random r = new Random();
Game(int sizeX,int sizeY,int numberOfColors) {
this.sizeX=sizeX;
this.sizeY=sizeY;
this.numberOfColors=numberOfColors;
a=new Bubble[sizeX][sizeY];
}
public void fill() {
for (int i = 0; i < sizeX; i++)
for (int j = 0; j < sizeY; j++)
//a[i][j] = new Bubble(4, a, i, j);
a[i][j] = new Bubble(r.nextInt(numberOfColors) + 1, a, i, j);
}
public ArrayList<Bubble> findSame(int i,int j) {
ArrayList<Bubble> l1 = new ArrayList<Bubble>();
l1 = a[i][j].searchColor(i, j);
return l1;
}
public int countSameBubble(int i, int j) {
return a[i][j].searchColor(i, j).size();
}
public void deleteSameBubble(int i, int j) {
List<Bubble> l1 = new ArrayList<Bubble>();
l1 = a[i][j].searchColor(i, j);
for (int k = 0; k < l1.size(); k++) {
l1.get(k).color = 0;
}
}
public void moveBubbleDown() {
for (int i = 0; i < sizeX; i++) {
for (int j = 0; j < sizeY; j++) {
a[i][j].moveDown(i, j);
}
}
}
public void generateColumn() {
boolean b = true;
for (int i = 0; i < sizeX; i++) {
if (a[i][0].color == 0)
continue;
else {
b = false;
break;
}
}
if (b == true) {
for (int i = 0; i < sizeX; i++)
a[i][0].color = r.nextInt(numberOfColors) + 1;
}
}
public void checkIfColumnsEmpty() {
int j = 0;
boolean b = false;
while (j <sizeY) {
for (int i = 0; i <sizeX; i++) {
if (a[i][j].color == 0) {
b = true;
} else {
b = false;
break;
}
if(b==true) {
moveColumnRight();
generateColumn();
}
}
j++;
}
}
public void moveColumnRight() {
int j = sizeY - 1;
boolean b = false;
try {
while (j >= 0) {
for (int i = 0; i < sizeX; i++) {
if (a[i][j].color == 0) {
b = true;
} else {
b = false;
break;
}
}
if (b == true) {
for (int i = 0; i < sizeX; i++) {
a[i][j] = a[i][j - 1];
a[i][j - 1] = new Bubble(0, a, i, j);
}
}
j--;
}
} catch (ArrayIndexOutOfBoundsException e) {
}
}
boolean checkIfGameFinish() {
for (int i = 0; i < sizeX; i++) {
for (int j = 0; j < sizeY; j++) {
if (a[i][j].color == 0)
continue;
if(a[i][j].color==11)
return false;
if(a[i][j].color==12)
return false;
try {
if (a[i][j].color == a[i + 1][j].color)
return false;
} catch (ArrayIndexOutOfBoundsException e) {
}
try {
if (a[i][j].color == a[i - 1][j].color)
return false;
} catch (ArrayIndexOutOfBoundsException e) {
}
try {
if (a[i][j].color == a[i][j + 1].color)
return false;
} catch (ArrayIndexOutOfBoundsException e) {
}
try {
if (a[i][j].color == a[i][j - 1].color)
return false;
} catch (ArrayIndexOutOfBoundsException e) {
}
}
}
return true;
}
public void print() {
for (int i = 0; i < sizeX; i++) {
for (int j = 0; j < sizeY; j++) {
System.out.print(a[i][j].color + " ");
}
System.out.println();
}
System.out.println("\n==========================\n");
}
} |
package com.mp;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.additional.update.impl.LambdaUpdateChainWrapper;
import com.mp.dao.UserMapper;
import com.mp.entity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* @Description
* @auther mohuani
* @create 2019-12-24 23:01
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class DeleteTest {
@Autowired
private UserMapper userMapper;
@Test
public void deleteById() {
int rows = userMapper.deleteById(1088248166370832385L);
System.out.println("删除记录条数:" + rows);
}
/**
* 构造where条件删除
*/
@Test
public void deleteByMap() {
Map<String, Object> columnMap = new HashMap<>();
columnMap.put("name", "刘明强5");
columnMap.put("age", 31);
int rows = userMapper.deleteByMap(columnMap);
System.out.println("删除记录条数:" + rows);
}
/**
* 批量删除
*/
@Test
public void deleteBatchIds() {
int rows = userMapper.deleteBatchIds(Arrays.asList(1209754139000852481L, 1209838254358319105L, 1209838329864204289L));
System.out.println("删除记录条数:" + rows);
}
/**
* 通过Lambda形式
*/
@Test
public void updateByWrapper4() {
LambdaQueryWrapper<User> lambdaQuery = Wrappers.lambdaQuery();
lambdaQuery.gt(User::getAge, 35).lt(User::getAge, 40);
int rows = userMapper.delete(lambdaQuery);
System.out.println("影响记录条数:" + rows);
}
}
|
package br.com.univag.logic;
import br.com.univag.controller.Logica;
import br.com.univag.exception.DaoException;
import br.com.univag.service.MovimentoVeiculoService;
import br.com.univag.service.VeiculoService;
import br.com.univag.util.Mensagem;
import java.io.IOException;
import java.sql.Connection;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author CRISTIANO
*/
public class ListMovimentoVeiculoAtivoLogic implements Logica {
Mensagem mensagem = new Mensagem();
MovimentoVeiculoService service = new MovimentoVeiculoService();
VeiculoService veiculoService = new VeiculoService();
Connection con;
@Override
public String execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
mensagem.setRequest(request);
con = (Connection) request.getAttribute("connection");
service.setCon(con);
veiculoService.setCon(con);
try {
Integer totalPaginas = service.quantidadePaginas()-1;
Integer totalVeiculo = service.totalVeiculosDentroDaUnivag();
request.setAttribute("totalVeiculo",totalVeiculo);
request.setAttribute("totalPgn", totalPaginas);
String valor = request.getParameter("valor");
if (valor != null) {
int parametro = Integer.parseInt(valor);
request.setAttribute("listMovimento", service.list(parametro));
return "sistema/listMovimentoView.jsp";
}
request.setAttribute("listMovimento", service.list(0));
} catch (DaoException ex) {
Logger.getLogger(ListMovimentoVeiculoAtivoLogic.class.getName()).log(Level.SEVERE, null, ex);
}
return "sistema/listMovimentoView.jsp";
}
}
|
package com.fixit.ui.fragments.feedback;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.fixit.app.R;
import com.fixit.controllers.ActivityController;
import com.fixit.ui.fragments.BaseFragment;
import com.fixit.utils.Constants;
import com.fixit.feedback.ChoiceSelection;
/**
* Created by Kostyantin on 8/20/2017.
*/
public class ChoiceSelectionFragment extends BaseFragment<ActivityController> {
public final static int SINGLE_CHOICE = 0;
public final static int MULTI_CHOICE = 1;
public final static int INPUT_CHOICE = 2;
protected LinearLayout mRoot;
private ChoiceSelectionListener mListener;
private int mSelectionCode;
public static ChoiceSelectionFragment newInstance(int type, String title, int selectionCode) {
ChoiceSelectionFragment fragment;
switch (type) {
case SINGLE_CHOICE:
fragment = new SingleChoiceSelectionFragment();
break;
case MULTI_CHOICE:
fragment = new MultiChoiceSelectionFragment();
break;
case INPUT_CHOICE:
fragment = new InputChoiceSelectionFragment();
break;
default:
throw new IllegalArgumentException("Invalid choice selection fragment type(" + type + ")");
}
Bundle args = new Bundle();
args.putString(Constants.ARG_TITLE, title);
args.putInt(Constants.ARG_SELECTION_CODE, selectionCode);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSelectionCode = getArguments().getInt(Constants.ARG_SELECTION_CODE);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_choice_selection, container, false);
mRoot = (LinearLayout) v.findViewById(R.id.root);
String title = getArguments().getString(Constants.ARG_TITLE);
TextView tvTitle = (TextView) v.findViewById(R.id.tv_title);
tvTitle.setText(title);
return v;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof ChoiceSelectionListener) {
mListener = (ChoiceSelectionListener) context;
} else {
throw new IllegalStateException(context.getClass().getName() + " must implement "
+ ChoiceSelectionListener.class.getName());
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
protected void onSelectionMade(Object selection) {
if(mListener != null) {
mListener.onSelectionMade(mSelectionCode, selection);
}
}
protected ChoiceSelection.Builder getSelectionsBuilder() {
return mListener.getSelections(mSelectionCode);
}
public interface ChoiceSelectionListener {
ChoiceSelection.Builder getSelections(int selectionCode);
void onSelectionMade(int selectionCode, Object selection);
}
}
|
/*
* 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 inventorywrc;
import java.awt.ComponentOrientation;
import java.awt.Frame;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import net.proteanit.sql.DbUtils;
/**
*
* @author Sushil
*/
public class Stocks extends javax.swing.JFrame {
/**
* Creates new form DashBoard
*/
public Stocks() {
initComponents();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
dbh = new DBHelper();
myTable.setModel(DbUtils.resultSetToTableModel(dbh.returnResultTotal()));
getname.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
warn();
}
@Override
public void removeUpdate(DocumentEvent e) {
warn();
}
@Override
public void changedUpdate(DocumentEvent e) {
warn();
}
public void warn(){
myTable.setModel(DbUtils.resultSetToTableModel(dbh.returnResult(getname.getText())));
// myTable.setModel(DbUtils.resultSetToTableModel(dbh.returnResultt(getname1.getText())));
}
});
getname1.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
warn();
}
@Override
public void removeUpdate(DocumentEvent e) {
warn();
}
@Override
public void changedUpdate(DocumentEvent e) {
warn();
}
public void warn(){
//myTable.setModel(DbUtils.resultSetToTableModel(dbh.returnResult(getname.getText())));
myTable.setModel(DbUtils.resultSetToTableModel(dbh.returnResultt(getname1.getText())));
}
});
}
/**
* @param args the command line arguments
*/
/**
* 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();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jPanel6 = new javax.swing.JPanel();
jLabel20 = new javax.swing.JLabel();
text3 = new javax.swing.JTextField();
jLabel22 = new javax.swing.JLabel();
text4 = new javax.swing.JTextField();
jLabel30 = new javax.swing.JLabel();
text2 = new javax.swing.JTextField();
jLabel31 = new javax.swing.JLabel();
text6 = new javax.swing.JTextField();
jLabel32 = new javax.swing.JLabel();
text5 = new javax.swing.JTextField();
jLabel33 = new javax.swing.JLabel();
text1 = new javax.swing.JTextField();
text7 = new javax.swing.JTextField();
jLabel34 = new javax.swing.JLabel();
jPanel5 = new javax.swing.JPanel();
jLabel6 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
myTable = new javax.swing.JTable();
jLabel15 = new javax.swing.JLabel();
getname = new javax.swing.JTextField();
getname1 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
add = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(new java.awt.Color(255, 255, 255));
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowOpened(java.awt.event.WindowEvent evt) {
formWindowOpened(evt);
}
});
jPanel1.setBackground(new java.awt.Color(123, 192, 226));
jLabel1.setFont(new java.awt.Font("Century Gothic", 0, 24)); // NOI18N
jLabel1.setForeground(java.awt.Color.white);
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("STOCK'S INFO");
jPanel6.setBackground(new java.awt.Color(255, 255, 255));
jLabel20.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N
jLabel20.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel20.setText("Description :");
text3.setEditable(false);
text3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
text3ActionPerformed(evt);
}
});
jLabel22.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N
jLabel22.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel22.setText("Category :");
text4.setEditable(false);
text4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
text4ActionPerformed(evt);
}
});
jLabel30.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N
jLabel30.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel30.setText("Item Name :");
text2.setEditable(false);
text2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
text2ActionPerformed(evt);
}
});
jLabel31.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N
jLabel31.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel31.setText("Stocks :");
text6.setEditable(false);
text6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
text6ActionPerformed(evt);
}
});
jLabel32.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N
jLabel32.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel32.setText("Price :");
text5.setEditable(false);
text5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
text5ActionPerformed(evt);
}
});
jLabel33.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N
jLabel33.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel33.setText("Item Code :");
text1.setEditable(false);
text1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
text1ActionPerformed(evt);
}
});
text7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
text7ActionPerformed(evt);
}
});
jLabel34.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N
jLabel34.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel34.setText("Add quantity:");
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addContainerGap(43, Short.MAX_VALUE)
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel22)
.addComponent(jLabel32)
.addComponent(jLabel20))
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel33)
.addComponent(jLabel30)))
.addGap(58, 58, 58)
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(text2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(text1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(text3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(text4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(text5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel6Layout.createSequentialGroup()
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel34)
.addComponent(jLabel31))
.addGap(58, 58, 58)
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(text6, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(text7, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(137, 137, 137))
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addGap(165, 165, 165)
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addComponent(jLabel22, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(67, 67, 67))
.addGroup(jPanel6Layout.createSequentialGroup()
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addGap(97, 97, 97)
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel20)
.addComponent(text3, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel6Layout.createSequentialGroup()
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(text1, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel33))
.addGap(20, 20, 20)
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(text2, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel30))))
.addGap(24, 24, 24)
.addComponent(text4, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(31, 31, 31)
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(text5, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel32))
.addGap(18, 18, 18)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 13, Short.MAX_VALUE)
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(text6, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel31))
.addGap(30, 30, 30)
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(text7, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel34))
.addGap(36, 36, 36))
);
jPanel5.setBackground(new java.awt.Color(255, 255, 255));
jLabel6.setFont(new java.awt.Font("Century Gothic", 0, 18)); // NOI18N
jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel6.setText("Category:");
jScrollPane1.setBackground(new java.awt.Color(255, 255, 255));
myTable.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
myTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null}
},
new String [] {
"ID", "Item Code", "Item Name", "Description", "Category", "Price", "Stocks", "Date"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false, false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
myTable.setRowHeight(30);
myTable.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
myTableMouseClicked(evt);
}
});
jScrollPane1.setViewportView(myTable);
if (myTable.getColumnModel().getColumnCount() > 0) {
myTable.getColumnModel().getColumn(0).setPreferredWidth(50);
myTable.getColumnModel().getColumn(1).setPreferredWidth(75);
myTable.getColumnModel().getColumn(2).setPreferredWidth(200);
}
jLabel15.setFont(new java.awt.Font("Century Gothic", 0, 18)); // NOI18N
jLabel15.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel15.setText("Name:");
getname.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
getnameActionPerformed(evt);
}
});
getname.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
getnameKeyPressed(evt);
}
});
getname1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
getname1ActionPerformed(evt);
}
});
getname1.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
getname1KeyPressed(evt);
}
public void keyReleased(java.awt.event.KeyEvent evt) {
getname1KeyReleased(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
getname1KeyTyped(evt);
}
});
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel5Layout.createSequentialGroup()
.addComponent(jLabel15)
.addGap(50, 50, 50)
.addComponent(getname1))
.addGroup(jPanel5Layout.createSequentialGroup()
.addComponent(jLabel6)
.addGap(18, 18, 18)
.addComponent(getname, javax.swing.GroupLayout.PREFERRED_SIZE, 336, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 836, Short.MAX_VALUE))
.addContainerGap())
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(25, 25, 25)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel6)
.addComponent(getname, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel15)
.addComponent(getname1, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 23, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 415, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(19, 19, 19))
);
jButton1.setText("Edit");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Delete");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
add.setText("Add");
add.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(add, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(98, 98, 98)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(92, 92, 92)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(82, 82, 82))
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 453, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 41, Short.MAX_VALUE)
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(add, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(28, 28, 28))
);
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 673, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 88, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
}//GEN-LAST:event_formWindowOpened
private void text3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_text3ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_text3ActionPerformed
private void text4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_text4ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_text4ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
if(selectedID!=null)
{
//new EditDetails(selectedID,info).setVisible(true);
} else
JOptionPane.showMessageDialog(this, "Select ITEMS to view Information.");
}//GEN-LAST:event_jButton1ActionPerformed
private void text2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_text2ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_text2ActionPerformed
private void text5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_text5ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_text5ActionPerformed
private void text1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_text1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_text1ActionPerformed
private void getnameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_getnameActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_getnameActionPerformed
private void myTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_myTableMouseClicked
// TODO add your handling code here:
int selectedRow = myTable.getSelectedRow();
selectedID = myTable.getValueAt(selectedRow, 0).toString();
info = dbh.returndata(selectedID);
text1.setText(info[0]);
text2.setText(info[1]);
text3.setText(info[2]);
text4.setText(info[3]);
text5.setText(info[4]);
text6.setText(info[5]);
}//GEN-LAST:event_myTableMouseClicked
@SuppressWarnings("empty-statement")
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
JDialog.setDefaultLookAndFeelDecorated(true);
int response = JOptionPane.showConfirmDialog(null, "Are you Sure about deleting Info?", "Confirm",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (response == JOptionPane.NO_OPTION) {
} else if (response == JOptionPane.YES_OPTION) {
dbh.deletestudent(selectedID);
myTable.setModel(DbUtils.resultSetToTableModel(dbh.returnResultTotal()));
text1.setText("");
text2.setText("");
text3.setText("");;
text4.setText("");;
text5.setText("");;
text6.setText("");;
// new StudentDetails().setVisible(true);
} else if (response == JOptionPane.CLOSED_OPTION) {
}
}//GEN-LAST:event_jButton2ActionPerformed
private void text6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_text6ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_text6ActionPerformed
private void getname1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_getname1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_getname1ActionPerformed
private void getname1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_getname1KeyPressed
// TODO add your handling code here:
myTable.setModel(DbUtils.resultSetToTableModel(dbh.returnResultt(getname1.getText())));
}//GEN-LAST:event_getname1KeyPressed
private void getname1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_getname1KeyReleased
// TODO add your handling code here:
//myTable.setModel(DbUtils.resultSetToTableModel(dbh.returnResult(getname.getText())));
}//GEN-LAST:event_getname1KeyReleased
private void getname1KeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_getname1KeyTyped
// TODO add your handling code here:
//myTable.setModel(DbUtils.resultSetToTableModel(dbh.returnResult(getname.getText())));
}//GEN-LAST:event_getname1KeyTyped
private void getnameKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_getnameKeyPressed
// TODO add your handling code here:
myTable.setModel(DbUtils.resultSetToTableModel(dbh.returnResult(getname.getText())));
}//GEN-LAST:event_getnameKeyPressed
private void addActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addActionPerformed
// TODO add your handling code here:
String text777 = text7.getText();
String text666 = text6.getText();
String text11 = text1.getText();
int total = Integer.parseInt(text777) + Integer.parseInt(text666);
String text77 = String.valueOf(total);
dbh.addQuantity(text77,text11);
JOptionPane.showMessageDialog(this, "Successfully Added.");
}//GEN-LAST:event_addActionPerformed
private void text7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_text7ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_text7ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton add;
private javax.swing.JTextField getname;
private javax.swing.JTextField getname1;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel20;
private javax.swing.JLabel jLabel22;
private javax.swing.JLabel jLabel30;
private javax.swing.JLabel jLabel31;
private javax.swing.JLabel jLabel32;
private javax.swing.JLabel jLabel33;
private javax.swing.JLabel jLabel34;
private javax.swing.JLabel jLabel6;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable myTable;
private javax.swing.JTextField text1;
private javax.swing.JTextField text2;
private javax.swing.JTextField text3;
private javax.swing.JTextField text4;
private javax.swing.JTextField text5;
private javax.swing.JTextField text6;
private javax.swing.JTextField text7;
// End of variables declaration//GEN-END:variables
DBHelper dbh;
String selectedID;
String[] info;
}
|
package com.podarbetweenus.Adapter;
import android.app.Activity;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.podarbetweenus.R;
import java.util.List;
import java.util.Map;
/**
* Created by Administrator on 10/9/2015.
*/
public class ExpandablelistVideosAdapter extends BaseExpandableListAdapter {
private Activity context;
private Map<String, List<String>> videosCollections;
private List<String> subject;
// final String namess[] ={"Jun 2015","Jul 2015","Aug 2015","Sept 2015"};
public ExpandablelistVideosAdapter(Activity context, List<String> subject, Map<String, List<String>> videos_collection) {
this.videosCollections = videos_collection;
this.subject = subject;
this.context = context;
}
@Override
public int getGroupCount() {
return subject.size();
}
@Override
public int getChildrenCount(int groupPosition) {
return videosCollections.get(subject.get(groupPosition)).size();
}
@Override
public Object getGroup(int groupPosition) {
return subject.get(groupPosition);
}
@Override
public Object getChild(int groupPosition, int childPosition) {
return videosCollections.get(subject.get(groupPosition)).get(childPosition);
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
String subject = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.group_item_videos,
null);
}
TextView subject_name = (TextView) convertView.findViewById(R.id.subject);
subject_name.setTypeface(null, Typeface.BOLD);
subject_name.setText(subject);
ImageView img_view = (ImageView) convertView.findViewById(R.id.img_view);
return convertView;
}
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
final String topic = (String) getChild(groupPosition, childPosition);
LayoutInflater inflater = context.getLayoutInflater();
if(convertView==null)
{
convertView = inflater.inflate(R.layout.child_item_videos, null);
}
TextView topics = (TextView) convertView.findViewById(R.id.topics);
topics.setText(topic);
return convertView;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.